hexsha
stringlengths 40
40
| repo
stringlengths 5
114
| path
stringlengths 4
295
| license
listlengths 1
10
| language
stringclasses 5
values | identifier
stringlengths 1
116
| original_docstring
stringlengths 133
7.85k
| docstring
stringlengths 7
2.1k
| docstring_tokens
listlengths 3
399
| code
stringlengths 350
22.6k
| code_tokens
listlengths 20
3.22k
| short_docstring
stringlengths 0
1.32k
| short_docstring_tokens
listlengths 0
359
| comment
listlengths 0
1.22k
| parameters
listlengths 0
13
| docstring_params
dict | has_error
bool 1
class | ast_depth
int64 13
29
| code_length
int64 151
3k
| original_docstring_length
int64 76
449
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5138132563da5d85becac8c849c6fc59212713e1
|
alex-harper/LottieSkiaSharp
|
LottieSkiaSharp/LottieComposition.cs
|
[
"Apache-2.0"
] |
C#
|
LottieComposition
|
/// <summary>
/// After Effects/Bodymovin composition model. This is the serialized model from which the
/// animation will be created.
///
/// To create one, use <see cref="LottieCompositionFactory"/>.
///
/// It can be used with a <seealso cref="LottieAnimationView"/> or
/// <seealso cref="LottieDrawable"/>.
/// </summary>
|
After Effects/Bodymovin composition model. This is the serialized model from which the
animation will be created.
To create one, use .
It can be used with a or
.
|
[
"After",
"Effects",
"/",
"Bodymovin",
"composition",
"model",
".",
"This",
"is",
"the",
"serialized",
"model",
"from",
"which",
"the",
"animation",
"will",
"be",
"created",
".",
"To",
"create",
"one",
"use",
".",
"It",
"can",
"be",
"used",
"with",
"a",
"or",
"."
] |
public class LottieComposition
{
private readonly PerformanceTracker _performanceTracker = new PerformanceTracker();
private readonly HashSet<string> _warnings = new HashSet<string>();
private Dictionary<string, List<Layer>> _precomps;
private Dictionary<string, LottieImageAsset> _images;
public Dictionary<string, Font> Fonts { get; private set; }
public Dictionary<int, FontCharacter> Characters { get; private set; }
private Dictionary<long, Layer> _layerMap;
public List<Layer> Layers { get; private set; }
public SKRect Bounds { get; private set; }
public float StartFrame { get; private set; }
public float EndFrame { get; private set; }
public float FrameRate { get; private set; }
internal void AddWarning(string warning)
{
Debug.WriteLine(warning, LottieLog.Tag);
_warnings.Add(warning);
}
public List<string> Warnings => _warnings.ToList();
public bool PerformanceTrackingEnabled
{
set => _performanceTracker.Enabled = value;
}
public PerformanceTracker PerformanceTracker => _performanceTracker;
internal Layer LayerModelForId(long id)
{
_layerMap.TryGetValue(id, out Layer layer);
return layer;
}
public float Duration
{
get
{
return (long)(DurationFrames / FrameRate * 1000);
}
}
public void Init(SKRect bounds, float startFrame, float endFrame, float frameRate, List<Layer> layers, Dictionary<long, Layer> layerMap, Dictionary<string, List<Layer>> precomps, Dictionary<string, LottieImageAsset> images, Dictionary<int, FontCharacter> characters, Dictionary<string, Font> fonts)
{
Bounds = bounds;
StartFrame = startFrame;
EndFrame = endFrame;
FrameRate = frameRate;
Layers = layers;
_layerMap = layerMap;
_precomps = precomps;
_images = images;
Characters = characters;
Fonts = fonts;
}
internal List<Layer> GetPrecomps(string id)
{
return _precomps[id];
}
public bool HasImages => _images.Count > 0;
public Dictionary<string, LottieImageAsset> Images => _images;
internal float DurationFrames => EndFrame - StartFrame;
public override string ToString()
{
var sb = new StringBuilder("LottieComposition:\n");
foreach (var layer in Layers)
{
sb.Append(layer.ToString("\t"));
}
return sb.ToString();
}
}
|
[
"public",
"class",
"LottieComposition",
"{",
"private",
"readonly",
"PerformanceTracker",
"_performanceTracker",
"=",
"new",
"PerformanceTracker",
"(",
")",
";",
"private",
"readonly",
"HashSet",
"<",
"string",
">",
"_warnings",
"=",
"new",
"HashSet",
"<",
"string",
">",
"(",
")",
";",
"private",
"Dictionary",
"<",
"string",
",",
"List",
"<",
"Layer",
">",
">",
"_precomps",
";",
"private",
"Dictionary",
"<",
"string",
",",
"LottieImageAsset",
">",
"_images",
";",
"public",
"Dictionary",
"<",
"string",
",",
"Font",
">",
"Fonts",
"{",
"get",
";",
"private",
"set",
";",
"}",
"public",
"Dictionary",
"<",
"int",
",",
"FontCharacter",
">",
"Characters",
"{",
"get",
";",
"private",
"set",
";",
"}",
"private",
"Dictionary",
"<",
"long",
",",
"Layer",
">",
"_layerMap",
";",
"public",
"List",
"<",
"Layer",
">",
"Layers",
"{",
"get",
";",
"private",
"set",
";",
"}",
"public",
"SKRect",
"Bounds",
"{",
"get",
";",
"private",
"set",
";",
"}",
"public",
"float",
"StartFrame",
"{",
"get",
";",
"private",
"set",
";",
"}",
"public",
"float",
"EndFrame",
"{",
"get",
";",
"private",
"set",
";",
"}",
"public",
"float",
"FrameRate",
"{",
"get",
";",
"private",
"set",
";",
"}",
"internal",
"void",
"AddWarning",
"(",
"string",
"warning",
")",
"{",
"Debug",
".",
"WriteLine",
"(",
"warning",
",",
"LottieLog",
".",
"Tag",
")",
";",
"_warnings",
".",
"Add",
"(",
"warning",
")",
";",
"}",
"public",
"List",
"<",
"string",
">",
"Warnings",
"=>",
"_warnings",
".",
"ToList",
"(",
")",
";",
"public",
"bool",
"PerformanceTrackingEnabled",
"{",
"set",
"=>",
"_performanceTracker",
".",
"Enabled",
"=",
"value",
";",
"}",
"public",
"PerformanceTracker",
"PerformanceTracker",
"=>",
"_performanceTracker",
";",
"internal",
"Layer",
"LayerModelForId",
"(",
"long",
"id",
")",
"{",
"_layerMap",
".",
"TryGetValue",
"(",
"id",
",",
"out",
"Layer",
"layer",
")",
";",
"return",
"layer",
";",
"}",
"public",
"float",
"Duration",
"{",
"get",
"{",
"return",
"(",
"long",
")",
"(",
"DurationFrames",
"/",
"FrameRate",
"*",
"1000",
")",
";",
"}",
"}",
"public",
"void",
"Init",
"(",
"SKRect",
"bounds",
",",
"float",
"startFrame",
",",
"float",
"endFrame",
",",
"float",
"frameRate",
",",
"List",
"<",
"Layer",
">",
"layers",
",",
"Dictionary",
"<",
"long",
",",
"Layer",
">",
"layerMap",
",",
"Dictionary",
"<",
"string",
",",
"List",
"<",
"Layer",
">",
">",
"precomps",
",",
"Dictionary",
"<",
"string",
",",
"LottieImageAsset",
">",
"images",
",",
"Dictionary",
"<",
"int",
",",
"FontCharacter",
">",
"characters",
",",
"Dictionary",
"<",
"string",
",",
"Font",
">",
"fonts",
")",
"{",
"Bounds",
"=",
"bounds",
";",
"StartFrame",
"=",
"startFrame",
";",
"EndFrame",
"=",
"endFrame",
";",
"FrameRate",
"=",
"frameRate",
";",
"Layers",
"=",
"layers",
";",
"_layerMap",
"=",
"layerMap",
";",
"_precomps",
"=",
"precomps",
";",
"_images",
"=",
"images",
";",
"Characters",
"=",
"characters",
";",
"Fonts",
"=",
"fonts",
";",
"}",
"internal",
"List",
"<",
"Layer",
">",
"GetPrecomps",
"(",
"string",
"id",
")",
"{",
"return",
"_precomps",
"[",
"id",
"]",
";",
"}",
"public",
"bool",
"HasImages",
"=>",
"_images",
".",
"Count",
">",
"0",
";",
"public",
"Dictionary",
"<",
"string",
",",
"LottieImageAsset",
">",
"Images",
"=>",
"_images",
";",
"internal",
"float",
"DurationFrames",
"=>",
"EndFrame",
"-",
"StartFrame",
";",
"public",
"override",
"string",
"ToString",
"(",
")",
"{",
"var",
"sb",
"=",
"new",
"StringBuilder",
"(",
"\"",
"LottieComposition:",
"\\n",
"\"",
")",
";",
"foreach",
"(",
"var",
"layer",
"in",
"Layers",
")",
"{",
"sb",
".",
"Append",
"(",
"layer",
".",
"ToString",
"(",
"\"",
"\\t",
"\"",
")",
")",
";",
"}",
"return",
"sb",
".",
"ToString",
"(",
")",
";",
"}",
"}"
] |
After Effects/Bodymovin composition model.
|
[
"After",
"Effects",
"/",
"Bodymovin",
"composition",
"model",
"."
] |
[
"/** Map of font names to fonts */",
"// This is stored as a set to avoid duplicates."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 555
| 79
|
8d04bd78e811aaadc882b41ffa905f02a5e2f1e4
|
tonotorres/Proyecto_anterior
|
node_modules/@ckeditor/ckeditor5-ui/src/panel/balloon/balloonpanelview.js
|
[
"MIT"
] |
JavaScript
|
BalloonPanelView
|
/**
* The balloon panel view class.
*
* A floating container which can
* {@link module:ui/panel/balloon/balloonpanelview~BalloonPanelView#pin pin} to any
* {@link module:utils/dom/position~Options#target target} in the DOM and remain in that position
* e.g. when the web page is scrolled.
*
* The balloon panel can be used to display contextual, non-blocking UI like forms, toolbars and
* the like in its {@link module:ui/panel/balloon/balloonpanelview~BalloonPanelView#content} view
* collection.
*
* There is a number of {@link module:ui/panel/balloon/balloonpanelview~BalloonPanelView.defaultPositions}
* that the balloon can use, automatically switching from one to another when the viewport space becomes
* scarce to keep the balloon visible to the user as long as it is possible. The balloon will also
* accept any custom position set provided by the user compatible with the
* {@link module:utils/dom/position~Options options}.
*
* const panel = new BalloonPanelView( locale );
* const childView = new ChildView();
* const positions = BalloonPanelView.defaultPositions;
*
* panel.render();
*
* // Add a child view to the panel's content collection.
* panel.content.add( childView );
*
* // Start pinning the panel to an element with the "target" id DOM.
* // The balloon will remain pinned until unpin() is called.
* panel.pin( {
* target: document.querySelector( '#target' ),
* positions: [
* positions.northArrowSouth,
* positions.southArrowNorth
* ]
* } );
*
* @extends module:ui/view~View
*/
|
The balloon panel view class.
The balloon panel can be used to display contextual, non-blocking UI like forms, toolbars and
the like in its module:ui/panel/balloon/balloonpanelview~BalloonPanelView#content view
collection.
There is a number of module:ui/panel/balloon/balloonpanelview~BalloonPanelView.defaultPositions
that the balloon can use, automatically switching from one to another when the viewport space becomes
scarce to keep the balloon visible to the user as long as it is possible. The balloon will also
accept any custom position set provided by the user compatible with the
module:utils/dom/position~Options options.
const panel = new BalloonPanelView( locale );
const childView = new ChildView();
const positions = BalloonPanelView.defaultPositions.
Add a child view to the panel's content collection.
Start pinning the panel to an element with the "target" id DOM.
The balloon will remain pinned until unpin() is called.
@extends module:ui/view~View
|
[
"The",
"balloon",
"panel",
"view",
"class",
".",
"The",
"balloon",
"panel",
"can",
"be",
"used",
"to",
"display",
"contextual",
"non",
"-",
"blocking",
"UI",
"like",
"forms",
"toolbars",
"and",
"the",
"like",
"in",
"its",
"module",
":",
"ui",
"/",
"panel",
"/",
"balloon",
"/",
"balloonpanelview~BalloonPanelView#content",
"view",
"collection",
".",
"There",
"is",
"a",
"number",
"of",
"module",
":",
"ui",
"/",
"panel",
"/",
"balloon",
"/",
"balloonpanelview~BalloonPanelView",
".",
"defaultPositions",
"that",
"the",
"balloon",
"can",
"use",
"automatically",
"switching",
"from",
"one",
"to",
"another",
"when",
"the",
"viewport",
"space",
"becomes",
"scarce",
"to",
"keep",
"the",
"balloon",
"visible",
"to",
"the",
"user",
"as",
"long",
"as",
"it",
"is",
"possible",
".",
"The",
"balloon",
"will",
"also",
"accept",
"any",
"custom",
"position",
"set",
"provided",
"by",
"the",
"user",
"compatible",
"with",
"the",
"module",
":",
"utils",
"/",
"dom",
"/",
"position~Options",
"options",
".",
"const",
"panel",
"=",
"new",
"BalloonPanelView",
"(",
"locale",
")",
";",
"const",
"childView",
"=",
"new",
"ChildView",
"()",
";",
"const",
"positions",
"=",
"BalloonPanelView",
".",
"defaultPositions",
".",
"Add",
"a",
"child",
"view",
"to",
"the",
"panel",
"'",
"s",
"content",
"collection",
".",
"Start",
"pinning",
"the",
"panel",
"to",
"an",
"element",
"with",
"the",
"\"",
"target",
"\"",
"id",
"DOM",
".",
"The",
"balloon",
"will",
"remain",
"pinned",
"until",
"unpin",
"()",
"is",
"called",
".",
"@extends",
"module",
":",
"ui",
"/",
"view~View"
] |
class BalloonPanelView extends View {
/**
* @inheritDoc
*/
constructor( locale ) {
super( locale );
const bind = this.bindTemplate;
/**
* The absolute top position of the balloon panel in pixels.
*
* @observable
* @default 0
* @member {Number} #top
*/
this.set( 'top', 0 );
/**
* The absolute left position of the balloon panel in pixels.
*
* @observable
* @default 0
* @member {Number} #left
*/
this.set( 'left', 0 );
/**
* The balloon panel's current position. The position name is reflected in the CSS class set
* to the balloon, i.e. `.ck-balloon-panel_arrow_nw` for the "arrow_nw" position. The class
* controls the minor aspects of the balloon's visual appearance like the placement
* of an {@link #withArrow arrow}. To support a new position, an additional CSS must be created.
*
* Default position names correspond with
* {@link module:ui/panel/balloon/balloonpanelview~BalloonPanelView.defaultPositions}.
*
* See the {@link #attachTo} and {@link #pin} methods to learn about custom balloon positions.
*
* @observable
* @default 'arrow_nw'
* @member {'arrow_nw'|'arrow_ne'|'arrow_sw'|'arrow_se'} #position
*/
this.set( 'position', 'arrow_nw' );
/**
* Controls whether the balloon panel is visible or not.
*
* @observable
* @default false
* @member {Boolean} #isVisible
*/
this.set( 'isVisible', false );
/**
* Controls whether the balloon panel has an arrow. The presence of the arrow
* is reflected in the `ck-balloon-panel_with-arrow` CSS class.
*
* @observable
* @default true
* @member {Boolean} #withArrow
*/
this.set( 'withArrow', true );
/**
* An additional CSS class added to the {@link #element}.
*
* @observable
* @member {String} #class
*/
this.set( 'class' );
/**
* A callback that starts pinning the panel when {@link #isVisible} gets
* `true`. Used by {@link #pin}.
*
* @private
* @member {Function} #_pinWhenIsVisibleCallback
*/
/**
* A collection of the child views that creates the balloon panel contents.
*
* @readonly
* @member {module:ui/viewcollection~ViewCollection}
*/
this.content = this.createCollection();
this.setTemplate( {
tag: 'div',
attributes: {
class: [
'ck',
'ck-balloon-panel',
bind.to( 'position', value => `ck-balloon-panel_${ value }` ),
bind.if( 'isVisible', 'ck-balloon-panel_visible' ),
bind.if( 'withArrow', 'ck-balloon-panel_with-arrow' ),
bind.to( 'class' )
],
style: {
top: bind.to( 'top', toPx ),
left: bind.to( 'left', toPx )
}
},
children: this.content
} );
}
/**
* Shows the panel.
*
* See {@link #isVisible}.
*/
show() {
this.isVisible = true;
}
/**
* Hides the panel.
*
* See {@link #isVisible}.
*/
hide() {
this.isVisible = false;
}
/**
* Attaches the panel to a specified {@link module:utils/dom/position~Options#target} with a
* smart positioning heuristics that chooses from available positions to make sure the panel
* is visible to the user i.e. within the limits of the viewport.
*
* This method accepts configuration {@link module:utils/dom/position~Options options}
* to set the `target`, optional `limiter` and `positions` the balloon should choose from.
*
* const panel = new BalloonPanelView( locale );
* const positions = BalloonPanelView.defaultPositions;
*
* panel.render();
*
* // Attach the panel to an element with the "target" id DOM.
* panel.attachTo( {
* target: document.querySelector( '#target' ),
* positions: [
* positions.northArrowSouth,
* positions.southArrowNorth
* ]
* } );
*
* **Note**: Attaching the panel will also automatically {@link #show} it.
*
* **Note**: An attached panel will not follow its target when the window is scrolled or resized.
* See the {@link #pin} method for a more permanent positioning strategy.
*
* @param {module:utils/dom/position~Options} options Positioning options compatible with
* {@link module:utils/dom/position~getOptimalPosition}. Default `positions` array is
* {@link module:ui/panel/balloon/balloonpanelview~BalloonPanelView.defaultPositions}.
*/
attachTo( options ) {
this.show();
const defaultPositions = BalloonPanelView.defaultPositions;
const positionOptions = Object.assign( {}, {
element: this.element,
positions: [
defaultPositions.southArrowNorth,
defaultPositions.southArrowNorthWest,
defaultPositions.southArrowNorthEast,
defaultPositions.northArrowSouth,
defaultPositions.northArrowSouthWest,
defaultPositions.northArrowSouthEast
],
limiter: defaultLimiterElement,
fitInViewport: true
}, options );
const optimalPosition = BalloonPanelView._getOptimalPosition( positionOptions );
// Usually browsers make some problems with super accurate values like 104.345px
// so it is better to use int values.
const left = parseInt( optimalPosition.left );
const top = parseInt( optimalPosition.top );
const position = optimalPosition.name;
Object.assign( this, { top, left, position } );
}
/**
* Works the same way as the {@link #attachTo} method except that the position of the panel is
* continuously updated when:
*
* * any ancestor of the {@link module:utils/dom/position~Options#target}
* or {@link module:utils/dom/position~Options#limiter} is scrolled,
* * the browser window gets resized or scrolled.
*
* Thanks to that, the panel always sticks to the {@link module:utils/dom/position~Options#target}
* and is immune to the changing environment.
*
* const panel = new BalloonPanelView( locale );
* const positions = BalloonPanelView.defaultPositions;
*
* panel.render();
*
* // Pin the panel to an element with the "target" id DOM.
* panel.pin( {
* target: document.querySelector( '#target' ),
* positions: [
* positions.northArrowSouth,
* positions.southArrowNorth
* ]
* } );
*
* To leave the pinned state, use the {@link #unpin} method.
*
* **Note**: Pinning the panel will also automatically {@link #show} it.
*
* @param {module:utils/dom/position~Options} options Positioning options compatible with
* {@link module:utils/dom/position~getOptimalPosition}. Default `positions` array is
* {@link module:ui/panel/balloon/balloonpanelview~BalloonPanelView.defaultPositions}.
*/
pin( options ) {
this.unpin();
this._pinWhenIsVisibleCallback = () => {
if ( this.isVisible ) {
this._startPinning( options );
} else {
this._stopPinning();
}
};
this._startPinning( options );
// Control the state of the listeners depending on whether the panel is visible
// or not.
// TODO: Use on() (https://github.com/ckeditor/ckeditor5-utils/issues/144).
this.listenTo( this, 'change:isVisible', this._pinWhenIsVisibleCallback );
}
/**
* Stops pinning the panel, as set up by {@link #pin}.
*/
unpin() {
if ( this._pinWhenIsVisibleCallback ) {
// Deactivate listeners attached by pin().
this._stopPinning();
// Deactivate the panel pin() control logic.
// TODO: Use off() (https://github.com/ckeditor/ckeditor5-utils/issues/144).
this.stopListening( this, 'change:isVisible', this._pinWhenIsVisibleCallback );
this._pinWhenIsVisibleCallback = null;
this.hide();
}
}
/**
* Starts managing the pinned state of the panel. See {@link #pin}.
*
* @private
* @param {module:utils/dom/position~Options} options Positioning options compatible with
* {@link module:utils/dom/position~getOptimalPosition}.
*/
_startPinning( options ) {
this.attachTo( options );
const targetElement = getDomElement( options.target );
const limiterElement = options.limiter ? getDomElement( options.limiter ) : defaultLimiterElement;
// Then we need to listen on scroll event of eny element in the document.
this.listenTo( global.document, 'scroll', ( evt, domEvt ) => {
const scrollTarget = domEvt.target;
// The position needs to be updated if the positioning target is within the scrolled element.
const isWithinScrollTarget = targetElement && scrollTarget.contains( targetElement );
// The position needs to be updated if the positioning limiter is within the scrolled element.
const isLimiterWithinScrollTarget = limiterElement && scrollTarget.contains( limiterElement );
// The positioning target and/or limiter can be a Rect, object etc..
// There's no way to optimize the listener then.
if ( isWithinScrollTarget || isLimiterWithinScrollTarget || !targetElement || !limiterElement ) {
this.attachTo( options );
}
}, { useCapture: true } );
// We need to listen on window resize event and update position.
this.listenTo( global.window, 'resize', () => {
this.attachTo( options );
} );
}
/**
* Stops managing the pinned state of the panel. See {@link #pin}.
*
* @private
*/
_stopPinning() {
this.stopListening( global.document, 'scroll' );
this.stopListening( global.window, 'resize' );
}
}
|
[
"class",
"BalloonPanelView",
"extends",
"View",
"{",
"constructor",
"(",
"locale",
")",
"{",
"super",
"(",
"locale",
")",
";",
"const",
"bind",
"=",
"this",
".",
"bindTemplate",
";",
"this",
".",
"set",
"(",
"'top'",
",",
"0",
")",
";",
"this",
".",
"set",
"(",
"'left'",
",",
"0",
")",
";",
"this",
".",
"set",
"(",
"'position'",
",",
"'arrow_nw'",
")",
";",
"this",
".",
"set",
"(",
"'isVisible'",
",",
"false",
")",
";",
"this",
".",
"set",
"(",
"'withArrow'",
",",
"true",
")",
";",
"this",
".",
"set",
"(",
"'class'",
")",
";",
"this",
".",
"content",
"=",
"this",
".",
"createCollection",
"(",
")",
";",
"this",
".",
"setTemplate",
"(",
"{",
"tag",
":",
"'div'",
",",
"attributes",
":",
"{",
"class",
":",
"[",
"'ck'",
",",
"'ck-balloon-panel'",
",",
"bind",
".",
"to",
"(",
"'position'",
",",
"value",
"=>",
"`",
"${",
"value",
"}",
"`",
")",
",",
"bind",
".",
"if",
"(",
"'isVisible'",
",",
"'ck-balloon-panel_visible'",
")",
",",
"bind",
".",
"if",
"(",
"'withArrow'",
",",
"'ck-balloon-panel_with-arrow'",
")",
",",
"bind",
".",
"to",
"(",
"'class'",
")",
"]",
",",
"style",
":",
"{",
"top",
":",
"bind",
".",
"to",
"(",
"'top'",
",",
"toPx",
")",
",",
"left",
":",
"bind",
".",
"to",
"(",
"'left'",
",",
"toPx",
")",
"}",
"}",
",",
"children",
":",
"this",
".",
"content",
"}",
")",
";",
"}",
"show",
"(",
")",
"{",
"this",
".",
"isVisible",
"=",
"true",
";",
"}",
"hide",
"(",
")",
"{",
"this",
".",
"isVisible",
"=",
"false",
";",
"}",
"attachTo",
"(",
"options",
")",
"{",
"this",
".",
"show",
"(",
")",
";",
"const",
"defaultPositions",
"=",
"BalloonPanelView",
".",
"defaultPositions",
";",
"const",
"positionOptions",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"{",
"element",
":",
"this",
".",
"element",
",",
"positions",
":",
"[",
"defaultPositions",
".",
"southArrowNorth",
",",
"defaultPositions",
".",
"southArrowNorthWest",
",",
"defaultPositions",
".",
"southArrowNorthEast",
",",
"defaultPositions",
".",
"northArrowSouth",
",",
"defaultPositions",
".",
"northArrowSouthWest",
",",
"defaultPositions",
".",
"northArrowSouthEast",
"]",
",",
"limiter",
":",
"defaultLimiterElement",
",",
"fitInViewport",
":",
"true",
"}",
",",
"options",
")",
";",
"const",
"optimalPosition",
"=",
"BalloonPanelView",
".",
"_getOptimalPosition",
"(",
"positionOptions",
")",
";",
"const",
"left",
"=",
"parseInt",
"(",
"optimalPosition",
".",
"left",
")",
";",
"const",
"top",
"=",
"parseInt",
"(",
"optimalPosition",
".",
"top",
")",
";",
"const",
"position",
"=",
"optimalPosition",
".",
"name",
";",
"Object",
".",
"assign",
"(",
"this",
",",
"{",
"top",
",",
"left",
",",
"position",
"}",
")",
";",
"}",
"pin",
"(",
"options",
")",
"{",
"this",
".",
"unpin",
"(",
")",
";",
"this",
".",
"_pinWhenIsVisibleCallback",
"=",
"(",
")",
"=>",
"{",
"if",
"(",
"this",
".",
"isVisible",
")",
"{",
"this",
".",
"_startPinning",
"(",
"options",
")",
";",
"}",
"else",
"{",
"this",
".",
"_stopPinning",
"(",
")",
";",
"}",
"}",
";",
"this",
".",
"_startPinning",
"(",
"options",
")",
";",
"this",
".",
"listenTo",
"(",
"this",
",",
"'change:isVisible'",
",",
"this",
".",
"_pinWhenIsVisibleCallback",
")",
";",
"}",
"unpin",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_pinWhenIsVisibleCallback",
")",
"{",
"this",
".",
"_stopPinning",
"(",
")",
";",
"this",
".",
"stopListening",
"(",
"this",
",",
"'change:isVisible'",
",",
"this",
".",
"_pinWhenIsVisibleCallback",
")",
";",
"this",
".",
"_pinWhenIsVisibleCallback",
"=",
"null",
";",
"this",
".",
"hide",
"(",
")",
";",
"}",
"}",
"_startPinning",
"(",
"options",
")",
"{",
"this",
".",
"attachTo",
"(",
"options",
")",
";",
"const",
"targetElement",
"=",
"getDomElement",
"(",
"options",
".",
"target",
")",
";",
"const",
"limiterElement",
"=",
"options",
".",
"limiter",
"?",
"getDomElement",
"(",
"options",
".",
"limiter",
")",
":",
"defaultLimiterElement",
";",
"this",
".",
"listenTo",
"(",
"global",
".",
"document",
",",
"'scroll'",
",",
"(",
"evt",
",",
"domEvt",
")",
"=>",
"{",
"const",
"scrollTarget",
"=",
"domEvt",
".",
"target",
";",
"const",
"isWithinScrollTarget",
"=",
"targetElement",
"&&",
"scrollTarget",
".",
"contains",
"(",
"targetElement",
")",
";",
"const",
"isLimiterWithinScrollTarget",
"=",
"limiterElement",
"&&",
"scrollTarget",
".",
"contains",
"(",
"limiterElement",
")",
";",
"if",
"(",
"isWithinScrollTarget",
"||",
"isLimiterWithinScrollTarget",
"||",
"!",
"targetElement",
"||",
"!",
"limiterElement",
")",
"{",
"this",
".",
"attachTo",
"(",
"options",
")",
";",
"}",
"}",
",",
"{",
"useCapture",
":",
"true",
"}",
")",
";",
"this",
".",
"listenTo",
"(",
"global",
".",
"window",
",",
"'resize'",
",",
"(",
")",
"=>",
"{",
"this",
".",
"attachTo",
"(",
"options",
")",
";",
"}",
")",
";",
"}",
"_stopPinning",
"(",
")",
"{",
"this",
".",
"stopListening",
"(",
"global",
".",
"document",
",",
"'scroll'",
")",
";",
"this",
".",
"stopListening",
"(",
"global",
".",
"window",
",",
"'resize'",
")",
";",
"}",
"}"
] |
The balloon panel view class.
|
[
"The",
"balloon",
"panel",
"view",
"class",
"."
] |
[
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t\t * The absolute top position of the balloon panel in pixels.\n\t\t *\n\t\t * @observable\n\t\t * @default 0\n\t\t * @member {Number} #top\n\t\t */",
"/**\n\t\t * The absolute left position of the balloon panel in pixels.\n\t\t *\n\t\t * @observable\n\t\t * @default 0\n\t\t * @member {Number} #left\n\t\t */",
"/**\n\t\t * The balloon panel's current position. The position name is reflected in the CSS class set\n\t\t * to the balloon, i.e. `.ck-balloon-panel_arrow_nw` for the \"arrow_nw\" position. The class\n\t\t * controls the minor aspects of the balloon's visual appearance like the placement\n\t\t * of an {@link #withArrow arrow}. To support a new position, an additional CSS must be created.\n\t\t *\n\t\t * Default position names correspond with\n\t\t * {@link module:ui/panel/balloon/balloonpanelview~BalloonPanelView.defaultPositions}.\n\t\t *\n\t\t * See the {@link #attachTo} and {@link #pin} methods to learn about custom balloon positions.\n\t\t *\n\t\t * @observable\n\t\t * @default 'arrow_nw'\n\t\t * @member {'arrow_nw'|'arrow_ne'|'arrow_sw'|'arrow_se'} #position\n\t\t */",
"/**\n\t\t * Controls whether the balloon panel is visible or not.\n\t\t *\n\t\t * @observable\n\t\t * @default false\n\t\t * @member {Boolean} #isVisible\n\t\t */",
"/**\n\t\t * Controls whether the balloon panel has an arrow. The presence of the arrow\n\t\t * is reflected in the `ck-balloon-panel_with-arrow` CSS class.\n\t\t *\n\t\t * @observable\n\t\t * @default true\n\t\t * @member {Boolean} #withArrow\n\t\t */",
"/**\n\t\t * An additional CSS class added to the {@link #element}.\n\t\t *\n\t\t * @observable\n\t\t * @member {String} #class\n\t\t */",
"/**\n\t\t * A callback that starts pinning the panel when {@link #isVisible} gets\n\t\t * `true`. Used by {@link #pin}.\n\t\t *\n\t\t * @private\n\t\t * @member {Function} #_pinWhenIsVisibleCallback\n\t\t */",
"/**\n\t\t * A collection of the child views that creates the balloon panel contents.\n\t\t *\n\t\t * @readonly\n\t\t * @member {module:ui/viewcollection~ViewCollection}\n\t\t */",
"/**\n\t * Shows the panel.\n\t *\n\t * See {@link #isVisible}.\n\t */",
"/**\n\t * Hides the panel.\n\t *\n\t * See {@link #isVisible}.\n\t */",
"/**\n\t * Attaches the panel to a specified {@link module:utils/dom/position~Options#target} with a\n\t * smart positioning heuristics that chooses from available positions to make sure the panel\n\t * is visible to the user i.e. within the limits of the viewport.\n\t *\n\t * This method accepts configuration {@link module:utils/dom/position~Options options}\n\t * to set the `target`, optional `limiter` and `positions` the balloon should choose from.\n\t *\n\t *\t\tconst panel = new BalloonPanelView( locale );\n\t *\t\tconst positions = BalloonPanelView.defaultPositions;\n\t *\n\t *\t\tpanel.render();\n\t *\n\t *\t\t// Attach the panel to an element with the \"target\" id DOM.\n\t *\t\tpanel.attachTo( {\n\t *\t\t\ttarget: document.querySelector( '#target' ),\n\t *\t\t\tpositions: [\n\t *\t\t\t\tpositions.northArrowSouth,\n\t *\t\t\t\tpositions.southArrowNorth\n\t *\t\t\t]\n\t *\t\t} );\n\t *\n\t * **Note**: Attaching the panel will also automatically {@link #show} it.\n\t *\n\t * **Note**: An attached panel will not follow its target when the window is scrolled or resized.\n\t * See the {@link #pin} method for a more permanent positioning strategy.\n\t *\n\t * @param {module:utils/dom/position~Options} options Positioning options compatible with\n\t * {@link module:utils/dom/position~getOptimalPosition}. Default `positions` array is\n\t * {@link module:ui/panel/balloon/balloonpanelview~BalloonPanelView.defaultPositions}.\n\t */",
"// Usually browsers make some problems with super accurate values like 104.345px",
"// so it is better to use int values.",
"/**\n\t * Works the same way as the {@link #attachTo} method except that the position of the panel is\n\t * continuously updated when:\n\t *\n\t * * any ancestor of the {@link module:utils/dom/position~Options#target}\n\t * or {@link module:utils/dom/position~Options#limiter} is scrolled,\n\t * * the browser window gets resized or scrolled.\n\t *\n\t * Thanks to that, the panel always sticks to the {@link module:utils/dom/position~Options#target}\n\t * and is immune to the changing environment.\n\t *\n\t *\t\tconst panel = new BalloonPanelView( locale );\n\t *\t\tconst positions = BalloonPanelView.defaultPositions;\n\t *\n\t *\t\tpanel.render();\n\t *\n\t *\t\t// Pin the panel to an element with the \"target\" id DOM.\n\t *\t\tpanel.pin( {\n\t *\t\t\ttarget: document.querySelector( '#target' ),\n\t *\t\t\tpositions: [\n\t *\t\t\t\tpositions.northArrowSouth,\n\t *\t\t\t\tpositions.southArrowNorth\n\t *\t\t\t]\n\t *\t\t} );\n\t *\n\t * To leave the pinned state, use the {@link #unpin} method.\n\t *\n\t * **Note**: Pinning the panel will also automatically {@link #show} it.\n\t *\n\t * @param {module:utils/dom/position~Options} options Positioning options compatible with\n\t * {@link module:utils/dom/position~getOptimalPosition}. Default `positions` array is\n\t * {@link module:ui/panel/balloon/balloonpanelview~BalloonPanelView.defaultPositions}.\n\t */",
"// Control the state of the listeners depending on whether the panel is visible",
"// or not.",
"// TODO: Use on() (https://github.com/ckeditor/ckeditor5-utils/issues/144).",
"/**\n\t * Stops pinning the panel, as set up by {@link #pin}.\n\t */",
"// Deactivate listeners attached by pin().",
"// Deactivate the panel pin() control logic.",
"// TODO: Use off() (https://github.com/ckeditor/ckeditor5-utils/issues/144).",
"/**\n\t * Starts managing the pinned state of the panel. See {@link #pin}.\n\t *\n\t * @private\n\t * @param {module:utils/dom/position~Options} options Positioning options compatible with\n\t * {@link module:utils/dom/position~getOptimalPosition}.\n\t */",
"// Then we need to listen on scroll event of eny element in the document.",
"// The position needs to be updated if the positioning target is within the scrolled element.",
"// The position needs to be updated if the positioning limiter is within the scrolled element.",
"// The positioning target and/or limiter can be a Rect, object etc..",
"// There's no way to optimize the listener then.",
"// We need to listen on window resize event and update position.",
"/**\n\t * Stops managing the pinned state of the panel. See {@link #pin}.\n\t *\n\t * @private\n\t */"
] |
[
{
"param": "View",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "View",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 18
| 2,441
| 398
|
5df042d492ff846df419c300f6f20d57d2cfe704
|
edfagan/ManuCostModel
|
src/ManuCostModel/CostModel.py
|
[
"BSD-3-Clause"
] |
Python
|
Equipment
|
Internal class for equipment cost centre related functions and variables.
Parameters
----------
activityLevels : list[str,str,...], default None
A list of the different activities the cost centres are associated with.
Options are customisable and can be found in the "activity" property
of the production methods database. Current options include: 'preform',
'cure', 'assembly', and 'finishing'
|
Internal class for equipment cost centre related functions and variables.
Parameters
activityLevels : list[str,str,...], default None
A list of the different activities the cost centres are associated with.
Options are customisable and can be found in the "activity" property
of the production methods database.
|
[
"Internal",
"class",
"for",
"equipment",
"cost",
"centre",
"related",
"functions",
"and",
"variables",
".",
"Parameters",
"activityLevels",
":",
"list",
"[",
"str",
"str",
"...",
"]",
"default",
"None",
"A",
"list",
"of",
"the",
"different",
"activities",
"the",
"cost",
"centres",
"are",
"associated",
"with",
".",
"Options",
"are",
"customisable",
"and",
"can",
"be",
"found",
"in",
"the",
"\"",
"activity",
"\"",
"property",
"of",
"the",
"production",
"methods",
"database",
"."
] |
class Equipment:
"""
Internal class for equipment cost centre related functions and variables.
Parameters
----------
activityLevels : list[str,str,...], default None
A list of the different activities the cost centres are associated with.
Options are customisable and can be found in the "activity" property
of the production methods database. Current options include: 'preform',
'cure', 'assembly', and 'finishing'
"""
def __init__(self, activityLevels):
# Make these into dictionaries to capture the values for each step
self.equipmentList = {}
self.equipmentCosts = {}
self.powerCosts = {}
self.activityCosts = {}
self.ActivityDict(activityLevels, self.equipmentList)
self.ActivityDict(activityLevels, self.activityCosts)
self.cost = 0.0
self.power = 0.0
def ActivityDict(self, activityLevels, equipDict):
"""
Parameters
----------
activityLevels : TYPE
DESCRIPTION.
equipDict : TYPE
DESCRIPTION.
Returns
-------
None.
"""
for act in activityLevels:
equipDict[act] = []
def LocateEquipment(self, productionSteps):
"""
A method to populate the dictionaries
Parameters
----------
productionSteps : TYPE
DESCRIPTION.
Returns
-------
None.
"""
try:
fullList = [val.capitalEquipment for val in iter(productionSteps)]
activityList = [val.activity for val in iter(productionSteps)]
for i, activity in enumerate(activityList):
if fullList[i][0] != 'N/A':
self.equipmentList[activity] += fullList[i]
for equip in fullList[i]:
if equip != 'N/A':
self.equipmentCosts[equip] = 0.0
self.powerCosts[equip] = 0.0
except:
pass
def TotalCost(self):
"""
Method for summing up the total costs
Returns
-------
None.
"""
self.cost = sum(self.equipmentCosts.values())
self.power = sum(self.powerCosts.values())
|
[
"class",
"Equipment",
":",
"def",
"__init__",
"(",
"self",
",",
"activityLevels",
")",
":",
"self",
".",
"equipmentList",
"=",
"{",
"}",
"self",
".",
"equipmentCosts",
"=",
"{",
"}",
"self",
".",
"powerCosts",
"=",
"{",
"}",
"self",
".",
"activityCosts",
"=",
"{",
"}",
"self",
".",
"ActivityDict",
"(",
"activityLevels",
",",
"self",
".",
"equipmentList",
")",
"self",
".",
"ActivityDict",
"(",
"activityLevels",
",",
"self",
".",
"activityCosts",
")",
"self",
".",
"cost",
"=",
"0.0",
"self",
".",
"power",
"=",
"0.0",
"def",
"ActivityDict",
"(",
"self",
",",
"activityLevels",
",",
"equipDict",
")",
":",
"\"\"\"\n \n\n Parameters\n ----------\n activityLevels : TYPE\n DESCRIPTION.\n equipDict : TYPE\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n \"\"\"",
"for",
"act",
"in",
"activityLevels",
":",
"equipDict",
"[",
"act",
"]",
"=",
"[",
"]",
"def",
"LocateEquipment",
"(",
"self",
",",
"productionSteps",
")",
":",
"\"\"\"\n A method to populate the dictionaries\n\n Parameters\n ----------\n productionSteps : TYPE\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n \"\"\"",
"try",
":",
"fullList",
"=",
"[",
"val",
".",
"capitalEquipment",
"for",
"val",
"in",
"iter",
"(",
"productionSteps",
")",
"]",
"activityList",
"=",
"[",
"val",
".",
"activity",
"for",
"val",
"in",
"iter",
"(",
"productionSteps",
")",
"]",
"for",
"i",
",",
"activity",
"in",
"enumerate",
"(",
"activityList",
")",
":",
"if",
"fullList",
"[",
"i",
"]",
"[",
"0",
"]",
"!=",
"'N/A'",
":",
"self",
".",
"equipmentList",
"[",
"activity",
"]",
"+=",
"fullList",
"[",
"i",
"]",
"for",
"equip",
"in",
"fullList",
"[",
"i",
"]",
":",
"if",
"equip",
"!=",
"'N/A'",
":",
"self",
".",
"equipmentCosts",
"[",
"equip",
"]",
"=",
"0.0",
"self",
".",
"powerCosts",
"[",
"equip",
"]",
"=",
"0.0",
"except",
":",
"pass",
"def",
"TotalCost",
"(",
"self",
")",
":",
"\"\"\"\n Method for summing up the total costs\n\n Returns\n -------\n None.\n\n \"\"\"",
"self",
".",
"cost",
"=",
"sum",
"(",
"self",
".",
"equipmentCosts",
".",
"values",
"(",
")",
")",
"self",
".",
"power",
"=",
"sum",
"(",
"self",
".",
"powerCosts",
".",
"values",
"(",
")",
")"
] |
Internal class for equipment cost centre related functions and variables.
|
[
"Internal",
"class",
"for",
"equipment",
"cost",
"centre",
"related",
"functions",
"and",
"variables",
"."
] |
[
"\"\"\"\n Internal class for equipment cost centre related functions and variables.\n \n Parameters\n ----------\n activityLevels : list[str,str,...], default None\n A list of the different activities the cost centres are associated with.\n Options are customisable and can be found in the \"activity\" property\n of the production methods database. Current options include: 'preform',\n 'cure', 'assembly', and 'finishing'\n \"\"\"",
"# Make these into dictionaries to capture the values for each step",
"\"\"\"\n \n\n Parameters\n ----------\n activityLevels : TYPE\n DESCRIPTION.\n equipDict : TYPE\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n \"\"\"",
"\"\"\"\n A method to populate the dictionaries\n\n Parameters\n ----------\n productionSteps : TYPE\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n \"\"\"",
"\"\"\"\n Method for summing up the total costs\n\n Returns\n -------\n None.\n\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 478
| 90
|
4282d83d9c786423af3e656ed42e13edfef87b4e
|
reitzig/texlogparser
|
lib/tex_log_parser/patterns/bad_hbox_warning.rb
|
[
"MIT"
] |
Ruby
|
BadHboxWarning
|
# Matches messages of this form:
#
# Overfull \hbox (68.36201pt too wide) in paragraph at lines 33--34
# []\OT1/cmr/m/n/10 Let's try to for-ce an over-full box: []
# []
#
# and
#
# Underfull \hbox (badness 10000) in paragraph at lines 35--36
#
# []
|
Matches messages of this form:
Overfull \hbox (68.36201pt too wide) in paragraph at lines 33--34
[]\OT1/cmr/m/n/10 Let's try to for-ce an over-full box: []
[]
and
Underfull \hbox (badness 10000) in paragraph at lines 35--36
|
[
"Matches",
"messages",
"of",
"this",
"form",
":",
"Overfull",
"\\",
"hbox",
"(",
"68",
".",
"36201pt",
"too",
"wide",
")",
"in",
"paragraph",
"at",
"lines",
"33",
"--",
"34",
"[]",
"\\",
"OT1",
"/",
"cmr",
"/",
"m",
"/",
"n",
"/",
"10",
"Let",
"'",
"s",
"try",
"to",
"for",
"-",
"ce",
"an",
"over",
"-",
"full",
"box",
":",
"[]",
"[]",
"and",
"Underfull",
"\\",
"hbox",
"(",
"badness",
"10000",
")",
"in",
"paragraph",
"at",
"lines",
"35",
"--",
"36"
] |
class BadHboxWarning
include LogParser::RegExpPattern
# Creates a new instance.
def initialize
super(/^(Over|Under)full \\hbox.*at line(?:s)? (\d+)(?:--(\d+))?/,
{ pattern: ->(_) { /^\s*(\[\])?\s*$/ }, until: :match, inclusive: false }
)
end
# (see LogParser::RegExpPattern#read)
def read(lines)
# @type [Message] msg
msg, consumed = super(lines)
from_line = @start_match[2].to_i
end_line = @start_match[3].nil? ? from_line : @start_match[3].to_i
msg.source_lines = { from: from_line, to: end_line }
msg.preformatted = true
msg.level = :warning
[msg, consumed]
end
end
|
[
"class",
"BadHboxWarning",
"include",
"LogParser",
"::",
"RegExpPattern",
"def",
"initialize",
"super",
"(",
"/",
"^(Over|Under)full ",
"\\\\",
"hbox.*at line(?:s)? (",
"\\d",
"+)(?:--(",
"\\d",
"+))?",
"/",
",",
"{",
"pattern",
":",
"->",
"(",
"_",
")",
"{",
"/",
"^",
"\\s",
"*(",
"\\[",
"\\]",
")?",
"\\s",
"*$",
"/",
"}",
",",
"until",
":",
":match",
",",
"inclusive",
":",
"false",
"}",
")",
"end",
"def",
"read",
"(",
"lines",
")",
"msg",
",",
"consumed",
"=",
"super",
"(",
"lines",
")",
"from_line",
"=",
"@start_match",
"[",
"2",
"]",
".",
"to_i",
"end_line",
"=",
"@start_match",
"[",
"3",
"]",
".",
"nil?",
"?",
"from_line",
":",
"@start_match",
"[",
"3",
"]",
".",
"to_i",
"msg",
".",
"source_lines",
"=",
"{",
"from",
":",
"from_line",
",",
"to",
":",
"end_line",
"}",
"msg",
".",
"preformatted",
"=",
"true",
"msg",
".",
"level",
"=",
":warning",
"[",
"msg",
",",
"consumed",
"]",
"end",
"end"
] |
Matches messages of this form:
Overfull \hbox (68.36201pt too wide) in paragraph at lines 33--34
[]\OT1/cmr/m/n/10 Let's try to for-ce an over-full box: []
[]
|
[
"Matches",
"messages",
"of",
"this",
"form",
":",
"Overfull",
"\\",
"hbox",
"(",
"68",
".",
"36201pt",
"too",
"wide",
")",
"in",
"paragraph",
"at",
"lines",
"33",
"--",
"34",
"[]",
"\\",
"OT1",
"/",
"cmr",
"/",
"m",
"/",
"n",
"/",
"10",
"Let",
"'",
"s",
"try",
"to",
"for",
"-",
"ce",
"an",
"over",
"-",
"full",
"box",
":",
"[]",
"[]"
] |
[
"# Creates a new instance.",
"# (see LogParser::RegExpPattern#read)",
"# @type [Message] msg"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 200
| 104
|
7f903f8858fccfae3fb4b5fa91b82af3e24f017d
|
koendeschacht/smile
|
nlp/src/main/java/smile/nlp/collocation/BigramCollocationFinder.java
|
[
"Apache-2.0"
] |
Java
|
BigramCollocationFinder
|
/**
* Tools to identify collocations (words that often appear consecutively) within
* corpora. They may also be used to find other associations between word
* occurrences.
* <p>
* Finding collocations requires first calculating the frequencies of words
* and their appearance in the context of other words. Often the collection
* of words will then requiring filtering to only retain useful content terms.
* Each n-gram of words may then be scored according to some association measure,
* in order to determine the relative likelihood of each n-gram being a
* collocation.
*
* @author Haifeng Li
*/
|
Tools to identify collocations (words that often appear consecutively) within
corpora. They may also be used to find other associations between word
occurrences.
Finding collocations requires first calculating the frequencies of words
and their appearance in the context of other words. Often the collection
of words will then requiring filtering to only retain useful content terms.
Each n-gram of words may then be scored according to some association measure,
in order to determine the relative likelihood of each n-gram being a
collocation.
@author Haifeng Li
|
[
"Tools",
"to",
"identify",
"collocations",
"(",
"words",
"that",
"often",
"appear",
"consecutively",
")",
"within",
"corpora",
".",
"They",
"may",
"also",
"be",
"used",
"to",
"find",
"other",
"associations",
"between",
"word",
"occurrences",
".",
"Finding",
"collocations",
"requires",
"first",
"calculating",
"the",
"frequencies",
"of",
"words",
"and",
"their",
"appearance",
"in",
"the",
"context",
"of",
"other",
"words",
".",
"Often",
"the",
"collection",
"of",
"words",
"will",
"then",
"requiring",
"filtering",
"to",
"only",
"retain",
"useful",
"content",
"terms",
".",
"Each",
"n",
"-",
"gram",
"of",
"words",
"may",
"then",
"be",
"scored",
"according",
"to",
"some",
"association",
"measure",
"in",
"order",
"to",
"determine",
"the",
"relative",
"likelihood",
"of",
"each",
"n",
"-",
"gram",
"being",
"a",
"collocation",
".",
"@author",
"Haifeng",
"Li"
] |
public class BigramCollocationFinder {
/**
* Chi-square distribution with 1 degree of freedom.
*/
private ChiSquareDistribution chisq = new ChiSquareDistribution(1);
/**
* The minimum frequency of collocation.
*/
private int minFreq;
/**
* Constructor.
* @param minFreq the minimum frequency of collocation.
*/
public BigramCollocationFinder(int minFreq) {
this.minFreq = minFreq;
}
/**
* Finds top k bigram collocations in the given corpus.
* @return the array of significant bigram collocations in descending order
* of likelihood ratio.
*/
public BigramCollocation[] find(Corpus corpus, int k) {
BigramCollocation[] bigrams = new BigramCollocation[k];
HeapSelect<BigramCollocation> heap = new HeapSelect<>(bigrams);
Iterator<Bigram> iterator = corpus.getBigrams();
while (iterator.hasNext()) {
Bigram bigram = iterator.next();
int c12 = corpus.getBigramFrequency(bigram);
if (c12 > minFreq) {
int c1 = corpus.getTermFrequency(bigram.w1);
int c2 = corpus.getTermFrequency(bigram.w2);
double score = likelihoodRatio(c1, c2, c12, corpus.size());
heap.add(new BigramCollocation(bigram.w1, bigram.w2, c12, -score));
}
}
heap.sort();
BigramCollocation[] collocations = new BigramCollocation[k];
for (int i = 0; i < k; i++) {
BigramCollocation bigram = bigrams[k-i-1];
collocations[i] = new BigramCollocation(bigram.w1(), bigram.w2(), bigram.frequency(), -bigram.score());
}
return collocations;
}
/**
* Finds bigram collocations in the given corpus whose p-value is less than
* the given threshold.
* @param p the p-value threshold
* @return the array of significant bigram collocations in descending order
* of likelihood ratio.
*/
public BigramCollocation[] find(Corpus corpus, double p) {
if (p <= 0.0 || p >= 1.0) {
throw new IllegalArgumentException("Invalid p = " + p);
}
double cutoff = chisq.quantile(p);
ArrayList<BigramCollocation> bigrams = new ArrayList<>();
Iterator<Bigram> iterator = corpus.getBigrams();
while (iterator.hasNext()) {
Bigram bigram = iterator.next();
int c12 = corpus.getBigramFrequency(bigram);
if (c12 > minFreq) {
int c1 = corpus.getTermFrequency(bigram.w1);
int c2 = corpus.getTermFrequency(bigram.w2);
double score = likelihoodRatio(c1, c2, c12, corpus.size());
if (score > cutoff) {
bigrams.add(new BigramCollocation(bigram.w1, bigram.w2, c12, score));
}
}
}
int n = bigrams.size();
BigramCollocation[] collocations = new BigramCollocation[n];
for (int i = 0; i < n; i++) {
collocations[i] = bigrams.get(i);
}
Arrays.sort(collocations);
// Reverse to descending order
for (int i = 0; i < n/2; i++) {
BigramCollocation b = collocations[i];
collocations[i] = collocations[n-i-1];
collocations[n-i-1] = b;
}
return collocations;
}
/**
* Returns the likelihood ratio test statistic -2 log λ
* @param c1 the number of occurrences of w1.
* @param c2 the number of occurrences of w2.
* @param c12 the number of occurrences of w1 w2.
* @param N the number of tokens in the corpus.
*/
private double likelihoodRatio(int c1, int c2, int c12, long N) {
double p = (double) c2 / N;
double p1 = (double) c12 / c1;
double p2 = (double) (c2 - c12) / (N - c1);
double logLambda = logL(c12, c1, p) + logL(c2-c12, N-c1, p) - logL(c12, c1, p1) - logL(c2-c12, N-c1, p2);
return -2 * logLambda;
}
/**
* Help function for calculating likelihood ratio statistic.
*/
private double logL(int k, long n, double x) {
if (x == 0.0) x = 0.01;
if (x == 1.0) x = 0.99;
return k * Math.log(x) + (n-k) * Math.log(1-x);
}
}
|
[
"public",
"class",
"BigramCollocationFinder",
"{",
"/**\n * Chi-square distribution with 1 degree of freedom.\n */",
"private",
"ChiSquareDistribution",
"chisq",
"=",
"new",
"ChiSquareDistribution",
"(",
"1",
")",
";",
"/**\n * The minimum frequency of collocation.\n */",
"private",
"int",
"minFreq",
";",
"/**\n * Constructor.\n * @param minFreq the minimum frequency of collocation.\n */",
"public",
"BigramCollocationFinder",
"(",
"int",
"minFreq",
")",
"{",
"this",
".",
"minFreq",
"=",
"minFreq",
";",
"}",
"/**\n * Finds top k bigram collocations in the given corpus.\n * @return the array of significant bigram collocations in descending order\n * of likelihood ratio.\n */",
"public",
"BigramCollocation",
"[",
"]",
"find",
"(",
"Corpus",
"corpus",
",",
"int",
"k",
")",
"{",
"BigramCollocation",
"[",
"]",
"bigrams",
"=",
"new",
"BigramCollocation",
"[",
"k",
"]",
";",
"HeapSelect",
"<",
"BigramCollocation",
">",
"heap",
"=",
"new",
"HeapSelect",
"<",
">",
"(",
"bigrams",
")",
";",
"Iterator",
"<",
"Bigram",
">",
"iterator",
"=",
"corpus",
".",
"getBigrams",
"(",
")",
";",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"Bigram",
"bigram",
"=",
"iterator",
".",
"next",
"(",
")",
";",
"int",
"c12",
"=",
"corpus",
".",
"getBigramFrequency",
"(",
"bigram",
")",
";",
"if",
"(",
"c12",
">",
"minFreq",
")",
"{",
"int",
"c1",
"=",
"corpus",
".",
"getTermFrequency",
"(",
"bigram",
".",
"w1",
")",
";",
"int",
"c2",
"=",
"corpus",
".",
"getTermFrequency",
"(",
"bigram",
".",
"w2",
")",
";",
"double",
"score",
"=",
"likelihoodRatio",
"(",
"c1",
",",
"c2",
",",
"c12",
",",
"corpus",
".",
"size",
"(",
")",
")",
";",
"heap",
".",
"add",
"(",
"new",
"BigramCollocation",
"(",
"bigram",
".",
"w1",
",",
"bigram",
".",
"w2",
",",
"c12",
",",
"-",
"score",
")",
")",
";",
"}",
"}",
"heap",
".",
"sort",
"(",
")",
";",
"BigramCollocation",
"[",
"]",
"collocations",
"=",
"new",
"BigramCollocation",
"[",
"k",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"k",
";",
"i",
"++",
")",
"{",
"BigramCollocation",
"bigram",
"=",
"bigrams",
"[",
"k",
"-",
"i",
"-",
"1",
"]",
";",
"collocations",
"[",
"i",
"]",
"=",
"new",
"BigramCollocation",
"(",
"bigram",
".",
"w1",
"(",
")",
",",
"bigram",
".",
"w2",
"(",
")",
",",
"bigram",
".",
"frequency",
"(",
")",
",",
"-",
"bigram",
".",
"score",
"(",
")",
")",
";",
"}",
"return",
"collocations",
";",
"}",
"/**\n * Finds bigram collocations in the given corpus whose p-value is less than\n * the given threshold.\n * @param p the p-value threshold\n * @return the array of significant bigram collocations in descending order\n * of likelihood ratio.\n */",
"public",
"BigramCollocation",
"[",
"]",
"find",
"(",
"Corpus",
"corpus",
",",
"double",
"p",
")",
"{",
"if",
"(",
"p",
"<=",
"0.0",
"||",
"p",
">=",
"1.0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Invalid p = ",
"\"",
"+",
"p",
")",
";",
"}",
"double",
"cutoff",
"=",
"chisq",
".",
"quantile",
"(",
"p",
")",
";",
"ArrayList",
"<",
"BigramCollocation",
">",
"bigrams",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"Iterator",
"<",
"Bigram",
">",
"iterator",
"=",
"corpus",
".",
"getBigrams",
"(",
")",
";",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"Bigram",
"bigram",
"=",
"iterator",
".",
"next",
"(",
")",
";",
"int",
"c12",
"=",
"corpus",
".",
"getBigramFrequency",
"(",
"bigram",
")",
";",
"if",
"(",
"c12",
">",
"minFreq",
")",
"{",
"int",
"c1",
"=",
"corpus",
".",
"getTermFrequency",
"(",
"bigram",
".",
"w1",
")",
";",
"int",
"c2",
"=",
"corpus",
".",
"getTermFrequency",
"(",
"bigram",
".",
"w2",
")",
";",
"double",
"score",
"=",
"likelihoodRatio",
"(",
"c1",
",",
"c2",
",",
"c12",
",",
"corpus",
".",
"size",
"(",
")",
")",
";",
"if",
"(",
"score",
">",
"cutoff",
")",
"{",
"bigrams",
".",
"add",
"(",
"new",
"BigramCollocation",
"(",
"bigram",
".",
"w1",
",",
"bigram",
".",
"w2",
",",
"c12",
",",
"score",
")",
")",
";",
"}",
"}",
"}",
"int",
"n",
"=",
"bigrams",
".",
"size",
"(",
")",
";",
"BigramCollocation",
"[",
"]",
"collocations",
"=",
"new",
"BigramCollocation",
"[",
"n",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"collocations",
"[",
"i",
"]",
"=",
"bigrams",
".",
"get",
"(",
"i",
")",
";",
"}",
"Arrays",
".",
"sort",
"(",
"collocations",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"n",
"/",
"2",
";",
"i",
"++",
")",
"{",
"BigramCollocation",
"b",
"=",
"collocations",
"[",
"i",
"]",
";",
"collocations",
"[",
"i",
"]",
"=",
"collocations",
"[",
"n",
"-",
"i",
"-",
"1",
"]",
";",
"collocations",
"[",
"n",
"-",
"i",
"-",
"1",
"]",
"=",
"b",
";",
"}",
"return",
"collocations",
";",
"}",
"/**\n * Returns the likelihood ratio test statistic -2 log λ\n * @param c1 the number of occurrences of w1.\n * @param c2 the number of occurrences of w2.\n * @param c12 the number of occurrences of w1 w2.\n * @param N the number of tokens in the corpus.\n */",
"private",
"double",
"likelihoodRatio",
"(",
"int",
"c1",
",",
"int",
"c2",
",",
"int",
"c12",
",",
"long",
"N",
")",
"{",
"double",
"p",
"=",
"(",
"double",
")",
"c2",
"/",
"N",
";",
"double",
"p1",
"=",
"(",
"double",
")",
"c12",
"/",
"c1",
";",
"double",
"p2",
"=",
"(",
"double",
")",
"(",
"c2",
"-",
"c12",
")",
"/",
"(",
"N",
"-",
"c1",
")",
";",
"double",
"logLambda",
"=",
"logL",
"(",
"c12",
",",
"c1",
",",
"p",
")",
"+",
"logL",
"(",
"c2",
"-",
"c12",
",",
"N",
"-",
"c1",
",",
"p",
")",
"-",
"logL",
"(",
"c12",
",",
"c1",
",",
"p1",
")",
"-",
"logL",
"(",
"c2",
"-",
"c12",
",",
"N",
"-",
"c1",
",",
"p2",
")",
";",
"return",
"-",
"2",
"*",
"logLambda",
";",
"}",
"/**\n * Help function for calculating likelihood ratio statistic.\n */",
"private",
"double",
"logL",
"(",
"int",
"k",
",",
"long",
"n",
",",
"double",
"x",
")",
"{",
"if",
"(",
"x",
"==",
"0.0",
")",
"x",
"=",
"0.01",
";",
"if",
"(",
"x",
"==",
"1.0",
")",
"x",
"=",
"0.99",
";",
"return",
"k",
"*",
"Math",
".",
"log",
"(",
"x",
")",
"+",
"(",
"n",
"-",
"k",
")",
"*",
"Math",
".",
"log",
"(",
"1",
"-",
"x",
")",
";",
"}",
"}"
] |
Tools to identify collocations (words that often appear consecutively) within
corpora.
|
[
"Tools",
"to",
"identify",
"collocations",
"(",
"words",
"that",
"often",
"appear",
"consecutively",
")",
"within",
"corpora",
"."
] |
[
"// Reverse to descending order"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 1,123
| 130
|
e50d7d787a4bdbf4d2ec93ed58392b23234ada14
|
nwops/autosign
|
lib/autosign/validator.rb
|
[
"Apache-2.0"
] |
Ruby
|
Validator
|
# Parent class for validation backends. Validators take the
# challenge_password and common name from a certificate signing request,
# and perform some action to determine whether the request is valid.
#
# Validators also get the raw X509 CSR in case the extracted information
# is insufficient for future, more powerful validators.
#
# All validators must inherit from this class, and must override several
# methods in order to function. At a minimum, the name and perform_validation
# methods must be implemented by child classes.
#
# @return [Autosign::Validator] instance of the Autosign::Validator class
|
Parent class for validation backends. Validators take the
challenge_password and common name from a certificate signing request,
and perform some action to determine whether the request is valid.
Validators also get the raw X509 CSR in case the extracted information
is insufficient for future, more powerful validators.
All validators must inherit from this class, and must override several
methods in order to function. At a minimum, the name and perform_validation
methods must be implemented by child classes.
|
[
"Parent",
"class",
"for",
"validation",
"backends",
".",
"Validators",
"take",
"the",
"challenge_password",
"and",
"common",
"name",
"from",
"a",
"certificate",
"signing",
"request",
"and",
"perform",
"some",
"action",
"to",
"determine",
"whether",
"the",
"request",
"is",
"valid",
".",
"Validators",
"also",
"get",
"the",
"raw",
"X509",
"CSR",
"in",
"case",
"the",
"extracted",
"information",
"is",
"insufficient",
"for",
"future",
"more",
"powerful",
"validators",
".",
"All",
"validators",
"must",
"inherit",
"from",
"this",
"class",
"and",
"must",
"override",
"several",
"methods",
"in",
"order",
"to",
"function",
".",
"At",
"a",
"minimum",
"the",
"name",
"and",
"perform_validation",
"methods",
"must",
"be",
"implemented",
"by",
"child",
"classes",
"."
] |
class Validator
def initialize()
start_logging()
settings() # just run to validate settings
setup()
# call name to ensure that the class fails immediately if child classes
# do not implement it.
name()
end
# Name of the validator. This must be implemented by validators which
# inherit from the Autosign::Validator class. The name is used to identify
# the validator in friendly messages and to determine which configuration
# file section settings will be loaded from.
#
# @example set the name of a child class validator to "example"
# module Autosign
# module Validators
# class Example < Autosign::Validator
# def name
# "example"
# end
# end
# end
# end
# @return [String] name of the validator. Do not use special characters.
def name
# override this after inheriting
# should return a string with no spaces
# this is the name used to reference the validator in config files
raise NotImplementedError
end
# define how a validator actually validates the request.
# This must be implemented by validators which inherit from the
# Autosign::Validator class.
#
# @param challenge_password [String] the challenge_password OID from the certificate signing request. The challenge_password field is the same setting as the "challengePassword" field in a `csr_attributes.yaml` file when the CSR is generated. In a request using a JSON web token, this would be the serialized token.
# @param certname [String] the common name being requested in the certificate signing request. Treat the certname as untrusted. This is user-submitted data that you must validate.
# @param raw_csr [String] the encoded X509 certificate signing request, as received by the autosign policy executable. This is provided as an optional extension point, but your validator may not need to use it.
# @return [True, False] return true if the certificate should be signed, and false if you cannot validate the request successfully.
def perform_validation(challenge_password, certname, raw_csr)
# override this after inheriting
# should return true to indicate success validating
# or false to indicate that the validator was unable to validate
raise NotImplementedError
end
# wrapper method that wraps input validation and logging around the perform_validation method.
# Do not override or use this class in child classes. This is the class that gets called
# on validator objects.
def validate(challenge_password, certname, raw_csr)
@log.debug "running validate"
fail unless challenge_password.is_a?(String)
fail unless certname.is_a?(String)
case perform_validation(challenge_password, certname, raw_csr)
when true
@log.debug "validated successfully"
@log.info "Validated '#{certname}' using '#{name}' validator"
return true
when false
@log.debug "validation failed"
@log.debug "Unable to validate '#{certname}' using '#{name}' validator"
return false
else
@log.error "perform_validation returned a non-boolean result"
raise "perform_validation returned a non-boolean result"
end
end
# Class method to attempt validation of a request against all validators which inherit from this class.
# The request is considered to be validated if any one validator succeeds.
# @param challenge_password [String] the challenge_password OID from the certificate signing request
# @param certname [String] the common name being requested in the certificate signing request
# @param raw_csr [String] the encoded X509 certificate signing request, as received by the autosign policy executable
# @return [True, False] return true if the certificate should be signed, and false if it cannot be validated
def self.any_validator(challenge_password, certname, raw_csr)
@log = Logging.logger[self.class]
# iterate over all known validators and attempt to validate using them
results_by_validator = {}
results = self.descendants.map {|c|
validator = c.new()
@log.debug "attempting to validate using #{validator.name}"
result = validator.validate(challenge_password, certname, raw_csr)
results_by_validator[validator.name] = result
@log.debug "result: #{result.to_s}"
result
}
@log.debug "validator results: " + results.to_s
@log.info "results by validator: " + results_by_validator.to_s
success = results.any?{|result| result == true}
if success
@log.info "successfully validated using one or more validators"
return true
else
@log.info "unable to validate using any validator"
return false
end
end
private
# this is automatically called when the class is initialized; do not
# override it in child classes.
def start_logging
@log = Logging.logger[self.class]
@log.debug "starting autosign validator: " + self.name.to_s
end
# (optionally) override this method in validator child classes to perform any additional
# setup during class initialization prior to beginning validation.
# If you need to create a database connection, this would be a good place to do it.
# @return [True, False] return true if setup succeeded, or false if setup failed and the validation should not continue
def setup
true
end
# Find other classes that inherit from this class.
# Used to discover autosign validators. There is probably no reason to use
# this directly.
# @return [Array] of classes inheriting from Autosign::Validator
def self.descendants
ObjectSpace.each_object(Class).select { |klass| klass < self }
end
# provide a merged settings hash of default settings for a validator,
# config file settings for the validator, and override settings defined in
# the validator.
#
# Do not override this in child classes. If you need to set
# custom config settings, override the get_override_settings method.
# The section of the config file this reads from is the same as the name
# method returns.
#
# @return [Hash] of config settings
def settings
@log.debug "merging settings"
setting_sources = [get_override_settings, load_config, default_settings]
merged_settings = setting_sources.inject({}) { |merged, hash| merged.deep_merge(hash) }
@log.debug "using merged settings: " + merged_settings.to_s
@log.debug "validating merged settings"
if validate_settings(merged_settings)
@log.debug "successfully validated merged settings"
return merged_settings
else
@log.warn "validation of merged settings failed"
@log.warn "unable to validate settings in #{self.name} validator"
raise "settings validation error"
end
end
# (optionally) override this from a child class to set config defaults.
# These will be overridden by config file settings.
#
# Override this when inheriting if you need to set config defaults.
# For example, if you want to pull settings from zookeeper, this would
# be a good place to do that.
#
# @return [Hash] of config settings
def default_settings
{}
end
# (optionally) override this to perform validation checks on the merged
# config hash of default settings, config file settings, and override
# settings.
# @return [True, False]
def validate_settings(settings)
settings.is_a?(Hash)
end
# load any required configuration from the config file.
# Do not override this in child classes.
# @return [Hash] configuration settings from the validator's section of the config file
def load_config
@log.debug "loading validator-specific configuration"
config = Autosign::Config.new
if config.settings.to_hash[self.name].nil?
@log.warn "Unable to load validator-specific configuration"
@log.warn "Cannot load configuration section named '#{self.name}'"
return {}
else
@log.debug "Set validator-specific settings from config file: " + config.settings.to_hash[self.name].to_s
return config.settings.to_hash[self.name]
end
end
# (optionally) override this from child classes to get custom configuration
# from a validator.
#
# This is how you override defaults and config file settings.
# @return [Hash] configuration settings
def get_override_settings
{}
end
end
|
[
"class",
"Validator",
"def",
"initialize",
"(",
")",
"start_logging",
"(",
")",
"settings",
"(",
")",
"setup",
"(",
")",
"name",
"(",
")",
"end",
"def",
"name",
"raise",
"NotImplementedError",
"end",
"def",
"perform_validation",
"(",
"challenge_password",
",",
"certname",
",",
"raw_csr",
")",
"raise",
"NotImplementedError",
"end",
"def",
"validate",
"(",
"challenge_password",
",",
"certname",
",",
"raw_csr",
")",
"@log",
".",
"debug",
"\"running validate\"",
"fail",
"unless",
"challenge_password",
".",
"is_a?",
"(",
"String",
")",
"fail",
"unless",
"certname",
".",
"is_a?",
"(",
"String",
")",
"case",
"perform_validation",
"(",
"challenge_password",
",",
"certname",
",",
"raw_csr",
")",
"when",
"true",
"@log",
".",
"debug",
"\"validated successfully\"",
"@log",
".",
"info",
"\"Validated '#{certname}' using '#{name}' validator\"",
"return",
"true",
"when",
"false",
"@log",
".",
"debug",
"\"validation failed\"",
"@log",
".",
"debug",
"\"Unable to validate '#{certname}' using '#{name}' validator\"",
"return",
"false",
"else",
"@log",
".",
"error",
"\"perform_validation returned a non-boolean result\"",
"raise",
"\"perform_validation returned a non-boolean result\"",
"end",
"end",
"def",
"self",
".",
"any_validator",
"(",
"challenge_password",
",",
"certname",
",",
"raw_csr",
")",
"@log",
"=",
"Logging",
".",
"logger",
"[",
"self",
".",
"class",
"]",
"results_by_validator",
"=",
"{",
"}",
"results",
"=",
"self",
".",
"descendants",
".",
"map",
"{",
"|",
"c",
"|",
"validator",
"=",
"c",
".",
"new",
"(",
")",
"@log",
".",
"debug",
"\"attempting to validate using #{validator.name}\"",
"result",
"=",
"validator",
".",
"validate",
"(",
"challenge_password",
",",
"certname",
",",
"raw_csr",
")",
"results_by_validator",
"[",
"validator",
".",
"name",
"]",
"=",
"result",
"@log",
".",
"debug",
"\"result: #{result.to_s}\"",
"result",
"}",
"@log",
".",
"debug",
"\"validator results: \"",
"+",
"results",
".",
"to_s",
"@log",
".",
"info",
"\"results by validator: \"",
"+",
"results_by_validator",
".",
"to_s",
"success",
"=",
"results",
".",
"any?",
"{",
"|",
"result",
"|",
"result",
"==",
"true",
"}",
"if",
"success",
"@log",
".",
"info",
"\"successfully validated using one or more validators\"",
"return",
"true",
"else",
"@log",
".",
"info",
"\"unable to validate using any validator\"",
"return",
"false",
"end",
"end",
"private",
"def",
"start_logging",
"@log",
"=",
"Logging",
".",
"logger",
"[",
"self",
".",
"class",
"]",
"@log",
".",
"debug",
"\"starting autosign validator: \"",
"+",
"self",
".",
"name",
".",
"to_s",
"end",
"def",
"setup",
"true",
"end",
"def",
"self",
".",
"descendants",
"ObjectSpace",
".",
"each_object",
"(",
"Class",
")",
".",
"select",
"{",
"|",
"klass",
"|",
"klass",
"<",
"self",
"}",
"end",
"def",
"settings",
"@log",
".",
"debug",
"\"merging settings\"",
"setting_sources",
"=",
"[",
"get_override_settings",
",",
"load_config",
",",
"default_settings",
"]",
"merged_settings",
"=",
"setting_sources",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"merged",
",",
"hash",
"|",
"merged",
".",
"deep_merge",
"(",
"hash",
")",
"}",
"@log",
".",
"debug",
"\"using merged settings: \"",
"+",
"merged_settings",
".",
"to_s",
"@log",
".",
"debug",
"\"validating merged settings\"",
"if",
"validate_settings",
"(",
"merged_settings",
")",
"@log",
".",
"debug",
"\"successfully validated merged settings\"",
"return",
"merged_settings",
"else",
"@log",
".",
"warn",
"\"validation of merged settings failed\"",
"@log",
".",
"warn",
"\"unable to validate settings in #{self.name} validator\"",
"raise",
"\"settings validation error\"",
"end",
"end",
"def",
"default_settings",
"{",
"}",
"end",
"def",
"validate_settings",
"(",
"settings",
")",
"settings",
".",
"is_a?",
"(",
"Hash",
")",
"end",
"def",
"load_config",
"@log",
".",
"debug",
"\"loading validator-specific configuration\"",
"config",
"=",
"Autosign",
"::",
"Config",
".",
"new",
"if",
"config",
".",
"settings",
".",
"to_hash",
"[",
"self",
".",
"name",
"]",
".",
"nil?",
"@log",
".",
"warn",
"\"Unable to load validator-specific configuration\"",
"@log",
".",
"warn",
"\"Cannot load configuration section named '#{self.name}'\"",
"return",
"{",
"}",
"else",
"@log",
".",
"debug",
"\"Set validator-specific settings from config file: \"",
"+",
"config",
".",
"settings",
".",
"to_hash",
"[",
"self",
".",
"name",
"]",
".",
"to_s",
"return",
"config",
".",
"settings",
".",
"to_hash",
"[",
"self",
".",
"name",
"]",
"end",
"end",
"def",
"get_override_settings",
"{",
"}",
"end",
"end"
] |
Parent class for validation backends.
|
[
"Parent",
"class",
"for",
"validation",
"backends",
"."
] |
[
"# just run to validate settings",
"# call name to ensure that the class fails immediately if child classes",
"# do not implement it.",
"# Name of the validator. This must be implemented by validators which",
"# inherit from the Autosign::Validator class. The name is used to identify",
"# the validator in friendly messages and to determine which configuration",
"# file section settings will be loaded from.",
"#",
"# @example set the name of a child class validator to \"example\"",
"# module Autosign",
"# module Validators",
"# class Example < Autosign::Validator",
"# def name",
"# \"example\"",
"# end",
"# end",
"# end",
"# end",
"# @return [String] name of the validator. Do not use special characters.",
"# override this after inheriting",
"# should return a string with no spaces",
"# this is the name used to reference the validator in config files",
"# define how a validator actually validates the request.",
"# This must be implemented by validators which inherit from the",
"# Autosign::Validator class.",
"#",
"# @param challenge_password [String] the challenge_password OID from the certificate signing request. The challenge_password field is the same setting as the \"challengePassword\" field in a `csr_attributes.yaml` file when the CSR is generated. In a request using a JSON web token, this would be the serialized token.",
"# @param certname [String] the common name being requested in the certificate signing request. Treat the certname as untrusted. This is user-submitted data that you must validate.",
"# @param raw_csr [String] the encoded X509 certificate signing request, as received by the autosign policy executable. This is provided as an optional extension point, but your validator may not need to use it.",
"# @return [True, False] return true if the certificate should be signed, and false if you cannot validate the request successfully.",
"# override this after inheriting",
"# should return true to indicate success validating",
"# or false to indicate that the validator was unable to validate",
"# wrapper method that wraps input validation and logging around the perform_validation method.",
"# Do not override or use this class in child classes. This is the class that gets called",
"# on validator objects.",
"# Class method to attempt validation of a request against all validators which inherit from this class.",
"# The request is considered to be validated if any one validator succeeds.",
"# @param challenge_password [String] the challenge_password OID from the certificate signing request",
"# @param certname [String] the common name being requested in the certificate signing request",
"# @param raw_csr [String] the encoded X509 certificate signing request, as received by the autosign policy executable",
"# @return [True, False] return true if the certificate should be signed, and false if it cannot be validated",
"# iterate over all known validators and attempt to validate using them",
"# this is automatically called when the class is initialized; do not",
"# override it in child classes.",
"# (optionally) override this method in validator child classes to perform any additional",
"# setup during class initialization prior to beginning validation.",
"# If you need to create a database connection, this would be a good place to do it.",
"# @return [True, False] return true if setup succeeded, or false if setup failed and the validation should not continue",
"# Find other classes that inherit from this class.",
"# Used to discover autosign validators. There is probably no reason to use",
"# this directly.",
"# @return [Array] of classes inheriting from Autosign::Validator",
"# provide a merged settings hash of default settings for a validator,",
"# config file settings for the validator, and override settings defined in",
"# the validator.",
"#",
"# Do not override this in child classes. If you need to set",
"# custom config settings, override the get_override_settings method.",
"# The section of the config file this reads from is the same as the name",
"# method returns.",
"#",
"# @return [Hash] of config settings",
"# (optionally) override this from a child class to set config defaults.",
"# These will be overridden by config file settings.",
"#",
"# Override this when inheriting if you need to set config defaults.",
"# For example, if you want to pull settings from zookeeper, this would",
"# be a good place to do that.",
"#",
"# @return [Hash] of config settings",
"# (optionally) override this to perform validation checks on the merged",
"# config hash of default settings, config file settings, and override",
"# settings.",
"# @return [True, False]",
"# load any required configuration from the config file.",
"# Do not override this in child classes.",
"# @return [Hash] configuration settings from the validator's section of the config file",
"# (optionally) override this from child classes to get custom configuration",
"# from a validator.",
"#",
"# This is how you override defaults and config file settings.",
"# @return [Hash] configuration settings"
] |
[] |
{
"returns": [
{
"docstring": "instance of the Autosign::Validator class",
"docstring_tokens": [
"instance",
"of",
"the",
"Autosign",
"::",
"Validator",
"class"
],
"type": "Autosign::Validator"
}
],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 1,879
| 125
|
68747ac5c81cf052ba3695f9674a6543f9755145
|
sciage/Apponrent
|
lib/src/main/java/com/example/android/architecture/blueprints/todoapp/addedittask/AddEditTaskViewModel.java
|
[
"MIT"
] |
Java
|
AddEditTaskViewModel
|
/**
* ViewModel for the Add/Edit screen.
* <p>
* This ViewModel only exposes {@link ObservableField}s, so it doesn't need to extend
* {@link androidx.databinding.BaseObservable} and updates are notified automatically. See
* {@link com.example.android.architecture.blueprints.todoapp.statistics.StatisticsViewModel} for
* how to deal with more complex scenarios.
*/
|
ViewModel for the Add/Edit screen.
This ViewModel only exposes ObservableFields, so it doesn't need to extend
androidx.databinding.BaseObservable and updates are notified automatically. See
com.example.android.architecture.blueprints.todoapp.statistics.StatisticsViewModel for
how to deal with more complex scenarios.
|
[
"ViewModel",
"for",
"the",
"Add",
"/",
"Edit",
"screen",
".",
"This",
"ViewModel",
"only",
"exposes",
"ObservableFields",
"so",
"it",
"doesn",
"'",
"t",
"need",
"to",
"extend",
"androidx",
".",
"databinding",
".",
"BaseObservable",
"and",
"updates",
"are",
"notified",
"automatically",
".",
"See",
"com",
".",
"example",
".",
"android",
".",
"architecture",
".",
"blueprints",
".",
"todoapp",
".",
"statistics",
".",
"StatisticsViewModel",
"for",
"how",
"to",
"deal",
"with",
"more",
"complex",
"scenarios",
"."
] |
public class AddEditTaskViewModel extends ViewModel implements TasksDataSource.GetTaskCallback {
// Two-way databinding, exposing MutableLiveData
public final MutableLiveData<String> title = new MutableLiveData<>();
// Two-way databinding, exposing MutableLiveData
public final MutableLiveData<String> description = new MutableLiveData<>();
private final MutableLiveData<Boolean> dataLoading = new MutableLiveData<>();
private final MutableLiveData<Event<Integer>> mSnackbarText = new MutableLiveData<>();
private final MutableLiveData<Event<Object>> mTaskUpdated = new MutableLiveData<>();
private final TasksRepository mTasksRepository;
@Nullable
private String mTaskId;
private boolean mIsNewTask;
private boolean mIsDataLoaded = false;
private boolean mTaskCompleted = false;
public AddEditTaskViewModel(TasksRepository tasksRepository) {
mTasksRepository = tasksRepository;
}
public void start(String taskId) {
if (dataLoading.getValue() != null && dataLoading.getValue()) {
// Already loading, ignore.
return;
}
mTaskId = taskId;
if (taskId == null) {
// No need to populate, it's a new task
mIsNewTask = true;
return;
}
if (mIsDataLoaded) {
// No need to populate, already have data.
return;
}
mIsNewTask = false;
dataLoading.setValue(true);
mTasksRepository.getTask(taskId, this);
}
@Override
public void onTaskLoaded(Task task) {
title.setValue(task.getTitle());
description.setValue(task.getDescription());
mTaskCompleted = task.isCompleted();
dataLoading.setValue(false);
mIsDataLoaded = true;
}
@Override
public void onDataNotAvailable() {
dataLoading.setValue(false);
}
// Called when clicking on fab.
void saveTask() {
Task task = new Task(title.getValue(), description.getValue());
if (task.isEmpty()) {
mSnackbarText.setValue(new Event<>(R.string.empty_task_message));
return;
}
if (isNewTask() || mTaskId == null) {
createTask(task);
} else {
task = new Task(title.getValue(), description.getValue(), mTaskId, mTaskCompleted);
updateTask(task);
}
}
public LiveData<Event<Integer>> getSnackbarMessage() {
return mSnackbarText;
}
public LiveData<Event<Object>> getTaskUpdatedEvent() {
return mTaskUpdated;
}
public LiveData<Boolean> getDataLoading() {
return dataLoading;
}
private boolean isNewTask() {
return mIsNewTask;
}
private void createTask(Task newTask) {
mTasksRepository.saveTask(newTask);
mTaskUpdated.setValue(new Event<>(new Object()));
}
private void updateTask(Task task) {
if (isNewTask()) {
throw new RuntimeException("updateTask() was called but task is new.");
}
mTasksRepository.saveTask(task);
mTaskUpdated.setValue(new Event<>(new Object()));
}
}
|
[
"public",
"class",
"AddEditTaskViewModel",
"extends",
"ViewModel",
"implements",
"TasksDataSource",
".",
"GetTaskCallback",
"{",
"public",
"final",
"MutableLiveData",
"<",
"String",
">",
"title",
"=",
"new",
"MutableLiveData",
"<",
">",
"(",
")",
";",
"public",
"final",
"MutableLiveData",
"<",
"String",
">",
"description",
"=",
"new",
"MutableLiveData",
"<",
">",
"(",
")",
";",
"private",
"final",
"MutableLiveData",
"<",
"Boolean",
">",
"dataLoading",
"=",
"new",
"MutableLiveData",
"<",
">",
"(",
")",
";",
"private",
"final",
"MutableLiveData",
"<",
"Event",
"<",
"Integer",
">",
">",
"mSnackbarText",
"=",
"new",
"MutableLiveData",
"<",
">",
"(",
")",
";",
"private",
"final",
"MutableLiveData",
"<",
"Event",
"<",
"Object",
">",
">",
"mTaskUpdated",
"=",
"new",
"MutableLiveData",
"<",
">",
"(",
")",
";",
"private",
"final",
"TasksRepository",
"mTasksRepository",
";",
"@",
"Nullable",
"private",
"String",
"mTaskId",
";",
"private",
"boolean",
"mIsNewTask",
";",
"private",
"boolean",
"mIsDataLoaded",
"=",
"false",
";",
"private",
"boolean",
"mTaskCompleted",
"=",
"false",
";",
"public",
"AddEditTaskViewModel",
"(",
"TasksRepository",
"tasksRepository",
")",
"{",
"mTasksRepository",
"=",
"tasksRepository",
";",
"}",
"public",
"void",
"start",
"(",
"String",
"taskId",
")",
"{",
"if",
"(",
"dataLoading",
".",
"getValue",
"(",
")",
"!=",
"null",
"&&",
"dataLoading",
".",
"getValue",
"(",
")",
")",
"{",
"return",
";",
"}",
"mTaskId",
"=",
"taskId",
";",
"if",
"(",
"taskId",
"==",
"null",
")",
"{",
"mIsNewTask",
"=",
"true",
";",
"return",
";",
"}",
"if",
"(",
"mIsDataLoaded",
")",
"{",
"return",
";",
"}",
"mIsNewTask",
"=",
"false",
";",
"dataLoading",
".",
"setValue",
"(",
"true",
")",
";",
"mTasksRepository",
".",
"getTask",
"(",
"taskId",
",",
"this",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onTaskLoaded",
"(",
"Task",
"task",
")",
"{",
"title",
".",
"setValue",
"(",
"task",
".",
"getTitle",
"(",
")",
")",
";",
"description",
".",
"setValue",
"(",
"task",
".",
"getDescription",
"(",
")",
")",
";",
"mTaskCompleted",
"=",
"task",
".",
"isCompleted",
"(",
")",
";",
"dataLoading",
".",
"setValue",
"(",
"false",
")",
";",
"mIsDataLoaded",
"=",
"true",
";",
"}",
"@",
"Override",
"public",
"void",
"onDataNotAvailable",
"(",
")",
"{",
"dataLoading",
".",
"setValue",
"(",
"false",
")",
";",
"}",
"void",
"saveTask",
"(",
")",
"{",
"Task",
"task",
"=",
"new",
"Task",
"(",
"title",
".",
"getValue",
"(",
")",
",",
"description",
".",
"getValue",
"(",
")",
")",
";",
"if",
"(",
"task",
".",
"isEmpty",
"(",
")",
")",
"{",
"mSnackbarText",
".",
"setValue",
"(",
"new",
"Event",
"<",
">",
"(",
"R",
".",
"string",
".",
"empty_task_message",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"isNewTask",
"(",
")",
"||",
"mTaskId",
"==",
"null",
")",
"{",
"createTask",
"(",
"task",
")",
";",
"}",
"else",
"{",
"task",
"=",
"new",
"Task",
"(",
"title",
".",
"getValue",
"(",
")",
",",
"description",
".",
"getValue",
"(",
")",
",",
"mTaskId",
",",
"mTaskCompleted",
")",
";",
"updateTask",
"(",
"task",
")",
";",
"}",
"}",
"public",
"LiveData",
"<",
"Event",
"<",
"Integer",
">",
">",
"getSnackbarMessage",
"(",
")",
"{",
"return",
"mSnackbarText",
";",
"}",
"public",
"LiveData",
"<",
"Event",
"<",
"Object",
">",
">",
"getTaskUpdatedEvent",
"(",
")",
"{",
"return",
"mTaskUpdated",
";",
"}",
"public",
"LiveData",
"<",
"Boolean",
">",
"getDataLoading",
"(",
")",
"{",
"return",
"dataLoading",
";",
"}",
"private",
"boolean",
"isNewTask",
"(",
")",
"{",
"return",
"mIsNewTask",
";",
"}",
"private",
"void",
"createTask",
"(",
"Task",
"newTask",
")",
"{",
"mTasksRepository",
".",
"saveTask",
"(",
"newTask",
")",
";",
"mTaskUpdated",
".",
"setValue",
"(",
"new",
"Event",
"<",
">",
"(",
"new",
"Object",
"(",
")",
")",
")",
";",
"}",
"private",
"void",
"updateTask",
"(",
"Task",
"task",
")",
"{",
"if",
"(",
"isNewTask",
"(",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"updateTask() was called but task is new.",
"\"",
")",
";",
"}",
"mTasksRepository",
".",
"saveTask",
"(",
"task",
")",
";",
"mTaskUpdated",
".",
"setValue",
"(",
"new",
"Event",
"<",
">",
"(",
"new",
"Object",
"(",
")",
")",
")",
";",
"}",
"}"
] |
ViewModel for the Add/Edit screen.
|
[
"ViewModel",
"for",
"the",
"Add",
"/",
"Edit",
"screen",
"."
] |
[
"// Two-way databinding, exposing MutableLiveData",
"// Two-way databinding, exposing MutableLiveData",
"// Already loading, ignore.",
"// No need to populate, it's a new task",
"// No need to populate, already have data.",
"// Called when clicking on fab."
] |
[
{
"param": "ViewModel",
"type": null
},
{
"param": "TasksDataSource.GetTaskCallback",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ViewModel",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "TasksDataSource.GetTaskCallback",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 627
| 77
|
1b2a8e5f895bf4f7ed344fa5ea692b2d815ae8ab
|
riddopic/garcun
|
lib/garcon/chef/resource/blender.rb
|
[
"Apache-2.0"
] |
Ruby
|
Blender
|
# Combine a resource and provider class for quick and easy oven baked
# goodness. Never has cooking been this fun since the invention of the
# grocery store!
#
# @example
# class Chef::Resource::HouseKeeping < Chef::Resource
# include Garcon(blender: true)
#
# attribute :path,
# kind_of: String,
# name_attribute: true
# attribute :message,
# kind_of: String,
# default: 'Clean the kitchen'
#
# action :run do
# file new_resource.path do
# content new_resource.message
# end
# end
# end
#
|
Combine a resource and provider class for quick and easy oven baked
goodness. Never has cooking been this fun since the invention of the
grocery store!
|
[
"Combine",
"a",
"resource",
"and",
"provider",
"class",
"for",
"quick",
"and",
"easy",
"oven",
"baked",
"goodness",
".",
"Never",
"has",
"cooking",
"been",
"this",
"fun",
"since",
"the",
"invention",
"of",
"the",
"grocery",
"store!"
] |
module Blender
# Coerce is_a? so that the DSL will consider this a Provider for the
# purposes of attaching enclosing_provider.
#
# @param klass [Class]
#
# @return [Boolean]
#
# @api private
def is_a?(klass)
klass == Chef::Provider ? true : super
end
# Coerce provider_for_action so that the resource is also the provider.
#
# @param action [Symbol]
#
# @return [Chef::Provider]
#
# @api private
def provider_for_action(action)
provider(self.class.blender_provider_class) unless provider
super
end
module ClassMethods
# Define a provider action. The block should contain the usual provider
# code.
#
# @param name [Symbol]
# Name of the action.
#
# @param block [Proc]
# Action implementation.
#
def action(name, &block)
blender_actions[name.to_sym] = block
actions(name.to_sym) if respond_to?(:actions)
end
# Storage accessor for blended action blocks. Maps action name to proc.
#
# @return [Hash<Symbol, Proc>]
#
# @api private
def blender_actions
(@blender_actions ||= {})
end
# Create a provider class for the blender actions in this resource.
# Inherits from the blender provider class of the resource's
# superclass if present.
#
# @return [Class]
#
# @api private
def blender_provider_class
@blender_provider_class ||= begin
provider_superclass = begin
self.superclass.blender_provider_class
rescue NoMethodError
Chef::Provider
end
actions = blender_actions
class_name = self.name
Class.new(provider_superclass) do
include Garcon
define_singleton_method(:name) { class_name + ' (blender)' }
actions.each do |action, block|
define_method(:"action_#{action}", &block)
end
end
end
end
# Hook called when module is included, extends a descendant with class
# and instance methods.
#
# @param [Module] descendant
# The module or class including Garcon::Resource::Blender
#
# @return [self]
#
# @api private
def included(descendant)
super
descendant.extend ClassMethods
end
end
extend ClassMethods
end
|
[
"module",
"Blender",
"def",
"is_a?",
"(",
"klass",
")",
"klass",
"==",
"Chef",
"::",
"Provider",
"?",
"true",
":",
"super",
"end",
"def",
"provider_for_action",
"(",
"action",
")",
"provider",
"(",
"self",
".",
"class",
".",
"blender_provider_class",
")",
"unless",
"provider",
"super",
"end",
"module",
"ClassMethods",
"def",
"action",
"(",
"name",
",",
"&",
"block",
")",
"blender_actions",
"[",
"name",
".",
"to_sym",
"]",
"=",
"block",
"actions",
"(",
"name",
".",
"to_sym",
")",
"if",
"respond_to?",
"(",
":actions",
")",
"end",
"def",
"blender_actions",
"(",
"@blender_actions",
"||=",
"{",
"}",
")",
"end",
"def",
"blender_provider_class",
"@blender_provider_class",
"||=",
"begin",
"provider_superclass",
"=",
"begin",
"self",
".",
"superclass",
".",
"blender_provider_class",
"rescue",
"NoMethodError",
"Chef",
"::",
"Provider",
"end",
"actions",
"=",
"blender_actions",
"class_name",
"=",
"self",
".",
"name",
"Class",
".",
"new",
"(",
"provider_superclass",
")",
"do",
"include",
"Garcon",
"define_singleton_method",
"(",
":name",
")",
"{",
"class_name",
"+",
"' (blender)'",
"}",
"actions",
".",
"each",
"do",
"|",
"action",
",",
"block",
"|",
"define_method",
"(",
":\"",
"action_",
"#{",
"action",
"}",
"\"",
",",
"&",
"block",
")",
"end",
"end",
"end",
"end",
"def",
"included",
"(",
"descendant",
")",
"super",
"descendant",
".",
"extend",
"ClassMethods",
"end",
"end",
"extend",
"ClassMethods",
"end"
] |
Combine a resource and provider class for quick and easy oven baked
goodness.
|
[
"Combine",
"a",
"resource",
"and",
"provider",
"class",
"for",
"quick",
"and",
"easy",
"oven",
"baked",
"goodness",
"."
] |
[
"# Coerce is_a? so that the DSL will consider this a Provider for the",
"# purposes of attaching enclosing_provider.",
"#",
"# @param klass [Class]",
"#",
"# @return [Boolean]",
"#",
"# @api private",
"# Coerce provider_for_action so that the resource is also the provider.",
"#",
"# @param action [Symbol]",
"#",
"# @return [Chef::Provider]",
"#",
"# @api private",
"# Define a provider action. The block should contain the usual provider",
"# code.",
"#",
"# @param name [Symbol]",
"# Name of the action.",
"#",
"# @param block [Proc]",
"# Action implementation.",
"#",
"# Storage accessor for blended action blocks. Maps action name to proc.",
"#",
"# @return [Hash<Symbol, Proc>]",
"#",
"# @api private",
"# Create a provider class for the blender actions in this resource.",
"# Inherits from the blender provider class of the resource's",
"# superclass if present.",
"#",
"# @return [Class]",
"#",
"# @api private",
"# Hook called when module is included, extends a descendant with class",
"# and instance methods.",
"#",
"# @param [Module] descendant",
"# The module or class including Garcon::Resource::Blender",
"#",
"# @return [self]",
"#",
"# @api private"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "example",
"docstring": "class Chef::Resource::HouseKeeping < Chef::Resource include Garcon(blender: true) attribute :path, kind_of: String, name_attribute: true attribute :message, kind_of: String, default: 'Clean the kitchen' action :run do file new_resource.path do content new_resource.message end end end",
"docstring_tokens": [
"class",
"Chef",
"::",
"Resource",
"::",
"HouseKeeping",
"<",
"Chef",
"::",
"Resource",
"include",
"Garcon",
"(",
"blender",
":",
"true",
")",
"attribute",
":",
"path",
"kind_of",
":",
"String",
"name_attribute",
":",
"true",
"attribute",
":",
"message",
"kind_of",
":",
"String",
"default",
":",
"'",
"Clean",
"the",
"kitchen",
"'",
"action",
":",
"run",
"do",
"file",
"new_resource",
".",
"path",
"do",
"content",
"new_resource",
".",
"message",
"end",
"end",
"end"
]
}
]
}
| false
| 19
| 558
| 141
|
49a1e6d130ba220cdeda21457ee8c8d19a6b84b2
|
Freaky/ruby-reattempt
|
lib/reattempt.rb
|
[
"MIT"
] |
Ruby
|
Retry
|
# Retry the loop iterator if configured caught exceptions are raised and retry
# count is not exceeded, sleeping as per a given backoff configuration.
#
# @example
# bo = Reattempt::Backoff.new(min_delay: 0.1, max_delay: 1.0, jitter: 0.5)
# try = Reattempt::Retry.new(tries: 5, rescue: TempError, backoff: bo)
# begin
# try.each do |attempt|
# raise TempError, "Failed in attempt #{attempt}"
# end
# rescue Reattempt::RetriesExceeded => e
# p e.cause # => #<TempError: "Failed in attempt 5">
# end
|
Retry the loop iterator if configured caught exceptions are raised and retry
count is not exceeded, sleeping as per a given backoff configuration.
|
[
"Retry",
"the",
"loop",
"iterator",
"if",
"configured",
"caught",
"exceptions",
"are",
"raised",
"and",
"retry",
"count",
"is",
"not",
"exceeded",
"sleeping",
"as",
"per",
"a",
"given",
"backoff",
"configuration",
"."
] |
class Retry
include Enumerable
extend Dry::Initializer[undefined: false]
# @!method initialize(tries: 5, rescue: StandardError, backoff: Backoff.new, sleep_proc: Kernel.method(:sleep), rescue_proc: ->(_) {})
#
# @param tries [Integer] the number of attempts, including the first
# @param rescue [#===, Array<#===>] matchers for raised exceptions to retry
# @param backoff [Backoff,Enumerable] a +Backoff+ instance or a custom work-alike to generate sleep times
# @param sleep_proc [#call] a custom handler for the number of seconds to sleep
# @param rescue_proc [#call] a custom handler for rescued exceptions (e.g. for logging)
# @return [Retry]
option :tries,
default: -> { 5 },
type: Dry::Types['strict.integer'].constrained(gteq: 0)
option :rescue,
default: -> { StandardError },
type: Dry::Types['coercible.array'].constrained(min_size: 1)
.of(Dry::Types::Any.constrained(attr: :===))
option :backoff,
default: -> { Backoff.new },
type: Dry::Types::Definition.new(Backoff).constrained(type: Enumerable)
option :sleep_proc,
default: -> { Kernel.method(:sleep) },
type: Dry::Types::Any.constrained(attr: :call)
option :rescue_proc,
default: -> { ->(_ex) {} },
type: Dry::Types::Any.constrained(attr: :call)
# Yield the block with the current attempt number, starting from 1, for up
# to +tries+ times. Setting +tries+ to zero will result in an instant
# +RetriesExceeded+, which may be useful for testing.
#
# If any of the configured +rescue+ exceptions are raised (as matched by
# +===+), call +rescue_proc+ with the exception, call +sleep_proc+ with the
# delay as configured by +backoff+, and try again up to +retries+ times.
#
# +rescue_proc+ defaults to a no-op.
#
# +sleep_proc+ defaults to +Kernel#sleep+.
#
# @yieldparam [Integer] try the current attempt number, starting at 1
# @raise [Reattempt::RetriesExceeded] see +cause+ for the original exception
# @return [nil, Enumerator]
def each
return enum_for(:each) unless block_given?
ex = nil
backoff.lazy.take(tries).each_with_index do |delay, try|
return yield(try + 1)
rescue Exception => ex
raise unless self.rescue.any? { |r| r === ex }
rescue_proc.call ex
sleep_proc.call delay
end
raise RetriesExceeded, cause: ex
end
end
|
[
"class",
"Retry",
"include",
"Enumerable",
"extend",
"Dry",
"::",
"Initializer",
"[",
"undefined",
":",
"false",
"]",
"option",
":tries",
",",
"default",
":",
"->",
"{",
"5",
"}",
",",
"type",
":",
"Dry",
"::",
"Types",
"[",
"'strict.integer'",
"]",
".",
"constrained",
"(",
"gteq",
":",
"0",
")",
"option",
":rescue",
",",
"default",
":",
"->",
"{",
"StandardError",
"}",
",",
"type",
":",
"Dry",
"::",
"Types",
"[",
"'coercible.array'",
"]",
".",
"constrained",
"(",
"min_size",
":",
"1",
")",
".",
"of",
"(",
"Dry",
"::",
"Types",
"::",
"Any",
".",
"constrained",
"(",
"attr",
":",
":===",
")",
")",
"option",
":backoff",
",",
"default",
":",
"->",
"{",
"Backoff",
".",
"new",
"}",
",",
"type",
":",
"Dry",
"::",
"Types",
"::",
"Definition",
".",
"new",
"(",
"Backoff",
")",
".",
"constrained",
"(",
"type",
":",
"Enumerable",
")",
"option",
":sleep_proc",
",",
"default",
":",
"->",
"{",
"Kernel",
".",
"method",
"(",
":sleep",
")",
"}",
",",
"type",
":",
"Dry",
"::",
"Types",
"::",
"Any",
".",
"constrained",
"(",
"attr",
":",
":call",
")",
"option",
":rescue_proc",
",",
"default",
":",
"->",
"{",
"->",
"(",
"_ex",
")",
"{",
"}",
"}",
",",
"type",
":",
"Dry",
"::",
"Types",
"::",
"Any",
".",
"constrained",
"(",
"attr",
":",
":call",
")",
"def",
"each",
"return",
"enum_for",
"(",
":each",
")",
"unless",
"block_given?",
"ex",
"=",
"nil",
"backoff",
".",
"lazy",
".",
"take",
"(",
"tries",
")",
".",
"each_with_index",
"do",
"|",
"delay",
",",
"try",
"|",
"return",
"yield",
"(",
"try",
"+",
"1",
")",
"rescue",
"Exception",
"=>",
"ex",
"raise",
"unless",
"self",
".",
"rescue",
".",
"any?",
"{",
"|",
"r",
"|",
"r",
"===",
"ex",
"}",
"rescue_proc",
".",
"call",
"ex",
"sleep_proc",
".",
"call",
"delay",
"end",
"raise",
"RetriesExceeded",
",",
"cause",
":",
"ex",
"end",
"end"
] |
Retry the loop iterator if configured caught exceptions are raised and retry
count is not exceeded, sleeping as per a given backoff configuration.
|
[
"Retry",
"the",
"loop",
"iterator",
"if",
"configured",
"caught",
"exceptions",
"are",
"raised",
"and",
"retry",
"count",
"is",
"not",
"exceeded",
"sleeping",
"as",
"per",
"a",
"given",
"backoff",
"configuration",
"."
] |
[
"# @!method initialize(tries: 5, rescue: StandardError, backoff: Backoff.new, sleep_proc: Kernel.method(:sleep), rescue_proc: ->(_) {})",
"#",
"# @param tries [Integer] the number of attempts, including the first",
"# @param rescue [#===, Array<#===>] matchers for raised exceptions to retry",
"# @param backoff [Backoff,Enumerable] a +Backoff+ instance or a custom work-alike to generate sleep times",
"# @param sleep_proc [#call] a custom handler for the number of seconds to sleep",
"# @param rescue_proc [#call] a custom handler for rescued exceptions (e.g. for logging)",
"# @return [Retry]",
"# Yield the block with the current attempt number, starting from 1, for up",
"# to +tries+ times. Setting +tries+ to zero will result in an instant",
"# +RetriesExceeded+, which may be useful for testing.",
"#",
"# If any of the configured +rescue+ exceptions are raised (as matched by",
"# +===+), call +rescue_proc+ with the exception, call +sleep_proc+ with the",
"# delay as configured by +backoff+, and try again up to +retries+ times.",
"#",
"# +rescue_proc+ defaults to a no-op.",
"#",
"# +sleep_proc+ defaults to +Kernel#sleep+.",
"#",
"# @yieldparam [Integer] try the current attempt number, starting at 1",
"# @raise [Reattempt::RetriesExceeded] see +cause+ for the original exception",
"# @return [nil, Enumerator]"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "example",
"docstring": "bo = Reattempt::Backoff.new(min_delay: 0.1, max_delay: 1.0, jitter: 0.5) try = Reattempt::Retry.new(tries: 5, rescue: TempError, backoff: bo) begin try.each do |attempt| raise TempError, \"Failed in attempt #{attempt}\" end rescue Reattempt::RetriesExceeded => e p e.cause # => # end",
"docstring_tokens": [
"bo",
"=",
"Reattempt",
"::",
"Backoff",
".",
"new",
"(",
"min_delay",
":",
"0",
".",
"1",
"max_delay",
":",
"1",
".",
"0",
"jitter",
":",
"0",
".",
"5",
")",
"try",
"=",
"Reattempt",
"::",
"Retry",
".",
"new",
"(",
"tries",
":",
"5",
"rescue",
":",
"TempError",
"backoff",
":",
"bo",
")",
"begin",
"try",
".",
"each",
"do",
"|attempt|",
"raise",
"TempError",
"\"",
"Failed",
"in",
"attempt",
"#",
"{",
"attempt",
"}",
"\"",
"end",
"rescue",
"Reattempt",
"::",
"RetriesExceeded",
"=",
">",
"e",
"p",
"e",
".",
"cause",
"#",
"=",
">",
"#",
"end"
]
}
]
}
| false
| 15
| 664
| 157
|
6a5073af1092b3d2b64764a3dc7f9129e54a5848
|
DDTH/ddth-id
|
ddth-id-core/src/main/java/com/github/ddth/id/SerialIdGenerator.java
|
[
"MIT"
] |
Java
|
SerialIdGenerator
|
/**
* Generate serial IDs.
*
* <p>
* Serial IDs are:
* </p>
* <ul>
* <li>Grouped into namespaces.</li>
* <li>Unique within the namespace.</li>
* <li>Ascending and Serial: {@code next_id = previous_id + 1}.</li>
* <li>Persistency: depends on implementation of concrete sub-classes</li>
* </ul>
*
* @author Thanh Nguyen <[email protected]>
* @since 0.1.0
*/
|
Serial IDs are:
Grouped into namespaces.
Unique within the namespace.
Ascending and Serial: next_id = previous_id + 1.
Persistency: depends on implementation of concrete sub-classes
@author Thanh Nguyen
@since 0.1.0
|
[
"Serial",
"IDs",
"are",
":",
"Grouped",
"into",
"namespaces",
".",
"Unique",
"within",
"the",
"namespace",
".",
"Ascending",
"and",
"Serial",
":",
"next_id",
"=",
"previous_id",
"+",
"1",
".",
"Persistency",
":",
"depends",
"on",
"implementation",
"of",
"concrete",
"sub",
"-",
"classes",
"@author",
"Thanh",
"Nguyen",
"@since",
"0",
".",
"1",
".",
"0"
] |
public abstract class SerialIdGenerator implements Closeable, AutoCloseable {
protected static Cache<String, SerialIdGenerator> idGenerators = CacheBuilder.newBuilder()
.expireAfterAccess(3600, TimeUnit.SECONDS)
.removalListener(new RemovalListener<String, SerialIdGenerator>() {
@Override
public void onRemoval(RemovalNotification<String, SerialIdGenerator> entry) {
entry.getValue().destroy();
}
}).build();
/**
* Invalidates all cached {@link SerialIdGenerator}.
*
* @since 0.4.0
*/
public static void invalidate() {
idGenerators.invalidateAll();
}
public SerialIdGenerator init() {
return this;
}
public void destroy() {
// EMPTY
}
/**
* @since 0.5.0
*/
public void close() {
destroy();
}
/**
* Generates next id.
*
* @return next id for the specified namespace as a long, {@code 0} if not
* supported or invalid namespace, negative value if error.
*/
public abstract long nextId(String namespace);
/**
* Generates next id, retries till successful or timed-out.
*
* @param namespace
* @param timeout
* @param timeoutUnit
* @return
* @since 0.5.0
*/
public long nextIdWithRetries(String namespace, long timeout, TimeUnit timeoutUnit) {
long timestamp = System.currentTimeMillis();
long timeoutMs = timeoutUnit.toMillis(timeout);
long nextId = nextId(namespace);
while (nextId < 0 && System.currentTimeMillis() - timestamp <= timeoutMs) {
nextId = nextId(namespace);
}
return nextId;
}
/**
* Gets current id.
*
* @param namespace
* @return current id for the specified namespace as long, negative value if
* error.
* @since 0.2.0
*/
public abstract long currentId(String namespace);
/**
* Gets current id, retries till successful or timed-out.
*
* @param namespace
* @param timeout
* @param timeoutUnit
* @return
* @since 0.5.0
*/
public long currentIdWithRetries(String namespace, long timeout, TimeUnit timeoutUnit) {
long timestamp = System.currentTimeMillis();
long timeoutMs = timeoutUnit.toMillis(timeout);
long currentId = currentId(namespace);
while (currentId < 0 && System.currentTimeMillis() - timestamp <= timeoutMs) {
currentId = currentId(namespace);
}
return currentId;
}
/**
* Sets an id's value.
*
* @param namespace
* @param value
* @return
* @since 0.4.0
*/
public abstract boolean setValue(String namespace, long value);
/**
* Sets an id's value, retries till successful or timed-out.
*
* @param namespace
* @param value
* @param timeout
* @param timeoutUnit
* @return
* @since 0.5.0
*/
public boolean setValueWithRetries(String namespace, long value, long timeout,
TimeUnit timeoutUnit) {
long timestamp = System.currentTimeMillis();
long timeoutMs = timeoutUnit.toMillis(timeout);
boolean result = setValue(namespace, value);
while (!result && System.currentTimeMillis() - timestamp <= timeoutMs) {
result = setValue(namespace, value);
}
return result;
}
}
|
[
"public",
"abstract",
"class",
"SerialIdGenerator",
"implements",
"Closeable",
",",
"AutoCloseable",
"{",
"protected",
"static",
"Cache",
"<",
"String",
",",
"SerialIdGenerator",
">",
"idGenerators",
"=",
"CacheBuilder",
".",
"newBuilder",
"(",
")",
".",
"expireAfterAccess",
"(",
"3600",
",",
"TimeUnit",
".",
"SECONDS",
")",
".",
"removalListener",
"(",
"new",
"RemovalListener",
"<",
"String",
",",
"SerialIdGenerator",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onRemoval",
"(",
"RemovalNotification",
"<",
"String",
",",
"SerialIdGenerator",
">",
"entry",
")",
"{",
"entry",
".",
"getValue",
"(",
")",
".",
"destroy",
"(",
")",
";",
"}",
"}",
")",
".",
"build",
"(",
")",
";",
"/**\n * Invalidates all cached {@link SerialIdGenerator}.\n * \n * @since 0.4.0\n */",
"public",
"static",
"void",
"invalidate",
"(",
")",
"{",
"idGenerators",
".",
"invalidateAll",
"(",
")",
";",
"}",
"public",
"SerialIdGenerator",
"init",
"(",
")",
"{",
"return",
"this",
";",
"}",
"public",
"void",
"destroy",
"(",
")",
"{",
"}",
"/**\n * @since 0.5.0\n */",
"public",
"void",
"close",
"(",
")",
"{",
"destroy",
"(",
")",
";",
"}",
"/**\n * Generates next id.\n * \n * @return next id for the specified namespace as a long, {@code 0} if not\n * supported or invalid namespace, negative value if error.\n */",
"public",
"abstract",
"long",
"nextId",
"(",
"String",
"namespace",
")",
";",
"/**\n * Generates next id, retries till successful or timed-out.\n * \n * @param namespace\n * @param timeout\n * @param timeoutUnit\n * @return\n * @since 0.5.0\n */",
"public",
"long",
"nextIdWithRetries",
"(",
"String",
"namespace",
",",
"long",
"timeout",
",",
"TimeUnit",
"timeoutUnit",
")",
"{",
"long",
"timestamp",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"long",
"timeoutMs",
"=",
"timeoutUnit",
".",
"toMillis",
"(",
"timeout",
")",
";",
"long",
"nextId",
"=",
"nextId",
"(",
"namespace",
")",
";",
"while",
"(",
"nextId",
"<",
"0",
"&&",
"System",
".",
"currentTimeMillis",
"(",
")",
"-",
"timestamp",
"<=",
"timeoutMs",
")",
"{",
"nextId",
"=",
"nextId",
"(",
"namespace",
")",
";",
"}",
"return",
"nextId",
";",
"}",
"/**\n * Gets current id.\n * \n * @param namespace\n * @return current id for the specified namespace as long, negative value if\n * error.\n * @since 0.2.0\n */",
"public",
"abstract",
"long",
"currentId",
"(",
"String",
"namespace",
")",
";",
"/**\n * Gets current id, retries till successful or timed-out.\n * \n * @param namespace\n * @param timeout\n * @param timeoutUnit\n * @return\n * @since 0.5.0\n */",
"public",
"long",
"currentIdWithRetries",
"(",
"String",
"namespace",
",",
"long",
"timeout",
",",
"TimeUnit",
"timeoutUnit",
")",
"{",
"long",
"timestamp",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"long",
"timeoutMs",
"=",
"timeoutUnit",
".",
"toMillis",
"(",
"timeout",
")",
";",
"long",
"currentId",
"=",
"currentId",
"(",
"namespace",
")",
";",
"while",
"(",
"currentId",
"<",
"0",
"&&",
"System",
".",
"currentTimeMillis",
"(",
")",
"-",
"timestamp",
"<=",
"timeoutMs",
")",
"{",
"currentId",
"=",
"currentId",
"(",
"namespace",
")",
";",
"}",
"return",
"currentId",
";",
"}",
"/**\n * Sets an id's value.\n * \n * @param namespace\n * @param value\n * @return\n * @since 0.4.0\n */",
"public",
"abstract",
"boolean",
"setValue",
"(",
"String",
"namespace",
",",
"long",
"value",
")",
";",
"/**\n * Sets an id's value, retries till successful or timed-out.\n * \n * @param namespace\n * @param value\n * @param timeout\n * @param timeoutUnit\n * @return\n * @since 0.5.0\n */",
"public",
"boolean",
"setValueWithRetries",
"(",
"String",
"namespace",
",",
"long",
"value",
",",
"long",
"timeout",
",",
"TimeUnit",
"timeoutUnit",
")",
"{",
"long",
"timestamp",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"long",
"timeoutMs",
"=",
"timeoutUnit",
".",
"toMillis",
"(",
"timeout",
")",
";",
"boolean",
"result",
"=",
"setValue",
"(",
"namespace",
",",
"value",
")",
";",
"while",
"(",
"!",
"result",
"&&",
"System",
".",
"currentTimeMillis",
"(",
")",
"-",
"timestamp",
"<=",
"timeoutMs",
")",
"{",
"result",
"=",
"setValue",
"(",
"namespace",
",",
"value",
")",
";",
"}",
"return",
"result",
";",
"}",
"}"
] |
Generate serial IDs.
|
[
"Generate",
"serial",
"IDs",
"."
] |
[
"// EMPTY"
] |
[
{
"param": "Closeable, AutoCloseable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Closeable, AutoCloseable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 16
| 784
| 119
|
f826e0c1eea098b371c3d8dbf640550c1f98bb06
|
SMotaal/experimental-quasi-parser-generator
|
src/scanner.js
|
[
"Apache-2.0"
] |
JavaScript
|
Scanner
|
/**
* The default base Parser class for parser traits to extend. This
* provides a simple conventional lexer, where the production rules
* correspond to conventional token types. Parsers defined using the
* <tt>bootbnf.bnf</tt> tag that extend this one generally define
* the second level of a two level grammar. It you wish to inherit
* from Scanner in order to define a derived lexer, you probably
* need to use EcmaScript class inheritance directly.
*/
|
The default base Parser class for parser traits to extend. This
provides a simple conventional lexer, where the production rules
correspond to conventional token types. Parsers defined using the
bootbnf.bnf tag that extend this one generally define
the second level of a two level grammar. It you wish to inherit
from Scanner in order to define a derived lexer, you probably
need to use EcmaScript class inheritance directly.
|
[
"The",
"default",
"base",
"Parser",
"class",
"for",
"parser",
"traits",
"to",
"extend",
".",
"This",
"provides",
"a",
"simple",
"conventional",
"lexer",
"where",
"the",
"production",
"rules",
"correspond",
"to",
"conventional",
"token",
"types",
".",
"Parsers",
"defined",
"using",
"the",
"bootbnf",
".",
"bnf",
"tag",
"that",
"extend",
"this",
"one",
"generally",
"define",
"the",
"second",
"level",
"of",
"a",
"two",
"level",
"grammar",
".",
"It",
"you",
"wish",
"to",
"inherit",
"from",
"Scanner",
"in",
"order",
"to",
"define",
"a",
"derived",
"lexer",
"you",
"probably",
"need",
"to",
"use",
"EcmaScript",
"class",
"inheritance",
"directly",
"."
] |
class Scanner extends Packratter {
constructor(template, tokenTypeList=[]) {
super();
this.template = template;
this.keywords = new Set();
this.otherTokenTypes = new Set();
tokenTypeList.forEach(tt => {
if (allRE(IDENT_RE).test(tt)) {
this.keywords.add(tt);
} else {
this.otherTokenTypes.add(tt);
}
});
def(this.keywords); // TODO: should also freeze set contents
def(this.otherTokenTypes); // TODO: should also freeze set contents
// TODO: derive TOKEN_RE from otherTokenTypes
this.toks = Token.tokensInTemplate(template.raw, TOKEN_RE);
def(this);
}
start() {
return this.toks.map(token => token.text);
}
syntaxError() {
console.log(`
-------template--------
${JSON.stringify(this.template, void 0, ' ')}
-------`);
const [last, fails] = this.lastFailures();
const tokStr = last < this.toks.length ?
`At ${this.toks[last]}` :
`Unexpected EOF after ${this.toks[this.toks.length - 1]}`;
const failStr = fails.length === 0 ?
`stuck` : `looking for ${fails.join(' ')}`;
throw new SyntaxError(`${tokStr} ${failStr}`);
}
skip(pos, RE) {
if (pos < this.toks.length) {
const token = this.toks[pos];
if (typeof token !== 'number') {
if (allRE(RE).test(token.text)) {
return [pos + 1, ''];
}
}
}
return [pos, FAIL];
}
rule_SPACE(pos) {
return this.skip(pos, SPACE_RE);
}
rule_COMMENT(pos) {
return this.skip(pos, LINE_COMMENT_RE);
}
// Must always succeed
// (SPACE / COMMENT)*
// Callers should not memoize calls to rule_SKIP as it is likely
// not worth it. rule_SKIP does not memoize its call to rule_SPACE
// for the same reason. However, it does memoize its call to
// rule_COMMENT.
rule_SKIP(pos) {
while (pos < this.toks.length) {
const token = this.toks[pos];
if (typeof token === 'number') { break; }
let pair = this.rule_SPACE(pos);
if (pair[1] !== FAIL) {
pos = pair[0];
} else {
pair = this.run(this.rule_COMMENT, pos, 'COMMENT');
if (pair[1] !== FAIL) {
pos = pair[0];
} else {
break;
}
}
}
return [pos, ''];
}
eat(pos, patt) {
[pos] = this.rule_SKIP(pos);
if (pos < this.toks.length) {
const token = this.toks[pos];
if (typeof token !== 'number') {
if ((typeof patt === 'string' && patt === token.text) ||
allRE(patt).test(token.text)) {
return [pos + 1, token.text];
}
}
}
return [pos, FAIL];
}
rule_NUMBER(pos) { return this.eat(pos, NUMBER_RE); }
rule_STRING(pos) { return this.eat(pos, STRING_RE); }
rule_IDENT(pos) {
[pos] = this.rule_SKIP(pos);
if (pos >= this.toks.length) { return [pos, FAIL]; }
const token = this.toks[pos];
if (typeof token === 'number') { return [pos, FAIL]; }
if (allRE(IDENT_RE).test(token.text) &&
!this.keywords.has(token.text)) {
return [pos + 1, token.text];
}
return [pos, FAIL];
}
rule_HOLE(pos) {
[pos] = this.rule_SKIP(pos);
if (pos >= this.toks.length) { return [pos, FAIL]; }
const token = this.toks[pos];
if (typeof token === 'number') {
return [pos + 1, token];
}
return [pos, FAIL];
}
rule_EOF(pos) {
[pos] = this.rule_SKIP(pos);
return [pos, pos >= this.toks.length ? EOF : FAIL];
}
}
|
[
"class",
"Scanner",
"extends",
"Packratter",
"{",
"constructor",
"(",
"template",
",",
"tokenTypeList",
"=",
"[",
"]",
")",
"{",
"super",
"(",
")",
";",
"this",
".",
"template",
"=",
"template",
";",
"this",
".",
"keywords",
"=",
"new",
"Set",
"(",
")",
";",
"this",
".",
"otherTokenTypes",
"=",
"new",
"Set",
"(",
")",
";",
"tokenTypeList",
".",
"forEach",
"(",
"tt",
"=>",
"{",
"if",
"(",
"allRE",
"(",
"IDENT_RE",
")",
".",
"test",
"(",
"tt",
")",
")",
"{",
"this",
".",
"keywords",
".",
"add",
"(",
"tt",
")",
";",
"}",
"else",
"{",
"this",
".",
"otherTokenTypes",
".",
"add",
"(",
"tt",
")",
";",
"}",
"}",
")",
";",
"def",
"(",
"this",
".",
"keywords",
")",
";",
"def",
"(",
"this",
".",
"otherTokenTypes",
")",
";",
"this",
".",
"toks",
"=",
"Token",
".",
"tokensInTemplate",
"(",
"template",
".",
"raw",
",",
"TOKEN_RE",
")",
";",
"def",
"(",
"this",
")",
";",
"}",
"start",
"(",
")",
"{",
"return",
"this",
".",
"toks",
".",
"map",
"(",
"token",
"=>",
"token",
".",
"text",
")",
";",
"}",
"syntaxError",
"(",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"JSON",
".",
"stringify",
"(",
"this",
".",
"template",
",",
"void",
"0",
",",
"' '",
")",
"}",
"`",
")",
";",
"const",
"[",
"last",
",",
"fails",
"]",
"=",
"this",
".",
"lastFailures",
"(",
")",
";",
"const",
"tokStr",
"=",
"last",
"<",
"this",
".",
"toks",
".",
"length",
"?",
"`",
"${",
"this",
".",
"toks",
"[",
"last",
"]",
"}",
"`",
":",
"`",
"${",
"this",
".",
"toks",
"[",
"this",
".",
"toks",
".",
"length",
"-",
"1",
"]",
"}",
"`",
";",
"const",
"failStr",
"=",
"fails",
".",
"length",
"===",
"0",
"?",
"`",
"`",
":",
"`",
"${",
"fails",
".",
"join",
"(",
"' '",
")",
"}",
"`",
";",
"throw",
"new",
"SyntaxError",
"(",
"`",
"${",
"tokStr",
"}",
"${",
"failStr",
"}",
"`",
")",
";",
"}",
"skip",
"(",
"pos",
",",
"RE",
")",
"{",
"if",
"(",
"pos",
"<",
"this",
".",
"toks",
".",
"length",
")",
"{",
"const",
"token",
"=",
"this",
".",
"toks",
"[",
"pos",
"]",
";",
"if",
"(",
"typeof",
"token",
"!==",
"'number'",
")",
"{",
"if",
"(",
"allRE",
"(",
"RE",
")",
".",
"test",
"(",
"token",
".",
"text",
")",
")",
"{",
"return",
"[",
"pos",
"+",
"1",
",",
"''",
"]",
";",
"}",
"}",
"}",
"return",
"[",
"pos",
",",
"FAIL",
"]",
";",
"}",
"rule_SPACE",
"(",
"pos",
")",
"{",
"return",
"this",
".",
"skip",
"(",
"pos",
",",
"SPACE_RE",
")",
";",
"}",
"rule_COMMENT",
"(",
"pos",
")",
"{",
"return",
"this",
".",
"skip",
"(",
"pos",
",",
"LINE_COMMENT_RE",
")",
";",
"}",
"rule_SKIP",
"(",
"pos",
")",
"{",
"while",
"(",
"pos",
"<",
"this",
".",
"toks",
".",
"length",
")",
"{",
"const",
"token",
"=",
"this",
".",
"toks",
"[",
"pos",
"]",
";",
"if",
"(",
"typeof",
"token",
"===",
"'number'",
")",
"{",
"break",
";",
"}",
"let",
"pair",
"=",
"this",
".",
"rule_SPACE",
"(",
"pos",
")",
";",
"if",
"(",
"pair",
"[",
"1",
"]",
"!==",
"FAIL",
")",
"{",
"pos",
"=",
"pair",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"pair",
"=",
"this",
".",
"run",
"(",
"this",
".",
"rule_COMMENT",
",",
"pos",
",",
"'COMMENT'",
")",
";",
"if",
"(",
"pair",
"[",
"1",
"]",
"!==",
"FAIL",
")",
"{",
"pos",
"=",
"pair",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"break",
";",
"}",
"}",
"}",
"return",
"[",
"pos",
",",
"''",
"]",
";",
"}",
"eat",
"(",
"pos",
",",
"patt",
")",
"{",
"[",
"pos",
"]",
"=",
"this",
".",
"rule_SKIP",
"(",
"pos",
")",
";",
"if",
"(",
"pos",
"<",
"this",
".",
"toks",
".",
"length",
")",
"{",
"const",
"token",
"=",
"this",
".",
"toks",
"[",
"pos",
"]",
";",
"if",
"(",
"typeof",
"token",
"!==",
"'number'",
")",
"{",
"if",
"(",
"(",
"typeof",
"patt",
"===",
"'string'",
"&&",
"patt",
"===",
"token",
".",
"text",
")",
"||",
"allRE",
"(",
"patt",
")",
".",
"test",
"(",
"token",
".",
"text",
")",
")",
"{",
"return",
"[",
"pos",
"+",
"1",
",",
"token",
".",
"text",
"]",
";",
"}",
"}",
"}",
"return",
"[",
"pos",
",",
"FAIL",
"]",
";",
"}",
"rule_NUMBER",
"(",
"pos",
")",
"{",
"return",
"this",
".",
"eat",
"(",
"pos",
",",
"NUMBER_RE",
")",
";",
"}",
"rule_STRING",
"(",
"pos",
")",
"{",
"return",
"this",
".",
"eat",
"(",
"pos",
",",
"STRING_RE",
")",
";",
"}",
"rule_IDENT",
"(",
"pos",
")",
"{",
"[",
"pos",
"]",
"=",
"this",
".",
"rule_SKIP",
"(",
"pos",
")",
";",
"if",
"(",
"pos",
">=",
"this",
".",
"toks",
".",
"length",
")",
"{",
"return",
"[",
"pos",
",",
"FAIL",
"]",
";",
"}",
"const",
"token",
"=",
"this",
".",
"toks",
"[",
"pos",
"]",
";",
"if",
"(",
"typeof",
"token",
"===",
"'number'",
")",
"{",
"return",
"[",
"pos",
",",
"FAIL",
"]",
";",
"}",
"if",
"(",
"allRE",
"(",
"IDENT_RE",
")",
".",
"test",
"(",
"token",
".",
"text",
")",
"&&",
"!",
"this",
".",
"keywords",
".",
"has",
"(",
"token",
".",
"text",
")",
")",
"{",
"return",
"[",
"pos",
"+",
"1",
",",
"token",
".",
"text",
"]",
";",
"}",
"return",
"[",
"pos",
",",
"FAIL",
"]",
";",
"}",
"rule_HOLE",
"(",
"pos",
")",
"{",
"[",
"pos",
"]",
"=",
"this",
".",
"rule_SKIP",
"(",
"pos",
")",
";",
"if",
"(",
"pos",
">=",
"this",
".",
"toks",
".",
"length",
")",
"{",
"return",
"[",
"pos",
",",
"FAIL",
"]",
";",
"}",
"const",
"token",
"=",
"this",
".",
"toks",
"[",
"pos",
"]",
";",
"if",
"(",
"typeof",
"token",
"===",
"'number'",
")",
"{",
"return",
"[",
"pos",
"+",
"1",
",",
"token",
"]",
";",
"}",
"return",
"[",
"pos",
",",
"FAIL",
"]",
";",
"}",
"rule_EOF",
"(",
"pos",
")",
"{",
"[",
"pos",
"]",
"=",
"this",
".",
"rule_SKIP",
"(",
"pos",
")",
";",
"return",
"[",
"pos",
",",
"pos",
">=",
"this",
".",
"toks",
".",
"length",
"?",
"EOF",
":",
"FAIL",
"]",
";",
"}",
"}"
] |
The default base Parser class for parser traits to extend.
|
[
"The",
"default",
"base",
"Parser",
"class",
"for",
"parser",
"traits",
"to",
"extend",
"."
] |
[
"// TODO: should also freeze set contents",
"// TODO: should also freeze set contents",
"// TODO: derive TOKEN_RE from otherTokenTypes",
"// Must always succeed",
"// (SPACE / COMMENT)*",
"// Callers should not memoize calls to rule_SKIP as it is likely",
"// not worth it. rule_SKIP does not memoize its call to rule_SPACE",
"// for the same reason. However, it does memoize its call to",
"// rule_COMMENT."
] |
[
{
"param": "Packratter",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Packratter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 17
| 942
| 110
|
acfa1f6cd582574c8918951a639499f6c30deb32
|
RoadToZion123/secrets-for-android-master
|
app/src/main/java/net/tawacentral/roger/secrets/OnlineAgentManager.java
|
[
"OML"
] |
Java
|
OnlineAgentManager
|
/**
* Provides support for Online Sync Agents.
*
* Sync process overview
*
* On each resume a roll call is broadcast. Agents that respond are recorded in
* a list of available agents.
*
* Sync operations are always initiated from secrets. A sync request is
* broadcast at the selected (or only) available agent, together with the
* unencrypted secrets and a one-time validation key. The sync response is
* validated against the key,and the returned secrets (updated or deleted) are
* merged with the existing ones.
*
* Multiple concurrent sync requests are not supported. It is the caller's
* responsibility to ensure there is no active request when calling
* sendSecrets().
*
* @author Chris Wood
*/
|
Provides support for Online Sync Agents.
Sync process overview
On each resume a roll call is broadcast. Agents that respond are recorded in
a list of available agents.
Sync operations are always initiated from secrets. A sync request is
broadcast at the selected (or only) available agent, together with the
unencrypted secrets and a one-time validation key. The sync response is
validated against the key,and the returned secrets (updated or deleted) are
merged with the existing ones.
Multiple concurrent sync requests are not supported. It is the caller's
responsibility to ensure there is no active request when calling
sendSecrets().
@author Chris Wood
|
[
"Provides",
"support",
"for",
"Online",
"Sync",
"Agents",
".",
"Sync",
"process",
"overview",
"On",
"each",
"resume",
"a",
"roll",
"call",
"is",
"broadcast",
".",
"Agents",
"that",
"respond",
"are",
"recorded",
"in",
"a",
"list",
"of",
"available",
"agents",
".",
"Sync",
"operations",
"are",
"always",
"initiated",
"from",
"secrets",
".",
"A",
"sync",
"request",
"is",
"broadcast",
"at",
"the",
"selected",
"(",
"or",
"only",
")",
"available",
"agent",
"together",
"with",
"the",
"unencrypted",
"secrets",
"and",
"a",
"one",
"-",
"time",
"validation",
"key",
".",
"The",
"sync",
"response",
"is",
"validated",
"against",
"the",
"key",
"and",
"the",
"returned",
"secrets",
"(",
"updated",
"or",
"deleted",
")",
"are",
"merged",
"with",
"the",
"existing",
"ones",
".",
"Multiple",
"concurrent",
"sync",
"requests",
"are",
"not",
"supported",
".",
"It",
"is",
"the",
"caller",
"'",
"s",
"responsibility",
"to",
"ensure",
"there",
"is",
"no",
"active",
"request",
"when",
"calling",
"sendSecrets",
"()",
".",
"@author",
"Chris",
"Wood"
] |
public class OnlineAgentManager extends BroadcastReceiver {
private static final String LOG_TAG = "OnlineAgentManager";
private static final String SECRETS_PERMISSION =
"net.tawacentral.roger.secrets.permission.SECRETS";
// broadcast ACTIONS
private static final String ROLLCALL =
"net.tawacentral.roger.secrets.OSA_ROLLCALL";
private static final String ROLLCALL_RESPONSE =
"net.tawacentral.roger.secrets.OSA_ROLLCALL_RESPONSE";
private static final String SYNC = "net.tawacentral.roger.secrets.SYNC";
private static final String SYNC_RESPONSE =
"net.tawacentral.roger.secrets.SYNC_RESPONSE";
private static final String SYNC_CANCEL =
"net.tawacentral.roger.secrets.SYNC_CANCEL";
private static final String INTENT_CLASSID = "net.tawacentral.roger.secrets.ClassId";
private static final String INTENT_DISPLAYNAME = "net.tawacentral.roger.secrets.DisplayName";
private static final String INTENT_RESPONSEKEY = "net.tawacentral.roger.secrets.ResponseKey";
private static final String INTENT_SECRETS = "net.tawacentral.roger.secrets.Secrets";
// for the current request
private static OnlineSyncAgent requestAgent;
private static SecretsListActivity responseActivity;
private static boolean active;
/*
* The response key is a randomly generated string that is provided to the
* OSA as part of the sync request and must be returned in the response in
* order for it to be accepted. The key is changed when the response is
* received to ensure that any subsequent or unsolicited responses are
* rejected.
*/
private static String responseKey;
private static final int RESPONSEKEY_LENGTH = 8;
private static Map<String, OnlineSyncAgent> AVAILABLE_AGENTS =
new HashMap<String, OnlineSyncAgent>();
/*
* Handle the received broadcast
*/
@Override
public void onReceive(Context context, Intent intent) {
Log.d(LOG_TAG, "Agent Manager received msg: " + intent.getAction());
// handle roll call response
if (intent.getAction().equals(ROLLCALL_RESPONSE)
&& intent.getExtras() != null) {
String classId = (String) intent.getExtras().get(INTENT_CLASSID);
String displayName = (String) intent.getExtras().get(INTENT_DISPLAYNAME);
if (classId == null || classId.length() == 0 || displayName == null
|| displayName.length() == 0) {
// invalid info, so do not add it
Log.e(LOG_TAG, "Received invalid OSA rollcall resp: classId=" + classId
+ ",displayName=" + displayName);
} else {
AVAILABLE_AGENTS
.put(classId, new OnlineSyncAgent(displayName, classId));
Log.d(LOG_TAG, "Received OSA rollcall resp: " + classId + " "
+ displayName);
}
// handle sync response
} else if (intent.getAction().equals(SYNC_RESPONSE)
&& validateResponse(intent)) {
String secretsString = intent.getStringExtra(INTENT_SECRETS);
ArrayList<Secret> secrets = null;
if (secretsString != null) {
try {
secrets = FileUtils.fromJSONSecrets(new JSONObject(secretsString));
} catch (JSONException e) {
Log.e(LOG_TAG, "Received invalid JSON secrets data", e);
}
}
active = false;
responseActivity.syncSecrets(secrets, requestAgent.getDisplayName());
requestAgent = null;
responseKey = generateResponseKey(); // change response key
}
}
/*
* Validate the sync response from the agent. The key in the response must
* match the one sent in the original sync request.
*
* @param intent
*
* @return true if response is OK, false otherwise
*/
private boolean validateResponse(Intent intent) {
if (intent.getExtras() != null) {
String classId = (String) intent.getExtras().get(INTENT_CLASSID);
String responseKey = (String) intent.getExtras().get(INTENT_RESPONSEKEY);
OnlineSyncAgent agent = AVAILABLE_AGENTS.get(classId);
if (agent != null) {
if (agent == requestAgent) { // is a response expected?
if (OnlineAgentManager.responseKey != null // does the key match?
&& OnlineAgentManager.responseKey.equals(responseKey)) {
if (active) return true; // if request not cancelled
Log.w(LOG_TAG, "SYNC response received from agent " + classId
+ " after request was cancelled - discarded");
} else {
Log.w(LOG_TAG, "SYNC response received from agent " + classId
+ " with invalid response key");
}
} else {
Log.w(LOG_TAG, "Unexpected SYNC response received from agent "
+ classId + " - no request outstanding");
}
} else {
Log.w(LOG_TAG, "SYNC response received from unknown app: " + classId);
}
} else {
Log.w(LOG_TAG, "SYNC response received with no extras");
}
return false;
}
/**
* Generate a new response key
*
* @return String response key
*/
public static String generateResponseKey() {
SecureRandom random = new SecureRandom();
byte[] keyBytes = new byte[RESPONSEKEY_LENGTH];
random.nextBytes(keyBytes);
return new String(keyBytes);
}
/**
* Get available agents
*
* @return collection of installed agents
*/
public static Collection<OnlineSyncAgent> getAvailableAgents() {
return Collections.unmodifiableCollection(AVAILABLE_AGENTS.values());
}
/**
* Sends out the rollcall broadcast and will keep track of all OSAs that
* respond.
*
* Forget previous agents - only ones that respond are considered available.
*
* @param context
*/
public static void sendRollCallBroadcast(Context context) {
AVAILABLE_AGENTS.clear();
Intent broadcastIntent = new Intent(ROLLCALL);
context.sendBroadcast(broadcastIntent, SECRETS_PERMISSION);
Log.d(LOG_TAG, "sent broadcast");
}
/**
* Sends secrets to the specified OSA.
*
* Returns true if secrets are successfully sent, but makes no guarantees that
* the secrets were received.
*
* A one-time key is sent to the OSA and must be returned in the reply for it
* to be considered valid.
*
* @param agent
* @param secrets
* @param activity
* @return true if secrets were sent
*/
public static boolean sendSecrets(OnlineSyncAgent agent,
ArrayList<Secret> secrets,
SecretsListActivity activity) {
requestAgent = agent;
responseActivity = activity;
responseKey = generateResponseKey();
try {
Intent secretsIntent = new Intent(SYNC);
secretsIntent.setPackage(agent.getClassId());
secretsIntent.putExtra(INTENT_RESPONSEKEY, OnlineAgentManager.responseKey);
String secretString = FileUtils.toJSONSecrets(secrets).toString();
secretsIntent.putExtra(INTENT_SECRETS, secretString);
activity.sendBroadcast(secretsIntent, SECRETS_PERMISSION);
Log.d(LOG_TAG, "Secrets sent to OSA " + agent.getClassId());
active = true;
return true;
} catch (Exception e) {
Log.e(LOG_TAG, "Error sending secrets to OSA", e);
// ignore the exception, false will be returned below
}
return false;
}
/**
* Test for active request
* @return true if active
*/
public static boolean isActive() {
return active;
}
/**
* Cancel the active request
*/
public static void cancel() {
OnlineAgentManager.active = false;
Intent secretsIntent = new Intent(SYNC_CANCEL);
secretsIntent.setPackage(requestAgent.getClassId());
responseActivity.sendBroadcast(secretsIntent, SECRETS_PERMISSION);
}
/* Helper functions */
/**
* Add, update or delete the current secrets in the given collection.
*
* Assumes that the collection sort sequences are the same.
*
* @param secrets
* - target secrets collection
* @param changedSecrets
* - added, changed or deleted secrets
*/
public static void syncSecrets(ArrayList<Secret> secrets,
ArrayList<Secret> changedSecrets) {
for (Secret changedSecret : changedSecrets) {
boolean done = false;
for (int i = 0; i < secrets.size(); i++) {
Secret existingSecret = secrets.get(i);
int compare = changedSecret.compareTo(existingSecret);
if (compare < 0 && !changedSecret.isDeleted()) {
secrets.add(i, changedSecret);
done = true;
Log.d(LOG_TAG, "syncSecrets: added '" +
changedSecret.getDescription() + "'");
break;
} else if (compare == 0) {
if (changedSecret.isDeleted()) {
secrets.remove(existingSecret);
Log.d(LOG_TAG, "syncSecrets: removed '" +
changedSecret.getDescription() + "'");
} else {
existingSecret.update(changedSecret, LogEntry.SYNCED);
Log.d(LOG_TAG, "syncSecrets: updated '" +
changedSecret.getDescription() + "'");
}
done = true;
break;
}
}
if (!done && !changedSecret.isDeleted())
secrets.add(changedSecret);
Log.d(LOG_TAG, "syncSecrets: added '" +
changedSecret.getDescription() + "'");
}
}
}
|
[
"public",
"class",
"OnlineAgentManager",
"extends",
"BroadcastReceiver",
"{",
"private",
"static",
"final",
"String",
"LOG_TAG",
"=",
"\"",
"OnlineAgentManager",
"\"",
";",
"private",
"static",
"final",
"String",
"SECRETS_PERMISSION",
"=",
"\"",
"net.tawacentral.roger.secrets.permission.SECRETS",
"\"",
";",
"private",
"static",
"final",
"String",
"ROLLCALL",
"=",
"\"",
"net.tawacentral.roger.secrets.OSA_ROLLCALL",
"\"",
";",
"private",
"static",
"final",
"String",
"ROLLCALL_RESPONSE",
"=",
"\"",
"net.tawacentral.roger.secrets.OSA_ROLLCALL_RESPONSE",
"\"",
";",
"private",
"static",
"final",
"String",
"SYNC",
"=",
"\"",
"net.tawacentral.roger.secrets.SYNC",
"\"",
";",
"private",
"static",
"final",
"String",
"SYNC_RESPONSE",
"=",
"\"",
"net.tawacentral.roger.secrets.SYNC_RESPONSE",
"\"",
";",
"private",
"static",
"final",
"String",
"SYNC_CANCEL",
"=",
"\"",
"net.tawacentral.roger.secrets.SYNC_CANCEL",
"\"",
";",
"private",
"static",
"final",
"String",
"INTENT_CLASSID",
"=",
"\"",
"net.tawacentral.roger.secrets.ClassId",
"\"",
";",
"private",
"static",
"final",
"String",
"INTENT_DISPLAYNAME",
"=",
"\"",
"net.tawacentral.roger.secrets.DisplayName",
"\"",
";",
"private",
"static",
"final",
"String",
"INTENT_RESPONSEKEY",
"=",
"\"",
"net.tawacentral.roger.secrets.ResponseKey",
"\"",
";",
"private",
"static",
"final",
"String",
"INTENT_SECRETS",
"=",
"\"",
"net.tawacentral.roger.secrets.Secrets",
"\"",
";",
"private",
"static",
"OnlineSyncAgent",
"requestAgent",
";",
"private",
"static",
"SecretsListActivity",
"responseActivity",
";",
"private",
"static",
"boolean",
"active",
";",
"/*\n * The response key is a randomly generated string that is provided to the\n * OSA as part of the sync request and must be returned in the response in\n * order for it to be accepted. The key is changed when the response is\n * received to ensure that any subsequent or unsolicited responses are\n * rejected.\n */",
"private",
"static",
"String",
"responseKey",
";",
"private",
"static",
"final",
"int",
"RESPONSEKEY_LENGTH",
"=",
"8",
";",
"private",
"static",
"Map",
"<",
"String",
",",
"OnlineSyncAgent",
">",
"AVAILABLE_AGENTS",
"=",
"new",
"HashMap",
"<",
"String",
",",
"OnlineSyncAgent",
">",
"(",
")",
";",
"/*\n * Handle the received broadcast\n */",
"@",
"Override",
"public",
"void",
"onReceive",
"(",
"Context",
"context",
",",
"Intent",
"intent",
")",
"{",
"Log",
".",
"d",
"(",
"LOG_TAG",
",",
"\"",
"Agent Manager received msg: ",
"\"",
"+",
"intent",
".",
"getAction",
"(",
")",
")",
";",
"if",
"(",
"intent",
".",
"getAction",
"(",
")",
".",
"equals",
"(",
"ROLLCALL_RESPONSE",
")",
"&&",
"intent",
".",
"getExtras",
"(",
")",
"!=",
"null",
")",
"{",
"String",
"classId",
"=",
"(",
"String",
")",
"intent",
".",
"getExtras",
"(",
")",
".",
"get",
"(",
"INTENT_CLASSID",
")",
";",
"String",
"displayName",
"=",
"(",
"String",
")",
"intent",
".",
"getExtras",
"(",
")",
".",
"get",
"(",
"INTENT_DISPLAYNAME",
")",
";",
"if",
"(",
"classId",
"==",
"null",
"||",
"classId",
".",
"length",
"(",
")",
"==",
"0",
"||",
"displayName",
"==",
"null",
"||",
"displayName",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"Log",
".",
"e",
"(",
"LOG_TAG",
",",
"\"",
"Received invalid OSA rollcall resp: classId=",
"\"",
"+",
"classId",
"+",
"\"",
",displayName=",
"\"",
"+",
"displayName",
")",
";",
"}",
"else",
"{",
"AVAILABLE_AGENTS",
".",
"put",
"(",
"classId",
",",
"new",
"OnlineSyncAgent",
"(",
"displayName",
",",
"classId",
")",
")",
";",
"Log",
".",
"d",
"(",
"LOG_TAG",
",",
"\"",
"Received OSA rollcall resp: ",
"\"",
"+",
"classId",
"+",
"\"",
" ",
"\"",
"+",
"displayName",
")",
";",
"}",
"}",
"else",
"if",
"(",
"intent",
".",
"getAction",
"(",
")",
".",
"equals",
"(",
"SYNC_RESPONSE",
")",
"&&",
"validateResponse",
"(",
"intent",
")",
")",
"{",
"String",
"secretsString",
"=",
"intent",
".",
"getStringExtra",
"(",
"INTENT_SECRETS",
")",
";",
"ArrayList",
"<",
"Secret",
">",
"secrets",
"=",
"null",
";",
"if",
"(",
"secretsString",
"!=",
"null",
")",
"{",
"try",
"{",
"secrets",
"=",
"FileUtils",
".",
"fromJSONSecrets",
"(",
"new",
"JSONObject",
"(",
"secretsString",
")",
")",
";",
"}",
"catch",
"(",
"JSONException",
"e",
")",
"{",
"Log",
".",
"e",
"(",
"LOG_TAG",
",",
"\"",
"Received invalid JSON secrets data",
"\"",
",",
"e",
")",
";",
"}",
"}",
"active",
"=",
"false",
";",
"responseActivity",
".",
"syncSecrets",
"(",
"secrets",
",",
"requestAgent",
".",
"getDisplayName",
"(",
")",
")",
";",
"requestAgent",
"=",
"null",
";",
"responseKey",
"=",
"generateResponseKey",
"(",
")",
";",
"}",
"}",
"/*\n * Validate the sync response from the agent. The key in the response must\n * match the one sent in the original sync request.\n * \n * @param intent\n * \n * @return true if response is OK, false otherwise\n */",
"private",
"boolean",
"validateResponse",
"(",
"Intent",
"intent",
")",
"{",
"if",
"(",
"intent",
".",
"getExtras",
"(",
")",
"!=",
"null",
")",
"{",
"String",
"classId",
"=",
"(",
"String",
")",
"intent",
".",
"getExtras",
"(",
")",
".",
"get",
"(",
"INTENT_CLASSID",
")",
";",
"String",
"responseKey",
"=",
"(",
"String",
")",
"intent",
".",
"getExtras",
"(",
")",
".",
"get",
"(",
"INTENT_RESPONSEKEY",
")",
";",
"OnlineSyncAgent",
"agent",
"=",
"AVAILABLE_AGENTS",
".",
"get",
"(",
"classId",
")",
";",
"if",
"(",
"agent",
"!=",
"null",
")",
"{",
"if",
"(",
"agent",
"==",
"requestAgent",
")",
"{",
"if",
"(",
"OnlineAgentManager",
".",
"responseKey",
"!=",
"null",
"&&",
"OnlineAgentManager",
".",
"responseKey",
".",
"equals",
"(",
"responseKey",
")",
")",
"{",
"if",
"(",
"active",
")",
"return",
"true",
";",
"Log",
".",
"w",
"(",
"LOG_TAG",
",",
"\"",
"SYNC response received from agent ",
"\"",
"+",
"classId",
"+",
"\"",
" after request was cancelled - discarded",
"\"",
")",
";",
"}",
"else",
"{",
"Log",
".",
"w",
"(",
"LOG_TAG",
",",
"\"",
"SYNC response received from agent ",
"\"",
"+",
"classId",
"+",
"\"",
" with invalid response key",
"\"",
")",
";",
"}",
"}",
"else",
"{",
"Log",
".",
"w",
"(",
"LOG_TAG",
",",
"\"",
"Unexpected SYNC response received from agent ",
"\"",
"+",
"classId",
"+",
"\"",
" - no request outstanding",
"\"",
")",
";",
"}",
"}",
"else",
"{",
"Log",
".",
"w",
"(",
"LOG_TAG",
",",
"\"",
"SYNC response received from unknown app: ",
"\"",
"+",
"classId",
")",
";",
"}",
"}",
"else",
"{",
"Log",
".",
"w",
"(",
"LOG_TAG",
",",
"\"",
"SYNC response received with no extras",
"\"",
")",
";",
"}",
"return",
"false",
";",
"}",
"/**\n * Generate a new response key\n * \n * @return String response key\n */",
"public",
"static",
"String",
"generateResponseKey",
"(",
")",
"{",
"SecureRandom",
"random",
"=",
"new",
"SecureRandom",
"(",
")",
";",
"byte",
"[",
"]",
"keyBytes",
"=",
"new",
"byte",
"[",
"RESPONSEKEY_LENGTH",
"]",
";",
"random",
".",
"nextBytes",
"(",
"keyBytes",
")",
";",
"return",
"new",
"String",
"(",
"keyBytes",
")",
";",
"}",
"/**\n * Get available agents\n * \n * @return collection of installed agents\n */",
"public",
"static",
"Collection",
"<",
"OnlineSyncAgent",
">",
"getAvailableAgents",
"(",
")",
"{",
"return",
"Collections",
".",
"unmodifiableCollection",
"(",
"AVAILABLE_AGENTS",
".",
"values",
"(",
")",
")",
";",
"}",
"/**\n * Sends out the rollcall broadcast and will keep track of all OSAs that\n * respond.\n * \n * Forget previous agents - only ones that respond are considered available.\n * \n * @param context\n */",
"public",
"static",
"void",
"sendRollCallBroadcast",
"(",
"Context",
"context",
")",
"{",
"AVAILABLE_AGENTS",
".",
"clear",
"(",
")",
";",
"Intent",
"broadcastIntent",
"=",
"new",
"Intent",
"(",
"ROLLCALL",
")",
";",
"context",
".",
"sendBroadcast",
"(",
"broadcastIntent",
",",
"SECRETS_PERMISSION",
")",
";",
"Log",
".",
"d",
"(",
"LOG_TAG",
",",
"\"",
"sent broadcast",
"\"",
")",
";",
"}",
"/**\n * Sends secrets to the specified OSA.\n * \n * Returns true if secrets are successfully sent, but makes no guarantees that\n * the secrets were received.\n * \n * A one-time key is sent to the OSA and must be returned in the reply for it\n * to be considered valid.\n * \n * @param agent\n * @param secrets\n * @param activity\n * @return true if secrets were sent\n */",
"public",
"static",
"boolean",
"sendSecrets",
"(",
"OnlineSyncAgent",
"agent",
",",
"ArrayList",
"<",
"Secret",
">",
"secrets",
",",
"SecretsListActivity",
"activity",
")",
"{",
"requestAgent",
"=",
"agent",
";",
"responseActivity",
"=",
"activity",
";",
"responseKey",
"=",
"generateResponseKey",
"(",
")",
";",
"try",
"{",
"Intent",
"secretsIntent",
"=",
"new",
"Intent",
"(",
"SYNC",
")",
";",
"secretsIntent",
".",
"setPackage",
"(",
"agent",
".",
"getClassId",
"(",
")",
")",
";",
"secretsIntent",
".",
"putExtra",
"(",
"INTENT_RESPONSEKEY",
",",
"OnlineAgentManager",
".",
"responseKey",
")",
";",
"String",
"secretString",
"=",
"FileUtils",
".",
"toJSONSecrets",
"(",
"secrets",
")",
".",
"toString",
"(",
")",
";",
"secretsIntent",
".",
"putExtra",
"(",
"INTENT_SECRETS",
",",
"secretString",
")",
";",
"activity",
".",
"sendBroadcast",
"(",
"secretsIntent",
",",
"SECRETS_PERMISSION",
")",
";",
"Log",
".",
"d",
"(",
"LOG_TAG",
",",
"\"",
"Secrets sent to OSA ",
"\"",
"+",
"agent",
".",
"getClassId",
"(",
")",
")",
";",
"active",
"=",
"true",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"Log",
".",
"e",
"(",
"LOG_TAG",
",",
"\"",
"Error sending secrets to OSA",
"\"",
",",
"e",
")",
";",
"}",
"return",
"false",
";",
"}",
"/**\n * Test for active request\n * @return true if active\n */",
"public",
"static",
"boolean",
"isActive",
"(",
")",
"{",
"return",
"active",
";",
"}",
"/**\n * Cancel the active request\n */",
"public",
"static",
"void",
"cancel",
"(",
")",
"{",
"OnlineAgentManager",
".",
"active",
"=",
"false",
";",
"Intent",
"secretsIntent",
"=",
"new",
"Intent",
"(",
"SYNC_CANCEL",
")",
";",
"secretsIntent",
".",
"setPackage",
"(",
"requestAgent",
".",
"getClassId",
"(",
")",
")",
";",
"responseActivity",
".",
"sendBroadcast",
"(",
"secretsIntent",
",",
"SECRETS_PERMISSION",
")",
";",
"}",
"/* Helper functions */",
"/**\n * Add, update or delete the current secrets in the given collection.\n *\n * Assumes that the collection sort sequences are the same.\n * \n * @param secrets \n * - target secrets collection\n * @param changedSecrets\n * - added, changed or deleted secrets\n */",
"public",
"static",
"void",
"syncSecrets",
"(",
"ArrayList",
"<",
"Secret",
">",
"secrets",
",",
"ArrayList",
"<",
"Secret",
">",
"changedSecrets",
")",
"{",
"for",
"(",
"Secret",
"changedSecret",
":",
"changedSecrets",
")",
"{",
"boolean",
"done",
"=",
"false",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"secrets",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"Secret",
"existingSecret",
"=",
"secrets",
".",
"get",
"(",
"i",
")",
";",
"int",
"compare",
"=",
"changedSecret",
".",
"compareTo",
"(",
"existingSecret",
")",
";",
"if",
"(",
"compare",
"<",
"0",
"&&",
"!",
"changedSecret",
".",
"isDeleted",
"(",
")",
")",
"{",
"secrets",
".",
"add",
"(",
"i",
",",
"changedSecret",
")",
";",
"done",
"=",
"true",
";",
"Log",
".",
"d",
"(",
"LOG_TAG",
",",
"\"",
"syncSecrets: added '",
"\"",
"+",
"changedSecret",
".",
"getDescription",
"(",
")",
"+",
"\"",
"'",
"\"",
")",
";",
"break",
";",
"}",
"else",
"if",
"(",
"compare",
"==",
"0",
")",
"{",
"if",
"(",
"changedSecret",
".",
"isDeleted",
"(",
")",
")",
"{",
"secrets",
".",
"remove",
"(",
"existingSecret",
")",
";",
"Log",
".",
"d",
"(",
"LOG_TAG",
",",
"\"",
"syncSecrets: removed '",
"\"",
"+",
"changedSecret",
".",
"getDescription",
"(",
")",
"+",
"\"",
"'",
"\"",
")",
";",
"}",
"else",
"{",
"existingSecret",
".",
"update",
"(",
"changedSecret",
",",
"LogEntry",
".",
"SYNCED",
")",
";",
"Log",
".",
"d",
"(",
"LOG_TAG",
",",
"\"",
"syncSecrets: updated '",
"\"",
"+",
"changedSecret",
".",
"getDescription",
"(",
")",
"+",
"\"",
"'",
"\"",
")",
";",
"}",
"done",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"done",
"&&",
"!",
"changedSecret",
".",
"isDeleted",
"(",
")",
")",
"secrets",
".",
"add",
"(",
"changedSecret",
")",
";",
"Log",
".",
"d",
"(",
"LOG_TAG",
",",
"\"",
"syncSecrets: added '",
"\"",
"+",
"changedSecret",
".",
"getDescription",
"(",
")",
"+",
"\"",
"'",
"\"",
")",
";",
"}",
"}",
"}"
] |
Provides support for Online Sync Agents.
|
[
"Provides",
"support",
"for",
"Online",
"Sync",
"Agents",
"."
] |
[
"// broadcast ACTIONS",
"// for the current request",
"// handle roll call response",
"// invalid info, so do not add it",
"// handle sync response",
"// change response key",
"// is a response expected?",
"// does the key match?",
"// if request not cancelled",
"// ignore the exception, false will be returned below"
] |
[
{
"param": "BroadcastReceiver",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "BroadcastReceiver",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 21
| 2,095
| 156
|
a5894bb70491acb72bc55c8f80930c36b0a37385
|
gravitee-io/gravitee-ui-components
|
src/atoms/gv-link.js
|
[
"ECL-2.0",
"Apache-2.0"
] |
JavaScript
|
GvLink
|
/**
* A link
*
* ## Details
* * has @theme facet
*
* @fires gv-link:click - Custom click event from inner link element
*
* @slot - The content of the link (text or HTML)
*
* @attr {Boolean} active - set if link is active
* @attr {String} path - link path
* @attr {String} title - link title
* @attr {String} target - link target
* @attr {String} help - help text left between parentheses
*
* @cssprop {Length} [--gv-link-a--pv=15px] - Vertical padding for the inner <a> tag
* @cssprop {Length} [--gv-link-a--ph=15px] - Horizontal padding for the inner <a> tag
* @cssprop {Color} [--gv-link--c=var(--gv-theme-font-color-dark, #262626)] - Color
* @cssprop {Color} [--gv-link-active--c=var(--gv-theme-font-color-light, #ffffff)] - Active color
* @cssprop {Color} [--gv-link--bgc=transparent] - Background color
* @cssprop {Color} [--gv-link-active--bgc=var(--gv-theme-color-dark, #28444f)] - Active background color
* @cssprop {Color} [--gv-link-active--bdc=none] - Active border color
* @cssprop {String} [--gv-link-active--bds=none] - Active border style
* @cssprop {Length} [--gv-link-active--bdw=none] - Active border width
* @cssprop {String} [--gv-link--ta=center] - Text align
* @cssprop {String} [--gv-link--td=none] - Text decoration
* @cssprop {String} [--gv-link--tsh=none]- Text shadow
* @cssprop {Length} [--gv-link-icon--s=24px] - Height and icon width
*/
|
A link
Details
has @theme facet
@fires gv-link:click - Custom click event from inner link element
@slot - The content of the link (text or HTML)
|
[
"A",
"link",
"Details",
"has",
"@theme",
"facet",
"@fires",
"gv",
"-",
"link",
":",
"click",
"-",
"Custom",
"click",
"event",
"from",
"inner",
"link",
"element",
"@slot",
"-",
"The",
"content",
"of",
"the",
"link",
"(",
"text",
"or",
"HTML",
")"
] |
class GvLink extends LitElement {
static get properties() {
return {
active: { type: Boolean, reflect: true },
icon: { type: String },
path: { type: String },
title: { type: String },
target: { type: String },
_title: { type: String, attribute: false },
help: { type: String },
skeleton: { type: Boolean },
small: { type: Boolean },
};
}
static get styles() {
return [
link,
// language=css
css`
:host {
display: inline-flex;
vertical-align: middle;
--gv-icon--s: var(--gv-link-icon--s, 24px);
--link-active--c: var(--gv-link-active--c, var(--gv-theme-font-color-light, #ffffff));
--link--c: var(--gv-link--c, var(--gv-theme-font-color-dark, #262626));
--pv: var(--gv-link-a--pv, 15px);
--ph: var(--gv-link-a--ph, 15px);
}
*,
*:before,
*:after {
box-sizing: border-box;
}
a {
opacity: 1;
padding: var(--pv) var(--ph);
color: var(--link--c);
background-color: var(--gv-link--bgc, transparent);
width: 100%;
display: inline-flex;
align-content: center;
text-align: var(--gv-link--ta, center);
text-shadow: var(--gv-link--tsh, none);
border-color: var(--gv-link--bgc, transparent);
border-style: var(--gv-link-active--bds, none);
border-width: var(--gv-link-active--bdw, none);
}
a > * {
align-self: center;
}
.active {
color: var(--link-active--c);
background-color: var(--gv-link-active--bgc, var(--gv-theme-color-dark, #28444f));
border-color: var(--gv-link-active--bdc, none);
}
.link.active:hover {
opacity: 1;
}
a span,
a gv-icon {
align-self: center;
}
a span {
flex: 1;
align-self: center;
white-space: nowrap;
margin: 0.3rem 0.5rem;
text-decoration: var(--gv-link--td, none);
text-overflow: ellipsis;
overflow: hidden;
}
a.small span {
margin: 0.3rem 0;
width: 0;
visibility: hidden;
}
.help {
margin: 0 0.2rem;
opacity: 0.5;
font-size: var(--gv-theme-font-size-xs, 10px);
}
.help::before {
content: '(';
}
.help::after {
content: ')';
}
.skeleton {
min-width: 100px;
margin: 0 0.2rem;
opacity: 0.5;
}
`,
skeleton,
];
}
async _onClick(e) {
e.preventDefault();
dispatchCustomEvent(this, 'click', {
active: this.active,
icon: this.icon,
path: this.path,
title: this._title,
target: this.target,
});
}
set title(value) {
Promise.resolve(value)
.then((title) => {
this._title = title;
})
.catch((e) => {});
}
render() {
const classes = {
active: this.active,
link: true,
skeleton: this.skeleton,
small: this.small,
};
const iconStyle = this.active
? { '--gv-icon--c': 'var(--link-active--c)', '--gv-icon-opacity--c': 'var(--link-active--c)' }
: { '--gv-icon--c': 'var(--link--c)', '--gv-icon-opacity--c': 'var(--link--c)' };
return html`
<a
@click=${this._onClick}
class="${classMap(classes)}"
.href="${ifDefined(this.path)}"
.target="${ifDefined(this.target)}"
?title="${until(this._title, '')}"
>
${this.icon ? html`<gv-icon shape=${this.icon} style=${styleMap(iconStyle)}></gv-icon>` : ''}
<span>${until(this._title, '')}${this.help ? html`<span class="help">${until(this.help, '')}</span>` : ''}</span>
</a>
`;
}
}
|
[
"class",
"GvLink",
"extends",
"LitElement",
"{",
"static",
"get",
"properties",
"(",
")",
"{",
"return",
"{",
"active",
":",
"{",
"type",
":",
"Boolean",
",",
"reflect",
":",
"true",
"}",
",",
"icon",
":",
"{",
"type",
":",
"String",
"}",
",",
"path",
":",
"{",
"type",
":",
"String",
"}",
",",
"title",
":",
"{",
"type",
":",
"String",
"}",
",",
"target",
":",
"{",
"type",
":",
"String",
"}",
",",
"_title",
":",
"{",
"type",
":",
"String",
",",
"attribute",
":",
"false",
"}",
",",
"help",
":",
"{",
"type",
":",
"String",
"}",
",",
"skeleton",
":",
"{",
"type",
":",
"Boolean",
"}",
",",
"small",
":",
"{",
"type",
":",
"Boolean",
"}",
",",
"}",
";",
"}",
"static",
"get",
"styles",
"(",
")",
"{",
"return",
"[",
"link",
",",
"css",
"`",
"`",
",",
"skeleton",
",",
"]",
";",
"}",
"async",
"_onClick",
"(",
"e",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"dispatchCustomEvent",
"(",
"this",
",",
"'click'",
",",
"{",
"active",
":",
"this",
".",
"active",
",",
"icon",
":",
"this",
".",
"icon",
",",
"path",
":",
"this",
".",
"path",
",",
"title",
":",
"this",
".",
"_title",
",",
"target",
":",
"this",
".",
"target",
",",
"}",
")",
";",
"}",
"set",
"title",
"(",
"value",
")",
"{",
"Promise",
".",
"resolve",
"(",
"value",
")",
".",
"then",
"(",
"(",
"title",
")",
"=>",
"{",
"this",
".",
"_title",
"=",
"title",
";",
"}",
")",
".",
"catch",
"(",
"(",
"e",
")",
"=>",
"{",
"}",
")",
";",
"}",
"render",
"(",
")",
"{",
"const",
"classes",
"=",
"{",
"active",
":",
"this",
".",
"active",
",",
"link",
":",
"true",
",",
"skeleton",
":",
"this",
".",
"skeleton",
",",
"small",
":",
"this",
".",
"small",
",",
"}",
";",
"const",
"iconStyle",
"=",
"this",
".",
"active",
"?",
"{",
"'--gv-icon--c'",
":",
"'var(--link-active--c)'",
",",
"'--gv-icon-opacity--c'",
":",
"'var(--link-active--c)'",
"}",
":",
"{",
"'--gv-icon--c'",
":",
"'var(--link--c)'",
",",
"'--gv-icon-opacity--c'",
":",
"'var(--link--c)'",
"}",
";",
"return",
"html",
"`",
"${",
"this",
".",
"_onClick",
"}",
"${",
"classMap",
"(",
"classes",
")",
"}",
"${",
"ifDefined",
"(",
"this",
".",
"path",
")",
"}",
"${",
"ifDefined",
"(",
"this",
".",
"target",
")",
"}",
"${",
"until",
"(",
"this",
".",
"_title",
",",
"''",
")",
"}",
"${",
"this",
".",
"icon",
"?",
"html",
"`",
"${",
"this",
".",
"icon",
"}",
"${",
"styleMap",
"(",
"iconStyle",
")",
"}",
"`",
":",
"''",
"}",
"${",
"until",
"(",
"this",
".",
"_title",
",",
"''",
")",
"}",
"${",
"this",
".",
"help",
"?",
"html",
"`",
"${",
"until",
"(",
"this",
".",
"help",
",",
"''",
")",
"}",
"`",
":",
"''",
"}",
"`",
";",
"}",
"}"
] |
A link
## Details
* has @theme facet
|
[
"A",
"link",
"##",
"Details",
"*",
"has",
"@theme",
"facet"
] |
[
"// language=css"
] |
[
{
"param": "LitElement",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "LitElement",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 16
| 1,042
| 433
|
0afa90ecd0ef6ffa65860eb076989edfbaec094d
|
dotchetter/CoronaBot
|
source/coronafeatureclient.py
|
[
"MIT"
] |
Python
|
ApiHandle
|
Call api and parse output to JSON. Returns cache
unless the data over 2 hours old by default as to not
overload the api service. The object calls the api upon
instantiation, and will automatically cache the response.
:uri:
URI for the REST api
:_last_api_call:
datetime stamp for when data was most recently fetched
from the api, used to return cache within the defined
span upon construction, minmum 0 hours.
:_wait_time:
seconds calculated by the defined standby_hours parameter
:_cached_response:
last response received by the API
:_headers_:
dictionary which can be added to with the add_header method.
Contains headers which will be used upon a request with the
fetch() call.
|
Call api and parse output to JSON. Returns cache
unless the data over 2 hours old by default as to not
overload the api service. The object calls the api upon
instantiation, and will automatically cache the response.
|
[
"Call",
"api",
"and",
"parse",
"output",
"to",
"JSON",
".",
"Returns",
"cache",
"unless",
"the",
"data",
"over",
"2",
"hours",
"old",
"by",
"default",
"as",
"to",
"not",
"overload",
"the",
"api",
"service",
".",
"The",
"object",
"calls",
"the",
"api",
"upon",
"instantiation",
"and",
"will",
"automatically",
"cache",
"the",
"response",
"."
] |
class ApiHandle:
"""
Call api and parse output to JSON. Returns cache
unless the data over 2 hours old by default as to not
overload the api service. The object calls the api upon
instantiation, and will automatically cache the response.
:uri:
URI for the REST api
:_last_api_call:
datetime stamp for when data was most recently fetched
from the api, used to return cache within the defined
span upon construction, minmum 0 hours.
:_wait_time:
seconds calculated by the defined standby_hours parameter
:_cached_response:
last response received by the API
:_headers_:
dictionary which can be added to with the add_header method.
Contains headers which will be used upon a request with the
fetch() call.
"""
def __init__(self, uri: str, standby_hours = 2):
self.uri: str = uri
self.last_api_call: datetime = None
self._wait_time = (60 * 60) * standby_hours
self._cached_response = None
self._cached_response: dict = None
self._headers = {}
@property
def uri(self) -> str:
return self._uri
@uri.setter
def uri(self, uri: str) -> None:
if uri.startswith('https'):
self._uri = uri
else:
raise AttributeError('Got "http", expected "https"')
@property
def last_api_call(self) -> str:
"""
Return property in string format for easy readability
for users.
"""
return self._last_api_call.strftime("%Y-%m-%d %H:%M")
@last_api_call.setter
def last_api_call(self, val: datetime) -> None:
self._last_api_call = val
def add_header(self, key: str, value: str) -> None:
"""
Allows this object to add HTML headers for the
request. The method is meant to be used prior to
a call for an API which requires headers to work.
:param key:
str
the key in the header, example: 'User-Agent'
:param vaue:
str
The value behind said key.
:returns:
None
"""
self._headers[key] = value
def fetch(self) -> dict:
"""
Call the api and mutate the instance variable _cached_response
at the same time, if either none prior were made or the time
expired and it needs to be refreshed.
:returns:
dict
"""
if self._cached_response:
seconds_since_last_call = (datetime.now() - self._last_api_call).seconds
if seconds_since_last_call < self._wait_time:
return self._cached_response
try:
response = requests.get(self.uri, headers = self._headers).json()
except Exception:
raise
self._cached_response = response
self.last_api_call = datetime.now()
return response
|
[
"class",
"ApiHandle",
":",
"def",
"__init__",
"(",
"self",
",",
"uri",
":",
"str",
",",
"standby_hours",
"=",
"2",
")",
":",
"self",
".",
"uri",
":",
"str",
"=",
"uri",
"self",
".",
"last_api_call",
":",
"datetime",
"=",
"None",
"self",
".",
"_wait_time",
"=",
"(",
"60",
"*",
"60",
")",
"*",
"standby_hours",
"self",
".",
"_cached_response",
"=",
"None",
"self",
".",
"_cached_response",
":",
"dict",
"=",
"None",
"self",
".",
"_headers",
"=",
"{",
"}",
"@",
"property",
"def",
"uri",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_uri",
"@",
"uri",
".",
"setter",
"def",
"uri",
"(",
"self",
",",
"uri",
":",
"str",
")",
"->",
"None",
":",
"if",
"uri",
".",
"startswith",
"(",
"'https'",
")",
":",
"self",
".",
"_uri",
"=",
"uri",
"else",
":",
"raise",
"AttributeError",
"(",
"'Got \"http\", expected \"https\"'",
")",
"@",
"property",
"def",
"last_api_call",
"(",
"self",
")",
"->",
"str",
":",
"\"\"\"\n\t\tReturn property in string format for easy readability\n\t\tfor users.\n\t\t\"\"\"",
"return",
"self",
".",
"_last_api_call",
".",
"strftime",
"(",
"\"%Y-%m-%d %H:%M\"",
")",
"@",
"last_api_call",
".",
"setter",
"def",
"last_api_call",
"(",
"self",
",",
"val",
":",
"datetime",
")",
"->",
"None",
":",
"self",
".",
"_last_api_call",
"=",
"val",
"def",
"add_header",
"(",
"self",
",",
"key",
":",
"str",
",",
"value",
":",
"str",
")",
"->",
"None",
":",
"\"\"\"\n\t\tAllows this object to add HTML headers for the \n\t\trequest. The method is meant to be used prior to\n\t\ta call for an API which requires headers to work.\n\n\t\t:param key:\n\t\t\tstr\n\t\t\tthe key in the header, example: 'User-Agent'\n\t\t:param vaue:\n\t\t\tstr\n\t\t\tThe value behind said key.\n\t\t:returns:\n\t\t\tNone\n\t\t\"\"\"",
"self",
".",
"_headers",
"[",
"key",
"]",
"=",
"value",
"def",
"fetch",
"(",
"self",
")",
"->",
"dict",
":",
"\"\"\"\n\t\tCall the api and mutate the instance variable _cached_response\n\t\tat the same time, if either none prior were made or the time \n\t\texpired and it needs to be refreshed. \n\n\t\t:returns:\n\t\t\tdict\n\t\t\"\"\"",
"if",
"self",
".",
"_cached_response",
":",
"seconds_since_last_call",
"=",
"(",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"_last_api_call",
")",
".",
"seconds",
"if",
"seconds_since_last_call",
"<",
"self",
".",
"_wait_time",
":",
"return",
"self",
".",
"_cached_response",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"uri",
",",
"headers",
"=",
"self",
".",
"_headers",
")",
".",
"json",
"(",
")",
"except",
"Exception",
":",
"raise",
"self",
".",
"_cached_response",
"=",
"response",
"self",
".",
"last_api_call",
"=",
"datetime",
".",
"now",
"(",
")",
"return",
"response"
] |
Call api and parse output to JSON.
|
[
"Call",
"api",
"and",
"parse",
"output",
"to",
"JSON",
"."
] |
[
"\"\"\"\n\tCall api and parse output to JSON. Returns cache \n\tunless the data over 2 hours old by default as to not \n\toverload the api service. The object calls the api upon\n\tinstantiation, and will automatically cache the response.\n\n\t:uri:\n\t\tURI for the REST api\n\n\t:_last_api_call:\n\t\tdatetime stamp for when data was most recently fetched\n\t\tfrom the api, used to return cache within the defined\n\t\tspan upon construction, minmum 0 hours.\n\n\t:_wait_time:\n\t\tseconds calculated by the defined standby_hours parameter\n\n\t:_cached_response:\n\t\tlast response received by the API\n\n\t:_headers_:\n\t\tdictionary which can be added to with the add_header method.\n\t\tContains headers which will be used upon a request with the \n\t\tfetch() call.\n\t\"\"\"",
"\"\"\"\n\t\tReturn property in string format for easy readability\n\t\tfor users.\n\t\t\"\"\"",
"\"\"\"\n\t\tAllows this object to add HTML headers for the \n\t\trequest. The method is meant to be used prior to\n\t\ta call for an API which requires headers to work.\n\n\t\t:param key:\n\t\t\tstr\n\t\t\tthe key in the header, example: 'User-Agent'\n\t\t:param vaue:\n\t\t\tstr\n\t\t\tThe value behind said key.\n\t\t:returns:\n\t\t\tNone\n\t\t\"\"\"",
"\"\"\"\n\t\tCall the api and mutate the instance variable _cached_response\n\t\tat the same time, if either none prior were made or the time \n\t\texpired and it needs to be refreshed. \n\n\t\t:returns:\n\t\t\tdict\n\t\t\"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "uri",
"docstring": "URI for the REST api",
"docstring_tokens": [
"URI",
"for",
"the",
"REST",
"api"
]
},
{
"identifier": "_last_api_call",
"docstring": "datetime stamp for when data was most recently fetched\nfrom the api, used to return cache within the defined\nspan upon construction, minmum 0 hours.",
"docstring_tokens": [
"datetime",
"stamp",
"for",
"when",
"data",
"was",
"most",
"recently",
"fetched",
"from",
"the",
"api",
"used",
"to",
"return",
"cache",
"within",
"the",
"defined",
"span",
"upon",
"construction",
"minmum",
"0",
"hours",
"."
]
},
{
"identifier": "_wait_time",
"docstring": "seconds calculated by the defined standby_hours parameter",
"docstring_tokens": [
"seconds",
"calculated",
"by",
"the",
"defined",
"standby_hours",
"parameter"
]
},
{
"identifier": "_cached_response",
"docstring": "last response received by the API",
"docstring_tokens": [
"last",
"response",
"received",
"by",
"the",
"API"
]
},
{
"identifier": "_headers_",
"docstring": "dictionary which can be added to with the add_header method.\nContains headers which will be used upon a request with the\nfetch() call.",
"docstring_tokens": [
"dictionary",
"which",
"can",
"be",
"added",
"to",
"with",
"the",
"add_header",
"method",
".",
"Contains",
"headers",
"which",
"will",
"be",
"used",
"upon",
"a",
"request",
"with",
"the",
"fetch",
"()",
"call",
"."
]
}
]
}
| false
| 15
| 672
| 178
|
4d3e7db2b90e7e8083492e147b617f0cc1076575
|
AlexHamlet/RevitPlayground
|
RevitUtils/KdTree2D.cs
|
[
"MIT"
] |
C#
|
KdTree2D
|
/// <summary>
/// A class used to find the closest point in a 2D Space
///
/// It is often useful to be able to find the closes element in 2D space. This class is an optimized way to do that.
///
/// Note for beginners: If you look for an element contained in the tree, it will git you that element. Nothing
/// can be closer than itself.
/// </summary>
/// <typeparam name="T"></typeparam>
|
A class used to find the closest point in a 2D Space
It is often useful to be able to find the closes element in 2D space. This class is an optimized way to do that.
Note for beginners: If you look for an element contained in the tree, it will git you that element. Nothing
can be closer than itself.
|
[
"A",
"class",
"used",
"to",
"find",
"the",
"closest",
"point",
"in",
"a",
"2D",
"Space",
"It",
"is",
"often",
"useful",
"to",
"be",
"able",
"to",
"find",
"the",
"closes",
"element",
"in",
"2D",
"space",
".",
"This",
"class",
"is",
"an",
"optimized",
"way",
"to",
"do",
"that",
".",
"Note",
"for",
"beginners",
":",
"If",
"you",
"look",
"for",
"an",
"element",
"contained",
"in",
"the",
"tree",
"it",
"will",
"git",
"you",
"that",
"element",
".",
"Nothing",
"can",
"be",
"closer",
"than",
"itself",
"."
] |
public class KdTree2D<T>
{
private Node head;
public int Count { get; private set; }
public KdTree2D()
{
Count = 0;
}
public void Put(T data, Point2D position)
{
if (position == null)
throw new ArgumentNullException("position");
head = Put(head, data, position, Rectangle.Infinite, true);
Count++;
}
private Node Put(Node current, T Data, Point2D position, Rectangle rect, bool xy)
{
if (current == null)
return new Node(Data, position, rect);
if(xy)
{
if (position.X < current.Position.X)
{
current.less = Put(current.less, Data, position,
new Rectangle(rect.MinX, rect.MinY, current.Position.X, rect.MaxY)
, !xy);
}
else
{
current.more = Put(current.more, Data, position,
new Rectangle(current.Position.X, rect.MinY, rect.MaxX, rect.MaxY)
, !xy);
}
}
else
{
if (position.Y < current.Position.Y)
{
current.less = Put(current.less, Data, position,
new Rectangle(rect.MinX, rect.MinY, rect.MaxX, current.Position.Y)
, !xy);
}
else
{
current.more = Put(current.more, Data, position,
new Rectangle(rect.MinX, current.Position.Y, rect.MaxX, rect.MaxY)
, !xy);
}
}
return current;
}
public T Get(Point3D point)
{
return Get(head, point, true);
}
private T Get(Node current, Point3D position, bool xy)
{
if (current == null)
return default(T);
if (current.Position.Equals(position))
return current.Data;
if (xy)
{
if (position.X < current.Position.X)
{
return Get(current.less, position, !xy);
}
else
{
return Get(current.less, position, !xy);
}
}
else
{
if (position.Y < current.Position.Y)
{
return Get(current.less, position, !xy);
}
else
{
return Get(current.less, position, !xy);
}
}
}
public T Nearest(Point2D point)
{
if (Count == 0)
throw new InvalidOperationException("Tree has no elements");
if (point == null)
throw new ArgumentNullException("point");
Node champ = head;
Nearest(head, point, true, ref champ);
return champ.Data;
}
private void Nearest(Node current, Point2D position, bool xy, ref Node nearest)
{
if (current == null)
return;
if (nearest.Position.DistTo(position) <= position.DistTo(current.RectPrism))
return;
if (current.Position.DistTo(position) < nearest.Position.DistTo(position))
nearest = current;
if (xy)
{
if (position.X < current.Position.X)
{
Nearest(current.less, position, !xy, ref nearest);
Nearest(current.more, position, !xy, ref nearest);
}
else
{
Nearest(current.more, position, !xy, ref nearest);
Nearest(current.less, position, !xy, ref nearest);
}
}
else
{
if (position.Y < current.Position.Y)
{
Nearest(current.less, position, !xy, ref nearest);
Nearest(current.more, position, !xy, ref nearest);
}
else
{
Nearest(current.more, position, !xy, ref nearest);
Nearest(current.less, position, !xy, ref nearest);
}
}
}
private class Node
{
public T Data { get; }
public Rectangle RectPrism { get; }
public Point2D Position { get; }
public Node less { get; set; }
public Node more { get; set; }
public Node(T data, Point2D position, Rectangle rectPrism)
{
Data = data;
Position = position;
RectPrism = rectPrism;
}
}
}
|
[
"public",
"class",
"KdTree2D",
"<",
"T",
">",
"{",
"private",
"Node",
"head",
";",
"public",
"int",
"Count",
"{",
"get",
";",
"private",
"set",
";",
"}",
"public",
"KdTree2D",
"(",
")",
"{",
"Count",
"=",
"0",
";",
"}",
"public",
"void",
"Put",
"(",
"T",
"data",
",",
"Point2D",
"position",
")",
"{",
"if",
"(",
"position",
"==",
"null",
")",
"throw",
"new",
"ArgumentNullException",
"(",
"\"",
"position",
"\"",
")",
";",
"head",
"=",
"Put",
"(",
"head",
",",
"data",
",",
"position",
",",
"Rectangle",
".",
"Infinite",
",",
"true",
")",
";",
"Count",
"++",
";",
"}",
"private",
"Node",
"Put",
"(",
"Node",
"current",
",",
"T",
"Data",
",",
"Point2D",
"position",
",",
"Rectangle",
"rect",
",",
"bool",
"xy",
")",
"{",
"if",
"(",
"current",
"==",
"null",
")",
"return",
"new",
"Node",
"(",
"Data",
",",
"position",
",",
"rect",
")",
";",
"if",
"(",
"xy",
")",
"{",
"if",
"(",
"position",
".",
"X",
"<",
"current",
".",
"Position",
".",
"X",
")",
"{",
"current",
".",
"less",
"=",
"Put",
"(",
"current",
".",
"less",
",",
"Data",
",",
"position",
",",
"new",
"Rectangle",
"(",
"rect",
".",
"MinX",
",",
"rect",
".",
"MinY",
",",
"current",
".",
"Position",
".",
"X",
",",
"rect",
".",
"MaxY",
")",
",",
"!",
"xy",
")",
";",
"}",
"else",
"{",
"current",
".",
"more",
"=",
"Put",
"(",
"current",
".",
"more",
",",
"Data",
",",
"position",
",",
"new",
"Rectangle",
"(",
"current",
".",
"Position",
".",
"X",
",",
"rect",
".",
"MinY",
",",
"rect",
".",
"MaxX",
",",
"rect",
".",
"MaxY",
")",
",",
"!",
"xy",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"position",
".",
"Y",
"<",
"current",
".",
"Position",
".",
"Y",
")",
"{",
"current",
".",
"less",
"=",
"Put",
"(",
"current",
".",
"less",
",",
"Data",
",",
"position",
",",
"new",
"Rectangle",
"(",
"rect",
".",
"MinX",
",",
"rect",
".",
"MinY",
",",
"rect",
".",
"MaxX",
",",
"current",
".",
"Position",
".",
"Y",
")",
",",
"!",
"xy",
")",
";",
"}",
"else",
"{",
"current",
".",
"more",
"=",
"Put",
"(",
"current",
".",
"more",
",",
"Data",
",",
"position",
",",
"new",
"Rectangle",
"(",
"rect",
".",
"MinX",
",",
"current",
".",
"Position",
".",
"Y",
",",
"rect",
".",
"MaxX",
",",
"rect",
".",
"MaxY",
")",
",",
"!",
"xy",
")",
";",
"}",
"}",
"return",
"current",
";",
"}",
"public",
"T",
"Get",
"(",
"Point3D",
"point",
")",
"{",
"return",
"Get",
"(",
"head",
",",
"point",
",",
"true",
")",
";",
"}",
"private",
"T",
"Get",
"(",
"Node",
"current",
",",
"Point3D",
"position",
",",
"bool",
"xy",
")",
"{",
"if",
"(",
"current",
"==",
"null",
")",
"return",
"default",
"(",
"T",
")",
";",
"if",
"(",
"current",
".",
"Position",
".",
"Equals",
"(",
"position",
")",
")",
"return",
"current",
".",
"Data",
";",
"if",
"(",
"xy",
")",
"{",
"if",
"(",
"position",
".",
"X",
"<",
"current",
".",
"Position",
".",
"X",
")",
"{",
"return",
"Get",
"(",
"current",
".",
"less",
",",
"position",
",",
"!",
"xy",
")",
";",
"}",
"else",
"{",
"return",
"Get",
"(",
"current",
".",
"less",
",",
"position",
",",
"!",
"xy",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"position",
".",
"Y",
"<",
"current",
".",
"Position",
".",
"Y",
")",
"{",
"return",
"Get",
"(",
"current",
".",
"less",
",",
"position",
",",
"!",
"xy",
")",
";",
"}",
"else",
"{",
"return",
"Get",
"(",
"current",
".",
"less",
",",
"position",
",",
"!",
"xy",
")",
";",
"}",
"}",
"}",
"public",
"T",
"Nearest",
"(",
"Point2D",
"point",
")",
"{",
"if",
"(",
"Count",
"==",
"0",
")",
"throw",
"new",
"InvalidOperationException",
"(",
"\"",
"Tree has no elements",
"\"",
")",
";",
"if",
"(",
"point",
"==",
"null",
")",
"throw",
"new",
"ArgumentNullException",
"(",
"\"",
"point",
"\"",
")",
";",
"Node",
"champ",
"=",
"head",
";",
"Nearest",
"(",
"head",
",",
"point",
",",
"true",
",",
"ref",
"champ",
")",
";",
"return",
"champ",
".",
"Data",
";",
"}",
"private",
"void",
"Nearest",
"(",
"Node",
"current",
",",
"Point2D",
"position",
",",
"bool",
"xy",
",",
"ref",
"Node",
"nearest",
")",
"{",
"if",
"(",
"current",
"==",
"null",
")",
"return",
";",
"if",
"(",
"nearest",
".",
"Position",
".",
"DistTo",
"(",
"position",
")",
"<=",
"position",
".",
"DistTo",
"(",
"current",
".",
"RectPrism",
")",
")",
"return",
";",
"if",
"(",
"current",
".",
"Position",
".",
"DistTo",
"(",
"position",
")",
"<",
"nearest",
".",
"Position",
".",
"DistTo",
"(",
"position",
")",
")",
"nearest",
"=",
"current",
";",
"if",
"(",
"xy",
")",
"{",
"if",
"(",
"position",
".",
"X",
"<",
"current",
".",
"Position",
".",
"X",
")",
"{",
"Nearest",
"(",
"current",
".",
"less",
",",
"position",
",",
"!",
"xy",
",",
"ref",
"nearest",
")",
";",
"Nearest",
"(",
"current",
".",
"more",
",",
"position",
",",
"!",
"xy",
",",
"ref",
"nearest",
")",
";",
"}",
"else",
"{",
"Nearest",
"(",
"current",
".",
"more",
",",
"position",
",",
"!",
"xy",
",",
"ref",
"nearest",
")",
";",
"Nearest",
"(",
"current",
".",
"less",
",",
"position",
",",
"!",
"xy",
",",
"ref",
"nearest",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"position",
".",
"Y",
"<",
"current",
".",
"Position",
".",
"Y",
")",
"{",
"Nearest",
"(",
"current",
".",
"less",
",",
"position",
",",
"!",
"xy",
",",
"ref",
"nearest",
")",
";",
"Nearest",
"(",
"current",
".",
"more",
",",
"position",
",",
"!",
"xy",
",",
"ref",
"nearest",
")",
";",
"}",
"else",
"{",
"Nearest",
"(",
"current",
".",
"more",
",",
"position",
",",
"!",
"xy",
",",
"ref",
"nearest",
")",
";",
"Nearest",
"(",
"current",
".",
"less",
",",
"position",
",",
"!",
"xy",
",",
"ref",
"nearest",
")",
";",
"}",
"}",
"}",
"private",
"class",
"Node",
"{",
"public",
"T",
"Data",
"{",
"get",
";",
"}",
"public",
"Rectangle",
"RectPrism",
"{",
"get",
";",
"}",
"public",
"Point2D",
"Position",
"{",
"get",
";",
"}",
"public",
"Node",
"less",
"{",
"get",
";",
"set",
";",
"}",
"public",
"Node",
"more",
"{",
"get",
";",
"set",
";",
"}",
"public",
"Node",
"(",
"T",
"data",
",",
"Point2D",
"position",
",",
"Rectangle",
"rectPrism",
")",
"{",
"Data",
"=",
"data",
";",
"Position",
"=",
"position",
";",
"RectPrism",
"=",
"rectPrism",
";",
"}",
"}",
"}"
] |
A class used to find the closest point in a 2D Space
|
[
"A",
"class",
"used",
"to",
"find",
"the",
"closest",
"point",
"in",
"a",
"2D",
"Space"
] |
[
"/// <summary>",
"/// A count of the elements contained in the KdTree",
"/// </summary>",
"/// <summary>",
"/// Constructor for KdTree2D",
"/// </summary>",
"/// <summary>",
"/// Place Data on the tree at the specified position.",
"/// </summary>",
"/// <param name=\"data\">Data to store</param>",
"/// <param name=\"position\">Position associated with the data</param>",
"//Position is requried to place data",
"/// <summary>",
"/// Recursive Put method. Traverses the tree to place Data in the position corresponding with the position.",
"/// </summary>",
"/// <param name=\"current\">Current Tree node</param>",
"/// <param name=\"Data\">Data to store</param>",
"/// <param name=\"position\">Position associated with the data</param>",
"/// <param name=\"rect\">A rectangular prism used to prune and optimize searches</param>",
"/// <param name=\"xyz\">Argument checks against X(true), Y(false)</param>",
"/// <returns></returns>",
"//If node is null, the data goes here.",
"//Check X,Y, or Z",
"//Check Y",
"/// <summary>",
"/// Get the Data at the specified point",
"/// </summary>",
"/// <param name=\"point\">Point to find data at</param>",
"/// <returns>The Data at the point, returns the default value if not found</returns>",
"/// <summary>",
"/// Recursive get method",
"/// </summary>",
"/// <param name=\"current\">Current search node</param>",
"/// <param name=\"position\">Position to search for</param>",
"/// <param name=\"xyz\">Flag to check X(true), Y(false)</param>",
"/// <returns>The Data at the point, returns the default value if not found</returns>",
"//Did not find",
"//Found",
"//Search",
"//Check X,Y, or Z",
"//Check Y",
"/// <summary>",
"/// Returns the data Nearest to the given point",
"/// </summary>",
"/// <param name=\"point\">Position to search for data near</param>",
"/// <returns>The data closest to the point passed in.</returns>",
"/// <summary>",
"/// Recursive search for the nearest node",
"/// </summary>",
"/// <param name=\"current\">Current Node to search from</param>",
"/// <param name=\"position\">Position to compare to (find nearest to this point)</param>",
"/// <param name=\"xyz\">Flag to check X(true), Y(false)</param>",
"/// <param name=\"nearest\">Current closest node</param>",
"//Done checking branch",
"//Branch cannot get closer",
"//Assign new nearest",
"//Compare and recurse",
"//Check in the correct direction first",
"//Check Y",
"//Check in the correct direction first",
"/// <summary>",
"/// Private Node class. Used to store and traverse KdTree.",
"/// </summary>",
"/// <summary>",
"/// Data stored in this node",
"/// </summary>",
"/// <summary>",
"/// Rectangular Prism used to prune and optimize nearest search",
"/// </summary>",
"/// <summary>",
"/// Position associated with the data.",
"/// </summary>",
"/// <summary>",
"/// Node that compares less than the parent node for the XY flag.",
"/// </summary>",
"/// <summary>",
"/// Node that compares greater than the parent node for the XY flag.",
"/// </summary>",
"/// <summary>",
"/// Constructor for the node class",
"/// </summary>",
"/// <param name=\"data\">Data stored in the node</param>",
"/// <param name=\"position\">Position associated with the data</param>",
"/// <param name=\"rectPrism\">Rectangular prism used to prune and optimize nearest search</param>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "typeparam",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 19
| 927
| 100
|
8c4c54453183db8a6af761b3d9d70de1087a59b2
|
kddnewton/fast_camelize
|
lib/fast_camelize.rb
|
[
"MIT"
] |
Ruby
|
FastCamelize
|
# By default, FastCamelize already defines String#camelize and
# FastCamelize::camelize. In the case that we're using ActiveSupport,
# however, there is the additional functionality of defined acronyms that we
# need to account for. In this case, we're going to first allow ActiveSupport to
# do that work, then we're going to do the actual camelization.
|
By default, FastCamelize already defines String#camelize and
FastCamelize::camelize. In the case that we're using ActiveSupport,
however, there is the additional functionality of defined acronyms that we
need to account for. In this case, we're going to first allow ActiveSupport to
do that work, then we're going to do the actual camelization.
|
[
"By",
"default",
"FastCamelize",
"already",
"defines",
"String#camelize",
"and",
"FastCamelize",
"::",
"camelize",
".",
"In",
"the",
"case",
"that",
"we",
"'",
"re",
"using",
"ActiveSupport",
"however",
"there",
"is",
"the",
"additional",
"functionality",
"of",
"defined",
"acronyms",
"that",
"we",
"need",
"to",
"account",
"for",
".",
"In",
"this",
"case",
"we",
"'",
"re",
"going",
"to",
"first",
"allow",
"ActiveSupport",
"to",
"do",
"that",
"work",
"then",
"we",
"'",
"re",
"going",
"to",
"do",
"the",
"actual",
"camelization",
"."
] |
module FastCamelize
# Override ActiveSupport::Inflector::camelize to use FastCamelize::camelize.
module ActiveSupportInflectorPatch
# Disabling rubocop here so that we can directly match the implementation in
# the Rails source, so it's easier when Rails changes it.
# rubocop:disable all
def camelize(string, uppercase_first_letter = true)
# This assignment is largely just here for type checking. This module is
# always going to be included in ActiveSupport::Inflector, but rbs doesn't
# have requires_ancestor-ish support yet.
inflections = ActiveSupport::Inflector.inflections
string = string.to_s
if uppercase_first_letter
string = string.sub(/^[a-z\d]*/) { |match| inflections.acronyms[match] || match.capitalize }
else
string = string.sub(inflections.acronyms_camelize_regex) { |match| match.downcase }
end
FastCamelize.camelize(string, acronyms: inflections.acronyms)
end
# rubocop:disable all
end
# Override String#camelize if we need to get back to the original behavior
# that fast_camelize overroad.
module ActiveSupportStringPatch
def camelize(first_letter = :upper)
case first_letter
when :upper
ActiveSupport::Inflector.camelize(self, true)
when :lower
ActiveSupport::Inflector.camelize(self, false)
else
# Skipping here because Steep doesn't understand that this is going to
# be included into a class that has Kernel included.
__skip__ =
begin
raise ArgumentError, 'Invalid option, use either :upper or :lower.'
end
end
end
end
# Override ActiveSupport::Inflector::method_added so that if and when the
# camelize method gets defined, we can immediately redefine it.
module ActiveSupportDelayedPatch
def method_added(method)
FastCamelize.active_support if method == :camelize
super
end
end
# Hook into ActiveSupport::Inflector to take advantage of FastCamelize.
def self.active_support
ActiveSupport::Inflector.alias_method(:as_camelize, :camelize)
ActiveSupport::Inflector.prepend(ActiveSupportInflectorPatch)
String.prepend(ActiveSupportStringPatch)
end
end
|
[
"module",
"FastCamelize",
"module",
"ActiveSupportInflectorPatch",
"def",
"camelize",
"(",
"string",
",",
"uppercase_first_letter",
"=",
"true",
")",
"inflections",
"=",
"ActiveSupport",
"::",
"Inflector",
".",
"inflections",
"string",
"=",
"string",
".",
"to_s",
"if",
"uppercase_first_letter",
"string",
"=",
"string",
".",
"sub",
"(",
"/",
"^[a-z",
"\\d",
"]*",
"/",
")",
"{",
"|",
"match",
"|",
"inflections",
".",
"acronyms",
"[",
"match",
"]",
"||",
"match",
".",
"capitalize",
"}",
"else",
"string",
"=",
"string",
".",
"sub",
"(",
"inflections",
".",
"acronyms_camelize_regex",
")",
"{",
"|",
"match",
"|",
"match",
".",
"downcase",
"}",
"end",
"FastCamelize",
".",
"camelize",
"(",
"string",
",",
"acronyms",
":",
"inflections",
".",
"acronyms",
")",
"end",
"end",
"module",
"ActiveSupportStringPatch",
"def",
"camelize",
"(",
"first_letter",
"=",
":upper",
")",
"case",
"first_letter",
"when",
":upper",
"ActiveSupport",
"::",
"Inflector",
".",
"camelize",
"(",
"self",
",",
"true",
")",
"when",
":lower",
"ActiveSupport",
"::",
"Inflector",
".",
"camelize",
"(",
"self",
",",
"false",
")",
"else",
"__skip__",
"=",
"begin",
"raise",
"ArgumentError",
",",
"'Invalid option, use either :upper or :lower.'",
"end",
"end",
"end",
"end",
"module",
"ActiveSupportDelayedPatch",
"def",
"method_added",
"(",
"method",
")",
"FastCamelize",
".",
"active_support",
"if",
"method",
"==",
":camelize",
"super",
"end",
"end",
"def",
"self",
".",
"active_support",
"ActiveSupport",
"::",
"Inflector",
".",
"alias_method",
"(",
":as_camelize",
",",
":camelize",
")",
"ActiveSupport",
"::",
"Inflector",
".",
"prepend",
"(",
"ActiveSupportInflectorPatch",
")",
"String",
".",
"prepend",
"(",
"ActiveSupportStringPatch",
")",
"end",
"end"
] |
By default, FastCamelize already defines String#camelize and
FastCamelize::camelize.
|
[
"By",
"default",
"FastCamelize",
"already",
"defines",
"String#camelize",
"and",
"FastCamelize",
"::",
"camelize",
"."
] |
[
"# Override ActiveSupport::Inflector::camelize to use FastCamelize::camelize.",
"# Disabling rubocop here so that we can directly match the implementation in",
"# the Rails source, so it's easier when Rails changes it.",
"# rubocop:disable all",
"# This assignment is largely just here for type checking. This module is",
"# always going to be included in ActiveSupport::Inflector, but rbs doesn't",
"# have requires_ancestor-ish support yet.",
"# rubocop:disable all",
"# Override String#camelize if we need to get back to the original behavior",
"# that fast_camelize overroad.",
"# Skipping here because Steep doesn't understand that this is going to",
"# be included into a class that has Kernel included.",
"# Override ActiveSupport::Inflector::method_added so that if and when the",
"# camelize method gets defined, we can immediately redefine it.",
"# Hook into ActiveSupport::Inflector to take advantage of FastCamelize."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 514
| 83
|
417a11c7fb768998666eb9592324d9006aef6409
|
rafaelescoffier/locca
|
lib/locca/collection.rb
|
[
"MIT"
] |
Ruby
|
Locca
|
#
# The MIT License (MIT)
#
# Copyright (c) 2014 Evgeny Shurakov
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
|
The MIT License (MIT)
Copyright (c) 2014 Evgeny Shurakov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
|
[
"The",
"MIT",
"License",
"(",
"MIT",
")",
"Copyright",
"(",
"c",
")",
"2014",
"Evgeny",
"Shurakov",
"Permission",
"is",
"hereby",
"granted",
"free",
"of",
"charge",
"to",
"any",
"person",
"obtaining",
"a",
"copy",
"of",
"this",
"software",
"and",
"associated",
"documentation",
"files",
"(",
"the",
"\"",
"Software",
"\"",
")",
"to",
"deal",
"in",
"the",
"Software",
"without",
"restriction",
"including",
"without",
"limitation",
"the",
"rights",
"to",
"use",
"copy",
"modify",
"merge",
"publish",
"distribute",
"sublicense",
"and",
"/",
"or",
"sell",
"copies",
"of",
"the",
"Software",
"and",
"to",
"permit",
"persons",
"to",
"whom",
"the",
"Software",
"is",
"furnished",
"to",
"do",
"so",
"subject",
"to",
"the",
"following",
"conditions",
".",
"The",
"above",
"copyright",
"notice",
"and",
"this",
"permission",
"notice",
"shall",
"be",
"included",
"in",
"all",
"copies",
"or",
"substantial",
"portions",
"of",
"the",
"Software",
"."
] |
module Locca
class Collection
attr_accessor :name
attr_accessor :lang
def initialize(name = nil, lang = nil)
@name = name
@lang = lang
@items = {}
end
def add_item(item)
if !item || !item.key
raise ArgumentError, 'item or item.key is nil'
end
@items[item.key] = item
end
def remove_item_for_key(key)
return @items.delete(key)
end
def item_for_key(key)
return @items[key]
end
def has_key?(key)
return @items.has_key?(key)
end
def all_keys
return @items.keys
end
def keys_without_comments
result = []
@items.each do |key, item|
if item.comment == nil || item.comment.strip.length == 0
result.push(key)
end
end
return result
end
def translated?
@items.each do |key, item|
if !item.translated?
return false
end
end
return true
end
def count
return @items.count
end
def each
@items.each do |key, item|
yield(item)
end
end
def sorted_each
sorted_keys = all_keys.sort(&:casecmp)
sorted_keys.each do |key|
yield(@items[key])
end
end
def to_s ; "<#{self.class}: lang = #{lang}, name = #{name}>" ; end
end
end
|
[
"module",
"Locca",
"class",
"Collection",
"attr_accessor",
":name",
"attr_accessor",
":lang",
"def",
"initialize",
"(",
"name",
"=",
"nil",
",",
"lang",
"=",
"nil",
")",
"@name",
"=",
"name",
"@lang",
"=",
"lang",
"@items",
"=",
"{",
"}",
"end",
"def",
"add_item",
"(",
"item",
")",
"if",
"!",
"item",
"||",
"!",
"item",
".",
"key",
"raise",
"ArgumentError",
",",
"'item or item.key is nil'",
"end",
"@items",
"[",
"item",
".",
"key",
"]",
"=",
"item",
"end",
"def",
"remove_item_for_key",
"(",
"key",
")",
"return",
"@items",
".",
"delete",
"(",
"key",
")",
"end",
"def",
"item_for_key",
"(",
"key",
")",
"return",
"@items",
"[",
"key",
"]",
"end",
"def",
"has_key?",
"(",
"key",
")",
"return",
"@items",
".",
"has_key?",
"(",
"key",
")",
"end",
"def",
"all_keys",
"return",
"@items",
".",
"keys",
"end",
"def",
"keys_without_comments",
"result",
"=",
"[",
"]",
"@items",
".",
"each",
"do",
"|",
"key",
",",
"item",
"|",
"if",
"item",
".",
"comment",
"==",
"nil",
"||",
"item",
".",
"comment",
".",
"strip",
".",
"length",
"==",
"0",
"result",
".",
"push",
"(",
"key",
")",
"end",
"end",
"return",
"result",
"end",
"def",
"translated?",
"@items",
".",
"each",
"do",
"|",
"key",
",",
"item",
"|",
"if",
"!",
"item",
".",
"translated?",
"return",
"false",
"end",
"end",
"return",
"true",
"end",
"def",
"count",
"return",
"@items",
".",
"count",
"end",
"def",
"each",
"@items",
".",
"each",
"do",
"|",
"key",
",",
"item",
"|",
"yield",
"(",
"item",
")",
"end",
"end",
"def",
"sorted_each",
"sorted_keys",
"=",
"all_keys",
".",
"sort",
"(",
"&",
":casecmp",
")",
"sorted_keys",
".",
"each",
"do",
"|",
"key",
"|",
"yield",
"(",
"@items",
"[",
"key",
"]",
")",
"end",
"end",
"def",
"to_s",
";",
"\"<#{self.class}: lang = #{lang}, name = #{name}>\"",
";",
"end",
"end",
"end"
] |
The MIT License (MIT)
Copyright (c) 2014 Evgeny Shurakov
|
[
"The",
"MIT",
"License",
"(",
"MIT",
")",
"Copyright",
"(",
"c",
")",
"2014",
"Evgeny",
"Shurakov"
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 351
| 247
|
64f08c52ddc4f3282c20e294c4bf1648ae210449
|
AeroNexus/AspireStudio
|
Core/Messaging/TcpPeerToPeerClient.cs
|
[
"Apache-2.0"
] |
C#
|
TcpPeerToPeerClient
|
/// <summary>
/// TcpPeerToPeerClient implements message passing over TCP where the user has no desire
/// to track individual session. Messages are framed with a network-order int32 message
/// length header. Otherwise messages are passed as provided.
/// <para>
/// This is fairly close to the c++ design but not nearly as tuned or refined. There is still
/// plenty of room for improvement here, especially in startup/shutdown behavior, auditing the
/// resources to make sure the Sockets get disposed of properly, etc.
/// </para>
/// <para>
/// Synchronization is performed at the TcpPeerToPeerClient level using a mutex to protect the
/// mapping from IPEndPoint to TcpSession. Readable packets are currently signaled with a
/// semaphore. Sessions are synchronized using a monitor that is pulsed on the 'interesting'
/// edge of state changes.
/// </para>
/// </summary>
|
TcpPeerToPeerClient implements message passing over TCP where the user has no desire
to track individual session. Messages are framed with a network-order int32 message
length header. Otherwise messages are passed as provided.
This is fairly close to the c++ design but not nearly as tuned or refined. There is still
plenty of room for improvement here, especially in startup/shutdown behavior, auditing the
resources to make sure the Sockets get disposed of properly, etc.
Synchronization is performed at the TcpPeerToPeerClient level using a mutex to protect the
mapping from IPEndPoint to TcpSession. Readable packets are currently signaled with a
semaphore. Sessions are synchronized using a monitor that is pulsed on the 'interesting'
edge of state changes.
|
[
"TcpPeerToPeerClient",
"implements",
"message",
"passing",
"over",
"TCP",
"where",
"the",
"user",
"has",
"no",
"desire",
"to",
"track",
"individual",
"session",
".",
"Messages",
"are",
"framed",
"with",
"a",
"network",
"-",
"order",
"int32",
"message",
"length",
"header",
".",
"Otherwise",
"messages",
"are",
"passed",
"as",
"provided",
".",
"This",
"is",
"fairly",
"close",
"to",
"the",
"c",
"++",
"design",
"but",
"not",
"nearly",
"as",
"tuned",
"or",
"refined",
".",
"There",
"is",
"still",
"plenty",
"of",
"room",
"for",
"improvement",
"here",
"especially",
"in",
"startup",
"/",
"shutdown",
"behavior",
"auditing",
"the",
"resources",
"to",
"make",
"sure",
"the",
"Sockets",
"get",
"disposed",
"of",
"properly",
"etc",
".",
"Synchronization",
"is",
"performed",
"at",
"the",
"TcpPeerToPeerClient",
"level",
"using",
"a",
"mutex",
"to",
"protect",
"the",
"mapping",
"from",
"IPEndPoint",
"to",
"TcpSession",
".",
"Readable",
"packets",
"are",
"currently",
"signaled",
"with",
"a",
"semaphore",
".",
"Sessions",
"are",
"synchronized",
"using",
"a",
"monitor",
"that",
"is",
"pulsed",
"on",
"the",
"'",
"interesting",
"'",
"edge",
"of",
"state",
"changes",
"."
] |
public class TcpPeerToPeerClient
{
private readonly object mutex = new object();
private readonly Semaphore readCount = new Semaphore(0, int.MaxValue);
private readonly LinkedList<byte[]> readPackets = new LinkedList<byte[]>();
private readonly Dictionary<IPEndPoint, TcpSession> sessionByEp = new Dictionary<IPEndPoint, TcpSession>();
private readonly Socket acceptSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
private readonly int listenPort;
private bool wasOpened = false;
private bool isOpen = false;
public EndPoint LocalEndpoint { get; private set; }
public TcpPeerToPeerClient() : this(0) { }
public TcpPeerToPeerClient(int port)
{
if (port < 0 || port > 65535)
throw new ArgumentOutOfRangeException("port");
this.listenPort = port;
}
public int Open()
{
if (wasOpened)
throw new InvalidOperationException("Client has already been opened");
wasOpened = true;
try
{
acceptSocket.Bind(new IPEndPoint(IPAddress.Any, this.listenPort));
acceptSocket.Listen(int.MaxValue);
acceptSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
this.LocalEndpoint = acceptSocket.LocalEndPoint;
this.acceptSocket.BeginAccept(OnAccept, this);
isOpen = true;
return 0;
}
catch(Exception ex)
{
return -1;
}
}
public int Close()
{
if (!isOpen)
return 0;
isOpen = false;
try
{
this.acceptSocket.Close();
}
catch { }
return 0;
}
public int Read(byte[] buffer, int msTimeout)
{
if (!readCount.WaitOne(msTimeout))
return 0;
byte[] packet;
lock (this.mutex)
{
System.Diagnostics.Debug.Assert(readPackets.Count > 0);
packet = readPackets.First.Value;
readPackets.RemoveFirst();
}
System.Diagnostics.Debug.Assert(packet != null);
int copyLen = buffer.Length < packet.Length ? buffer.Length : packet.Length;
Array.Copy(packet, buffer, copyLen);
return copyLen;
}
public int Write(byte[] buffer, int offset, int length, IPEndPoint ep, int msTimeout)
{
TcpSession session = null;
lock (this.mutex)
{
if(!this.sessionByEp.TryGetValue(ep, out session))
{
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
clientSock.NoDelay = true;
session = new TcpSession(clientSock, ep);
sessionByEp[ep] = session;
clientSock.BeginConnect(ep, OnConnect, session);
}
}
try
{
lock(session.Monitor)
{
while(true)
{
if (session.Closing) break;
if (session.Connected && session.PendingSend == null) break;
if (!Monitor.Wait(session.Monitor, msTimeout))
return 0;
;
}
if (session.Closing)
return 0;
FramingState state = new FramingState(buffer, offset, length);
session.PendingSend = state;
session.Socket.BeginSend(state.HeaderBuffer, 0, state.HeaderBuffer.Length, SocketFlags.None, OnSendHeader, session);
}
return length;
}
catch(ObjectDisposedException)
{
return 0;
}
}
private void OnPacketReceived(byte[] bytes)
{
lock(this.mutex)
{
this.readPackets.AddLast(bytes);
this.readCount.Release();
}
}
private void OnAccept(IAsyncResult result)
{
TcpPeerToPeerClient client = result.AsyncState as TcpPeerToPeerClient;
try
{
Socket sock = client.acceptSocket.EndAccept(result);
sock.NoDelay = true;
IPEndPoint ep = sock.RemoteEndPoint as IPEndPoint;
FramingState recvState = new FramingState();
lock (client.mutex)
{
if (client.sessionByEp.ContainsKey(ep))
return;
var session = new TcpSession(sock, ep);
lock (session.Monitor)
{
client.sessionByEp[ep] = session;
session.Connected = true;
session.PendingReceive = recvState;
session.Socket.BeginReceive(recvState.HeaderBuffer, 0, 4, SocketFlags.None, OnReceiveHeader, session);
}
}
}
catch
{
;
}
finally
{
client.acceptSocket.BeginAccept(OnAccept, client);
}
}
private void OnConnect(IAsyncResult result)
{
var session = result.AsyncState as TcpSession;
lock (session.Monitor)
{
try
{
session.Socket.EndConnect(result);
FramingState state = new FramingState();
session.PendingReceive = state;
session.Socket.BeginReceive(state.HeaderBuffer, 0, 4, SocketFlags.None, OnReceiveHeader, session);
session.Connected = true;
}
catch
{
lock (this.mutex)
{
this.sessionByEp.Remove(session.ep);
}
session.Closing = true;
session.Dispose();
}
}
}
private void OnSendHeader(IAsyncResult result)
{
TcpSession session = result.AsyncState as TcpSession;
lock (session.Monitor)
{
try
{
FramingState writeState = session.PendingSend;
System.Diagnostics.Debug.Assert(writeState != null);
writeState.HeaderBytesTransferred += session.Socket.EndSend(result);
int total = 4;
int remain = total - writeState.HeaderBytesTransferred;
System.Diagnostics.Debug.Assert(remain >= 0);
if (remain > 0)
{
session.Socket.BeginSend(
writeState.HeaderBuffer,
writeState.HeaderBytesTransferred,
remain,
SocketFlags.None, OnSendHeader, session
);
}
else
{
if (writeState.DataBuffer.Length <= 0)
session.PendingSend = null;
else
{
session.Socket.BeginSend(
writeState.DataBuffer,
0,
writeState.DataBuffer.Length,
SocketFlags.None, OnSendData, session
);
}
}
}
catch
{
session.Closing = true;
}
}
}
private void OnSendData(IAsyncResult result)
{
TcpSession session = result.AsyncState as TcpSession;
lock (session.Monitor)
{
try
{
FramingState sendState = session.PendingSend;
System.Diagnostics.Debug.Assert(sendState != null);
sendState.DataBytesTransferred += session.Socket.EndSend(result);
int total = sendState.DataBuffer.Length;
int remain = total - sendState.DataBytesTransferred;
System.Diagnostics.Debug.Assert(remain >= 0);
if (remain > 0)
{
session.Socket.BeginSend(
sendState.DataBuffer,
sendState.DataBytesTransferred,
remain,
SocketFlags.None, OnSendData, session
);
}
else
{
session.PendingSend = null;
}
}
catch
{
session.Closing = true;
}
}
}
private void OnReceiveHeader(IAsyncResult result)
{
TcpSession session = result.AsyncState as TcpSession;
lock (session.Monitor)
{
try
{
FramingState recvState = session.PendingReceive;
System.Diagnostics.Debug.Assert(recvState != null);
recvState.HeaderBytesTransferred += session.Socket.EndReceive(result);
int total = 4;
int remain = total - recvState.HeaderBytesTransferred;
System.Diagnostics.Debug.Assert(remain >= 0);
if (remain > 0)
{
session.Socket.BeginReceive(
recvState.HeaderBuffer,
recvState.HeaderBytesTransferred,
remain,
SocketFlags.None, OnReceiveHeader, session
);
}
else
{
int datalen = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(recvState.HeaderBuffer, 0));
if (datalen < 0 || datalen > 1024 * 1024)
throw new InvalidOperationException("Bad recv length " + datalen);
recvState.DataBuffer = new byte[datalen];
if (datalen == 0)
{
OnPacketReceived(recvState.DataBuffer);
recvState = new FramingState();
session.PendingReceive = recvState;
session.Socket.BeginReceive(recvState.HeaderBuffer, 0, 4, SocketFlags.None, OnReceiveHeader, session);
}
else
{
session.Socket.BeginReceive(
recvState.DataBuffer,
0,
recvState.DataBuffer.Length,
SocketFlags.None, OnReceiveData, session
);
}
}
}
catch
{
session.Closing = true;
}
}
}
private void OnReceiveData(IAsyncResult result)
{
TcpSession session = result.AsyncState as TcpSession;
lock (session.Monitor)
{
try
{
FramingState recvState = session.PendingReceive;
System.Diagnostics.Debug.Assert(recvState != null);
recvState.DataBytesTransferred += session.Socket.EndReceive(result);
int total = recvState.DataBuffer.Length;
int remain = total - recvState.DataBytesTransferred;
System.Diagnostics.Debug.Assert(remain >= 0);
if(remain == 0)
{
OnPacketReceived(recvState.DataBuffer);
recvState = new FramingState();
session.PendingReceive = recvState;
session.Socket.BeginReceive(recvState.HeaderBuffer, 0, 4, SocketFlags.None, OnReceiveHeader, session);
}
else
{
session.Socket.BeginReceive(
recvState.DataBuffer,
recvState.DataBytesTransferred,
remain,
SocketFlags.None, OnReceiveData, session
);
}
}
catch
{
session.Closing = true;
}
}
}
private class FramingState
{
public byte[] HeaderBuffer { get; private set; }
public byte[] DataBuffer { get; internal set; }
public int HeaderBytesTransferred { get; set; }
public int DataBytesTransferred { get; set; }
public FramingState()
{
this.HeaderBuffer = new byte[4];
}
public FramingState(byte[] buffer, int offset, int length)
{
if (length < 0 || length > 1024 * 1024)
throw new InvalidOperationException("Invalid length " + length);
this.HeaderBuffer = BitConverter.GetBytes((int)IPAddress.HostToNetworkOrder((int)length));
this.DataBuffer = new byte[length];
Array.Copy(buffer, offset, this.DataBuffer, 0, length);
}
}
private class TcpSession : IDisposable
{
public object Monitor { get; private set; }
private bool _closing = false;
public bool Closing
{
get { return _closing; }
internal set
{
_closing = value;
if (_closing)
System.Threading.Monitor.PulseAll(this.Monitor);
}
}
private bool _connected = false;
public bool Connected
{
get { return _connected; }
internal set
{
_connected = value;
if(_connected)
System.Threading.Monitor.PulseAll(this.Monitor);
}
}
private FramingState _pendingRead = null;
public FramingState PendingReceive
{
get { return _pendingRead; }
internal set
{
_pendingRead = value;
if(_pendingRead == null)
System.Threading.Monitor.PulseAll(this.Monitor);
}
}
private FramingState _pendingWrite = null;
public FramingState PendingSend
{
get { return _pendingWrite; }
internal set
{
_pendingWrite = value;
if(_pendingWrite == null)
System.Threading.Monitor.PulseAll(this.Monitor);
}
}
public Socket Socket { get; private set; }
public IPEndPoint ep { get; private set; }
public TcpSession(Socket sock, IPEndPoint ep)
{
this.ep = ep;
this.Monitor = new object();
this.Socket = sock;
}
#region IDisposable Support
public void Dispose()
{
this.Socket.Dispose();
}
#endregion
}
}
|
[
"public",
"class",
"TcpPeerToPeerClient",
"{",
"private",
"readonly",
"object",
"mutex",
"=",
"new",
"object",
"(",
")",
";",
"private",
"readonly",
"Semaphore",
"readCount",
"=",
"new",
"Semaphore",
"(",
"0",
",",
"int",
".",
"MaxValue",
")",
";",
"private",
"readonly",
"LinkedList",
"<",
"byte",
"[",
"]",
">",
"readPackets",
"=",
"new",
"LinkedList",
"<",
"byte",
"[",
"]",
">",
"(",
")",
";",
"private",
"readonly",
"Dictionary",
"<",
"IPEndPoint",
",",
"TcpSession",
">",
"sessionByEp",
"=",
"new",
"Dictionary",
"<",
"IPEndPoint",
",",
"TcpSession",
">",
"(",
")",
";",
"private",
"readonly",
"Socket",
"acceptSocket",
"=",
"new",
"Socket",
"(",
"AddressFamily",
".",
"InterNetwork",
",",
"SocketType",
".",
"Stream",
",",
"ProtocolType",
".",
"IP",
")",
";",
"private",
"readonly",
"int",
"listenPort",
";",
"private",
"bool",
"wasOpened",
"=",
"false",
";",
"private",
"bool",
"isOpen",
"=",
"false",
";",
"public",
"EndPoint",
"LocalEndpoint",
"{",
"get",
";",
"private",
"set",
";",
"}",
"public",
"TcpPeerToPeerClient",
"(",
")",
":",
"this",
"(",
"0",
")",
"{",
"}",
"public",
"TcpPeerToPeerClient",
"(",
"int",
"port",
")",
"{",
"if",
"(",
"port",
"<",
"0",
"||",
"port",
">",
"65535",
")",
"throw",
"new",
"ArgumentOutOfRangeException",
"(",
"\"",
"port",
"\"",
")",
";",
"this",
".",
"listenPort",
"=",
"port",
";",
"}",
"public",
"int",
"Open",
"(",
")",
"{",
"if",
"(",
"wasOpened",
")",
"throw",
"new",
"InvalidOperationException",
"(",
"\"",
"Client has already been opened",
"\"",
")",
";",
"wasOpened",
"=",
"true",
";",
"try",
"{",
"acceptSocket",
".",
"Bind",
"(",
"new",
"IPEndPoint",
"(",
"IPAddress",
".",
"Any",
",",
"this",
".",
"listenPort",
")",
")",
";",
"acceptSocket",
".",
"Listen",
"(",
"int",
".",
"MaxValue",
")",
";",
"acceptSocket",
".",
"SetSocketOption",
"(",
"SocketOptionLevel",
".",
"IP",
",",
"SocketOptionName",
".",
"ReuseAddress",
",",
"true",
")",
";",
"this",
".",
"LocalEndpoint",
"=",
"acceptSocket",
".",
"LocalEndPoint",
";",
"this",
".",
"acceptSocket",
".",
"BeginAccept",
"(",
"OnAccept",
",",
"this",
")",
";",
"isOpen",
"=",
"true",
";",
"return",
"0",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"return",
"-",
"1",
";",
"}",
"}",
"public",
"int",
"Close",
"(",
")",
"{",
"if",
"(",
"!",
"isOpen",
")",
"return",
"0",
";",
"isOpen",
"=",
"false",
";",
"try",
"{",
"this",
".",
"acceptSocket",
".",
"Close",
"(",
")",
";",
"}",
"catch",
"{",
"}",
"return",
"0",
";",
"}",
"public",
"int",
"Read",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"msTimeout",
")",
"{",
"if",
"(",
"!",
"readCount",
".",
"WaitOne",
"(",
"msTimeout",
")",
")",
"return",
"0",
";",
"byte",
"[",
"]",
"packet",
";",
"lock",
"(",
"this",
".",
"mutex",
")",
"{",
"System",
".",
"Diagnostics",
".",
"Debug",
".",
"Assert",
"(",
"readPackets",
".",
"Count",
">",
"0",
")",
";",
"packet",
"=",
"readPackets",
".",
"First",
".",
"Value",
";",
"readPackets",
".",
"RemoveFirst",
"(",
")",
";",
"}",
"System",
".",
"Diagnostics",
".",
"Debug",
".",
"Assert",
"(",
"packet",
"!=",
"null",
")",
";",
"int",
"copyLen",
"=",
"buffer",
".",
"Length",
"<",
"packet",
".",
"Length",
"?",
"buffer",
".",
"Length",
":",
"packet",
".",
"Length",
";",
"Array",
".",
"Copy",
"(",
"packet",
",",
"buffer",
",",
"copyLen",
")",
";",
"return",
"copyLen",
";",
"}",
"public",
"int",
"Write",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"offset",
",",
"int",
"length",
",",
"IPEndPoint",
"ep",
",",
"int",
"msTimeout",
")",
"{",
"TcpSession",
"session",
"=",
"null",
";",
"lock",
"(",
"this",
".",
"mutex",
")",
"{",
"if",
"(",
"!",
"this",
".",
"sessionByEp",
".",
"TryGetValue",
"(",
"ep",
",",
"out",
"session",
")",
")",
"{",
"Socket",
"clientSock",
"=",
"new",
"Socket",
"(",
"AddressFamily",
".",
"InterNetwork",
",",
"SocketType",
".",
"Stream",
",",
"ProtocolType",
".",
"IP",
")",
";",
"clientSock",
".",
"NoDelay",
"=",
"true",
";",
"session",
"=",
"new",
"TcpSession",
"(",
"clientSock",
",",
"ep",
")",
";",
"sessionByEp",
"[",
"ep",
"]",
"=",
"session",
";",
"clientSock",
".",
"BeginConnect",
"(",
"ep",
",",
"OnConnect",
",",
"session",
")",
";",
"}",
"}",
"try",
"{",
"lock",
"(",
"session",
".",
"Monitor",
")",
"{",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"session",
".",
"Closing",
")",
"break",
";",
"if",
"(",
"session",
".",
"Connected",
"&&",
"session",
".",
"PendingSend",
"==",
"null",
")",
"break",
";",
"if",
"(",
"!",
"Monitor",
".",
"Wait",
"(",
"session",
".",
"Monitor",
",",
"msTimeout",
")",
")",
"return",
"0",
";",
";",
"}",
"if",
"(",
"session",
".",
"Closing",
")",
"return",
"0",
";",
"FramingState",
"state",
"=",
"new",
"FramingState",
"(",
"buffer",
",",
"offset",
",",
"length",
")",
";",
"session",
".",
"PendingSend",
"=",
"state",
";",
"session",
".",
"Socket",
".",
"BeginSend",
"(",
"state",
".",
"HeaderBuffer",
",",
"0",
",",
"state",
".",
"HeaderBuffer",
".",
"Length",
",",
"SocketFlags",
".",
"None",
",",
"OnSendHeader",
",",
"session",
")",
";",
"}",
"return",
"length",
";",
"}",
"catch",
"(",
"ObjectDisposedException",
")",
"{",
"return",
"0",
";",
"}",
"}",
"private",
"void",
"OnPacketReceived",
"(",
"byte",
"[",
"]",
"bytes",
")",
"{",
"lock",
"(",
"this",
".",
"mutex",
")",
"{",
"this",
".",
"readPackets",
".",
"AddLast",
"(",
"bytes",
")",
";",
"this",
".",
"readCount",
".",
"Release",
"(",
")",
";",
"}",
"}",
"private",
"void",
"OnAccept",
"(",
"IAsyncResult",
"result",
")",
"{",
"TcpPeerToPeerClient",
"client",
"=",
"result",
".",
"AsyncState",
"as",
"TcpPeerToPeerClient",
";",
"try",
"{",
"Socket",
"sock",
"=",
"client",
".",
"acceptSocket",
".",
"EndAccept",
"(",
"result",
")",
";",
"sock",
".",
"NoDelay",
"=",
"true",
";",
"IPEndPoint",
"ep",
"=",
"sock",
".",
"RemoteEndPoint",
"as",
"IPEndPoint",
";",
"FramingState",
"recvState",
"=",
"new",
"FramingState",
"(",
")",
";",
"lock",
"(",
"client",
".",
"mutex",
")",
"{",
"if",
"(",
"client",
".",
"sessionByEp",
".",
"ContainsKey",
"(",
"ep",
")",
")",
"return",
";",
"var",
"session",
"=",
"new",
"TcpSession",
"(",
"sock",
",",
"ep",
")",
";",
"lock",
"(",
"session",
".",
"Monitor",
")",
"{",
"client",
".",
"sessionByEp",
"[",
"ep",
"]",
"=",
"session",
";",
"session",
".",
"Connected",
"=",
"true",
";",
"session",
".",
"PendingReceive",
"=",
"recvState",
";",
"session",
".",
"Socket",
".",
"BeginReceive",
"(",
"recvState",
".",
"HeaderBuffer",
",",
"0",
",",
"4",
",",
"SocketFlags",
".",
"None",
",",
"OnReceiveHeader",
",",
"session",
")",
";",
"}",
"}",
"}",
"catch",
"{",
";",
"}",
"finally",
"{",
"client",
".",
"acceptSocket",
".",
"BeginAccept",
"(",
"OnAccept",
",",
"client",
")",
";",
"}",
"}",
"private",
"void",
"OnConnect",
"(",
"IAsyncResult",
"result",
")",
"{",
"var",
"session",
"=",
"result",
".",
"AsyncState",
"as",
"TcpSession",
";",
"lock",
"(",
"session",
".",
"Monitor",
")",
"{",
"try",
"{",
"session",
".",
"Socket",
".",
"EndConnect",
"(",
"result",
")",
";",
"FramingState",
"state",
"=",
"new",
"FramingState",
"(",
")",
";",
"session",
".",
"PendingReceive",
"=",
"state",
";",
"session",
".",
"Socket",
".",
"BeginReceive",
"(",
"state",
".",
"HeaderBuffer",
",",
"0",
",",
"4",
",",
"SocketFlags",
".",
"None",
",",
"OnReceiveHeader",
",",
"session",
")",
";",
"session",
".",
"Connected",
"=",
"true",
";",
"}",
"catch",
"{",
"lock",
"(",
"this",
".",
"mutex",
")",
"{",
"this",
".",
"sessionByEp",
".",
"Remove",
"(",
"session",
".",
"ep",
")",
";",
"}",
"session",
".",
"Closing",
"=",
"true",
";",
"session",
".",
"Dispose",
"(",
")",
";",
"}",
"}",
"}",
"private",
"void",
"OnSendHeader",
"(",
"IAsyncResult",
"result",
")",
"{",
"TcpSession",
"session",
"=",
"result",
".",
"AsyncState",
"as",
"TcpSession",
";",
"lock",
"(",
"session",
".",
"Monitor",
")",
"{",
"try",
"{",
"FramingState",
"writeState",
"=",
"session",
".",
"PendingSend",
";",
"System",
".",
"Diagnostics",
".",
"Debug",
".",
"Assert",
"(",
"writeState",
"!=",
"null",
")",
";",
"writeState",
".",
"HeaderBytesTransferred",
"+=",
"session",
".",
"Socket",
".",
"EndSend",
"(",
"result",
")",
";",
"int",
"total",
"=",
"4",
";",
"int",
"remain",
"=",
"total",
"-",
"writeState",
".",
"HeaderBytesTransferred",
";",
"System",
".",
"Diagnostics",
".",
"Debug",
".",
"Assert",
"(",
"remain",
">=",
"0",
")",
";",
"if",
"(",
"remain",
">",
"0",
")",
"{",
"session",
".",
"Socket",
".",
"BeginSend",
"(",
"writeState",
".",
"HeaderBuffer",
",",
"writeState",
".",
"HeaderBytesTransferred",
",",
"remain",
",",
"SocketFlags",
".",
"None",
",",
"OnSendHeader",
",",
"session",
")",
";",
"}",
"else",
"{",
"if",
"(",
"writeState",
".",
"DataBuffer",
".",
"Length",
"<=",
"0",
")",
"session",
".",
"PendingSend",
"=",
"null",
";",
"else",
"{",
"session",
".",
"Socket",
".",
"BeginSend",
"(",
"writeState",
".",
"DataBuffer",
",",
"0",
",",
"writeState",
".",
"DataBuffer",
".",
"Length",
",",
"SocketFlags",
".",
"None",
",",
"OnSendData",
",",
"session",
")",
";",
"}",
"}",
"}",
"catch",
"{",
"session",
".",
"Closing",
"=",
"true",
";",
"}",
"}",
"}",
"private",
"void",
"OnSendData",
"(",
"IAsyncResult",
"result",
")",
"{",
"TcpSession",
"session",
"=",
"result",
".",
"AsyncState",
"as",
"TcpSession",
";",
"lock",
"(",
"session",
".",
"Monitor",
")",
"{",
"try",
"{",
"FramingState",
"sendState",
"=",
"session",
".",
"PendingSend",
";",
"System",
".",
"Diagnostics",
".",
"Debug",
".",
"Assert",
"(",
"sendState",
"!=",
"null",
")",
";",
"sendState",
".",
"DataBytesTransferred",
"+=",
"session",
".",
"Socket",
".",
"EndSend",
"(",
"result",
")",
";",
"int",
"total",
"=",
"sendState",
".",
"DataBuffer",
".",
"Length",
";",
"int",
"remain",
"=",
"total",
"-",
"sendState",
".",
"DataBytesTransferred",
";",
"System",
".",
"Diagnostics",
".",
"Debug",
".",
"Assert",
"(",
"remain",
">=",
"0",
")",
";",
"if",
"(",
"remain",
">",
"0",
")",
"{",
"session",
".",
"Socket",
".",
"BeginSend",
"(",
"sendState",
".",
"DataBuffer",
",",
"sendState",
".",
"DataBytesTransferred",
",",
"remain",
",",
"SocketFlags",
".",
"None",
",",
"OnSendData",
",",
"session",
")",
";",
"}",
"else",
"{",
"session",
".",
"PendingSend",
"=",
"null",
";",
"}",
"}",
"catch",
"{",
"session",
".",
"Closing",
"=",
"true",
";",
"}",
"}",
"}",
"private",
"void",
"OnReceiveHeader",
"(",
"IAsyncResult",
"result",
")",
"{",
"TcpSession",
"session",
"=",
"result",
".",
"AsyncState",
"as",
"TcpSession",
";",
"lock",
"(",
"session",
".",
"Monitor",
")",
"{",
"try",
"{",
"FramingState",
"recvState",
"=",
"session",
".",
"PendingReceive",
";",
"System",
".",
"Diagnostics",
".",
"Debug",
".",
"Assert",
"(",
"recvState",
"!=",
"null",
")",
";",
"recvState",
".",
"HeaderBytesTransferred",
"+=",
"session",
".",
"Socket",
".",
"EndReceive",
"(",
"result",
")",
";",
"int",
"total",
"=",
"4",
";",
"int",
"remain",
"=",
"total",
"-",
"recvState",
".",
"HeaderBytesTransferred",
";",
"System",
".",
"Diagnostics",
".",
"Debug",
".",
"Assert",
"(",
"remain",
">=",
"0",
")",
";",
"if",
"(",
"remain",
">",
"0",
")",
"{",
"session",
".",
"Socket",
".",
"BeginReceive",
"(",
"recvState",
".",
"HeaderBuffer",
",",
"recvState",
".",
"HeaderBytesTransferred",
",",
"remain",
",",
"SocketFlags",
".",
"None",
",",
"OnReceiveHeader",
",",
"session",
")",
";",
"}",
"else",
"{",
"int",
"datalen",
"=",
"IPAddress",
".",
"NetworkToHostOrder",
"(",
"BitConverter",
".",
"ToInt32",
"(",
"recvState",
".",
"HeaderBuffer",
",",
"0",
")",
")",
";",
"if",
"(",
"datalen",
"<",
"0",
"||",
"datalen",
">",
"1024",
"*",
"1024",
")",
"throw",
"new",
"InvalidOperationException",
"(",
"\"",
"Bad recv length ",
"\"",
"+",
"datalen",
")",
";",
"recvState",
".",
"DataBuffer",
"=",
"new",
"byte",
"[",
"datalen",
"]",
";",
"if",
"(",
"datalen",
"==",
"0",
")",
"{",
"OnPacketReceived",
"(",
"recvState",
".",
"DataBuffer",
")",
";",
"recvState",
"=",
"new",
"FramingState",
"(",
")",
";",
"session",
".",
"PendingReceive",
"=",
"recvState",
";",
"session",
".",
"Socket",
".",
"BeginReceive",
"(",
"recvState",
".",
"HeaderBuffer",
",",
"0",
",",
"4",
",",
"SocketFlags",
".",
"None",
",",
"OnReceiveHeader",
",",
"session",
")",
";",
"}",
"else",
"{",
"session",
".",
"Socket",
".",
"BeginReceive",
"(",
"recvState",
".",
"DataBuffer",
",",
"0",
",",
"recvState",
".",
"DataBuffer",
".",
"Length",
",",
"SocketFlags",
".",
"None",
",",
"OnReceiveData",
",",
"session",
")",
";",
"}",
"}",
"}",
"catch",
"{",
"session",
".",
"Closing",
"=",
"true",
";",
"}",
"}",
"}",
"private",
"void",
"OnReceiveData",
"(",
"IAsyncResult",
"result",
")",
"{",
"TcpSession",
"session",
"=",
"result",
".",
"AsyncState",
"as",
"TcpSession",
";",
"lock",
"(",
"session",
".",
"Monitor",
")",
"{",
"try",
"{",
"FramingState",
"recvState",
"=",
"session",
".",
"PendingReceive",
";",
"System",
".",
"Diagnostics",
".",
"Debug",
".",
"Assert",
"(",
"recvState",
"!=",
"null",
")",
";",
"recvState",
".",
"DataBytesTransferred",
"+=",
"session",
".",
"Socket",
".",
"EndReceive",
"(",
"result",
")",
";",
"int",
"total",
"=",
"recvState",
".",
"DataBuffer",
".",
"Length",
";",
"int",
"remain",
"=",
"total",
"-",
"recvState",
".",
"DataBytesTransferred",
";",
"System",
".",
"Diagnostics",
".",
"Debug",
".",
"Assert",
"(",
"remain",
">=",
"0",
")",
";",
"if",
"(",
"remain",
"==",
"0",
")",
"{",
"OnPacketReceived",
"(",
"recvState",
".",
"DataBuffer",
")",
";",
"recvState",
"=",
"new",
"FramingState",
"(",
")",
";",
"session",
".",
"PendingReceive",
"=",
"recvState",
";",
"session",
".",
"Socket",
".",
"BeginReceive",
"(",
"recvState",
".",
"HeaderBuffer",
",",
"0",
",",
"4",
",",
"SocketFlags",
".",
"None",
",",
"OnReceiveHeader",
",",
"session",
")",
";",
"}",
"else",
"{",
"session",
".",
"Socket",
".",
"BeginReceive",
"(",
"recvState",
".",
"DataBuffer",
",",
"recvState",
".",
"DataBytesTransferred",
",",
"remain",
",",
"SocketFlags",
".",
"None",
",",
"OnReceiveData",
",",
"session",
")",
";",
"}",
"}",
"catch",
"{",
"session",
".",
"Closing",
"=",
"true",
";",
"}",
"}",
"}",
"private",
"class",
"FramingState",
"{",
"public",
"byte",
"[",
"]",
"HeaderBuffer",
"{",
"get",
";",
"private",
"set",
";",
"}",
"public",
"byte",
"[",
"]",
"DataBuffer",
"{",
"get",
";",
"internal",
"set",
";",
"}",
"public",
"int",
"HeaderBytesTransferred",
"{",
"get",
";",
"set",
";",
"}",
"public",
"int",
"DataBytesTransferred",
"{",
"get",
";",
"set",
";",
"}",
"public",
"FramingState",
"(",
")",
"{",
"this",
".",
"HeaderBuffer",
"=",
"new",
"byte",
"[",
"4",
"]",
";",
"}",
"public",
"FramingState",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"offset",
",",
"int",
"length",
")",
"{",
"if",
"(",
"length",
"<",
"0",
"||",
"length",
">",
"1024",
"*",
"1024",
")",
"throw",
"new",
"InvalidOperationException",
"(",
"\"",
"Invalid length ",
"\"",
"+",
"length",
")",
";",
"this",
".",
"HeaderBuffer",
"=",
"BitConverter",
".",
"GetBytes",
"(",
"(",
"int",
")",
"IPAddress",
".",
"HostToNetworkOrder",
"(",
"(",
"int",
")",
"length",
")",
")",
";",
"this",
".",
"DataBuffer",
"=",
"new",
"byte",
"[",
"length",
"]",
";",
"Array",
".",
"Copy",
"(",
"buffer",
",",
"offset",
",",
"this",
".",
"DataBuffer",
",",
"0",
",",
"length",
")",
";",
"}",
"}",
"private",
"class",
"TcpSession",
":",
"IDisposable",
"{",
"public",
"object",
"Monitor",
"{",
"get",
";",
"private",
"set",
";",
"}",
"private",
"bool",
"_closing",
"=",
"false",
";",
"public",
"bool",
"Closing",
"{",
"get",
"{",
"return",
"_closing",
";",
"}",
"internal",
"set",
"{",
"_closing",
"=",
"value",
";",
"if",
"(",
"_closing",
")",
"System",
".",
"Threading",
".",
"Monitor",
".",
"PulseAll",
"(",
"this",
".",
"Monitor",
")",
";",
"}",
"}",
"private",
"bool",
"_connected",
"=",
"false",
";",
"public",
"bool",
"Connected",
"{",
"get",
"{",
"return",
"_connected",
";",
"}",
"internal",
"set",
"{",
"_connected",
"=",
"value",
";",
"if",
"(",
"_connected",
")",
"System",
".",
"Threading",
".",
"Monitor",
".",
"PulseAll",
"(",
"this",
".",
"Monitor",
")",
";",
"}",
"}",
"private",
"FramingState",
"_pendingRead",
"=",
"null",
";",
"public",
"FramingState",
"PendingReceive",
"{",
"get",
"{",
"return",
"_pendingRead",
";",
"}",
"internal",
"set",
"{",
"_pendingRead",
"=",
"value",
";",
"if",
"(",
"_pendingRead",
"==",
"null",
")",
"System",
".",
"Threading",
".",
"Monitor",
".",
"PulseAll",
"(",
"this",
".",
"Monitor",
")",
";",
"}",
"}",
"private",
"FramingState",
"_pendingWrite",
"=",
"null",
";",
"public",
"FramingState",
"PendingSend",
"{",
"get",
"{",
"return",
"_pendingWrite",
";",
"}",
"internal",
"set",
"{",
"_pendingWrite",
"=",
"value",
";",
"if",
"(",
"_pendingWrite",
"==",
"null",
")",
"System",
".",
"Threading",
".",
"Monitor",
".",
"PulseAll",
"(",
"this",
".",
"Monitor",
")",
";",
"}",
"}",
"public",
"Socket",
"Socket",
"{",
"get",
";",
"private",
"set",
";",
"}",
"public",
"IPEndPoint",
"ep",
"{",
"get",
";",
"private",
"set",
";",
"}",
"public",
"TcpSession",
"(",
"Socket",
"sock",
",",
"IPEndPoint",
"ep",
")",
"{",
"this",
".",
"ep",
"=",
"ep",
";",
"this",
".",
"Monitor",
"=",
"new",
"object",
"(",
")",
";",
"this",
".",
"Socket",
"=",
"sock",
";",
"}",
"region",
" IDisposable Support",
"public",
"void",
"Dispose",
"(",
")",
"{",
"this",
".",
"Socket",
".",
"Dispose",
"(",
")",
";",
"}",
"endregion",
"}",
"}"
] |
TcpPeerToPeerClient implements message passing over TCP where the user has no desire
to track individual session.
|
[
"TcpPeerToPeerClient",
"implements",
"message",
"passing",
"over",
"TCP",
"where",
"the",
"user",
"has",
"no",
"desire",
"to",
"track",
"individual",
"session",
"."
] |
[
"// <shrug>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 21
| 2,684
| 188
|
e593f2e384b0f58c70faf724f18027f558aee6f3
|
Unknown6656/Piglet
|
Piglet/Parser/Configuration/Generic/ParsingUitilities.cs
|
[
"MIT"
] |
C#
|
ProductionWrapper
|
/// <summary>
/// Represents a generic reduce function of the type "<c>(T0, T1, T2, T3, T4, T5, R) -> <typeparamref name="R"/></c>".
/// </summary>
/// <inheritdoc/>
/// <typeparam name="T0">The generic input type of the symbol no. 0.</typeparam>
/// <typeparam name="T1">The generic input type of the symbol no. 1.</typeparam>
/// <typeparam name="T2">The generic input type of the symbol no. 2.</typeparam>
/// <typeparam name="T3">The generic input type of the symbol no. 3.</typeparam>
/// <typeparam name="T4">The generic input type of the symbol no. 4.</typeparam>
/// <typeparam name="T5">The generic input type of the symbol no. 5.</typeparam>
/// <typeparam name="R">The generic return type of the production.</typeparam>
|
Represents a generic reduce function of the type "(T0, T1, T2, T3, T4, T5, R) -> ".
|
[
"Represents",
"a",
"generic",
"reduce",
"function",
"of",
"the",
"type",
"\"",
"(",
"T0",
"T1",
"T2",
"T3",
"T4",
"T5",
"R",
")",
"-",
">",
"\"",
"."
] |
public sealed class ProductionWrapper<T0, T1, T2, T3, T4, T5, R>
: ProductionWrapperBase<ProductionWrapper<T0, T1, T2, T3, T4, T5, R>>
{
public ProductionWrapper(IProduction<object> production)
: base(production)
{
}
public ProductionWrapper<T0, T1, T2, T3, T4, T5, R> SetReduceFunction(Func<T0, T1, T2, T3, T4, T5, R> f)
{
Production.SetReduceFunction(args => f((T0)args[0], (T1)args[1], (T2)args[2], (T3)args[3], (T4)args[4], (T5)args[5]));
return this;
}
}
|
[
"public",
"sealed",
"class",
"ProductionWrapper",
"<",
"T0",
",",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
",",
"R",
">",
":",
"ProductionWrapperBase",
"<",
"ProductionWrapper",
"<",
"T0",
",",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
",",
"R",
">",
">",
"{",
"public",
"ProductionWrapper",
"(",
"IProduction",
"<",
"object",
">",
"production",
")",
":",
"base",
"(",
"production",
")",
"{",
"}",
"public",
"ProductionWrapper",
"<",
"T0",
",",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
",",
"R",
">",
"SetReduceFunction",
"(",
"Func",
"<",
"T0",
",",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
",",
"R",
">",
"f",
")",
"{",
"Production",
".",
"SetReduceFunction",
"(",
"args",
"=>",
"f",
"(",
"(",
"T0",
")",
"args",
"[",
"0",
"]",
",",
"(",
"T1",
")",
"args",
"[",
"1",
"]",
",",
"(",
"T2",
")",
"args",
"[",
"2",
"]",
",",
"(",
"T3",
")",
"args",
"[",
"3",
"]",
",",
"(",
"T4",
")",
"args",
"[",
"4",
"]",
",",
"(",
"T5",
")",
"args",
"[",
"5",
"]",
")",
")",
";",
"return",
"this",
";",
"}",
"}"
] |
Represents a generic reduce function of the type "(T0, T1, T2, T3, T4, T5, R) -> ".
|
[
"Represents",
"a",
"generic",
"reduce",
"function",
"of",
"the",
"type",
"\"",
"(",
"T0",
"T1",
"T2",
"T3",
"T4",
"T5",
"R",
")",
"-",
">",
"\"",
"."
] |
[
"/// <summary>",
"/// Creates a new generic production wrapper based on the given (boxed) production.",
"/// </summary>",
"/// <inheritdoc/>",
"/// <param name=\"production\">Boxed production instance.</param>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "inheritdoc",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "typeparam",
"docstring": "The generic input type of the symbol no. 0.",
"docstring_tokens": [
"The",
"generic",
"input",
"type",
"of",
"the",
"symbol",
"no",
".",
"0",
"."
]
},
{
"identifier": "typeparam",
"docstring": "The generic input type of the symbol no. 1.",
"docstring_tokens": [
"The",
"generic",
"input",
"type",
"of",
"the",
"symbol",
"no",
".",
"1",
"."
]
},
{
"identifier": "typeparam",
"docstring": "The generic input type of the symbol no. 2.",
"docstring_tokens": [
"The",
"generic",
"input",
"type",
"of",
"the",
"symbol",
"no",
".",
"2",
"."
]
},
{
"identifier": "typeparam",
"docstring": "The generic input type of the symbol no. 3.",
"docstring_tokens": [
"The",
"generic",
"input",
"type",
"of",
"the",
"symbol",
"no",
".",
"3",
"."
]
},
{
"identifier": "typeparam",
"docstring": "The generic input type of the symbol no. 4.",
"docstring_tokens": [
"The",
"generic",
"input",
"type",
"of",
"the",
"symbol",
"no",
".",
"4",
"."
]
},
{
"identifier": "typeparam",
"docstring": "The generic input type of the symbol no. 5.",
"docstring_tokens": [
"The",
"generic",
"input",
"type",
"of",
"the",
"symbol",
"no",
".",
"5",
"."
]
},
{
"identifier": "typeparam",
"docstring": "The generic return type of the production.",
"docstring_tokens": [
"The",
"generic",
"return",
"type",
"of",
"the",
"production",
"."
]
}
]
}
| false
| 17
| 191
| 207
|
e2211b37277abb267f110685231c170e74084f6a
|
MellowYarker/CryptoNotifier
|
request.py
|
[
"MIT"
] |
Python
|
Scraper
|
A web scraper that connects to the CoinMarketCap API.
Args:
coins (List(Obj)): A list of coin.Coin objects.
Attributes:
coins (List(Obj)): A list of coin.Coin objects.
time (int): The time the scrape retrived the data. (not implemented)
link (str): The coinmarketcap api link.
http (obj): A urllib3 object.
|
A web scraper that connects to the CoinMarketCap API.
|
[
"A",
"web",
"scraper",
"that",
"connects",
"to",
"the",
"CoinMarketCap",
"API",
"."
] |
class Scraper:
""" A web scraper that connects to the CoinMarketCap API.
Args:
coins (List(Obj)): A list of coin.Coin objects.
Attributes:
coins (List(Obj)): A list of coin.Coin objects.
time (int): The time the scrape retrived the data. (not implemented)
link (str): The coinmarketcap api link.
http (obj): A urllib3 object.
"""
def __init__(self, coins):
self.coins = coins
self.time = 0
self.link = "https://api.coinmarketcap.com/v1/ticker/" # Why is this a property? Lets make it a constant.
self.http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where())
# TODO: replace ValueError with a logger.
def get_coin_with_id(self, id):
"""
Args:
id (string): An id of a coin.Coin object.
Return:
returns coin.Coin with id id, if it exists.
>>> import coin
>>> btc = coin.Coin("bitcoin", "BTC", 8000, 10000, 10, -15)
>>> b = Scraper([btc])
>>> passes = b.get_coin_with_id("bitcoin")
>>> passes.symbol
'BTC'
>>> fails = b.get_coin_with_id("fail")
Traceback (most recent call last):
...
ValueError: You have not added this coin in coins.txt!
"""
for coin in self.coins:
if coin.has_id(id):
return coin
raise ValueError("You have not added this coin in settings/coins.txt!")
def update_frequency(self):
"""
Returns:
The number of minutes between the script updating the information.
"""
# global UPDATE const from settings
return UPDATE
def print_coins(self):
"""
Returns:
A string of the coins this scraper searches for.
>>> import coin
>>> lst = [coin.Coin("bitcoin", "BTC", 8000, 10000, 10, -10), \
coin.Coin("litecoin", "LTC", 200, 400, 15, -15), \
coin.Coin("monero", "XMR", 300, 500, 10, -5)]
>>> test = Scraper(lst)
>>> test.print_coins()
Coins and Tokens:
bitcoin
litecoin
monero
"""
coins = self.coins
result = "Coins and Tokens:"
for coin in coins:
result += "\n" + coin.id
print(result)
# TODO: work on exceptions
def request_coin(self, name):
"""
Requests data about a coin, stores data in this coin's pickle file.
Args:
name (str): a string that represents a Coin objects id.
Returns:
JSON data describing the coin with the id name.
"""
try:
r = self.http.request('GET', self.link + "/" + name)
result = json.loads(r.data.decode('utf-8'))
if result == {'error': 'id not found'}:
raise ValueError("{} is either not a valid id or is not listed "
"on CoinMarketCap.com. Please remove it from "
"coins.txt".format(name))
else:
dest = 'Currencies/' + name
try:
previous = self.__load(dest)
updated = previous + result
self.__dump(updated, dest)
except FileNotFoundError:
self.__dump(result, dest)
return result
# error connecting to site
except urllib3.exceptions.MaxRetryError:
os.system(
"""osascript -e 'display notification "FAILED TO CONNECT"
with title "FATAL ERROR"'""")
raise Exception("Failed to connect to server. Check internet "
"connection.")
except ValueError:
raise ValueError("Something went wrong")
def __load(self, file):
"""
Load a pickled file.
Args:
file (file): A pickled file that contains information.
Return:
A string of data retrived from the pickle file `file`.
"""
try:
with open(file + ".pickle", 'rb') as f:
return pickle.load(f)
except FileNotFoundError:
raise FileNotFoundError("The file doesn't exist!")
def __dump(self, obj, file):
"""
Serialize the data gathered to access it elsewhere.
Args:
obj (:obj:): The object(s) to be serialized.
file (file): The file the data will be stored in
"""
with open(file + ".pickle", 'wb') as f:
pickle.dump(obj, f)
|
[
"class",
"Scraper",
":",
"def",
"__init__",
"(",
"self",
",",
"coins",
")",
":",
"self",
".",
"coins",
"=",
"coins",
"self",
".",
"time",
"=",
"0",
"self",
".",
"link",
"=",
"\"https://api.coinmarketcap.com/v1/ticker/\"",
"self",
".",
"http",
"=",
"urllib3",
".",
"PoolManager",
"(",
"cert_reqs",
"=",
"'CERT_REQUIRED'",
",",
"ca_certs",
"=",
"certifi",
".",
"where",
"(",
")",
")",
"def",
"get_coin_with_id",
"(",
"self",
",",
"id",
")",
":",
"\"\"\"\n Args:\n id (string): An id of a coin.Coin object.\n Return:\n returns coin.Coin with id id, if it exists.\n >>> import coin\n >>> btc = coin.Coin(\"bitcoin\", \"BTC\", 8000, 10000, 10, -15)\n >>> b = Scraper([btc])\n >>> passes = b.get_coin_with_id(\"bitcoin\")\n >>> passes.symbol\n 'BTC'\n >>> fails = b.get_coin_with_id(\"fail\")\n Traceback (most recent call last):\n ...\n ValueError: You have not added this coin in coins.txt!\n\n \"\"\"",
"for",
"coin",
"in",
"self",
".",
"coins",
":",
"if",
"coin",
".",
"has_id",
"(",
"id",
")",
":",
"return",
"coin",
"raise",
"ValueError",
"(",
"\"You have not added this coin in settings/coins.txt!\"",
")",
"def",
"update_frequency",
"(",
"self",
")",
":",
"\"\"\"\n Returns:\n The number of minutes between the script updating the information.\n\n \"\"\"",
"return",
"UPDATE",
"def",
"print_coins",
"(",
"self",
")",
":",
"\"\"\"\n Returns:\n A string of the coins this scraper searches for.\n\n >>> import coin\n >>> lst = [coin.Coin(\"bitcoin\", \"BTC\", 8000, 10000, 10, -10), \\\n coin.Coin(\"litecoin\", \"LTC\", 200, 400, 15, -15), \\\n coin.Coin(\"monero\", \"XMR\", 300, 500, 10, -5)]\n >>> test = Scraper(lst)\n >>> test.print_coins()\n Coins and Tokens:\n bitcoin\n litecoin\n monero\n\n \"\"\"",
"coins",
"=",
"self",
".",
"coins",
"result",
"=",
"\"Coins and Tokens:\"",
"for",
"coin",
"in",
"coins",
":",
"result",
"+=",
"\"\\n\"",
"+",
"coin",
".",
"id",
"print",
"(",
"result",
")",
"def",
"request_coin",
"(",
"self",
",",
"name",
")",
":",
"\"\"\"\n Requests data about a coin, stores data in this coin's pickle file.\n\n Args:\n name (str): a string that represents a Coin objects id.\n\n Returns:\n JSON data describing the coin with the id name.\n \"\"\"",
"try",
":",
"r",
"=",
"self",
".",
"http",
".",
"request",
"(",
"'GET'",
",",
"self",
".",
"link",
"+",
"\"/\"",
"+",
"name",
")",
"result",
"=",
"json",
".",
"loads",
"(",
"r",
".",
"data",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"if",
"result",
"==",
"{",
"'error'",
":",
"'id not found'",
"}",
":",
"raise",
"ValueError",
"(",
"\"{} is either not a valid id or is not listed \"",
"\"on CoinMarketCap.com. Please remove it from \"",
"\"coins.txt\"",
".",
"format",
"(",
"name",
")",
")",
"else",
":",
"dest",
"=",
"'Currencies/'",
"+",
"name",
"try",
":",
"previous",
"=",
"self",
".",
"__load",
"(",
"dest",
")",
"updated",
"=",
"previous",
"+",
"result",
"self",
".",
"__dump",
"(",
"updated",
",",
"dest",
")",
"except",
"FileNotFoundError",
":",
"self",
".",
"__dump",
"(",
"result",
",",
"dest",
")",
"return",
"result",
"except",
"urllib3",
".",
"exceptions",
".",
"MaxRetryError",
":",
"os",
".",
"system",
"(",
"\"\"\"osascript -e 'display notification \"FAILED TO CONNECT\"\n with title \"FATAL ERROR\"'\"\"\"",
")",
"raise",
"Exception",
"(",
"\"Failed to connect to server. Check internet \"",
"\"connection.\"",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"Something went wrong\"",
")",
"def",
"__load",
"(",
"self",
",",
"file",
")",
":",
"\"\"\"\n Load a pickled file.\n\n Args:\n file (file): A pickled file that contains information.\n\n Return:\n A string of data retrived from the pickle file `file`.\n\n \"\"\"",
"try",
":",
"with",
"open",
"(",
"file",
"+",
"\".pickle\"",
",",
"'rb'",
")",
"as",
"f",
":",
"return",
"pickle",
".",
"load",
"(",
"f",
")",
"except",
"FileNotFoundError",
":",
"raise",
"FileNotFoundError",
"(",
"\"The file doesn't exist!\"",
")",
"def",
"__dump",
"(",
"self",
",",
"obj",
",",
"file",
")",
":",
"\"\"\"\n Serialize the data gathered to access it elsewhere.\n\n Args:\n obj (:obj:): The object(s) to be serialized.\n\n file (file): The file the data will be stored in\n\n \"\"\"",
"with",
"open",
"(",
"file",
"+",
"\".pickle\"",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"obj",
",",
"f",
")"
] |
A web scraper that connects to the CoinMarketCap API.
|
[
"A",
"web",
"scraper",
"that",
"connects",
"to",
"the",
"CoinMarketCap",
"API",
"."
] |
[
"\"\"\" A web scraper that connects to the CoinMarketCap API.\n\n Args:\n coins (List(Obj)): A list of coin.Coin objects.\n Attributes:\n coins (List(Obj)): A list of coin.Coin objects.\n time (int): The time the scrape retrived the data. (not implemented)\n link (str): The coinmarketcap api link.\n http (obj): A urllib3 object.\n \"\"\"",
"# Why is this a property? Lets make it a constant.",
"# TODO: replace ValueError with a logger.",
"\"\"\"\n Args:\n id (string): An id of a coin.Coin object.\n Return:\n returns coin.Coin with id id, if it exists.\n >>> import coin\n >>> btc = coin.Coin(\"bitcoin\", \"BTC\", 8000, 10000, 10, -15)\n >>> b = Scraper([btc])\n >>> passes = b.get_coin_with_id(\"bitcoin\")\n >>> passes.symbol\n 'BTC'\n >>> fails = b.get_coin_with_id(\"fail\")\n Traceback (most recent call last):\n ...\n ValueError: You have not added this coin in coins.txt!\n\n \"\"\"",
"\"\"\"\n Returns:\n The number of minutes between the script updating the information.\n\n \"\"\"",
"# global UPDATE const from settings",
"\"\"\"\n Returns:\n A string of the coins this scraper searches for.\n\n >>> import coin\n >>> lst = [coin.Coin(\"bitcoin\", \"BTC\", 8000, 10000, 10, -10), \\\n coin.Coin(\"litecoin\", \"LTC\", 200, 400, 15, -15), \\\n coin.Coin(\"monero\", \"XMR\", 300, 500, 10, -5)]\n >>> test = Scraper(lst)\n >>> test.print_coins()\n Coins and Tokens:\n bitcoin\n litecoin\n monero\n\n \"\"\"",
"# TODO: work on exceptions",
"\"\"\"\n Requests data about a coin, stores data in this coin's pickle file.\n\n Args:\n name (str): a string that represents a Coin objects id.\n\n Returns:\n JSON data describing the coin with the id name.\n \"\"\"",
"# error connecting to site",
"\"\"\"\n Load a pickled file.\n\n Args:\n file (file): A pickled file that contains information.\n\n Return:\n A string of data retrived from the pickle file `file`.\n\n \"\"\"",
"\"\"\"\n Serialize the data gathered to access it elsewhere.\n\n Args:\n obj (:obj:): The object(s) to be serialized.\n\n file (file): The file the data will be stored in\n\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "coins",
"type": null,
"docstring": "A list of coin.Coin objects.",
"docstring_tokens": [
"A",
"list",
"of",
"coin",
".",
"Coin",
"objects",
"."
],
"default": null,
"is_optional": false
},
{
"identifier": "time",
"type": null,
"docstring": "The time the scrape retrived the data. (not implemented)",
"docstring_tokens": [
"The",
"time",
"the",
"scrape",
"retrived",
"the",
"data",
".",
"(",
"not",
"implemented",
")"
],
"default": null,
"is_optional": false
},
{
"identifier": "link",
"type": null,
"docstring": "The coinmarketcap api link.",
"docstring_tokens": [
"The",
"coinmarketcap",
"api",
"link",
"."
],
"default": null,
"is_optional": false
},
{
"identifier": "http",
"type": null,
"docstring": "A urllib3 object.",
"docstring_tokens": [
"A",
"urllib3",
"object",
"."
],
"default": null,
"is_optional": false
}
],
"others": []
}
| false
| 16
| 1,040
| 89
|
0234c2654db8de854601b51aa6a48d0f3689e69c
|
robert-95/AutomadTry
|
automad/gui/js/editorjs/inline/fontsize.js
|
[
"MIT"
] |
JavaScript
|
AutomadFontSize
|
/*
* ....
* .: '':.
* :::: ':..
* ::. ''..
* .:'.. ..':.:::' . :. '':.
* :. '' '' '. ::::.. ..:
* ::::. ..':.. .'''::::: .
* :::::::.. '..:::: :. :::: :
* ::'':::::::. ':::.'':.:::: :
* :.. ''::::::....': '':: :
* :::::. '::::: : .. '' .
* .''::::::::... ':::.'' ..'' :.''''.
* :..:::''::::: :::::...:'' :..:
* ::::::. ':::: :::::::: ..:: .
* ::::::::.:::: :::::::: :'':.:: .''
* ::: '::::::::.' ''::::: :.' '': :
* ::: :::::::::..' :::: ::...' .
* ::: .:::::::::: :::: :::: .:'
* '::' ''::::::: :::: : :: :
* ':::: :::: :'' .:
* :::: :::: ..''
* :::: ..:::: .:''
* '''' '''''
*
*
* AUTOMAD
*
* Copyright (c) 2021 by Marc Anton Dahmen
* https://marcdahmen.de
*
* Licensed under the MIT license.
* https://automad.org/license
*/
|
AUTOMAD
Licensed under the MIT license.
|
[
"AUTOMAD",
"Licensed",
"under",
"the",
"MIT",
"license",
"."
] |
class AutomadFontSize extends AutomadInlineTool {
static get title() {
return 'Font Size';
}
static get sanitize() {
return {
'am-fontsize': true
};
}
get tag() {
return 'AM-FONTSIZE';
}
get icon() {
return '<path d="M7.14,2h12.2C19.7,2,20,2.3,20,2.66v1.82c0,0.36-0.3,0.66-0.66,0.66h-3.53c-0.36,0-0.66,0.3-0.66,0.66v11.54 c0,0.36-0.3,0.66-0.66,0.66H12c-0.36,0-0.66-0.3-0.66-0.66V5.8c0-0.36-0.3-0.66-0.66-0.66H7.14c-0.36,0-0.66-0.3-0.66-0.66V2.66 C6.48,2.3,6.77,2,7.14,2z"/><path d="M0.45,7h8.39C9.09,7,9.3,7.2,9.3,7.45v1.25c0,0.25-0.2,0.45-0.45,0.45H6.42c-0.25,0-0.45,0.2-0.45,0.45v7.93 c0,0.25-0.2,0.45-0.45,0.45H3.79c-0.25,0-0.45-0.2-0.45-0.45V9.61c0-0.25-0.2-0.45-0.45-0.45H0.45C0.2,9.16,0,8.96,0,8.71V7.45 C0,7.2,0.2,7,0.45,7z"/>';
}
get options() {
return ['70%', '80%', '90%', '100%', '110%', '120%', '130%', '140%', '150%', '160%', '170%', '180%', '190%', '200%'];
}
renderActions() {
const create = Automad.util.create,
label = create.label(AutomadFontSize.title);
this.select = create.select([this.cls.input], this.options, this.selected);
this.wrapper = create.element('span', [this.cls.wrapper]);
this.wrapper.appendChild(label);
this.wrapper.appendChild(this.select);
this.wrapper.hidden = true;
return this.wrapper;
}
showActions(node) {
const { fontSize } = node.style;
this.select.value = fontSize ? fontSize : '100%';
node.style.fontSize = this.select.value;
this.select.onchange = () => {
node.style.fontSize = this.select.value;
};
this.wrapper.hidden = false;
}
hideActions() {
this.select.onchange = null;
this.wrapper.hidden = true;
}
}
|
[
"class",
"AutomadFontSize",
"extends",
"AutomadInlineTool",
"{",
"static",
"get",
"title",
"(",
")",
"{",
"return",
"'Font Size'",
";",
"}",
"static",
"get",
"sanitize",
"(",
")",
"{",
"return",
"{",
"'am-fontsize'",
":",
"true",
"}",
";",
"}",
"get",
"tag",
"(",
")",
"{",
"return",
"'AM-FONTSIZE'",
";",
"}",
"get",
"icon",
"(",
")",
"{",
"return",
"'<path d=\"M7.14,2h12.2C19.7,2,20,2.3,20,2.66v1.82c0,0.36-0.3,0.66-0.66,0.66h-3.53c-0.36,0-0.66,0.3-0.66,0.66v11.54 c0,0.36-0.3,0.66-0.66,0.66H12c-0.36,0-0.66-0.3-0.66-0.66V5.8c0-0.36-0.3-0.66-0.66-0.66H7.14c-0.36,0-0.66-0.3-0.66-0.66V2.66 C6.48,2.3,6.77,2,7.14,2z\"/><path d=\"M0.45,7h8.39C9.09,7,9.3,7.2,9.3,7.45v1.25c0,0.25-0.2,0.45-0.45,0.45H6.42c-0.25,0-0.45,0.2-0.45,0.45v7.93 c0,0.25-0.2,0.45-0.45,0.45H3.79c-0.25,0-0.45-0.2-0.45-0.45V9.61c0-0.25-0.2-0.45-0.45-0.45H0.45C0.2,9.16,0,8.96,0,8.71V7.45 C0,7.2,0.2,7,0.45,7z\"/>'",
";",
"}",
"get",
"options",
"(",
")",
"{",
"return",
"[",
"'70%'",
",",
"'80%'",
",",
"'90%'",
",",
"'100%'",
",",
"'110%'",
",",
"'120%'",
",",
"'130%'",
",",
"'140%'",
",",
"'150%'",
",",
"'160%'",
",",
"'170%'",
",",
"'180%'",
",",
"'190%'",
",",
"'200%'",
"]",
";",
"}",
"renderActions",
"(",
")",
"{",
"const",
"create",
"=",
"Automad",
".",
"util",
".",
"create",
",",
"label",
"=",
"create",
".",
"label",
"(",
"AutomadFontSize",
".",
"title",
")",
";",
"this",
".",
"select",
"=",
"create",
".",
"select",
"(",
"[",
"this",
".",
"cls",
".",
"input",
"]",
",",
"this",
".",
"options",
",",
"this",
".",
"selected",
")",
";",
"this",
".",
"wrapper",
"=",
"create",
".",
"element",
"(",
"'span'",
",",
"[",
"this",
".",
"cls",
".",
"wrapper",
"]",
")",
";",
"this",
".",
"wrapper",
".",
"appendChild",
"(",
"label",
")",
";",
"this",
".",
"wrapper",
".",
"appendChild",
"(",
"this",
".",
"select",
")",
";",
"this",
".",
"wrapper",
".",
"hidden",
"=",
"true",
";",
"return",
"this",
".",
"wrapper",
";",
"}",
"showActions",
"(",
"node",
")",
"{",
"const",
"{",
"fontSize",
"}",
"=",
"node",
".",
"style",
";",
"this",
".",
"select",
".",
"value",
"=",
"fontSize",
"?",
"fontSize",
":",
"'100%'",
";",
"node",
".",
"style",
".",
"fontSize",
"=",
"this",
".",
"select",
".",
"value",
";",
"this",
".",
"select",
".",
"onchange",
"=",
"(",
")",
"=>",
"{",
"node",
".",
"style",
".",
"fontSize",
"=",
"this",
".",
"select",
".",
"value",
";",
"}",
";",
"this",
".",
"wrapper",
".",
"hidden",
"=",
"false",
";",
"}",
"hideActions",
"(",
")",
"{",
"this",
".",
"select",
".",
"onchange",
"=",
"null",
";",
"this",
".",
"wrapper",
".",
"hidden",
"=",
"true",
";",
"}",
"}"
] |
....
|
[
"...."
] |
[] |
[
{
"param": "AutomadInlineTool",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "AutomadInlineTool",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 823
| 353
|
a6e91767a042bdc7377e208ea42d6778fe6b7768
|
bassclefstudio/.NET
|
BassClefStudio.NET.Core/Structures/Graph.cs
|
[
"MIT"
] |
C#
|
Graph
|
/// <summary>
/// Represents a mathematical graph data structure, containing <typeparamref name="TNode"/> nodes connected by <typeparamref name="TConnection"/> connections.
/// </summary>
/// <typeparam name="TNode">The type of <see cref="INode"/> nodes in the graph.</typeparam>
/// <typeparam name="TConnection">The type of <see cref="IConnection{T}"/> connections between <typeparamref name="TNode"/> nodes in the graph.</typeparam>
|
Represents a mathematical graph data structure, containing nodes connected by connections.
|
[
"Represents",
"a",
"mathematical",
"graph",
"data",
"structure",
"containing",
"nodes",
"connected",
"by",
"connections",
"."
] |
public class Graph<TNode, TConnection> : Observable where TNode : INode where TConnection : IConnection<TNode>
{
protected ObservableCollection<TNode> nodes;
public ReadOnlyObservableCollection<TNode> Nodes { get; }
protected ObservableCollection<TConnection> connections;
public ReadOnlyObservableCollection<TConnection> Connections { get; }
public Graph()
{
nodes = new ObservableCollection<TNode>();
Nodes = new ReadOnlyObservableCollection<TNode>(nodes);
connections = new ObservableCollection<TConnection>();
Connections = new ReadOnlyObservableCollection<TConnection>(connections);
}
#region Actions
public virtual void AddConnection(TConnection connection)
{
if (!Nodes.Contains(connection.StartNode))
{
AddNode(connection.StartNode);
}
if (!Nodes.Contains(connection.EndNode))
{
AddNode(connection.EndNode);
}
connections.Add(connection);
}
public virtual void AddNode(TNode node)
{
nodes.Add(node);
}
public virtual void RemoveConnection(TConnection connection)
{
connections.Remove(connection);
}
public virtual void RemoveNode(TNode node)
{
nodes.Remove(node);
foreach (var connection in connections.Where(l => l.StartNode.Equals(node) || l.EndNode.Equals(node)).ToArray())
{
RemoveConnection(connection);
}
}
#endregion
#region Queries
public IEnumerable<TNode> GetNodes(TNode myNode, bool useModes = true)
{
if (useModes)
{
return Connections.Where(c => c.Mode.HasFlag(ConnectionMode.Forwards) && c.StartNode.Equals(myNode))
.Select(c => c.EndNode)
.Concat(Connections.Where(c => c.Mode.HasFlag(ConnectionMode.Backwards) && c.EndNode.Equals(myNode))
.Select(c => c.StartNode)).Distinct();
}
else
{
return Connections.Where(c => c.StartNode.Equals(myNode))
.Select(c => c.EndNode)
.Concat(Connections.Where(c => c.EndNode.Equals(myNode))
.Select(c => c.StartNode)).Distinct();
}
}
public IEnumerable<TConnection> GetConnections(TNode myNode, bool useModes = true)
{
if (useModes)
{
return Connections.Where(c => c.Mode.HasFlag(ConnectionMode.Forwards) && c.StartNode.Equals(myNode))
.Concat(Connections.Where(c => c.Mode.HasFlag(ConnectionMode.Backwards) && c.EndNode.Equals(myNode)))
.Distinct();
}
else
{
return Connections.Where(c => c.StartNode.Equals(myNode) || c.EndNode.Equals(myNode));
}
}
public IPath<TNode, TConnection> FindPath(TNode start, TNode end, bool useModes = true)
{
HashSet<TNode> visitedNodes = new HashSet<TNode>();
IPath<TNode, TConnection>[] paths = new IPath<TNode, TConnection>[] { new Path<TNode, TConnection>(start) };
while (paths.Length > 0 && !paths.Any(p => p.EndNode.Equals(end)))
{
paths = paths.SelectMany(p => GetConnections(p.EndNode, useModes)
.Select(c => p.Concat(c)))
.Where(p => visitedNodes.Add(p.EndNode))
.ToArray();
}
return paths.FirstOrDefault(p => p.EndNode.Equals(end));
}
#endregion
}
|
[
"public",
"class",
"Graph",
"<",
"TNode",
",",
"TConnection",
">",
":",
"Observable",
"where",
"TNode",
":",
"INode",
"where",
"TConnection",
":",
"IConnection",
"<",
"TNode",
">",
"{",
"protected",
"ObservableCollection",
"<",
"TNode",
">",
"nodes",
";",
"public",
"ReadOnlyObservableCollection",
"<",
"TNode",
">",
"Nodes",
"{",
"get",
";",
"}",
"protected",
"ObservableCollection",
"<",
"TConnection",
">",
"connections",
";",
"public",
"ReadOnlyObservableCollection",
"<",
"TConnection",
">",
"Connections",
"{",
"get",
";",
"}",
"public",
"Graph",
"(",
")",
"{",
"nodes",
"=",
"new",
"ObservableCollection",
"<",
"TNode",
">",
"(",
")",
";",
"Nodes",
"=",
"new",
"ReadOnlyObservableCollection",
"<",
"TNode",
">",
"(",
"nodes",
")",
";",
"connections",
"=",
"new",
"ObservableCollection",
"<",
"TConnection",
">",
"(",
")",
";",
"Connections",
"=",
"new",
"ReadOnlyObservableCollection",
"<",
"TConnection",
">",
"(",
"connections",
")",
";",
"}",
"region",
" Actions",
"public",
"virtual",
"void",
"AddConnection",
"(",
"TConnection",
"connection",
")",
"{",
"if",
"(",
"!",
"Nodes",
".",
"Contains",
"(",
"connection",
".",
"StartNode",
")",
")",
"{",
"AddNode",
"(",
"connection",
".",
"StartNode",
")",
";",
"}",
"if",
"(",
"!",
"Nodes",
".",
"Contains",
"(",
"connection",
".",
"EndNode",
")",
")",
"{",
"AddNode",
"(",
"connection",
".",
"EndNode",
")",
";",
"}",
"connections",
".",
"Add",
"(",
"connection",
")",
";",
"}",
"public",
"virtual",
"void",
"AddNode",
"(",
"TNode",
"node",
")",
"{",
"nodes",
".",
"Add",
"(",
"node",
")",
";",
"}",
"public",
"virtual",
"void",
"RemoveConnection",
"(",
"TConnection",
"connection",
")",
"{",
"connections",
".",
"Remove",
"(",
"connection",
")",
";",
"}",
"public",
"virtual",
"void",
"RemoveNode",
"(",
"TNode",
"node",
")",
"{",
"nodes",
".",
"Remove",
"(",
"node",
")",
";",
"foreach",
"(",
"var",
"connection",
"in",
"connections",
".",
"Where",
"(",
"l",
"=>",
"l",
".",
"StartNode",
".",
"Equals",
"(",
"node",
")",
"||",
"l",
".",
"EndNode",
".",
"Equals",
"(",
"node",
")",
")",
".",
"ToArray",
"(",
")",
")",
"{",
"RemoveConnection",
"(",
"connection",
")",
";",
"}",
"}",
"endregion",
"region",
" Queries",
"public",
"IEnumerable",
"<",
"TNode",
">",
"GetNodes",
"(",
"TNode",
"myNode",
",",
"bool",
"useModes",
"=",
"true",
")",
"{",
"if",
"(",
"useModes",
")",
"{",
"return",
"Connections",
".",
"Where",
"(",
"c",
"=>",
"c",
".",
"Mode",
".",
"HasFlag",
"(",
"ConnectionMode",
".",
"Forwards",
")",
"&&",
"c",
".",
"StartNode",
".",
"Equals",
"(",
"myNode",
")",
")",
".",
"Select",
"(",
"c",
"=>",
"c",
".",
"EndNode",
")",
".",
"Concat",
"(",
"Connections",
".",
"Where",
"(",
"c",
"=>",
"c",
".",
"Mode",
".",
"HasFlag",
"(",
"ConnectionMode",
".",
"Backwards",
")",
"&&",
"c",
".",
"EndNode",
".",
"Equals",
"(",
"myNode",
")",
")",
".",
"Select",
"(",
"c",
"=>",
"c",
".",
"StartNode",
")",
")",
".",
"Distinct",
"(",
")",
";",
"}",
"else",
"{",
"return",
"Connections",
".",
"Where",
"(",
"c",
"=>",
"c",
".",
"StartNode",
".",
"Equals",
"(",
"myNode",
")",
")",
".",
"Select",
"(",
"c",
"=>",
"c",
".",
"EndNode",
")",
".",
"Concat",
"(",
"Connections",
".",
"Where",
"(",
"c",
"=>",
"c",
".",
"EndNode",
".",
"Equals",
"(",
"myNode",
")",
")",
".",
"Select",
"(",
"c",
"=>",
"c",
".",
"StartNode",
")",
")",
".",
"Distinct",
"(",
")",
";",
"}",
"}",
"public",
"IEnumerable",
"<",
"TConnection",
">",
"GetConnections",
"(",
"TNode",
"myNode",
",",
"bool",
"useModes",
"=",
"true",
")",
"{",
"if",
"(",
"useModes",
")",
"{",
"return",
"Connections",
".",
"Where",
"(",
"c",
"=>",
"c",
".",
"Mode",
".",
"HasFlag",
"(",
"ConnectionMode",
".",
"Forwards",
")",
"&&",
"c",
".",
"StartNode",
".",
"Equals",
"(",
"myNode",
")",
")",
".",
"Concat",
"(",
"Connections",
".",
"Where",
"(",
"c",
"=>",
"c",
".",
"Mode",
".",
"HasFlag",
"(",
"ConnectionMode",
".",
"Backwards",
")",
"&&",
"c",
".",
"EndNode",
".",
"Equals",
"(",
"myNode",
")",
")",
")",
".",
"Distinct",
"(",
")",
";",
"}",
"else",
"{",
"return",
"Connections",
".",
"Where",
"(",
"c",
"=>",
"c",
".",
"StartNode",
".",
"Equals",
"(",
"myNode",
")",
"||",
"c",
".",
"EndNode",
".",
"Equals",
"(",
"myNode",
")",
")",
";",
"}",
"}",
"public",
"IPath",
"<",
"TNode",
",",
"TConnection",
">",
"FindPath",
"(",
"TNode",
"start",
",",
"TNode",
"end",
",",
"bool",
"useModes",
"=",
"true",
")",
"{",
"HashSet",
"<",
"TNode",
">",
"visitedNodes",
"=",
"new",
"HashSet",
"<",
"TNode",
">",
"(",
")",
";",
"IPath",
"<",
"TNode",
",",
"TConnection",
">",
"[",
"]",
"paths",
"=",
"new",
"IPath",
"<",
"TNode",
",",
"TConnection",
">",
"[",
"]",
"{",
"new",
"Path",
"<",
"TNode",
",",
"TConnection",
">",
"(",
"start",
")",
"}",
";",
"while",
"(",
"paths",
".",
"Length",
">",
"0",
"&&",
"!",
"paths",
".",
"Any",
"(",
"p",
"=>",
"p",
".",
"EndNode",
".",
"Equals",
"(",
"end",
")",
")",
")",
"{",
"paths",
"=",
"paths",
".",
"SelectMany",
"(",
"p",
"=>",
"GetConnections",
"(",
"p",
".",
"EndNode",
",",
"useModes",
")",
".",
"Select",
"(",
"c",
"=>",
"p",
".",
"Concat",
"(",
"c",
")",
")",
")",
".",
"Where",
"(",
"p",
"=>",
"visitedNodes",
".",
"Add",
"(",
"p",
".",
"EndNode",
")",
")",
".",
"ToArray",
"(",
")",
";",
"}",
"return",
"paths",
".",
"FirstOrDefault",
"(",
"p",
"=>",
"p",
".",
"EndNode",
".",
"Equals",
"(",
"end",
")",
")",
";",
"}",
"endregion",
"}"
] |
Represents a mathematical graph data structure, containing nodes connected by connections.
|
[
"Represents",
"a",
"mathematical",
"graph",
"data",
"structure",
"containing",
"nodes",
"connected",
"by",
"connections",
"."
] |
[
"/// <summary>",
"/// The writable <see cref=\"Nodes\"/> collection.",
"/// </summary>",
"/// <summary>",
"/// The full collection of all <typeparamref name=\"TNode\"/> nodes in the graph.",
"/// </summary>",
"/// <summary>",
"/// The writable <see cref=\"Connections\"/> collection.",
"/// </summary>",
"/// <summary>",
"/// The full collection of all <typeparamref name=\"TNode\"/> nodes in the graph.",
"/// </summary>",
"/// <summary>",
"/// Creates a new, empty <see cref=\"Graph{TNode, TConnection}\"/>.",
"/// </summary>",
"/// <summary>",
"/// Adds a <see cref=\"IConnection{T}\"/> and all its dependencies to the <see cref=\"Graph{TNode, TConnection}\"/>.",
"/// </summary>",
"/// <param name=\"connection\">The <typeparamref name=\"TConnection\"/> connection to add.</param>",
"/// <summary>",
"/// Adds a <see cref=\"INode\"/> and all its dependencies to the <see cref=\"Graph{TNode, TConnection}\"/>.",
"/// </summary>",
"/// <param name=\"node\">The <typeparamref name=\"TNode\"/> node to add.</param>",
"/// <summary>",
"/// Removes a <see cref=\"IConnection{T}\"/> and any dependencies from the <see cref=\"Graph{TNode, TConnection}\"/>.",
"/// </summary>",
"/// <param name=\"connection\">The <typeparamref name=\"TConnection\"/> connection to remove.</param>",
"/// <summary>",
"/// Removes a <see cref=\"INode\"/> and any dependencies from the <see cref=\"Graph{TNode, TConnection}\"/>.",
"/// </summary>",
"/// <param name=\"node\">The <typeparamref name=\"TNode\"/> node to remove.</param>",
"/// <summary>",
"/// Get all <typeparamref name=\"TNode\"/> nodes that can be connected to the given <typeparamref name=\"TNode\"/>.",
"/// </summary>",
"/// <param name=\"myNode\">The <see cref=\"INode\"/> being queried.</param>",
"/// <param name=\"useModes\">A <see cref=\"bool\"/> indicating whether the query should take the <see cref=\"IConnection{T}.Mode\"/> into account.</param>",
"/// <returns>A collection of all <see cref=\"INode\"/>s that are connected via <see cref=\"IConnection{T}\"/>s to <paramref name=\"myNode\"/>.</returns>",
"/// <summary>",
"/// Get all <typeparamref name=\"TConnection\"/> connections from a given <typeparamref name=\"TNode\"/>.",
"/// </summary>",
"/// <param name=\"myNode\">The <see cref=\"INode\"/> being queried.</param>",
"/// <param name=\"useModes\">A <see cref=\"bool\"/> indicating whether the query should take the <see cref=\"IConnection{T}.Mode\"/> into account.</param>",
"/// <returns>A collection of <see cref=\"IConnection{T}\"/>s coming from <paramref name=\"myNode\"/>.</returns>",
"/// <summary>",
"/// Uses a brute-force method to calculate the shortest <see cref=\"IPath{TNode, TConnection}\"/> between a start and end <typeparamref name=\"TNode\"/>.",
"/// </summary>",
"/// <param name=\"start\">The <see cref=\"INode\"/> to start at.</param>",
"/// <param name=\"end\">The <see cref=\"INode\"/> to end at.</param>",
"/// <param name=\"useModes\">A <see cref=\"bool\"/> indicating whether the search should take the <see cref=\"IConnection{T}.Mode\"/> into account when building a route.</param>",
"/// <returns>The shortest <see cref=\"IPath{TNode, TConnection}\"/> between the two nodes, or 'null' if none exists.</returns>"
] |
[
{
"param": "Observable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Observable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "typeparam",
"docstring": "The type of nodes in the graph.",
"docstring_tokens": [
"The",
"type",
"of",
"nodes",
"in",
"the",
"graph",
"."
]
},
{
"identifier": "typeparam",
"docstring": "The type of connections between nodes in the graph.",
"docstring_tokens": [
"The",
"type",
"of",
"connections",
"between",
"nodes",
"in",
"the",
"graph",
"."
]
}
]
}
| false
| 24
| 710
| 100
|
8ddac750810ebc3e0a29dd7845c4ce85e6491137
|
blackjid/semantic_logger
|
lib/semantic_logger/loggable.rb
|
[
"Apache-2.0"
] |
Ruby
|
SemanticLogger
|
# Logger class variable mix-in
#
# Lazy initialize a logger class variable with instance accessor
#
# By including this mix-in into any class it will define a class level logger
# and also make it accessible via instance methods
#
# Example:
# require 'semantic_logger'
# SemanticLogger.default_level = :debug
# SemanticLogger.add_appender(io: $stdout, formatter: :color)
#
# class ExternalSupplier
# # Create class and instance logger methods
# include SemanticLogger::Loggable
#
# def call_supplier(amount, name)
# logger.debug "Calculating with amount", { amount: amount, name: name }
#
# # Measure and log on completion how long the call took to the external supplier
# logger.measure_info "Calling external interface" do
# # Code to call the external supplier ...
# end
# end
# end
#
# Notes:
# * To forcibly replace Rails or any other existing logging methods
# use `prepend` instead of `include`. For example:
# ExternalSupplier.prepend SemanticLogger::Loggable
|
Logger class variable mix-in
Lazy initialize a logger class variable with instance accessor
By including this mix-in into any class it will define a class level logger
and also make it accessible via instance methods
class ExternalSupplier
Create class and instance logger methods
include SemanticLogger::Loggable
Measure and log on completion how long the call took to the external supplier
logger.measure_info "Calling external interface" do
Code to call the external supplier
end
end
end
To forcibly replace Rails or any other existing logging methods
use `prepend` instead of `include`.
|
[
"Logger",
"class",
"variable",
"mix",
"-",
"in",
"Lazy",
"initialize",
"a",
"logger",
"class",
"variable",
"with",
"instance",
"accessor",
"By",
"including",
"this",
"mix",
"-",
"in",
"into",
"any",
"class",
"it",
"will",
"define",
"a",
"class",
"level",
"logger",
"and",
"also",
"make",
"it",
"accessible",
"via",
"instance",
"methods",
"class",
"ExternalSupplier",
"Create",
"class",
"and",
"instance",
"logger",
"methods",
"include",
"SemanticLogger",
"::",
"Loggable",
"Measure",
"and",
"log",
"on",
"completion",
"how",
"long",
"the",
"call",
"took",
"to",
"the",
"external",
"supplier",
"logger",
".",
"measure_info",
"\"",
"Calling",
"external",
"interface",
"\"",
"do",
"Code",
"to",
"call",
"the",
"external",
"supplier",
"end",
"end",
"end",
"To",
"forcibly",
"replace",
"Rails",
"or",
"any",
"other",
"existing",
"logging",
"methods",
"use",
"`",
"prepend",
"`",
"instead",
"of",
"`",
"include",
"`",
"."
] |
module SemanticLogger
module Loggable
def self.included(base)
base.extend ClassMethods
base.class_eval do
# Returns [SemanticLogger::Logger] class level logger
def self.logger
@semantic_logger ||= SemanticLogger[self]
end
# Replace instance class level logger
def self.logger=(logger)
@semantic_logger = logger
end
# Returns [SemanticLogger::Logger] instance level logger
def logger
@semantic_logger ||= self.class.logger
end
# Replace instance level logger
def logger=(logger)
@semantic_logger = logger
end
end
end
module ClassMethods
# Measure and log the performance of an instance method.
#
# Parameters:
# method_name: [Symbol]
# The name of the method that should be measured.
#
# options: [Hash]
# Any valid options that can be passed to measure.
#
# Approximate overhead when logging a method call with a metric:
# 0.044 ms per method call.
# 0.009 ms per method call. If `min_duration` is not met
# 0.0005 ms per method call. If `level` is not met
def logger_measure_method(method_name,
min_duration: 0.0,
metric: "#{name}/#{method_name}",
log_exception: :partial,
on_exception_level: nil,
message: "##{method_name}",
level: :info)
# unless visibility = Utils.method_visibility(self, method_name)
# logger.warn("Unable to measure method: #{name}##{method_name} since it does not exist")
# return false
# end
index = Levels.index(level)
logger_measure_module.module_eval(<<~MEASURE_METHOD, __FILE__, __LINE__ + 1)
def #{method_name}(*args, &block)
if logger.send(:level_index) <= #{index}
logger.send(
:measure_method,
index: #{index},
level: #{level.inspect},
message: #{message.inspect},
min_duration: #{min_duration},
metric: #{metric.inspect},
log_exception: #{log_exception.inspect},
on_exception_level: #{on_exception_level.inspect}
) do
super(*args, &block)
end
else
super(*args, &block)
end
end
MEASURE_METHOD
# {"#{visibility} :#{method_name}" unless visibility == :public}
true
end
private
# Dynamic Module to intercept method calls for measuring purposes.
def logger_measure_module
if const_defined?(:SemanticLoggerMeasure, _search_ancestors = false)
const_get(:SemanticLoggerMeasure)
else
mod = const_set(:SemanticLoggerMeasure, Module.new)
prepend mod
mod
end
end
end
end
end
|
[
"module",
"SemanticLogger",
"module",
"Loggable",
"def",
"self",
".",
"included",
"(",
"base",
")",
"base",
".",
"extend",
"ClassMethods",
"base",
".",
"class_eval",
"do",
"def",
"self",
".",
"logger",
"@semantic_logger",
"||=",
"SemanticLogger",
"[",
"self",
"]",
"end",
"def",
"self",
".",
"logger",
"=",
"(",
"logger",
")",
"@semantic_logger",
"=",
"logger",
"end",
"def",
"logger",
"@semantic_logger",
"||=",
"self",
".",
"class",
".",
"logger",
"end",
"def",
"logger",
"=",
"(",
"logger",
")",
"@semantic_logger",
"=",
"logger",
"end",
"end",
"end",
"module",
"ClassMethods",
"def",
"logger_measure_method",
"(",
"method_name",
",",
"min_duration",
":",
"0.0",
",",
"metric",
":",
"\"#{name}/#{method_name}\"",
",",
"log_exception",
":",
":partial",
",",
"on_exception_level",
":",
"nil",
",",
"message",
":",
"\"##{method_name}\"",
",",
"level",
":",
":info",
")",
"index",
"=",
"Levels",
".",
"index",
"(",
"level",
")",
"logger_measure_module",
".",
"module_eval",
"(",
"<<~MEASURE_METHOD",
",",
"__FILE__",
",",
"__LINE__",
"+",
"1",
")",
"\n def ",
"#{",
"method_name",
"}",
"(*args, &block)\n if logger.send(:level_index) <= ",
"#{",
"index",
"}",
"\n logger.send(\n :measure_method,\n index: ",
"#{",
"index",
"}",
",\n level: ",
"#{",
"level",
".",
"inspect",
"}",
",\n message: ",
"#{",
"message",
".",
"inspect",
"}",
",\n min_duration: ",
"#{",
"min_duration",
"}",
",\n metric: ",
"#{",
"metric",
".",
"inspect",
"}",
",\n log_exception: ",
"#{",
"log_exception",
".",
"inspect",
"}",
",\n on_exception_level: ",
"#{",
"on_exception_level",
".",
"inspect",
"}",
"\n ) do\n super(*args, &block)\n end\n else\n super(*args, &block)\n end\n end\n ",
"MEASURE_METHOD",
"true",
"end",
"private",
"def",
"logger_measure_module",
"if",
"const_defined?",
"(",
":SemanticLoggerMeasure",
",",
"_search_ancestors",
"=",
"false",
")",
"const_get",
"(",
":SemanticLoggerMeasure",
")",
"else",
"mod",
"=",
"const_set",
"(",
":SemanticLoggerMeasure",
",",
"Module",
".",
"new",
")",
"prepend",
"mod",
"mod",
"end",
"end",
"end",
"end",
"end"
] |
Logger class variable mix-in
Lazy initialize a logger class variable with instance accessor
|
[
"Logger",
"class",
"variable",
"mix",
"-",
"in",
"Lazy",
"initialize",
"a",
"logger",
"class",
"variable",
"with",
"instance",
"accessor"
] |
[
"# Returns [SemanticLogger::Logger] class level logger",
"# Replace instance class level logger",
"# Returns [SemanticLogger::Logger] instance level logger",
"# Replace instance level logger",
"# Measure and log the performance of an instance method.",
"#",
"# Parameters:",
"# method_name: [Symbol]",
"# The name of the method that should be measured.",
"#",
"# options: [Hash]",
"# Any valid options that can be passed to measure.",
"#",
"# Approximate overhead when logging a method call with a metric:",
"# 0.044 ms per method call.",
"# 0.009 ms per method call. If `min_duration` is not met",
"# 0.0005 ms per method call. If `level` is not met",
"# unless visibility = Utils.method_visibility(self, method_name)",
"# logger.warn(\"Unable to measure method: #{name}##{method_name} since it does not exist\")",
"# return false",
"# end",
"# {\"#{visibility} :#{method_name}\" unless visibility == :public}",
"# Dynamic Module to intercept method calls for measuring purposes."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 657
| 237
|
9a0e70fc54a6e4e3533ae4cfde4f60e0f6c3b110
|
WeLikeIke/DubitaC
|
Source/Library/PackageCache/[email protected]/Runtime/Smart Format/Extensions/DictionarySource.cs
|
[
"MIT"
] |
C#
|
DictionarySource
|
/// <summary>
/// Provides the ability to extract an object with a matching Key from an
/// [IDictionary](https://docs.microsoft.com/en-us/dotnet/api/system.collections.idictionary) or
/// [IDictionary<string, object>](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.idictionary-2).
/// </summary>
|
Provides the ability to extract an object with a matching Key from an
[IDictionary] or
[IDictionary].
|
[
"Provides",
"the",
"ability",
"to",
"extract",
"an",
"object",
"with",
"a",
"matching",
"Key",
"from",
"an",
"[",
"IDictionary",
"]",
"or",
"[",
"IDictionary",
"]",
"."
] |
[Serializable]
public class DictionarySource : ISource
{
public DictionarySource(SmartFormatter formatter)
{
formatter.Parser.AddAlphanumericSelectors();
formatter.Parser.AddAdditionalSelectorChars("_");
formatter.Parser.AddOperators(".");
}
public bool TryEvaluateSelector(ISelectorInfo selectorInfo)
{
var current = selectorInfo.CurrentValue;
var selector = selectorInfo.SelectorText;
var rawDict = current as IDictionary;
if (rawDict != null)
foreach (DictionaryEntry entry in rawDict)
{
var key = entry.Key as string ?? entry.Key.ToString();
if (key.Equals(selector, selectorInfo.FormatDetails.Settings.GetCaseSensitivityComparison()))
{
selectorInfo.Result = entry.Value;
return true;
}
}
if (current is IDictionary<string, object> dict)
{
var val = dict.FirstOrDefault(x =>
x.Key.Equals(selector, selectorInfo.FormatDetails.Settings.GetCaseSensitivityComparison())).Value;
if (val != null)
{
selectorInfo.Result = val;
return true;
}
}
return false;
}
}
|
[
"[",
"Serializable",
"]",
"public",
"class",
"DictionarySource",
":",
"ISource",
"{",
"public",
"DictionarySource",
"(",
"SmartFormatter",
"formatter",
")",
"{",
"formatter",
".",
"Parser",
".",
"AddAlphanumericSelectors",
"(",
")",
";",
"formatter",
".",
"Parser",
".",
"AddAdditionalSelectorChars",
"(",
"\"",
"_",
"\"",
")",
";",
"formatter",
".",
"Parser",
".",
"AddOperators",
"(",
"\"",
".",
"\"",
")",
";",
"}",
"public",
"bool",
"TryEvaluateSelector",
"(",
"ISelectorInfo",
"selectorInfo",
")",
"{",
"var",
"current",
"=",
"selectorInfo",
".",
"CurrentValue",
";",
"var",
"selector",
"=",
"selectorInfo",
".",
"SelectorText",
";",
"var",
"rawDict",
"=",
"current",
"as",
"IDictionary",
";",
"if",
"(",
"rawDict",
"!=",
"null",
")",
"foreach",
"(",
"DictionaryEntry",
"entry",
"in",
"rawDict",
")",
"{",
"var",
"key",
"=",
"entry",
".",
"Key",
"as",
"string",
"??",
"entry",
".",
"Key",
".",
"ToString",
"(",
")",
";",
"if",
"(",
"key",
".",
"Equals",
"(",
"selector",
",",
"selectorInfo",
".",
"FormatDetails",
".",
"Settings",
".",
"GetCaseSensitivityComparison",
"(",
")",
")",
")",
"{",
"selectorInfo",
".",
"Result",
"=",
"entry",
".",
"Value",
";",
"return",
"true",
";",
"}",
"}",
"if",
"(",
"current",
"is",
"IDictionary",
"<",
"string",
",",
"object",
">",
"dict",
")",
"{",
"var",
"val",
"=",
"dict",
".",
"FirstOrDefault",
"(",
"x",
"=>",
"x",
".",
"Key",
".",
"Equals",
"(",
"selector",
",",
"selectorInfo",
".",
"FormatDetails",
".",
"Settings",
".",
"GetCaseSensitivityComparison",
"(",
")",
")",
")",
".",
"Value",
";",
"if",
"(",
"val",
"!=",
"null",
")",
"{",
"selectorInfo",
".",
"Result",
"=",
"val",
";",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}"
] |
Provides the ability to extract an object with a matching Key from an
[IDictionary](https://docs.microsoft.com/en-us/dotnet/api/system.collections.idictionary) or
[IDictionary<string, object>](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.idictionary-2).
|
[
"Provides",
"the",
"ability",
"to",
"extract",
"an",
"object",
"with",
"a",
"matching",
"Key",
"from",
"an",
"[",
"IDictionary",
"]",
"(",
"https",
":",
"//",
"docs",
".",
"microsoft",
".",
"com",
"/",
"en",
"-",
"us",
"/",
"dotnet",
"/",
"api",
"/",
"system",
".",
"collections",
".",
"idictionary",
")",
"or",
"[",
"IDictionary<string",
"object",
">",
"]",
"(",
"https",
":",
"//",
"docs",
".",
"microsoft",
".",
"com",
"/",
"en",
"-",
"us",
"/",
"dotnet",
"/",
"api",
"/",
"system",
".",
"collections",
".",
"generic",
".",
"idictionary",
"-",
"2",
")",
"."
] |
[
"/// <summary>",
"/// Creates a new instance of the formatter.",
"/// </summary>",
"/// <param name=\"formatter\">The formatter that the source will be added to.</param>",
"// Add some special info to the parser:",
"// (A-Z + a-z)",
"/// <inheritdoc/>",
"// See if current is a IDictionary and contains the selector:",
"// this check is for dynamics and generic dictionaries"
] |
[
{
"param": "ISource",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ISource",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 22
| 235
| 77
|
0a09fe3a96aa791ce1143835b7cf0ea7087c22ae
|
mattcolefla/SwarmOps
|
RandomOps/RandomOps/RandomOps/RanUInt32.cs
|
[
"0BSD"
] |
C#
|
RanUInt32
|
/// <summary>
/// Pseudo-Random Number Generator (PRNG) base-class for a generator of UInt32 integers.
/// </summary>
/// <remarks>
/// It is somewhat tricky to implement Index() using integer-operations and get the
/// rounding right for all cases, so we reuse the base-class implementation which
/// indirectly uses Uniform().
/// </remarks>
|
Pseudo-Random Number Generator (PRNG) base-class for a generator of UInt32 integers.
|
[
"Pseudo",
"-",
"Random",
"Number",
"Generator",
"(",
"PRNG",
")",
"base",
"-",
"class",
"for",
"a",
"generator",
"of",
"UInt32",
"integers",
"."
] |
public abstract class RanUInt32 : Random
{
#region Constructors.
public RanUInt32()
: base()
{
_randMaxHalf = RandMax / 2;
_randInv = 1.0 / ((double)RandMax + 2);
}
#endregion
#region Internal variables.
UInt32 _randMaxHalf;
double _randInv;
#endregion
#region PRNG Implementation.
public abstract UInt32 Rand();
public abstract UInt32 RandMax
{
get;
}
protected virtual void Seed()
{
UInt32 seed = (UInt32)(DateTime.Now.Ticks % (long)RandMax);
Seed(seed);
}
protected virtual void Seed(UInt32 seed)
{
throw new NotImplementedException();
}
#endregion
#region Base-class overrides.
public override double Uniform()
{
double rand = (double) Rand() + 1;
double value = rand * _randInv;
Debug.Assert(value > 0 && value < 1);
return value;
}
public override bool Bool()
{
return Rand() < _randMaxHalf;
}
public override byte Byte()
{
UInt32 r = Rand();
UInt32 value = r >> 24;
Debug.Assert(value >= 0 && value <= System.Byte.MaxValue);
byte b = (byte)value;
return b;
}
#endregion
}
|
[
"public",
"abstract",
"class",
"RanUInt32",
":",
"Random",
"{",
"region",
" Constructors.",
"public",
"RanUInt32",
"(",
")",
":",
"base",
"(",
")",
"{",
"_randMaxHalf",
"=",
"RandMax",
"/",
"2",
";",
"_randInv",
"=",
"1.0",
"/",
"(",
"(",
"double",
")",
"RandMax",
"+",
"2",
")",
";",
"}",
"endregion",
"region",
" Internal variables.",
"UInt32",
"_randMaxHalf",
";",
"double",
"_randInv",
";",
"endregion",
"region",
" PRNG Implementation.",
"public",
"abstract",
"UInt32",
"Rand",
"(",
")",
";",
"public",
"abstract",
"UInt32",
"RandMax",
"{",
"get",
";",
"}",
"protected",
"virtual",
"void",
"Seed",
"(",
")",
"{",
"UInt32",
"seed",
"=",
"(",
"UInt32",
")",
"(",
"DateTime",
".",
"Now",
".",
"Ticks",
"%",
"(",
"long",
")",
"RandMax",
")",
";",
"Seed",
"(",
"seed",
")",
";",
"}",
"protected",
"virtual",
"void",
"Seed",
"(",
"UInt32",
"seed",
")",
"{",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"endregion",
"region",
" Base-class overrides.",
"public",
"override",
"double",
"Uniform",
"(",
")",
"{",
"double",
"rand",
"=",
"(",
"double",
")",
"Rand",
"(",
")",
"+",
"1",
";",
"double",
"value",
"=",
"rand",
"*",
"_randInv",
";",
"Debug",
".",
"Assert",
"(",
"value",
">",
"0",
"&&",
"value",
"<",
"1",
")",
";",
"return",
"value",
";",
"}",
"public",
"override",
"bool",
"Bool",
"(",
")",
"{",
"return",
"Rand",
"(",
")",
"<",
"_randMaxHalf",
";",
"}",
"public",
"override",
"byte",
"Byte",
"(",
")",
"{",
"UInt32",
"r",
"=",
"Rand",
"(",
")",
";",
"UInt32",
"value",
"=",
"r",
">>",
"24",
";",
"Debug",
".",
"Assert",
"(",
"value",
">=",
"0",
"&&",
"value",
"<=",
"System",
".",
"Byte",
".",
"MaxValue",
")",
";",
"byte",
"b",
"=",
"(",
"byte",
")",
"value",
";",
"return",
"b",
";",
"}",
"endregion",
"}"
] |
Pseudo-Random Number Generator (PRNG) base-class for a generator of UInt32 integers.
|
[
"Pseudo",
"-",
"Random",
"Number",
"Generator",
"(",
"PRNG",
")",
"base",
"-",
"class",
"for",
"a",
"generator",
"of",
"UInt32",
"integers",
"."
] |
[
"/// <summary>",
"/// Constructs the PRNG-object.",
"/// </summary>",
"/// <summary>",
"/// Used in Bool(), for convenience and speed.",
"/// </summary>",
"/// <summary>",
"/// Used in Uniform(), for convenience and speed.",
"/// </summary>",
"/// <summary>",
"/// Draw a random number in inclusive range {0, .., RandMax}",
"/// </summary>",
"/// <summary>",
"/// The maximum possible value returned by Rand().",
"/// </summary>",
"/// <summary>",
"/// Seed with the time of day.",
"/// </summary>",
"/// <summary>",
"/// Seed with an integer.",
"/// </summary>",
"/// <summary>",
"/// Draw a uniform random number in the exclusive range (0,1).",
"/// Thread-safe if Rand() is thread-safe.",
"/// </summary>",
"/// <remarks>",
"/// Assumes that Rand() is in {0, .., RandMax}.",
"/// </remarks>",
"/// <summary>",
"/// Draw a random boolean with equal probability of drawing true or false.",
"/// Thread-safe if Rand() is thread-safe.",
"/// </summary>",
"/// <summary>",
"/// Draw a random and uniform byte.",
"/// Thread-safe if Rand() is thread-safe.",
"/// </summary>",
"/// <remarks>",
"/// The least significant bits are not that statistically random,",
"/// hence we must use the most significant bits by a bit-shift.",
"/// </remarks>"
] |
[
{
"param": "Random",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Random",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "It is somewhat tricky to implement Index() using integer-operations and get the\nrounding right for all cases, so we reuse the base-class implementation which\nindirectly uses Uniform().",
"docstring_tokens": [
"It",
"is",
"somewhat",
"tricky",
"to",
"implement",
"Index",
"()",
"using",
"integer",
"-",
"operations",
"and",
"get",
"the",
"rounding",
"right",
"for",
"all",
"cases",
"so",
"we",
"reuse",
"the",
"base",
"-",
"class",
"implementation",
"which",
"indirectly",
"uses",
"Uniform",
"()",
"."
]
}
]
}
| false
| 13
| 320
| 76
|
500e9a63226bcb6d9867c00343ad2032be4aa9b1
|
mikebarker/Plethora.NET
|
src/Plethora.Windows.Forms/Drawing/ToolboxBitmapEx.cs
|
[
"MIT",
"BSD-3-Clause"
] |
C#
|
ToolboxBitmapExAttribute
|
/// <summary>
/// Extension of the <see cref="ToolboxBitmapAttribute"/>, which allows an image or
/// icon to be retrieved from resources objects.
/// </summary>
/// <example>
/// <para>
/// This is attribute is used as follows:
/// <code>
/// [ToolboxBitmapEx(typeof(MyApplication.Properties.Resources), "MyControl")]
/// public class MyControl : UserControl
/// {
/// }
/// </code>
/// where MyApplication.Properties.Resources is the assembly's automatically created
/// resource, with an <see cref="Image"/> or <see cref="Icon"/> named "MyControl".
/// </para>
/// <para>
/// The "MyControl" file does NOT need to have the "Embedded Resource" build action set.
/// </para>
/// </example>
|
Extension of the , which allows an image or
icon to be retrieved from resources objects.
|
[
"Extension",
"of",
"the",
"which",
"allows",
"an",
"image",
"or",
"icon",
"to",
"be",
"retrieved",
"from",
"resources",
"objects",
"."
] |
public class ToolboxBitmapExAttribute : ToolboxBitmapAttribute
{
#region Fields
private static readonly FieldInfo largeImageField = typeof(ToolboxBitmapAttribute)
.GetField("largeImage", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly FieldInfo smallImageField = typeof(ToolboxBitmapAttribute)
.GetField("smallImage", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly FieldInfo largeDimField = typeof(ToolboxBitmapAttribute)
.GetField("largeDim", BindingFlags.Static | BindingFlags.NonPublic);
private static readonly FieldInfo smallDimField = typeof(ToolboxBitmapAttribute)
.GetField("smallDim", BindingFlags.Static | BindingFlags.NonPublic);
#endregion
#region Constructors
protected ToolboxBitmapExAttribute()
: base("/")
{
}
public ToolboxBitmapExAttribute(Type resourcesType, string imageName)
: this()
{
try
{
this.SetImagesFromResource(resourcesType, imageName);
}
catch (Exception)
{
this.SmallImage = null;
this.LargeImage = null;
}
}
#endregion
#region Properties
public Image SmallImage
{
get { return GetImage(smallImageField); }
protected set { SetImage(smallImageField, value); }
}
public Image LargeImage
{
get { return GetImage(largeImageField); }
protected set { SetImage(largeImageField, value); }
}
protected static Point SmallDim
{
get
{
if (smallDimField == null)
return Point.Empty;
return (Point)smallDimField.GetValue(null);
}
}
protected static Point LargeDim
{
get
{
if (largeDimField == null)
return Point.Empty;
return (Point)largeDimField.GetValue(null);
}
}
#endregion
#region Non-public Methods
protected void SetImagesFromResource(Type t, string imageName)
{
if (t == null)
return;
if (t.FullName == null)
return;
if (imageName == null)
return;
var resourceManager = new ResourceManager(t.FullName, t.Assembly);
object obj = resourceManager.GetObject(imageName);
if (obj == null)
return;
if (obj is Image)
{
Image image = (Image)obj;
Point largeDim = LargeDim;
this.SmallImage = (Image)obj;
this.LargeImage = new Bitmap(image, largeDim.X, largeDim.Y);
}
if (obj is Icon)
{
Icon icon = (Icon)obj;
Point smallDim = SmallDim;
Point largeDim = LargeDim;
this.SmallImage = new Icon(icon, smallDim.X, smallDim.Y).ToBitmap();
this.LargeImage = new Icon(icon, largeDim.X, largeDim.Y).ToBitmap();
}
return;
}
private void SetImage(FieldInfo imageField, Image image)
{
if (imageField == null)
return;
imageField.SetValue(this, image);
}
private Image GetImage(FieldInfo imageField)
{
if (imageField == null)
return null;
var image = imageField.GetValue(this) as Image;
return image;
}
#endregion
}
|
[
"public",
"class",
"ToolboxBitmapExAttribute",
":",
"ToolboxBitmapAttribute",
"{",
"region",
" Fields",
"private",
"static",
"readonly",
"FieldInfo",
"largeImageField",
"=",
"typeof",
"(",
"ToolboxBitmapAttribute",
")",
".",
"GetField",
"(",
"\"",
"largeImage",
"\"",
",",
"BindingFlags",
".",
"Instance",
"|",
"BindingFlags",
".",
"NonPublic",
")",
";",
"private",
"static",
"readonly",
"FieldInfo",
"smallImageField",
"=",
"typeof",
"(",
"ToolboxBitmapAttribute",
")",
".",
"GetField",
"(",
"\"",
"smallImage",
"\"",
",",
"BindingFlags",
".",
"Instance",
"|",
"BindingFlags",
".",
"NonPublic",
")",
";",
"private",
"static",
"readonly",
"FieldInfo",
"largeDimField",
"=",
"typeof",
"(",
"ToolboxBitmapAttribute",
")",
".",
"GetField",
"(",
"\"",
"largeDim",
"\"",
",",
"BindingFlags",
".",
"Static",
"|",
"BindingFlags",
".",
"NonPublic",
")",
";",
"private",
"static",
"readonly",
"FieldInfo",
"smallDimField",
"=",
"typeof",
"(",
"ToolboxBitmapAttribute",
")",
".",
"GetField",
"(",
"\"",
"smallDim",
"\"",
",",
"BindingFlags",
".",
"Static",
"|",
"BindingFlags",
".",
"NonPublic",
")",
";",
"endregion",
"region",
" Constructors",
"protected",
"ToolboxBitmapExAttribute",
"(",
")",
":",
"base",
"(",
"\"",
"/",
"\"",
")",
"{",
"}",
"public",
"ToolboxBitmapExAttribute",
"(",
"Type",
"resourcesType",
",",
"string",
"imageName",
")",
":",
"this",
"(",
")",
"{",
"try",
"{",
"this",
".",
"SetImagesFromResource",
"(",
"resourcesType",
",",
"imageName",
")",
";",
"}",
"catch",
"(",
"Exception",
")",
"{",
"this",
".",
"SmallImage",
"=",
"null",
";",
"this",
".",
"LargeImage",
"=",
"null",
";",
"}",
"}",
"endregion",
"region",
" Properties",
"public",
"Image",
"SmallImage",
"{",
"get",
"{",
"return",
"GetImage",
"(",
"smallImageField",
")",
";",
"}",
"protected",
"set",
"{",
"SetImage",
"(",
"smallImageField",
",",
"value",
")",
";",
"}",
"}",
"public",
"Image",
"LargeImage",
"{",
"get",
"{",
"return",
"GetImage",
"(",
"largeImageField",
")",
";",
"}",
"protected",
"set",
"{",
"SetImage",
"(",
"largeImageField",
",",
"value",
")",
";",
"}",
"}",
"protected",
"static",
"Point",
"SmallDim",
"{",
"get",
"{",
"if",
"(",
"smallDimField",
"==",
"null",
")",
"return",
"Point",
".",
"Empty",
";",
"return",
"(",
"Point",
")",
"smallDimField",
".",
"GetValue",
"(",
"null",
")",
";",
"}",
"}",
"protected",
"static",
"Point",
"LargeDim",
"{",
"get",
"{",
"if",
"(",
"largeDimField",
"==",
"null",
")",
"return",
"Point",
".",
"Empty",
";",
"return",
"(",
"Point",
")",
"largeDimField",
".",
"GetValue",
"(",
"null",
")",
";",
"}",
"}",
"endregion",
"region",
" Non-public Methods",
"protected",
"void",
"SetImagesFromResource",
"(",
"Type",
"t",
",",
"string",
"imageName",
")",
"{",
"if",
"(",
"t",
"==",
"null",
")",
"return",
";",
"if",
"(",
"t",
".",
"FullName",
"==",
"null",
")",
"return",
";",
"if",
"(",
"imageName",
"==",
"null",
")",
"return",
";",
"var",
"resourceManager",
"=",
"new",
"ResourceManager",
"(",
"t",
".",
"FullName",
",",
"t",
".",
"Assembly",
")",
";",
"object",
"obj",
"=",
"resourceManager",
".",
"GetObject",
"(",
"imageName",
")",
";",
"if",
"(",
"obj",
"==",
"null",
")",
"return",
";",
"if",
"(",
"obj",
"is",
"Image",
")",
"{",
"Image",
"image",
"=",
"(",
"Image",
")",
"obj",
";",
"Point",
"largeDim",
"=",
"LargeDim",
";",
"this",
".",
"SmallImage",
"=",
"(",
"Image",
")",
"obj",
";",
"this",
".",
"LargeImage",
"=",
"new",
"Bitmap",
"(",
"image",
",",
"largeDim",
".",
"X",
",",
"largeDim",
".",
"Y",
")",
";",
"}",
"if",
"(",
"obj",
"is",
"Icon",
")",
"{",
"Icon",
"icon",
"=",
"(",
"Icon",
")",
"obj",
";",
"Point",
"smallDim",
"=",
"SmallDim",
";",
"Point",
"largeDim",
"=",
"LargeDim",
";",
"this",
".",
"SmallImage",
"=",
"new",
"Icon",
"(",
"icon",
",",
"smallDim",
".",
"X",
",",
"smallDim",
".",
"Y",
")",
".",
"ToBitmap",
"(",
")",
";",
"this",
".",
"LargeImage",
"=",
"new",
"Icon",
"(",
"icon",
",",
"largeDim",
".",
"X",
",",
"largeDim",
".",
"Y",
")",
".",
"ToBitmap",
"(",
")",
";",
"}",
"return",
";",
"}",
"private",
"void",
"SetImage",
"(",
"FieldInfo",
"imageField",
",",
"Image",
"image",
")",
"{",
"if",
"(",
"imageField",
"==",
"null",
")",
"return",
";",
"imageField",
".",
"SetValue",
"(",
"this",
",",
"image",
")",
";",
"}",
"private",
"Image",
"GetImage",
"(",
"FieldInfo",
"imageField",
")",
"{",
"if",
"(",
"imageField",
"==",
"null",
")",
"return",
"null",
";",
"var",
"image",
"=",
"imageField",
".",
"GetValue",
"(",
"this",
")",
"as",
"Image",
";",
"return",
"image",
";",
"}",
"endregion",
"}"
] |
Extension of the , which allows an image or
icon to be retrieved from resources objects.
|
[
"Extension",
"of",
"the",
"which",
"allows",
"an",
"image",
"or",
"icon",
"to",
"be",
"retrieved",
"from",
"resources",
"objects",
"."
] |
[
"/// <summary>",
"/// Initialise a new instance of the <see cref=\"ToolboxBitmapExAttribute\"/> class.",
"/// </summary>",
"/// <summary>",
"/// Initialise a new instance of the <see cref=\"ToolboxBitmapExAttribute\"/> class.",
"/// </summary>"
] |
[
{
"param": "ToolboxBitmapAttribute",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ToolboxBitmapAttribute",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "example",
"docstring": "This is attribute is used as follows.\n\n[ToolboxBitmapEx(typeof(MyApplication.Properties.Resources), \"MyControl\")]\npublic class MyControl : UserControl\n{\n}\nor named \"MyControl\".\n\nThe \"MyControl\" file does NOT need to have the \"Embedded Resource\" build action set.",
"docstring_tokens": [
"This",
"is",
"attribute",
"is",
"used",
"as",
"follows",
".",
"[",
"ToolboxBitmapEx",
"(",
"typeof",
"(",
"MyApplication",
".",
"Properties",
".",
"Resources",
")",
"\"",
"MyControl",
"\"",
")",
"]",
"public",
"class",
"MyControl",
":",
"UserControl",
"{",
"}",
"or",
"named",
"\"",
"MyControl",
"\"",
".",
"The",
"\"",
"MyControl",
"\"",
"file",
"does",
"NOT",
"need",
"to",
"have",
"the",
"\"",
"Embedded",
"Resource",
"\"",
"build",
"action",
"set",
"."
]
}
]
}
| false
| 15
| 706
| 177
|
395abafce474b5157152a943db6a86d7fe90bed2
|
wutao0315/zooland
|
src/Zooyard.Rpc.NettyImpl/Processor/Server/ServerOnRequestProcessor.cs
|
[
"MIT"
] |
C#
|
ServerOnRequestProcessor
|
/// <summary>
/// process RM/TM client request message.
/// <para>
/// message type:
/// RM:
/// 1) <seealso cref="MergedWarpMessage"/>
/// 2) <seealso cref="BranchRegisterRequest"/>
/// 3) <seealso cref="BranchReportRequest"/>
/// 4) <seealso cref="GlobalLockQueryRequest"/>
/// TM:
/// 1) <seealso cref="MergedWarpMessage"/>
/// 2) <seealso cref="GlobalBeginRequest"/>
/// 3) <seealso cref="GlobalCommitRequest"/>
/// 4) <seealso cref="GlobalReportRequest"/>
/// 5) <seealso cref="GlobalRollbackRequest"/>
/// 6) <seealso cref="GlobalStatusRequest"/>
///
/// </para>
/// </summary>
|
process RM/TM client request message.
|
[
"process",
"RM",
"/",
"TM",
"client",
"request",
"message",
"."
] |
public class ServerOnRequestProcessor : IRemotingProcessor
{
private static readonly Func<Action<LogLevel, string, Exception>> Logger = () => LogManager.CreateLogger(typeof(ServerOnRequestProcessor));
private IRemotingServer remotingServer;
private ITransactionMessageHandler transactionMessageHandler;
public ServerOnRequestProcessor(IRemotingServer remotingServer, ITransactionMessageHandler transactionMessageHandler)
{
this.remotingServer = remotingServer;
this.transactionMessageHandler = transactionMessageHandler;
}
public virtual async Task Process(IChannelHandlerContext ctx, RpcMessage rpcMessage)
{
if (ChannelManager.IsRegistered(ctx.Channel))
{
await OnRequestMessage(ctx, rpcMessage);
}
else
{
try
{
if (Logger().IsEnabled(LogLevel.Debug))
{
Logger().LogInformation($"closeChannelHandlerContext channel:{ctx.Channel}");
}
await ctx.DisconnectAsync();
await ctx.CloseAsync();
}
catch (Exception exx)
{
Logger().LogError(exx, exx.Message);
}
if (Logger().IsEnabled(LogLevel.Debug))
{
Logger().LogInformation($"close a unhandled connection! [{ctx.Channel}]");
}
}
}
private async Task OnRequestMessage(IChannelHandlerContext ctx, RpcMessage rpcMessage)
{
object message = rpcMessage.Body;
RpcContext rpcContext = ChannelManager.GetContextFromIdentified(ctx.Channel);
if (Logger().IsEnabled(LogLevel.Debug))
{
Logger().LogDebug($"server received:{message},clientIp:{NetUtil.ToIpAddress(ctx.Channel.RemoteAddress)},vgroup:{rpcContext.TransactionServiceGroup}");
}
else
{
try
{
BatchLogHandler.INSTANCE.LogQueue.Add($"{message},clientIp:{NetUtil.ToIpAddress(ctx.Channel.RemoteAddress)},vgroup:{rpcContext.TransactionServiceGroup}");
}
catch (Exception e)
{
Logger().LogError(e, $"put message to logQueue error: {e.Message}");
}
}
if (!(message is AbstractMessage))
{
return;
}
if (message is MergedWarpMessage mergedWarpMessage)
{
AbstractResultMessage[] results = new AbstractResultMessage[mergedWarpMessage.msgs.Count];
for (int i = 0; i < results.Length; i++)
{
AbstractMessage subMessage = mergedWarpMessage.msgs[i];
results[i] = await transactionMessageHandler.OnRequest(subMessage, rpcContext);
}
MergeResultMessage resultMessage = new ()
{
Msgs = results
};
await remotingServer.SendAsyncResponse(rpcMessage, ctx.Channel, resultMessage);
}
else
{
var msg = (AbstractMessage) message;
AbstractResultMessage result = await transactionMessageHandler.OnRequest(msg, rpcContext);
await remotingServer.SendAsyncResponse(rpcMessage, ctx.Channel, result);
}
}
}
|
[
"public",
"class",
"ServerOnRequestProcessor",
":",
"IRemotingProcessor",
"{",
"private",
"static",
"readonly",
"Func",
"<",
"Action",
"<",
"LogLevel",
",",
"string",
",",
"Exception",
">",
">",
"Logger",
"=",
"(",
")",
"=>",
"LogManager",
".",
"CreateLogger",
"(",
"typeof",
"(",
"ServerOnRequestProcessor",
")",
")",
";",
"private",
"IRemotingServer",
"remotingServer",
";",
"private",
"ITransactionMessageHandler",
"transactionMessageHandler",
";",
"public",
"ServerOnRequestProcessor",
"(",
"IRemotingServer",
"remotingServer",
",",
"ITransactionMessageHandler",
"transactionMessageHandler",
")",
"{",
"this",
".",
"remotingServer",
"=",
"remotingServer",
";",
"this",
".",
"transactionMessageHandler",
"=",
"transactionMessageHandler",
";",
"}",
"public",
"virtual",
"async",
"Task",
"Process",
"(",
"IChannelHandlerContext",
"ctx",
",",
"RpcMessage",
"rpcMessage",
")",
"{",
"if",
"(",
"ChannelManager",
".",
"IsRegistered",
"(",
"ctx",
".",
"Channel",
")",
")",
"{",
"await",
"OnRequestMessage",
"(",
"ctx",
",",
"rpcMessage",
")",
";",
"}",
"else",
"{",
"try",
"{",
"if",
"(",
"Logger",
"(",
")",
".",
"IsEnabled",
"(",
"LogLevel",
".",
"Debug",
")",
")",
"{",
"Logger",
"(",
")",
".",
"LogInformation",
"(",
"$\"",
"closeChannelHandlerContext channel:",
"{",
"ctx",
".",
"Channel",
"}",
"\"",
")",
";",
"}",
"await",
"ctx",
".",
"DisconnectAsync",
"(",
")",
";",
"await",
"ctx",
".",
"CloseAsync",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"exx",
")",
"{",
"Logger",
"(",
")",
".",
"LogError",
"(",
"exx",
",",
"exx",
".",
"Message",
")",
";",
"}",
"if",
"(",
"Logger",
"(",
")",
".",
"IsEnabled",
"(",
"LogLevel",
".",
"Debug",
")",
")",
"{",
"Logger",
"(",
")",
".",
"LogInformation",
"(",
"$\"",
"close a unhandled connection! [",
"{",
"ctx",
".",
"Channel",
"}",
"]",
"\"",
")",
";",
"}",
"}",
"}",
"private",
"async",
"Task",
"OnRequestMessage",
"(",
"IChannelHandlerContext",
"ctx",
",",
"RpcMessage",
"rpcMessage",
")",
"{",
"object",
"message",
"=",
"rpcMessage",
".",
"Body",
";",
"RpcContext",
"rpcContext",
"=",
"ChannelManager",
".",
"GetContextFromIdentified",
"(",
"ctx",
".",
"Channel",
")",
";",
"if",
"(",
"Logger",
"(",
")",
".",
"IsEnabled",
"(",
"LogLevel",
".",
"Debug",
")",
")",
"{",
"Logger",
"(",
")",
".",
"LogDebug",
"(",
"$\"",
"server received:",
"{",
"message",
"}",
",clientIp:",
"{",
"NetUtil",
".",
"ToIpAddress",
"(",
"ctx",
".",
"Channel",
".",
"RemoteAddress",
")",
"}",
",vgroup:",
"{",
"rpcContext",
".",
"TransactionServiceGroup",
"}",
"\"",
")",
";",
"}",
"else",
"{",
"try",
"{",
"BatchLogHandler",
".",
"INSTANCE",
".",
"LogQueue",
".",
"Add",
"(",
"$\"",
"{",
"message",
"}",
",clientIp:",
"{",
"NetUtil",
".",
"ToIpAddress",
"(",
"ctx",
".",
"Channel",
".",
"RemoteAddress",
")",
"}",
",vgroup:",
"{",
"rpcContext",
".",
"TransactionServiceGroup",
"}",
"\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"Logger",
"(",
")",
".",
"LogError",
"(",
"e",
",",
"$\"",
"put message to logQueue error: ",
"{",
"e",
".",
"Message",
"}",
"\"",
")",
";",
"}",
"}",
"if",
"(",
"!",
"(",
"message",
"is",
"AbstractMessage",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"message",
"is",
"MergedWarpMessage",
"mergedWarpMessage",
")",
"{",
"AbstractResultMessage",
"[",
"]",
"results",
"=",
"new",
"AbstractResultMessage",
"[",
"mergedWarpMessage",
".",
"msgs",
".",
"Count",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"results",
".",
"Length",
";",
"i",
"++",
")",
"{",
"AbstractMessage",
"subMessage",
"=",
"mergedWarpMessage",
".",
"msgs",
"[",
"i",
"]",
";",
"results",
"[",
"i",
"]",
"=",
"await",
"transactionMessageHandler",
".",
"OnRequest",
"(",
"subMessage",
",",
"rpcContext",
")",
";",
"}",
"MergeResultMessage",
"resultMessage",
"=",
"new",
"(",
")",
"{",
"Msgs",
"=",
"results",
"}",
";",
"await",
"remotingServer",
".",
"SendAsyncResponse",
"(",
"rpcMessage",
",",
"ctx",
".",
"Channel",
",",
"resultMessage",
")",
";",
"}",
"else",
"{",
"var",
"msg",
"=",
"(",
"AbstractMessage",
")",
"message",
";",
"AbstractResultMessage",
"result",
"=",
"await",
"transactionMessageHandler",
".",
"OnRequest",
"(",
"msg",
",",
"rpcContext",
")",
";",
"await",
"remotingServer",
".",
"SendAsyncResponse",
"(",
"rpcMessage",
",",
"ctx",
".",
"Channel",
",",
"result",
")",
";",
"}",
"}",
"}"
] |
process RM/TM client request message.
|
[
"process",
"RM",
"/",
"TM",
"client",
"request",
"message",
"."
] |
[
"// the single send request message"
] |
[
{
"param": "IRemotingProcessor",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IRemotingProcessor",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 20
| 659
| 163
|
65385651236ddd96b6ba1ab48b6e2bc6558f9887
|
ev3dev-lang-java/lejos-nxj-code-mirror
|
classes/src/lejos/addon/gps/GSASentence.java
|
[
"Apache-2.0"
] |
Java
|
GSASentence
|
/**
* This class has been designed to manage a GSA Sentence
*
* GPS DOP and active satellites
*
* eg1. $GPGSA,A,3,,,,,,16,18,,22,24,,,3.6,2.1,2.2*3C
* eg2. $GPGSA,A,3,19,28,14,18,27,22,31,39,,,,,1.7,1.0,1.3*35
*
* 1 = Mode:
* M=Manual, forced to operate in 2D or 3D
* A=Automatic, 3D/2D
* 2 = Mode:
* 1=Fix not available
* 2=2D
* 3=3D
* 3-14 = IDs of SVs used in position fix (null for unused fields)
* 15 = PDOP
* 16 = HDOP
* 17 = VDOP
*
* @author Juan Antonio Brenha Moral
*
*/
|
This class has been designed to manage a GSA Sentence
GPS DOP and active satellites
eg1.
@author Juan Antonio Brenha Moral
|
[
"This",
"class",
"has",
"been",
"designed",
"to",
"manage",
"a",
"GSA",
"Sentence",
"GPS",
"DOP",
"and",
"active",
"satellites",
"eg1",
".",
"@author",
"Juan",
"Antonio",
"Brenha",
"Moral"
] |
public class GSASentence extends NMEASentence{
//GSA
private String nmeaHeader = "";
private String mode = "";
private int modeValue = 0;
private final int MAXIMUMSV = 12;
private int[] SV;
private float PDOP = 0f;
private float HDOP = 0f;
private float VDOP = 0f;
//Header
public static final String HEADER = "$GPGSA";
/**
* Constructor
*/
public GSASentence(){
SV = new int[MAXIMUMSV];
}
/**
* Returns the NMEA header for this sentence.
*/
@Override
public String getHeader() {
return HEADER;
}
/**
* Return Mode1.
* Mode1 can receive the following values:
*
* M=Manual, forced to operate in 2D or 3D
* A=Automatic, 3D/2D
*
*/
public String getMode(){
return mode;
}
/**
* Return Mode2.
* Mode1 can receive the following values:
*
* 1=Fix not available
* 2=2D
* 3=3D
*
*/
public int getModeValue(){
return modeValue;
}
/**
* Return an Array with Satellite IDs
*
* @return
*/
public int[] getPRN(){
return SV;
}
/**
* Return PDOP
*
* @return
*/
public float getPDOP(){
return PDOP;
}
/**
* Return HDOP
*
* @return
*/
public float getHDOP(){
return HDOP;
}
/**
* Return VDOP
*
* @return
*/
public float getVDOP(){
return VDOP;
}
/**
* Method used to parse a GGA Sentence
*/
protected void parse(String sentence){
//TODO StringTokenizer must not be used to parse NMEA sentences since it doesn't return empty tokens
StringTokenizer st = new StringTokenizer(sentence,",");
try{
//Extracting data from a GSA Sentence
String part1 = st.nextToken();//NMEA header
String part2 = st.nextToken();//mode
String part3 = st.nextToken();//modeValue
/*
String part4 = st.nextToken();//sv1
String part5 = st.nextToken();//sv2
String part6 = st.nextToken();//sv3
String part7 = st.nextToken();//sv4
String part8 = st.nextToken();//sv5
String part9 = st.nextToken();//sv6
String part10 = st.nextToken();//sv7
String part11 = st.nextToken();//sv8
String part12 = st.nextToken();//sv9
String part13 = st.nextToken();//sv10
String part14 = st.nextToken();//sv11
String part15 = st.nextToken();//sv12
*/
//Processing GSA data
nmeaHeader = part1;
mode = part2;
if(part3 == null){
modeValue = 0;
}else{
if(part3.length() == 0){
modeValue = 0;
}else{
modeValue = Math.round(Float.parseFloat(part3));
}
}
for(int i=0;i<12;i++){
String part = st.nextToken();
if(part.length() > 0){
SV[i] = Integer.parseInt(part);
}else{
SV[i] = 0;
}
}
String part16 = st.nextToken();//PDOP
String part17 = st.nextToken();//HDOP
String part18 = st.nextToken();//VDOP
st = null;
if(part16.length() == 0){
PDOP = 0;
}else{
PDOP = Float.parseFloat(part16);
}
if(part17.length() == 0){
HDOP = 0;
}else{
HDOP = Float.parseFloat(part17);
}
if(part18.length() == 0){
VDOP = 0;
}else{
VDOP = Float.parseFloat(part18);
}
}catch(NoSuchElementException e){
//System.err.println("GSASentence: NoSuchElementException");
}catch(NumberFormatException e){
//System.err.println("GSASentence: NumberFormatException");
}catch(Exception e){
//System.err.println("GSASentence: Exception");
}
}//End parse
}
|
[
"public",
"class",
"GSASentence",
"extends",
"NMEASentence",
"{",
"private",
"String",
"nmeaHeader",
"=",
"\"",
"\"",
";",
"private",
"String",
"mode",
"=",
"\"",
"\"",
";",
"private",
"int",
"modeValue",
"=",
"0",
";",
"private",
"final",
"int",
"MAXIMUMSV",
"=",
"12",
";",
"private",
"int",
"[",
"]",
"SV",
";",
"private",
"float",
"PDOP",
"=",
"0f",
";",
"private",
"float",
"HDOP",
"=",
"0f",
";",
"private",
"float",
"VDOP",
"=",
"0f",
";",
"public",
"static",
"final",
"String",
"HEADER",
"=",
"\"",
"$GPGSA",
"\"",
";",
"/**\n\t * Constructor\n\t */",
"public",
"GSASentence",
"(",
")",
"{",
"SV",
"=",
"new",
"int",
"[",
"MAXIMUMSV",
"]",
";",
"}",
"/**\n\t * Returns the NMEA header for this sentence.\n\t */",
"@",
"Override",
"public",
"String",
"getHeader",
"(",
")",
"{",
"return",
"HEADER",
";",
"}",
"/**\n\t * Return Mode1.\n\t * Mode1 can receive the following values:\n\t * \n\t * M=Manual, forced to operate in 2D or 3D\n\t * A=Automatic, 3D/2D\n\t * \n\t */",
"public",
"String",
"getMode",
"(",
")",
"{",
"return",
"mode",
";",
"}",
"/**\n\t * Return Mode2.\n\t * Mode1 can receive the following values:\n\t * \n\t * 1=Fix not available\n\t * 2=2D\n\t * 3=3D\n\t * \n\t */",
"public",
"int",
"getModeValue",
"(",
")",
"{",
"return",
"modeValue",
";",
"}",
"/**\n\t * Return an Array with Satellite IDs\n\t * \n\t * @return\n\t */",
"public",
"int",
"[",
"]",
"getPRN",
"(",
")",
"{",
"return",
"SV",
";",
"}",
"/**\n\t * Return PDOP\n\t * \n\t * @return\n\t */",
"public",
"float",
"getPDOP",
"(",
")",
"{",
"return",
"PDOP",
";",
"}",
"/**\n\t * Return HDOP\n\t * \n\t * @return\n\t */",
"public",
"float",
"getHDOP",
"(",
")",
"{",
"return",
"HDOP",
";",
"}",
"/**\n\t * Return VDOP\n\t * \n\t * @return\n\t */",
"public",
"float",
"getVDOP",
"(",
")",
"{",
"return",
"VDOP",
";",
"}",
"/**\n\t * Method used to parse a GGA Sentence\n\t */",
"protected",
"void",
"parse",
"(",
"String",
"sentence",
")",
"{",
"StringTokenizer",
"st",
"=",
"new",
"StringTokenizer",
"(",
"sentence",
",",
"\"",
",",
"\"",
")",
";",
"try",
"{",
"String",
"part1",
"=",
"st",
".",
"nextToken",
"(",
")",
";",
"String",
"part2",
"=",
"st",
".",
"nextToken",
"(",
")",
";",
"String",
"part3",
"=",
"st",
".",
"nextToken",
"(",
")",
";",
"/*\n\t\t\tString part4 = st.nextToken();//sv1\n\t\t\tString part5 = st.nextToken();//sv2\n\t\t\tString part6 = st.nextToken();//sv3\n\t\t\tString part7 = st.nextToken();//sv4\n\t\t\tString part8 = st.nextToken();//sv5\n\t\t\tString part9 = st.nextToken();//sv6\n\t\t\tString part10 = st.nextToken();//sv7\n\t\t\tString part11 = st.nextToken();//sv8\n\t\t\tString part12 = st.nextToken();//sv9\n\t\t\tString part13 = st.nextToken();//sv10\n\t\t\tString part14 = st.nextToken();//sv11\n\t\t\tString part15 = st.nextToken();//sv12\n\t\t\t*/",
"nmeaHeader",
"=",
"part1",
";",
"mode",
"=",
"part2",
";",
"if",
"(",
"part3",
"==",
"null",
")",
"{",
"modeValue",
"=",
"0",
";",
"}",
"else",
"{",
"if",
"(",
"part3",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"modeValue",
"=",
"0",
";",
"}",
"else",
"{",
"modeValue",
"=",
"Math",
".",
"round",
"(",
"Float",
".",
"parseFloat",
"(",
"part3",
")",
")",
";",
"}",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"12",
";",
"i",
"++",
")",
"{",
"String",
"part",
"=",
"st",
".",
"nextToken",
"(",
")",
";",
"if",
"(",
"part",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"SV",
"[",
"i",
"]",
"=",
"Integer",
".",
"parseInt",
"(",
"part",
")",
";",
"}",
"else",
"{",
"SV",
"[",
"i",
"]",
"=",
"0",
";",
"}",
"}",
"String",
"part16",
"=",
"st",
".",
"nextToken",
"(",
")",
";",
"String",
"part17",
"=",
"st",
".",
"nextToken",
"(",
")",
";",
"String",
"part18",
"=",
"st",
".",
"nextToken",
"(",
")",
";",
"st",
"=",
"null",
";",
"if",
"(",
"part16",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"PDOP",
"=",
"0",
";",
"}",
"else",
"{",
"PDOP",
"=",
"Float",
".",
"parseFloat",
"(",
"part16",
")",
";",
"}",
"if",
"(",
"part17",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"HDOP",
"=",
"0",
";",
"}",
"else",
"{",
"HDOP",
"=",
"Float",
".",
"parseFloat",
"(",
"part17",
")",
";",
"}",
"if",
"(",
"part18",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"VDOP",
"=",
"0",
";",
"}",
"else",
"{",
"VDOP",
"=",
"Float",
".",
"parseFloat",
"(",
"part18",
")",
";",
"}",
"}",
"catch",
"(",
"NoSuchElementException",
"e",
")",
"{",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
"}",
"}"
] |
This class has been designed to manage a GSA Sentence
|
[
"This",
"class",
"has",
"been",
"designed",
"to",
"manage",
"a",
"GSA",
"Sentence"
] |
[
"//GSA",
"//Header",
"//TODO StringTokenizer must not be used to parse NMEA sentences since it doesn't return empty tokens ",
"//Extracting data from a GSA Sentence",
"//NMEA header",
"//mode",
"//modeValue",
"//Processing GSA data",
"//PDOP",
"//HDOP",
"//VDOP",
"//System.err.println(\"GSASentence: NoSuchElementException\");",
"//System.err.println(\"GSASentence: NumberFormatException\");",
"//System.err.println(\"GSASentence: Exception\");",
"//End parse"
] |
[
{
"param": "NMEASentence",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "NMEASentence",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 17
| 1,028
| 253
|
e11fd152ccff2a2cb2c8cc0ceec6500248bbb199
|
licaon-kter/atalk-android
|
aTalk/src/main/java/org/atalk/impl/neomedia/transform/csrc/CsrcAudioLevelDispatcher.java
|
[
"Apache-2.0"
] |
Java
|
CsrcAudioLevelDispatcher
|
/**
* A simple thread that waits for new levels to be reported from incoming RTP packets and then
* delivers them to the <tt>AudioMediaStream</tt> associated with this engine. The reason we need to
* do this in a separate thread is, of course, the time sensitive nature of incoming RTP packets.
*
* @author Emil Ivov
* @author Lyubomir Marinov
*/
|
A simple thread that waits for new levels to be reported from incoming RTP packets and then
delivers them to the AudioMediaStream associated with this engine. The reason we need to
do this in a separate thread is, of course, the time sensitive nature of incoming RTP packets.
@author Emil Ivov
@author Lyubomir Marinov
|
[
"A",
"simple",
"thread",
"that",
"waits",
"for",
"new",
"levels",
"to",
"be",
"reported",
"from",
"incoming",
"RTP",
"packets",
"and",
"then",
"delivers",
"them",
"to",
"the",
"AudioMediaStream",
"associated",
"with",
"this",
"engine",
".",
"The",
"reason",
"we",
"need",
"to",
"do",
"this",
"in",
"a",
"separate",
"thread",
"is",
"of",
"course",
"the",
"time",
"sensitive",
"nature",
"of",
"incoming",
"RTP",
"packets",
".",
"@author",
"Emil",
"Ivov",
"@author",
"Lyubomir",
"Marinov"
] |
public class CsrcAudioLevelDispatcher implements Runnable
{
/**
* The pool of <tt>Thread</tt>s which run <tt>CsrcAudioLevelDispatcher</tt>s.
*/
private static final ExecutorService threadPool
= ExecutorUtils.newCachedThreadPool(true, "CsrcAudioLevelDispatcher");
/**
* The levels added to this instance (by the <tt>reverseTransform</tt> method of a
* <tt>PacketTransformer</tt> implementation) last.
*/
private long[] levels;
/**
* The <tt>AudioMediaStreamImpl</tt> which listens to this event dispatcher. If <tt>null</tt>,
* this event dispatcher is stopped. If non-<tt>null</tt>, this event dispatcher is started.
*/
private AudioMediaStreamImpl mediaStream;
/**
* The indicator which determines whether this event dispatcher has been scheduled for execution
* by {@link #threadPool}.
*/
private boolean scheduled = false;
/**
* Initializes a new <tt>CsrcAudioLevelDispatcher</tt> to dispatch events to a specific
* <tt>AudioMediaStreamImpl</tt>.
*
* @param mediaStream
* the <tt>AudioMediaStreamImpl</tt> to which the new instance is to dispatch events
*/
public CsrcAudioLevelDispatcher(AudioMediaStreamImpl mediaStream)
{
setMediaStream(mediaStream);
}
/**
* A level matrix that we should deliver to our media stream and its listeners in a separate
* thread.
*
* @param levels
* the levels that we'd like to queue for processing.
* @param rtpTime
* the timestamp carried by the RTP packet which carries the specified <tt>levels</tt>
*/
public void addLevels(long[] levels, long rtpTime)
{
synchronized (this) {
this.levels = levels;
if ((mediaStream != null) && !scheduled) {
threadPool.execute(this);
scheduled = true;
}
notifyAll();
}
}
/**
* Waits for new levels to be reported via the <tt>addLevels()</tt> method and then delivers
* them to the <tt>AudioMediaStream</tt> that we are associated with.
*/
@Override
public void run()
{
try {
do {
AudioMediaStreamImpl mediaStream;
long[] levels;
synchronized (this) {
// If the mediaStream is null, this instance is to stop.
mediaStream = this.mediaStream;
if (mediaStream == null) {
scheduled = false;
break;
}
if (this.levels == null) {
try {
wait();
}
catch (InterruptedException ie) {
}
continue;
}
else {
levels = this.levels;
this.levels = null;
}
}
if (levels != null)
mediaStream.audioLevelsReceived(levels);
} while (true);
}
finally {
synchronized (this) {
scheduled = false;
}
}
}
/**
* Causes our run method to exit so that this thread would stop handling levels.
*/
public void setMediaStream(AudioMediaStreamImpl mediaStream)
{
synchronized (this) {
if (this.mediaStream != mediaStream) {
this.mediaStream = mediaStream;
/*
* If the mediaStream changes, it is unlikely that the (audio) levels are associated
* with it.
*/
this.levels = null;
notifyAll();
}
}
}
}
|
[
"public",
"class",
"CsrcAudioLevelDispatcher",
"implements",
"Runnable",
"{",
"/**\n\t * The pool of <tt>Thread</tt>s which run <tt>CsrcAudioLevelDispatcher</tt>s.\n\t */",
"private",
"static",
"final",
"ExecutorService",
"threadPool",
"=",
"ExecutorUtils",
".",
"newCachedThreadPool",
"(",
"true",
",",
"\"",
"CsrcAudioLevelDispatcher",
"\"",
")",
";",
"/**\n\t * The levels added to this instance (by the <tt>reverseTransform</tt> method of a\n\t * <tt>PacketTransformer</tt> implementation) last.\n\t */",
"private",
"long",
"[",
"]",
"levels",
";",
"/**\n\t * The <tt>AudioMediaStreamImpl</tt> which listens to this event dispatcher. If <tt>null</tt>,\n\t * this event dispatcher is stopped. If non-<tt>null</tt>, this event dispatcher is started.\n\t */",
"private",
"AudioMediaStreamImpl",
"mediaStream",
";",
"/**\n\t * The indicator which determines whether this event dispatcher has been scheduled for execution\n\t * by {@link #threadPool}.\n\t */",
"private",
"boolean",
"scheduled",
"=",
"false",
";",
"/**\n\t * Initializes a new <tt>CsrcAudioLevelDispatcher</tt> to dispatch events to a specific\n\t * <tt>AudioMediaStreamImpl</tt>.\n\t *\n\t * @param mediaStream\n\t * the <tt>AudioMediaStreamImpl</tt> to which the new instance is to dispatch events\n\t */",
"public",
"CsrcAudioLevelDispatcher",
"(",
"AudioMediaStreamImpl",
"mediaStream",
")",
"{",
"setMediaStream",
"(",
"mediaStream",
")",
";",
"}",
"/**\n\t * A level matrix that we should deliver to our media stream and its listeners in a separate\n\t * thread.\n\t *\n\t * @param levels\n\t * the levels that we'd like to queue for processing.\n\t * @param rtpTime\n\t * the timestamp carried by the RTP packet which carries the specified <tt>levels</tt>\n\t */",
"public",
"void",
"addLevels",
"(",
"long",
"[",
"]",
"levels",
",",
"long",
"rtpTime",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"this",
".",
"levels",
"=",
"levels",
";",
"if",
"(",
"(",
"mediaStream",
"!=",
"null",
")",
"&&",
"!",
"scheduled",
")",
"{",
"threadPool",
".",
"execute",
"(",
"this",
")",
";",
"scheduled",
"=",
"true",
";",
"}",
"notifyAll",
"(",
")",
";",
"}",
"}",
"/**\n\t * Waits for new levels to be reported via the <tt>addLevels()</tt> method and then delivers\n\t * them to the <tt>AudioMediaStream</tt> that we are associated with.\n\t */",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"do",
"{",
"AudioMediaStreamImpl",
"mediaStream",
";",
"long",
"[",
"]",
"levels",
";",
"synchronized",
"(",
"this",
")",
"{",
"mediaStream",
"=",
"this",
".",
"mediaStream",
";",
"if",
"(",
"mediaStream",
"==",
"null",
")",
"{",
"scheduled",
"=",
"false",
";",
"break",
";",
"}",
"if",
"(",
"this",
".",
"levels",
"==",
"null",
")",
"{",
"try",
"{",
"wait",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"ie",
")",
"{",
"}",
"continue",
";",
"}",
"else",
"{",
"levels",
"=",
"this",
".",
"levels",
";",
"this",
".",
"levels",
"=",
"null",
";",
"}",
"}",
"if",
"(",
"levels",
"!=",
"null",
")",
"mediaStream",
".",
"audioLevelsReceived",
"(",
"levels",
")",
";",
"}",
"while",
"(",
"true",
")",
";",
"}",
"finally",
"{",
"synchronized",
"(",
"this",
")",
"{",
"scheduled",
"=",
"false",
";",
"}",
"}",
"}",
"/**\n\t * Causes our run method to exit so that this thread would stop handling levels.\n\t */",
"public",
"void",
"setMediaStream",
"(",
"AudioMediaStreamImpl",
"mediaStream",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"if",
"(",
"this",
".",
"mediaStream",
"!=",
"mediaStream",
")",
"{",
"this",
".",
"mediaStream",
"=",
"mediaStream",
";",
"/*\n\t\t\t\t * If the mediaStream changes, it is unlikely that the (audio) levels are associated\n\t\t\t\t * with it.\n\t\t\t\t */",
"this",
".",
"levels",
"=",
"null",
";",
"notifyAll",
"(",
")",
";",
"}",
"}",
"}",
"}"
] |
A simple thread that waits for new levels to be reported from incoming RTP packets and then
delivers them to the <tt>AudioMediaStream</tt> associated with this engine.
|
[
"A",
"simple",
"thread",
"that",
"waits",
"for",
"new",
"levels",
"to",
"be",
"reported",
"from",
"incoming",
"RTP",
"packets",
"and",
"then",
"delivers",
"them",
"to",
"the",
"<tt",
">",
"AudioMediaStream<",
"/",
"tt",
">",
"associated",
"with",
"this",
"engine",
"."
] |
[
"// If the mediaStream is null, this instance is to stop."
] |
[
{
"param": "Runnable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Runnable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 18
| 792
| 85
|
0dc86504b71ceb24a96f269637972a9a1807cd51
|
cimatl/cimatl.github.io
|
_plugins/donate_tag.rb
|
[
"MIT"
] |
Ruby
|
Jekyll
|
# Title: PayPal donation tag
# Author: Brett Terpstra http://brettterpstra.com
# Description: Add a paypal donate button.
#
# Set your default text and paypal id in _config.yaml:
# # Donation Button
# donate_text: "All donations are greatly appreciated!"
# donate_id: "A9KK2MTU7QSJU"
#
# You can pass a 1-time ID and/or alternate text for the button
#
# 1. If there's an ID passed first or alone, it will be used.
# 2. If there's a string passed after the ID, it will be used as alt text.
# 3. If there's only one argument and it doesn't match the regex for an id, it will be used as alt text.
#
# Syntax {% donate [alternate id] [optional text] %}
#
# Example:
#
# {% donate 78YFVY22AWW42 "Buy me coffee" %}
#
# Output:
# <form class="paypalform" action="https://www.paypal.com/cgi-bin/webscr" method="post">
# <input type="hidden" name="cmd" value="_s-xclick">
# <input type="hidden" name="hosted_button_id" value="78YFVY22AWW42">
# <button class="paypalbutton" name="submit">
# <span>Buy me coffee</span>
# </button>
# <img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
# </form>
#
|
Set your default text and paypal id in _config.yaml:
Donation Button
donate_text: "All donations are greatly appreciated!"
donate_id: "A9KK2MTU7QSJU"
You can pass a 1-time ID and/or alternate text for the button
1. If there's an ID passed first or alone, it will be used.
2. If there's a string passed after the ID, it will be used as alt text.
3. If there's only one argument and it doesn't match the regex for an id, it will be used as alt text.
Syntax {% donate [alternate id] [optional text] %}
{% donate 78YFVY22AWW42 "Buy me coffee" %}
Buy me coffee
|
[
"Set",
"your",
"default",
"text",
"and",
"paypal",
"id",
"in",
"_config",
".",
"yaml",
":",
"Donation",
"Button",
"donate_text",
":",
"\"",
"All",
"donations",
"are",
"greatly",
"appreciated!",
"\"",
"donate_id",
":",
"\"",
"A9KK2MTU7QSJU",
"\"",
"You",
"can",
"pass",
"a",
"1",
"-",
"time",
"ID",
"and",
"/",
"or",
"alternate",
"text",
"for",
"the",
"button",
"1",
".",
"If",
"there",
"'",
"s",
"an",
"ID",
"passed",
"first",
"or",
"alone",
"it",
"will",
"be",
"used",
".",
"2",
".",
"If",
"there",
"'",
"s",
"a",
"string",
"passed",
"after",
"the",
"ID",
"it",
"will",
"be",
"used",
"as",
"alt",
"text",
".",
"3",
".",
"If",
"there",
"'",
"s",
"only",
"one",
"argument",
"and",
"it",
"doesn",
"'",
"t",
"match",
"the",
"regex",
"for",
"an",
"id",
"it",
"will",
"be",
"used",
"as",
"alt",
"text",
".",
"Syntax",
"{",
"%",
"donate",
"[",
"alternate",
"id",
"]",
"[",
"optional",
"text",
"]",
"%",
"}",
"{",
"%",
"donate",
"78YFVY22AWW42",
"\"",
"Buy",
"me",
"coffee",
"\"",
"%",
"}",
"Buy",
"me",
"coffee"
] |
module Jekyll
class DonateTag < Liquid::Tag
@id = nil
@text = nil
def initialize(tag_name, markup, tokens)
if markup =~ /^([A-Z0-9]{12,16})?(.*)?/i
@id = $1 unless $1.nil? || $1.strip == ''
@text = $2.strip.gsub(/(^["']|["']$)/,'') unless $2.nil? || $2.strip == ''
end
super
end
def render(context)
output = super
@text ||= context.registers[:site].config['donate_text'] || "Your donations are appreciated!"
@id ||= context.registers[:site].config['donate_id'] || "UNCONFIGURED"
donate = %Q{<form class="paypalform" action="https://www.paypal.com/cgi-bin/webscr" method="post"><input type="hidden" name="cmd" value="_s-xclick"><input type="hidden" name="hosted_button_id" value="#{@id}"><button class="paypalbutton" name="submit"><span>#{@text}</span></button><img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"></form>}
end
end
end
|
[
"module",
"Jekyll",
"class",
"DonateTag",
"<",
"Liquid",
"::",
"Tag",
"@id",
"=",
"nil",
"@text",
"=",
"nil",
"def",
"initialize",
"(",
"tag_name",
",",
"markup",
",",
"tokens",
")",
"if",
"markup",
"=~",
"/",
"^([A-Z0-9]{12,16})?(.*)?",
"/i",
"@id",
"=",
"$1",
"unless",
"$1",
".",
"nil?",
"||",
"$1",
".",
"strip",
"==",
"''",
"@text",
"=",
"$2",
".",
"strip",
".",
"gsub",
"(",
"/",
"(^[\"']|[\"']$)",
"/",
",",
"''",
")",
"unless",
"$2",
".",
"nil?",
"||",
"$2",
".",
"strip",
"==",
"''",
"end",
"super",
"end",
"def",
"render",
"(",
"context",
")",
"output",
"=",
"super",
"@text",
"||=",
"context",
".",
"registers",
"[",
":site",
"]",
".",
"config",
"[",
"'donate_text'",
"]",
"||",
"\"Your donations are appreciated!\"",
"@id",
"||=",
"context",
".",
"registers",
"[",
":site",
"]",
".",
"config",
"[",
"'donate_id'",
"]",
"||",
"\"UNCONFIGURED\"",
"donate",
"=",
"%Q{<form class=\"paypalform\" action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\"><input type=\"hidden\" name=\"cmd\" value=\"_s-xclick\"><input type=\"hidden\" name=\"hosted_button_id\" value=\"#{@id}\"><button class=\"paypalbutton\" name=\"submit\"><span>#{@text}</span></button><img alt=\"\" border=\"0\" src=\"https://www.paypal.com/en_US/i/scr/pixel.gif\" width=\"1\" height=\"1\"></form>}",
"end",
"end",
"end"
] |
Title: PayPal donation tag
Author: Brett Terpstra http://brettterpstra.com
Description: Add a paypal donate button.
|
[
"Title",
":",
"PayPal",
"donation",
"tag",
"Author",
":",
"Brett",
"Terpstra",
"http",
":",
"//",
"brettterpstra",
".",
"com",
"Description",
":",
"Add",
"a",
"paypal",
"donate",
"button",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 297
| 355
|
229641718f0d8ca56dade8d10d7188ca8dcfec99
|
Charliocat/armeria
|
logback/src/main/java/com/linecorp/armeria/common/logback/RequestContextExportingAppender.java
|
[
"Apache-2.0"
] |
Java
|
RequestContextExportingAppender
|
/**
* A <a href="https://logback.qos.ch/">Logback</a> {@link Appender} that exports the properties of the current
* {@link RequestContext} to {@link MDC}.
*
* <p>Read '<a href="https://line.github.io/armeria/advanced-logging.html">Logging contextual information</a>'
* for more information.
*/
|
A Logback Appender that exports the properties of the current
RequestContext to MDC.
Read 'Logging contextual information'
for more information.
|
[
"A",
"Logback",
"Appender",
"that",
"exports",
"the",
"properties",
"of",
"the",
"current",
"RequestContext",
"to",
"MDC",
".",
"Read",
"'",
"Logging",
"contextual",
"information",
"'",
"for",
"more",
"information",
"."
] |
public final class RequestContextExportingAppender
extends UnsynchronizedAppenderBase<ILoggingEvent>
implements AppenderAttachable<ILoggingEvent> {
static {
if (InternalLoggerFactory.getDefaultFactory() == null) {
// Can happen due to initialization order.
InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);
}
}
private final AppenderAttachableImpl<ILoggingEvent> aai = new AppenderAttachableImpl<>();
private final RequestContextExporterBuilder builder = RequestContextExporter.builder();
@Nullable
private RequestContextExporter exporter;
@VisibleForTesting
RequestContextExporter exporter() {
checkState(exporter != null);
return exporter;
}
/**
* Adds the specified {@link BuiltInProperty} to the export list.
*/
public void addBuiltIn(BuiltInProperty property) {
ensureNotStarted();
builder.addBuiltIn(property);
}
/**
* Adds the specified {@link AttributeKey} to the export list.
*
* @param alias the alias of the attribute to export
* @param attrKey the key of the attribute to export
*/
public void addAttribute(String alias, AttributeKey<?> attrKey) {
ensureNotStarted();
builder.addAttribute(alias, attrKey);
}
/**
* Adds the specified {@link AttributeKey} to the export list.
*
* @param alias the alias of the attribute to export
* @param attrKey the key of the attribute to export
* @param stringifier the {@link Function} that converts the attribute value into a {@link String}
*/
public void addAttribute(String alias, AttributeKey<?> attrKey, Function<?, String> stringifier) {
ensureNotStarted();
requireNonNull(alias, "alias");
requireNonNull(attrKey, "attrKey");
requireNonNull(stringifier, "stringifier");
builder.addAttribute(alias, attrKey, stringifier);
}
/**
* Adds the specified HTTP request header name to the export list.
*/
public void addRequestHeader(CharSequence name) {
ensureNotStarted();
requireNonNull(name, "name");
builder.addRequestHeader(name);
}
/**
* Adds the specified HTTP response header name to the export list.
*/
public void addResponseHeader(CharSequence name) {
ensureNotStarted();
requireNonNull(name, "name");
builder.addResponseHeader(name);
}
/**
* Adds the property represented by the specified MDC key to the export list.
* Note: this method is meant to be used for XML configuration.
* Use {@code add*()} methods instead.
*/
public void setExport(String mdcKey) {
requireNonNull(mdcKey, "mdcKey");
builder.addKeyPattern(mdcKey);
}
/**
* Adds the properties represented by the specified comma-separated MDC keys to the export list.
* Note: this method is meant to be used for XML configuration.
* Use {@code add*()} methods instead.
*/
public void setExports(String mdcKeys) {
requireNonNull(mdcKeys, "mdcKeys");
builder.addKeyPattern(mdcKeys);
}
private void ensureNotStarted() {
if (isStarted()) {
throw new IllegalStateException("can't update the export list once started");
}
}
@Override
protected void append(ILoggingEvent eventObject) {
if (exporter == null) {
exporter = builder.build();
}
final Map<String, String> contextMap = exporter.export();
if (!contextMap.isEmpty()) {
final Map<String, String> originalMdcMap = eventObject.getMDCPropertyMap();
final Map<String, String> mdcMap;
if (!originalMdcMap.isEmpty()) {
mdcMap = new UnionMap<>(contextMap, originalMdcMap);
} else {
mdcMap = contextMap;
}
eventObject = new LoggingEventWrapper(eventObject, mdcMap);
}
aai.appendLoopOnAppenders(eventObject);
}
@Override
public void start() {
if (!aai.iteratorForAppenders().hasNext()) {
addWarn("No appender was attached to " + getClass().getSimpleName() + '.');
}
super.start();
}
@Override
public void stop() {
try {
aai.detachAndStopAllAppenders();
} finally {
super.stop();
}
}
@Override
public void addAppender(Appender<ILoggingEvent> newAppender) {
aai.addAppender(newAppender);
}
@Override
public Iterator<Appender<ILoggingEvent>> iteratorForAppenders() {
return aai.iteratorForAppenders();
}
@Override
public Appender<ILoggingEvent> getAppender(String name) {
return aai.getAppender(name);
}
@Override
public boolean isAttached(Appender<ILoggingEvent> appender) {
return aai.isAttached(appender);
}
@Override
public void detachAndStopAllAppenders() {
aai.detachAndStopAllAppenders();
}
@Override
public boolean detachAppender(Appender<ILoggingEvent> appender) {
return aai.detachAppender(appender);
}
@Override
public boolean detachAppender(String name) {
return aai.detachAppender(name);
}
private static final class LoggingEventWrapper implements ILoggingEvent {
private final ILoggingEvent event;
private final Map<String, String> mdcPropertyMap;
@Nullable
private final LoggerContextVO vo;
LoggingEventWrapper(ILoggingEvent event, Map<String, String> mdcPropertyMap) {
this.event = event;
this.mdcPropertyMap = mdcPropertyMap;
final LoggerContextVO oldVo = event.getLoggerContextVO();
if (oldVo != null) {
vo = new LoggerContextVO(oldVo.getName(), mdcPropertyMap, oldVo.getBirthTime());
} else {
vo = null;
}
}
@Override
public Object[] getArgumentArray() {
return event.getArgumentArray();
}
@Override
public Level getLevel() {
return event.getLevel();
}
@Override
public String getLoggerName() {
return event.getLoggerName();
}
@Override
public String getThreadName() {
return event.getThreadName();
}
@Override
public IThrowableProxy getThrowableProxy() {
return event.getThrowableProxy();
}
@Override
public void prepareForDeferredProcessing() {
event.prepareForDeferredProcessing();
}
@Override
@Nullable
public LoggerContextVO getLoggerContextVO() {
return vo;
}
@Override
public String getMessage() {
return event.getMessage();
}
@Override
public long getTimeStamp() {
return event.getTimeStamp();
}
@Override
public StackTraceElement[] getCallerData() {
return event.getCallerData();
}
@Override
public boolean hasCallerData() {
return event.hasCallerData();
}
@Override
public Marker getMarker() {
return event.getMarker();
}
@Override
public String getFormattedMessage() {
return event.getFormattedMessage();
}
@Override
public Map<String, String> getMDCPropertyMap() {
return mdcPropertyMap;
}
/**
* A synonym for {@link #getMDCPropertyMap}.
* @deprecated Use {@link #getMDCPropertyMap()}.
*/
@Override
@Deprecated
public Map<String, String> getMdc() {
return event.getMDCPropertyMap();
}
@Override
public String toString() {
return event.toString();
}
}
}
|
[
"public",
"final",
"class",
"RequestContextExportingAppender",
"extends",
"UnsynchronizedAppenderBase",
"<",
"ILoggingEvent",
">",
"implements",
"AppenderAttachable",
"<",
"ILoggingEvent",
">",
"{",
"static",
"{",
"if",
"(",
"InternalLoggerFactory",
".",
"getDefaultFactory",
"(",
")",
"==",
"null",
")",
"{",
"InternalLoggerFactory",
".",
"setDefaultFactory",
"(",
"Slf4JLoggerFactory",
".",
"INSTANCE",
")",
";",
"}",
"}",
"private",
"final",
"AppenderAttachableImpl",
"<",
"ILoggingEvent",
">",
"aai",
"=",
"new",
"AppenderAttachableImpl",
"<",
">",
"(",
")",
";",
"private",
"final",
"RequestContextExporterBuilder",
"builder",
"=",
"RequestContextExporter",
".",
"builder",
"(",
")",
";",
"@",
"Nullable",
"private",
"RequestContextExporter",
"exporter",
";",
"@",
"VisibleForTesting",
"RequestContextExporter",
"exporter",
"(",
")",
"{",
"checkState",
"(",
"exporter",
"!=",
"null",
")",
";",
"return",
"exporter",
";",
"}",
"/**\n * Adds the specified {@link BuiltInProperty} to the export list.\n */",
"public",
"void",
"addBuiltIn",
"(",
"BuiltInProperty",
"property",
")",
"{",
"ensureNotStarted",
"(",
")",
";",
"builder",
".",
"addBuiltIn",
"(",
"property",
")",
";",
"}",
"/**\n * Adds the specified {@link AttributeKey} to the export list.\n *\n * @param alias the alias of the attribute to export\n * @param attrKey the key of the attribute to export\n */",
"public",
"void",
"addAttribute",
"(",
"String",
"alias",
",",
"AttributeKey",
"<",
"?",
">",
"attrKey",
")",
"{",
"ensureNotStarted",
"(",
")",
";",
"builder",
".",
"addAttribute",
"(",
"alias",
",",
"attrKey",
")",
";",
"}",
"/**\n * Adds the specified {@link AttributeKey} to the export list.\n *\n * @param alias the alias of the attribute to export\n * @param attrKey the key of the attribute to export\n * @param stringifier the {@link Function} that converts the attribute value into a {@link String}\n */",
"public",
"void",
"addAttribute",
"(",
"String",
"alias",
",",
"AttributeKey",
"<",
"?",
">",
"attrKey",
",",
"Function",
"<",
"?",
",",
"String",
">",
"stringifier",
")",
"{",
"ensureNotStarted",
"(",
")",
";",
"requireNonNull",
"(",
"alias",
",",
"\"",
"alias",
"\"",
")",
";",
"requireNonNull",
"(",
"attrKey",
",",
"\"",
"attrKey",
"\"",
")",
";",
"requireNonNull",
"(",
"stringifier",
",",
"\"",
"stringifier",
"\"",
")",
";",
"builder",
".",
"addAttribute",
"(",
"alias",
",",
"attrKey",
",",
"stringifier",
")",
";",
"}",
"/**\n * Adds the specified HTTP request header name to the export list.\n */",
"public",
"void",
"addRequestHeader",
"(",
"CharSequence",
"name",
")",
"{",
"ensureNotStarted",
"(",
")",
";",
"requireNonNull",
"(",
"name",
",",
"\"",
"name",
"\"",
")",
";",
"builder",
".",
"addRequestHeader",
"(",
"name",
")",
";",
"}",
"/**\n * Adds the specified HTTP response header name to the export list.\n */",
"public",
"void",
"addResponseHeader",
"(",
"CharSequence",
"name",
")",
"{",
"ensureNotStarted",
"(",
")",
";",
"requireNonNull",
"(",
"name",
",",
"\"",
"name",
"\"",
")",
";",
"builder",
".",
"addResponseHeader",
"(",
"name",
")",
";",
"}",
"/**\n * Adds the property represented by the specified MDC key to the export list.\n * Note: this method is meant to be used for XML configuration.\n * Use {@code add*()} methods instead.\n */",
"public",
"void",
"setExport",
"(",
"String",
"mdcKey",
")",
"{",
"requireNonNull",
"(",
"mdcKey",
",",
"\"",
"mdcKey",
"\"",
")",
";",
"builder",
".",
"addKeyPattern",
"(",
"mdcKey",
")",
";",
"}",
"/**\n * Adds the properties represented by the specified comma-separated MDC keys to the export list.\n * Note: this method is meant to be used for XML configuration.\n * Use {@code add*()} methods instead.\n */",
"public",
"void",
"setExports",
"(",
"String",
"mdcKeys",
")",
"{",
"requireNonNull",
"(",
"mdcKeys",
",",
"\"",
"mdcKeys",
"\"",
")",
";",
"builder",
".",
"addKeyPattern",
"(",
"mdcKeys",
")",
";",
"}",
"private",
"void",
"ensureNotStarted",
"(",
")",
"{",
"if",
"(",
"isStarted",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"",
"can't update the export list once started",
"\"",
")",
";",
"}",
"}",
"@",
"Override",
"protected",
"void",
"append",
"(",
"ILoggingEvent",
"eventObject",
")",
"{",
"if",
"(",
"exporter",
"==",
"null",
")",
"{",
"exporter",
"=",
"builder",
".",
"build",
"(",
")",
";",
"}",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"contextMap",
"=",
"exporter",
".",
"export",
"(",
")",
";",
"if",
"(",
"!",
"contextMap",
".",
"isEmpty",
"(",
")",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"originalMdcMap",
"=",
"eventObject",
".",
"getMDCPropertyMap",
"(",
")",
";",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"mdcMap",
";",
"if",
"(",
"!",
"originalMdcMap",
".",
"isEmpty",
"(",
")",
")",
"{",
"mdcMap",
"=",
"new",
"UnionMap",
"<",
">",
"(",
"contextMap",
",",
"originalMdcMap",
")",
";",
"}",
"else",
"{",
"mdcMap",
"=",
"contextMap",
";",
"}",
"eventObject",
"=",
"new",
"LoggingEventWrapper",
"(",
"eventObject",
",",
"mdcMap",
")",
";",
"}",
"aai",
".",
"appendLoopOnAppenders",
"(",
"eventObject",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"start",
"(",
")",
"{",
"if",
"(",
"!",
"aai",
".",
"iteratorForAppenders",
"(",
")",
".",
"hasNext",
"(",
")",
")",
"{",
"addWarn",
"(",
"\"",
"No appender was attached to ",
"\"",
"+",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
"+",
"'.'",
")",
";",
"}",
"super",
".",
"start",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"stop",
"(",
")",
"{",
"try",
"{",
"aai",
".",
"detachAndStopAllAppenders",
"(",
")",
";",
"}",
"finally",
"{",
"super",
".",
"stop",
"(",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"addAppender",
"(",
"Appender",
"<",
"ILoggingEvent",
">",
"newAppender",
")",
"{",
"aai",
".",
"addAppender",
"(",
"newAppender",
")",
";",
"}",
"@",
"Override",
"public",
"Iterator",
"<",
"Appender",
"<",
"ILoggingEvent",
">",
">",
"iteratorForAppenders",
"(",
")",
"{",
"return",
"aai",
".",
"iteratorForAppenders",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"Appender",
"<",
"ILoggingEvent",
">",
"getAppender",
"(",
"String",
"name",
")",
"{",
"return",
"aai",
".",
"getAppender",
"(",
"name",
")",
";",
"}",
"@",
"Override",
"public",
"boolean",
"isAttached",
"(",
"Appender",
"<",
"ILoggingEvent",
">",
"appender",
")",
"{",
"return",
"aai",
".",
"isAttached",
"(",
"appender",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"detachAndStopAllAppenders",
"(",
")",
"{",
"aai",
".",
"detachAndStopAllAppenders",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"boolean",
"detachAppender",
"(",
"Appender",
"<",
"ILoggingEvent",
">",
"appender",
")",
"{",
"return",
"aai",
".",
"detachAppender",
"(",
"appender",
")",
";",
"}",
"@",
"Override",
"public",
"boolean",
"detachAppender",
"(",
"String",
"name",
")",
"{",
"return",
"aai",
".",
"detachAppender",
"(",
"name",
")",
";",
"}",
"private",
"static",
"final",
"class",
"LoggingEventWrapper",
"implements",
"ILoggingEvent",
"{",
"private",
"final",
"ILoggingEvent",
"event",
";",
"private",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"mdcPropertyMap",
";",
"@",
"Nullable",
"private",
"final",
"LoggerContextVO",
"vo",
";",
"LoggingEventWrapper",
"(",
"ILoggingEvent",
"event",
",",
"Map",
"<",
"String",
",",
"String",
">",
"mdcPropertyMap",
")",
"{",
"this",
".",
"event",
"=",
"event",
";",
"this",
".",
"mdcPropertyMap",
"=",
"mdcPropertyMap",
";",
"final",
"LoggerContextVO",
"oldVo",
"=",
"event",
".",
"getLoggerContextVO",
"(",
")",
";",
"if",
"(",
"oldVo",
"!=",
"null",
")",
"{",
"vo",
"=",
"new",
"LoggerContextVO",
"(",
"oldVo",
".",
"getName",
"(",
")",
",",
"mdcPropertyMap",
",",
"oldVo",
".",
"getBirthTime",
"(",
")",
")",
";",
"}",
"else",
"{",
"vo",
"=",
"null",
";",
"}",
"}",
"@",
"Override",
"public",
"Object",
"[",
"]",
"getArgumentArray",
"(",
")",
"{",
"return",
"event",
".",
"getArgumentArray",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"Level",
"getLevel",
"(",
")",
"{",
"return",
"event",
".",
"getLevel",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"getLoggerName",
"(",
")",
"{",
"return",
"event",
".",
"getLoggerName",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"getThreadName",
"(",
")",
"{",
"return",
"event",
".",
"getThreadName",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"IThrowableProxy",
"getThrowableProxy",
"(",
")",
"{",
"return",
"event",
".",
"getThrowableProxy",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"prepareForDeferredProcessing",
"(",
")",
"{",
"event",
".",
"prepareForDeferredProcessing",
"(",
")",
";",
"}",
"@",
"Override",
"@",
"Nullable",
"public",
"LoggerContextVO",
"getLoggerContextVO",
"(",
")",
"{",
"return",
"vo",
";",
"}",
"@",
"Override",
"public",
"String",
"getMessage",
"(",
")",
"{",
"return",
"event",
".",
"getMessage",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"long",
"getTimeStamp",
"(",
")",
"{",
"return",
"event",
".",
"getTimeStamp",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"StackTraceElement",
"[",
"]",
"getCallerData",
"(",
")",
"{",
"return",
"event",
".",
"getCallerData",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"boolean",
"hasCallerData",
"(",
")",
"{",
"return",
"event",
".",
"hasCallerData",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"Marker",
"getMarker",
"(",
")",
"{",
"return",
"event",
".",
"getMarker",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"getFormattedMessage",
"(",
")",
"{",
"return",
"event",
".",
"getFormattedMessage",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"Map",
"<",
"String",
",",
"String",
">",
"getMDCPropertyMap",
"(",
")",
"{",
"return",
"mdcPropertyMap",
";",
"}",
"/**\n * A synonym for {@link #getMDCPropertyMap}.\n * @deprecated Use {@link #getMDCPropertyMap()}.\n */",
"@",
"Override",
"@",
"Deprecated",
"public",
"Map",
"<",
"String",
",",
"String",
">",
"getMdc",
"(",
")",
"{",
"return",
"event",
".",
"getMDCPropertyMap",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"event",
".",
"toString",
"(",
")",
";",
"}",
"}",
"}"
] |
A <a href="https://logback.qos.ch/">Logback</a> {@link Appender} that exports the properties of the current
{@link RequestContext} to {@link MDC}.
|
[
"A",
"<a",
"href",
"=",
"\"",
"https",
":",
"//",
"logback",
".",
"qos",
".",
"ch",
"/",
"\"",
">",
"Logback<",
"/",
"a",
">",
"{",
"@link",
"Appender",
"}",
"that",
"exports",
"the",
"properties",
"of",
"the",
"current",
"{",
"@link",
"RequestContext",
"}",
"to",
"{",
"@link",
"MDC",
"}",
"."
] |
[
"// Can happen due to initialization order."
] |
[
{
"param": "AppenderAttachable<ILoggingEvent>",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "AppenderAttachable<ILoggingEvent>",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 15
| 1,680
| 80
|
dc09ed48ab56d1dcb764ff57748b72d40e21e4e9
|
seeq12/seeq-azureml
|
seeq/addons/azureml/backend/_aml_response_models.py
|
[
"Apache-2.0"
] |
Python
|
OnlineDeployment
|
Gets the serialized response from the Azure ML deployments endpoint and
deserializes it
Attributes
----------
id : str
ID of the Azure ML deployment
name : str
Name of the Azure ML deployment
modelId : str
ID of the model associated with the Azure ML deployment
traffic : str
Allowed traffic to this deployment
model : str
Name of the model associated with the Azure ML deployment
location : str
Location of the Azure ML deployment
Methods
-------
deserialize_aml_deployment_response(json)
Deserializes the Azure ML response from the deployment endpoint
|
Gets the serialized response from the Azure ML deployments endpoint and
deserializes it
Attributes
Methods
deserialize_aml_deployment_response(json)
Deserializes the Azure ML response from the deployment endpoint
|
[
"Gets",
"the",
"serialized",
"response",
"from",
"the",
"Azure",
"ML",
"deployments",
"endpoint",
"and",
"deserializes",
"it",
"Attributes",
"Methods",
"deserialize_aml_deployment_response",
"(",
"json",
")",
"Deserializes",
"the",
"Azure",
"ML",
"response",
"from",
"the",
"deployment",
"endpoint"
] |
class OnlineDeployment:
"""
Gets the serialized response from the Azure ML deployments endpoint and
deserializes it
Attributes
----------
id : str
ID of the Azure ML deployment
name : str
Name of the Azure ML deployment
modelId : str
ID of the model associated with the Azure ML deployment
traffic : str
Allowed traffic to this deployment
model : str
Name of the model associated with the Azure ML deployment
location : str
Location of the Azure ML deployment
Methods
-------
deserialize_aml_deployment_response(json)
Deserializes the Azure ML response from the deployment endpoint
"""
def __init__(self, name, idd, computeType) -> None:
"""
Parameters
----------
name : str
Name of the Azure ML deployment
idd : str or None
ID of the Azure ML deployment
"""
self.id = idd
self.name = name
self.computeType = computeType
self.modelId = None
self.traffic = None
self.model = None
self.model_version = None
self.location = None
@staticmethod
def deserialize_aml_deployment_response(json, computeType):
"""
Gets a serialized response from a given online endpoint in Azure ML and
deserializes each deployment associated with the endpoint.
Parameters
----------
json: dict
Serialized response of the Azure ML deployment endpoint
computeType: str
The type of compute: Managed, ACI, K8S
Returns
-------
ods: list
List of deployments associated with the endpoint
"""
ods = list()
for v in json['value']:
od = OnlineDeployment(name=v['name'], idd=v['id'], computeType=computeType)
od.modelId = v['properties']['model']['assetId']
od.location = v['location']
ods.append(od)
return ods
|
[
"class",
"OnlineDeployment",
":",
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"idd",
",",
"computeType",
")",
"->",
"None",
":",
"\"\"\"\n Parameters\n ----------\n name : str\n Name of the Azure ML deployment\n idd : str or None\n ID of the Azure ML deployment\n \"\"\"",
"self",
".",
"id",
"=",
"idd",
"self",
".",
"name",
"=",
"name",
"self",
".",
"computeType",
"=",
"computeType",
"self",
".",
"modelId",
"=",
"None",
"self",
".",
"traffic",
"=",
"None",
"self",
".",
"model",
"=",
"None",
"self",
".",
"model_version",
"=",
"None",
"self",
".",
"location",
"=",
"None",
"@",
"staticmethod",
"def",
"deserialize_aml_deployment_response",
"(",
"json",
",",
"computeType",
")",
":",
"\"\"\"\n Gets a serialized response from a given online endpoint in Azure ML and\n deserializes each deployment associated with the endpoint.\n\n Parameters\n ----------\n json: dict\n Serialized response of the Azure ML deployment endpoint\n computeType: str\n The type of compute: Managed, ACI, K8S\n\n Returns\n -------\n ods: list\n List of deployments associated with the endpoint\n\n \"\"\"",
"ods",
"=",
"list",
"(",
")",
"for",
"v",
"in",
"json",
"[",
"'value'",
"]",
":",
"od",
"=",
"OnlineDeployment",
"(",
"name",
"=",
"v",
"[",
"'name'",
"]",
",",
"idd",
"=",
"v",
"[",
"'id'",
"]",
",",
"computeType",
"=",
"computeType",
")",
"od",
".",
"modelId",
"=",
"v",
"[",
"'properties'",
"]",
"[",
"'model'",
"]",
"[",
"'assetId'",
"]",
"od",
".",
"location",
"=",
"v",
"[",
"'location'",
"]",
"ods",
".",
"append",
"(",
"od",
")",
"return",
"ods"
] |
Gets the serialized response from the Azure ML deployments endpoint and
deserializes it
|
[
"Gets",
"the",
"serialized",
"response",
"from",
"the",
"Azure",
"ML",
"deployments",
"endpoint",
"and",
"deserializes",
"it"
] |
[
"\"\"\"\n Gets the serialized response from the Azure ML deployments endpoint and\n deserializes it\n\n Attributes\n ----------\n id : str\n ID of the Azure ML deployment\n name : str\n Name of the Azure ML deployment\n modelId : str\n ID of the model associated with the Azure ML deployment\n traffic : str\n Allowed traffic to this deployment\n model : str\n Name of the model associated with the Azure ML deployment\n location : str\n Location of the Azure ML deployment\n\n Methods\n -------\n deserialize_aml_deployment_response(json)\n Deserializes the Azure ML response from the deployment endpoint\n \"\"\"",
"\"\"\"\n Parameters\n ----------\n name : str\n Name of the Azure ML deployment\n idd : str or None\n ID of the Azure ML deployment\n \"\"\"",
"\"\"\"\n Gets a serialized response from a given online endpoint in Azure ML and\n deserializes each deployment associated with the endpoint.\n\n Parameters\n ----------\n json: dict\n Serialized response of the Azure ML deployment endpoint\n computeType: str\n The type of compute: Managed, ACI, K8S\n\n Returns\n -------\n ods: list\n List of deployments associated with the endpoint\n\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 431
| 139
|
b7983737ebfc07caa52357624d583420cd03d375
|
A-Trash-Coder/dlive.py
|
dlive/models/user.py
|
[
"MIT"
] |
Python
|
User
|
Represents a user registered on DLive
Attributes
----------
username: :class:`str`
The users unique username
displayname: :class:`str`
The users display name, most
likely the username with a capitalization
differences
avatar_url: :class:`str`
Url to the users avatar image
partner_status: :class:`dlive.enums.PartnerStatus`
The status of their DLive partnership
created_at: :class:`datetime`
When the users account was created
wallet: :class:`models.tiny_model.Wallet`
The users wallet
is_subscribeable: :class:`bool`
Whether the user can be subscribed to
ban_status: :class:`dlive.enums.BanStatus`
The users ban status
is_deactivated: :class:`bool`
Whether the users account is deactivated
offline_image: :class:`str`
The users offline cover art
mention: :class:`str`
The users name in mention form
is_verified_partner: :class:`bool`
Whether the user is a verified partner
is_global_partner: :class:`bool`
Whether the user is a global partner
is_affliate: :class:`bool`
Whether the user is an affliate
is_global_partner_suspended: :class:`bool`
Whether the users global partner is a suspended status
is_account_suspended: :class:`bool`
Whether the users account is suspended
is_stream_banned: :class:`bool`
Whether the person is banned from streaming
|
Represents a user registered on DLive
Attributes
|
[
"Represents",
"a",
"user",
"registered",
"on",
"DLive",
"Attributes"
] |
class User:
"""Represents a user registered on DLive
Attributes
----------
username: :class:`str`
The users unique username
displayname: :class:`str`
The users display name, most
likely the username with a capitalization
differences
avatar_url: :class:`str`
Url to the users avatar image
partner_status: :class:`dlive.enums.PartnerStatus`
The status of their DLive partnership
created_at: :class:`datetime`
When the users account was created
wallet: :class:`models.tiny_model.Wallet`
The users wallet
is_subscribeable: :class:`bool`
Whether the user can be subscribed to
ban_status: :class:`dlive.enums.BanStatus`
The users ban status
is_deactivated: :class:`bool`
Whether the users account is deactivated
offline_image: :class:`str`
The users offline cover art
mention: :class:`str`
The users name in mention form
is_verified_partner: :class:`bool`
Whether the user is a verified partner
is_global_partner: :class:`bool`
Whether the user is a global partner
is_affliate: :class:`bool`
Whether the user is an affliate
is_global_partner_suspended: :class:`bool`
Whether the users global partner is a suspended status
is_account_suspended: :class:`bool`
Whether the users account is suspended
is_stream_banned: :class:`bool`
Whether the person is banned from streaming
"""
def __init__(self, data):
self.username = data["username"]
self.displayname = data["displayname"]
self.avatar_url = data["avatar"]
self.partner_status = PartnerStatus[data["partnerStatus"].lower()]
self.created_at = datetime.datetime.utcfromtimestamp(
int(data["createdAt"][:-3]))
self.wallet = tiny_models.Wallet(data["wallet"])
self.is_subscribeable: bool = data["canSubscribe"]
self.ban_status = BanStatus[data["banStatus"].lower()]
self.is_deactivated: bool = data["deactivated"]
self.offline_image = data["offlineImage"]
def __str__(self):
return self.displayname
def __eq__(self, other_user):
return isinstance(other_user, User) and other_user.username == self.username
def __ne__(self, other_user):
return not self.__eq__(other_user)
@property
def mention(self) -> str:
"""A string formatted to mention a user."""
return f"@{self.displayname}"
@property
def is_verified_partner(self) -> bool:
"""Whether the user is a verified partner on DLive."""
return self.partner_status == PartnerStatus.verified_partner
@property
def is_global_partner(self) -> bool:
"""Whether the user is a global partner on DLive."""
return self.partner_status == PartnerStatus.global_partner
@property
def is_affiliate(self) -> bool:
"""Whether the user is a DLive affiliate."""
return self.partner_status == PartnerStatus.affiliate
@property
def is_global_partner_suspended(self) -> bool:
"""Whether the user's global partner status is suspended."""
return self.partner_status == PartnerStatus.global_partner_suspended
@property
def is_account_suspended(self) -> bool:
"""Whether the user's account is suspended."""
return self.ban_status == BanStatus.account_suspended
@property
def is_stream_banned(self) -> bool:
"""Whether the user is banned from streaming."""
return self.ban_status == BanStatus.ban_from_streaming
|
[
"class",
"User",
":",
"def",
"__init__",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"username",
"=",
"data",
"[",
"\"username\"",
"]",
"self",
".",
"displayname",
"=",
"data",
"[",
"\"displayname\"",
"]",
"self",
".",
"avatar_url",
"=",
"data",
"[",
"\"avatar\"",
"]",
"self",
".",
"partner_status",
"=",
"PartnerStatus",
"[",
"data",
"[",
"\"partnerStatus\"",
"]",
".",
"lower",
"(",
")",
"]",
"self",
".",
"created_at",
"=",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"int",
"(",
"data",
"[",
"\"createdAt\"",
"]",
"[",
":",
"-",
"3",
"]",
")",
")",
"self",
".",
"wallet",
"=",
"tiny_models",
".",
"Wallet",
"(",
"data",
"[",
"\"wallet\"",
"]",
")",
"self",
".",
"is_subscribeable",
":",
"bool",
"=",
"data",
"[",
"\"canSubscribe\"",
"]",
"self",
".",
"ban_status",
"=",
"BanStatus",
"[",
"data",
"[",
"\"banStatus\"",
"]",
".",
"lower",
"(",
")",
"]",
"self",
".",
"is_deactivated",
":",
"bool",
"=",
"data",
"[",
"\"deactivated\"",
"]",
"self",
".",
"offline_image",
"=",
"data",
"[",
"\"offlineImage\"",
"]",
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"self",
".",
"displayname",
"def",
"__eq__",
"(",
"self",
",",
"other_user",
")",
":",
"return",
"isinstance",
"(",
"other_user",
",",
"User",
")",
"and",
"other_user",
".",
"username",
"==",
"self",
".",
"username",
"def",
"__ne__",
"(",
"self",
",",
"other_user",
")",
":",
"return",
"not",
"self",
".",
"__eq__",
"(",
"other_user",
")",
"@",
"property",
"def",
"mention",
"(",
"self",
")",
"->",
"str",
":",
"\"\"\"A string formatted to mention a user.\"\"\"",
"return",
"f\"@{self.displayname}\"",
"@",
"property",
"def",
"is_verified_partner",
"(",
"self",
")",
"->",
"bool",
":",
"\"\"\"Whether the user is a verified partner on DLive.\"\"\"",
"return",
"self",
".",
"partner_status",
"==",
"PartnerStatus",
".",
"verified_partner",
"@",
"property",
"def",
"is_global_partner",
"(",
"self",
")",
"->",
"bool",
":",
"\"\"\"Whether the user is a global partner on DLive.\"\"\"",
"return",
"self",
".",
"partner_status",
"==",
"PartnerStatus",
".",
"global_partner",
"@",
"property",
"def",
"is_affiliate",
"(",
"self",
")",
"->",
"bool",
":",
"\"\"\"Whether the user is a DLive affiliate.\"\"\"",
"return",
"self",
".",
"partner_status",
"==",
"PartnerStatus",
".",
"affiliate",
"@",
"property",
"def",
"is_global_partner_suspended",
"(",
"self",
")",
"->",
"bool",
":",
"\"\"\"Whether the user's global partner status is suspended.\"\"\"",
"return",
"self",
".",
"partner_status",
"==",
"PartnerStatus",
".",
"global_partner_suspended",
"@",
"property",
"def",
"is_account_suspended",
"(",
"self",
")",
"->",
"bool",
":",
"\"\"\"Whether the user's account is suspended.\"\"\"",
"return",
"self",
".",
"ban_status",
"==",
"BanStatus",
".",
"account_suspended",
"@",
"property",
"def",
"is_stream_banned",
"(",
"self",
")",
"->",
"bool",
":",
"\"\"\"Whether the user is banned from streaming.\"\"\"",
"return",
"self",
".",
"ban_status",
"==",
"BanStatus",
".",
"ban_from_streaming"
] |
Represents a user registered on DLive
Attributes
|
[
"Represents",
"a",
"user",
"registered",
"on",
"DLive",
"Attributes"
] |
[
"\"\"\"Represents a user registered on DLive\n\n Attributes\n ----------\n username: :class:`str`\n The users unique username\n displayname: :class:`str`\n The users display name, most\n likely the username with a capitalization\n differences\n avatar_url: :class:`str`\n Url to the users avatar image\n partner_status: :class:`dlive.enums.PartnerStatus`\n The status of their DLive partnership\n created_at: :class:`datetime`\n When the users account was created\n wallet: :class:`models.tiny_model.Wallet`\n The users wallet\n is_subscribeable: :class:`bool`\n Whether the user can be subscribed to\n ban_status: :class:`dlive.enums.BanStatus`\n The users ban status\n is_deactivated: :class:`bool`\n Whether the users account is deactivated\n offline_image: :class:`str`\n The users offline cover art\n mention: :class:`str`\n The users name in mention form\n is_verified_partner: :class:`bool`\n Whether the user is a verified partner\n is_global_partner: :class:`bool`\n Whether the user is a global partner\n is_affliate: :class:`bool`\n Whether the user is an affliate\n is_global_partner_suspended: :class:`bool`\n Whether the users global partner is a suspended status\n is_account_suspended: :class:`bool`\n Whether the users account is suspended\n is_stream_banned: :class:`bool`\n Whether the person is banned from streaming\n \"\"\"",
"\"\"\"A string formatted to mention a user.\"\"\"",
"\"\"\"Whether the user is a verified partner on DLive.\"\"\"",
"\"\"\"Whether the user is a global partner on DLive.\"\"\"",
"\"\"\"Whether the user is a DLive affiliate.\"\"\"",
"\"\"\"Whether the user's global partner status is suspended.\"\"\"",
"\"\"\"Whether the user's account is suspended.\"\"\"",
"\"\"\"Whether the user is banned from streaming.\"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 804
| 343
|
2fa939f5208b8781f97abd5ed131a8465388b1af
|
saadshams/puremvc-js-multicore-framework
|
src/main/org/puremvc/multicore/core/Controller.js
|
[
"Apache-2.0"
] |
JavaScript
|
Controller
|
/**
* A Multiton <code>IController</code> implementation.
*
* <P>In PureMVC, the <code>Controller</code> class follows the
* 'Command and Controller' strategy, and assumes these
* responsibilities:</P>
*
* <UL>
* <LI> Remembering which <code>ICommand</code>s
* are intended to handle which <code>INotifications</code>.</LI>
* <LI> Registering itself as an <code>IObserver</code> with
* the <code>View</code> for each <code>INotification</code>
* that it has an <code>ICommand</code> mapping for.</LI>
* <LI> Creating a new instance of the proper <code>ICommand</code>
* to handle a given <code>INotification</code> when notified by the <code>View</code>.</LI>
* <LI> Calling the <code>ICommand</code>'s <code>execute</code>
* method, passing in the <code>INotification</code>.</LI>
* </UL>
*
* <P>Your application must register <code>ICommands</code> with the
* Controller.</P>
*
* <P>The simplest way is to subclass </code>Facade</code>,
* and use its <code>initializeController</code> method to add your
* registrations.</P>
*
* @see puremvc.View View
* @see puremvc.Observer Observer
* @see puremvc.Notification Notification
* @see puremvc.SimpleCommand SimpleCommand
* @see puremvc.MacroCommand MacroCommand
*
* @class puremvc.Controller
* @implements puremvc.IController
*/
|
A Multiton IController implementation.
In PureMVC, the Controller class follows the
'Command and Controller' strategy, and assumes these
responsibilities:
Remembering which ICommands
are intended to handle which INotifications.
Registering itself as an IObserver with
the View for each INotification
that it has an ICommand mapping for.
Creating a new instance of the proper ICommand
to handle a given INotification when notified by the View.
Calling the ICommand's execute
method, passing in the INotification.
Your application must register ICommands with the
Controller.
The simplest way is to subclass Facade,
and use its initializeController method to add your
registrations.
|
[
"A",
"Multiton",
"IController",
"implementation",
".",
"In",
"PureMVC",
"the",
"Controller",
"class",
"follows",
"the",
"'",
"Command",
"and",
"Controller",
"'",
"strategy",
"and",
"assumes",
"these",
"responsibilities",
":",
"Remembering",
"which",
"ICommands",
"are",
"intended",
"to",
"handle",
"which",
"INotifications",
".",
"Registering",
"itself",
"as",
"an",
"IObserver",
"with",
"the",
"View",
"for",
"each",
"INotification",
"that",
"it",
"has",
"an",
"ICommand",
"mapping",
"for",
".",
"Creating",
"a",
"new",
"instance",
"of",
"the",
"proper",
"ICommand",
"to",
"handle",
"a",
"given",
"INotification",
"when",
"notified",
"by",
"the",
"View",
".",
"Calling",
"the",
"ICommand",
"'",
"s",
"execute",
"method",
"passing",
"in",
"the",
"INotification",
".",
"Your",
"application",
"must",
"register",
"ICommands",
"with",
"the",
"Controller",
".",
"The",
"simplest",
"way",
"is",
"to",
"subclass",
"Facade",
"and",
"use",
"its",
"initializeController",
"method",
"to",
"add",
"your",
"registrations",
"."
] |
class Controller {
/**
* Constructor.
*
* <P>This <code>IController</code> implementation is a Multiton,
* so you should not call the constructor
* directly, but instead call the static Factory method,
* passing the unique key for this instance
* <code>Controller.getInstance( multitonKey )</code></P>
*
* @throws {Error} Error if instance for this Multiton key has already been constructed
*
* @constructor
* @param {string} key
*/
constructor(key) {
if (Controller.instanceMap[key] != null) throw new Error(Controller.MULTITON_MSG);
// /** @protected {string} */
/**
* [multitonKey description]
* @protected
* @type {string}
*/
this.multitonKey = key;
Controller.instanceMap.set(this.multitonKey, this);
// /** @protected {Map<string, function():puremvc.ICommand>} */
/**
* [commandMap description]
* @protected
* @type {Map<string, function():puremvc.ICommand>}
*/
this.commandMap = new Map();
this.initializeController();
}
/**
* Initialize the Multiton <code>Controller</code> instance.
*
* <P>Called automatically by the constructor.</P>
*
* <P>Note that if you are using a subclass of <code>View</code>
* in your application, you should <i>also</i> subclass <code>Controller</code>
* and override the <code>initializeController</code> method in the
* following way:</P>
*
* <pre><code>
* // ensure that the Controller is talking to my IView implementation
* initializeController( )
* {
* this.view = MyView.getInstance(this.multitonKey, (key) => new MyView(key));
* }
* </code></pre>
*
*/
initializeController() {
/** @protected **/
this.view = View.getInstance(this.multitonKey, (key) => new View(key));
}
/**
* <code>Controller</code> Multiton Factory method.
*
* @static
* @param {string} key
* @param {factory} factory
* @param {function(string):puremvc.IController} factory
* @returns {puremvc.IController} the Multiton instance of <code>Controller</code>
*/
static getInstance(key, factory) {
if (this.instanceMap.get(key) == null) this.instanceMap.set(key, factory(key));
return this.instanceMap.get(key);
}
/**
* <P>If an <code>ICommand</code> has previously been registered
* to handle a the given <code>INotification</code>, then it is executed.</P>
*
* @param {puremvc.INotification} notification an <code>INotification</code>
*/
executeCommand(notification) {
let factory = this.commandMap.get(notification.name);
if (factory == null) return;
let commandInstance = factory();
commandInstance.initializeNotifier(this.multitonKey);
commandInstance.execute(notification);
}
/**
* <P>Register a particular <code>ICommand</code> class as the handler
* for a particular <code>INotification</code>.</P>
*
* <P>If an <code>ICommand</code> has already been registered to
* handle <code>INotification</code>s with this name, it is no longer
* used, the new <code>ICommand</code> is used instead.</P>
*
* <P>The Observer for the new ICommand is only created if this the
* first time an ICommand has been regisered for this Notification name.</P>
*
* @param notificationName the name of the <code>INotification</code>
* @param {factory} factory the <code>Class</code> of the <code>ICommand</code>
* @param {function():puremvc.ICommand} factory
*/
registerCommand(notificationName, factory) {
if (this.commandMap.get(notificationName) == null) {
this.view.registerObserver(notificationName, new Observer(this.executeCommand, this));
}
this.commandMap.set(notificationName, factory);
}
/**
* Check if a Command is registered for a given Notification
*
* @param {string} notificationName
* @return {boolean} whether a Command is currently registered for the given <code>notificationName</code>.
*/
hasCommand(notificationName) {
return this.commandMap.has(notificationName);
}
/**
* Remove a previously registered <code>ICommand</code> to <code>INotification</code> mapping.
*
* @param {string} notificationName the name of the <code>INotification</code> to remove the <code>ICommand</code> mapping for
*/
removeCommand(notificationName) {
// if the Command is registered...
if(this.hasCommand(notificationName)) {
// remove the observer
this.view.removeObserver(notificationName, this);
// remove the command
this.commandMap.delete(notificationName)
}
}
/**
* Remove an IController instance
*
* @static
* @param {string} key of IController instance to remove
*/
static removeController(key) {
Controller.instanceMap.delete(key);
}
/**
* Multiton instance
*
* @static
* @type {Map<string, puremvc.IController>}
*/
// static instanceMap = new Map();
static get instanceMap () {
let instanceMap = new Map()
Reflect.defineProperty(this, `instanceMap`, {value: instanceMap})
return instanceMap
}
/**
* Message Constants
*
* @static
* @type {string}
*/
static get MULTITON_MSG() { return "Controller instance for this Multiton key already constructed!" };
}
|
[
"class",
"Controller",
"{",
"constructor",
"(",
"key",
")",
"{",
"if",
"(",
"Controller",
".",
"instanceMap",
"[",
"key",
"]",
"!=",
"null",
")",
"throw",
"new",
"Error",
"(",
"Controller",
".",
"MULTITON_MSG",
")",
";",
"this",
".",
"multitonKey",
"=",
"key",
";",
"Controller",
".",
"instanceMap",
".",
"set",
"(",
"this",
".",
"multitonKey",
",",
"this",
")",
";",
"this",
".",
"commandMap",
"=",
"new",
"Map",
"(",
")",
";",
"this",
".",
"initializeController",
"(",
")",
";",
"}",
"initializeController",
"(",
")",
"{",
"this",
".",
"view",
"=",
"View",
".",
"getInstance",
"(",
"this",
".",
"multitonKey",
",",
"(",
"key",
")",
"=>",
"new",
"View",
"(",
"key",
")",
")",
";",
"}",
"static",
"getInstance",
"(",
"key",
",",
"factory",
")",
"{",
"if",
"(",
"this",
".",
"instanceMap",
".",
"get",
"(",
"key",
")",
"==",
"null",
")",
"this",
".",
"instanceMap",
".",
"set",
"(",
"key",
",",
"factory",
"(",
"key",
")",
")",
";",
"return",
"this",
".",
"instanceMap",
".",
"get",
"(",
"key",
")",
";",
"}",
"executeCommand",
"(",
"notification",
")",
"{",
"let",
"factory",
"=",
"this",
".",
"commandMap",
".",
"get",
"(",
"notification",
".",
"name",
")",
";",
"if",
"(",
"factory",
"==",
"null",
")",
"return",
";",
"let",
"commandInstance",
"=",
"factory",
"(",
")",
";",
"commandInstance",
".",
"initializeNotifier",
"(",
"this",
".",
"multitonKey",
")",
";",
"commandInstance",
".",
"execute",
"(",
"notification",
")",
";",
"}",
"registerCommand",
"(",
"notificationName",
",",
"factory",
")",
"{",
"if",
"(",
"this",
".",
"commandMap",
".",
"get",
"(",
"notificationName",
")",
"==",
"null",
")",
"{",
"this",
".",
"view",
".",
"registerObserver",
"(",
"notificationName",
",",
"new",
"Observer",
"(",
"this",
".",
"executeCommand",
",",
"this",
")",
")",
";",
"}",
"this",
".",
"commandMap",
".",
"set",
"(",
"notificationName",
",",
"factory",
")",
";",
"}",
"hasCommand",
"(",
"notificationName",
")",
"{",
"return",
"this",
".",
"commandMap",
".",
"has",
"(",
"notificationName",
")",
";",
"}",
"removeCommand",
"(",
"notificationName",
")",
"{",
"if",
"(",
"this",
".",
"hasCommand",
"(",
"notificationName",
")",
")",
"{",
"this",
".",
"view",
".",
"removeObserver",
"(",
"notificationName",
",",
"this",
")",
";",
"this",
".",
"commandMap",
".",
"delete",
"(",
"notificationName",
")",
"}",
"}",
"static",
"removeController",
"(",
"key",
")",
"{",
"Controller",
".",
"instanceMap",
".",
"delete",
"(",
"key",
")",
";",
"}",
"static",
"get",
"instanceMap",
"(",
")",
"{",
"let",
"instanceMap",
"=",
"new",
"Map",
"(",
")",
"Reflect",
".",
"defineProperty",
"(",
"this",
",",
"`",
"`",
",",
"{",
"value",
":",
"instanceMap",
"}",
")",
"return",
"instanceMap",
"}",
"static",
"get",
"MULTITON_MSG",
"(",
")",
"{",
"return",
"\"Controller instance for this Multiton key already constructed!\"",
"}",
";",
"}"
] |
A Multiton <code>IController</code> implementation.
|
[
"A",
"Multiton",
"<code",
">",
"IController<",
"/",
"code",
">",
"implementation",
"."
] |
[
"/**\n * Constructor.\n *\n * <P>This <code>IController</code> implementation is a Multiton,\n * so you should not call the constructor\n * directly, but instead call the static Factory method,\n * passing the unique key for this instance\n * <code>Controller.getInstance( multitonKey )</code></P>\n *\n * @throws {Error} Error if instance for this Multiton key has already been constructed\n *\n * @constructor\n * @param {string} key\n */",
"// /** @protected {string} */",
"/**\n * [multitonKey description]\n * @protected\n * @type {string}\n */",
"// /** @protected {Map<string, function():puremvc.ICommand>} */",
"/**\n * [commandMap description]\n * @protected\n * @type {Map<string, function():puremvc.ICommand>}\n */",
"/**\n * Initialize the Multiton <code>Controller</code> instance.\n *\n * <P>Called automatically by the constructor.</P>\n *\n * <P>Note that if you are using a subclass of <code>View</code>\n * in your application, you should <i>also</i> subclass <code>Controller</code>\n * and override the <code>initializeController</code> method in the\n * following way:</P>\n *\n * <pre><code>\n *\t\t// ensure that the Controller is talking to my IView implementation\n *\t\tinitializeController( )\n *\t\t{\n *\t\t\tthis.view = MyView.getInstance(this.multitonKey, (key) => new MyView(key));\n *\t\t}\n * </code></pre>\n *\n */",
"/** @protected **/",
"/**\n * <code>Controller</code> Multiton Factory method.\n *\n * @static\n * @param {string} key\n * @param {factory} factory\n * @param {function(string):puremvc.IController} factory\n * @returns {puremvc.IController} the Multiton instance of <code>Controller</code>\n */",
"/**\n * <P>If an <code>ICommand</code> has previously been registered\n * to handle a the given <code>INotification</code>, then it is executed.</P>\n *\n * @param {puremvc.INotification} notification an <code>INotification</code>\n */",
"/**\n * <P>Register a particular <code>ICommand</code> class as the handler\n * for a particular <code>INotification</code>.</P>\n *\n * <P>If an <code>ICommand</code> has already been registered to\n * handle <code>INotification</code>s with this name, it is no longer\n * used, the new <code>ICommand</code> is used instead.</P>\n *\n * <P>The Observer for the new ICommand is only created if this the\n * first time an ICommand has been regisered for this Notification name.</P>\n *\n * @param notificationName the name of the <code>INotification</code>\n * @param {factory} factory the <code>Class</code> of the <code>ICommand</code>\n * @param {function():puremvc.ICommand} factory\n */",
"/**\n * Check if a Command is registered for a given Notification\n *\n * @param {string} notificationName\n * @return {boolean} whether a Command is currently registered for the given <code>notificationName</code>.\n */",
"/**\n * Remove a previously registered <code>ICommand</code> to <code>INotification</code> mapping.\n *\n * @param {string} notificationName the name of the <code>INotification</code> to remove the <code>ICommand</code> mapping for\n */",
"// if the Command is registered...",
"// remove the observer",
"// remove the command",
"/**\n * Remove an IController instance\n *\n * @static\n * @param {string} key of IController instance to remove\n */",
"/**\n * Multiton instance\n *\n * @static\n * @type {Map<string, puremvc.IController>}\n */",
"// static instanceMap = new Map();",
"/**\n * Message Constants\n *\n * @static\n * @type {string}\n */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 1,325
| 358
|
c84dfcb64e988ae7269e33fdfd783659692fd4fc
|
sozu/py-dhampyr
|
dhampyr/variable.py
|
[
"MIT"
] |
Python
|
Variable
|
Instances of this class behave as variable of validated object in verifying functions.
A sequence of operations applied to the variable generates a function
which evaluates those operations to the validated object lazily in verification phase.
For exmaple,
>>> x.a.len * 3 > 5
is a function equivalent to
>>> lambda x: len(x.a) * 3 > 5
Available operations are:
- Operators and builtin functions whose behaviors can be overwritten by magic methods.
- `len()` should be represented with an attribute `.len`. This is because `__len__()` must be implemented to return `int`.
- `in_()` verifies that the variable equals to one item of the argument list.
- `has()` verifies that the variable contains the argument. `in` operator is not available because the returned value of `__contains__()` is evaluated as `bool`.
- Attribute and index access.
Additionally, `not_` property returns a variable which inversed the result logically.
The inversion is always evaluated after other operations. Use `inv()` instead to insert intermediate inversion.
Generated function as a result of those operations has `Verifier` which can produce `ValidationFailure`
with name and arguments corresponding to the operation causing the failure.
>>> f = (x.len > 5)._verifier.verify("abc")
>>> f.name, f.kwargs
('x.len.gt', {'gt.value': 5})
>>> class C:
... def __init__(self, a):
... self.a = a
...
>>> c = C("a")
>>> f = (x.a.len * 3 > 5)._verifier.verify(c)
>>> f.name, f.kwargs
('[email protected]', {'mul.value': 3, 'gt.value': 5})
There exists a constraint that, as shown in above example, keys in `kwargs` are overwritten by following operation of the same type.
|
Instances of this class behave as variable of validated object in verifying functions.
A sequence of operations applied to the variable generates a function
which evaluates those operations to the validated object lazily in verification phase.
For exmaple.
Available operations are.
Operators and builtin functions whose behaviors can be overwritten by magic methods.
`len()` should be represented with an attribute `.len`. This is because `__len__()` must be implemented to return `int`.
`in_()` verifies that the variable equals to one item of the argument list.
`has()` verifies that the variable contains the argument.
Additionally, `not_` property returns a variable which inversed the result logically.
The inversion is always evaluated after other operations. Use `inv()` instead to insert intermediate inversion.
Generated function as a result of those operations has `Verifier` which can produce `ValidationFailure`
with name and arguments corresponding to the operation causing the failure.
There exists a constraint that, as shown in above example, keys in `kwargs` are overwritten by following operation of the same type.
|
[
"Instances",
"of",
"this",
"class",
"behave",
"as",
"variable",
"of",
"validated",
"object",
"in",
"verifying",
"functions",
".",
"A",
"sequence",
"of",
"operations",
"applied",
"to",
"the",
"variable",
"generates",
"a",
"function",
"which",
"evaluates",
"those",
"operations",
"to",
"the",
"validated",
"object",
"lazily",
"in",
"verification",
"phase",
".",
"For",
"exmaple",
".",
"Available",
"operations",
"are",
".",
"Operators",
"and",
"builtin",
"functions",
"whose",
"behaviors",
"can",
"be",
"overwritten",
"by",
"magic",
"methods",
".",
"`",
"len",
"()",
"`",
"should",
"be",
"represented",
"with",
"an",
"attribute",
"`",
".",
"len",
"`",
".",
"This",
"is",
"because",
"`",
"__len__",
"()",
"`",
"must",
"be",
"implemented",
"to",
"return",
"`",
"int",
"`",
".",
"`",
"in_",
"()",
"`",
"verifies",
"that",
"the",
"variable",
"equals",
"to",
"one",
"item",
"of",
"the",
"argument",
"list",
".",
"`",
"has",
"()",
"`",
"verifies",
"that",
"the",
"variable",
"contains",
"the",
"argument",
".",
"Additionally",
"`",
"not_",
"`",
"property",
"returns",
"a",
"variable",
"which",
"inversed",
"the",
"result",
"logically",
".",
"The",
"inversion",
"is",
"always",
"evaluated",
"after",
"other",
"operations",
".",
"Use",
"`",
"inv",
"()",
"`",
"instead",
"to",
"insert",
"intermediate",
"inversion",
".",
"Generated",
"function",
"as",
"a",
"result",
"of",
"those",
"operations",
"has",
"`",
"Verifier",
"`",
"which",
"can",
"produce",
"`",
"ValidationFailure",
"`",
"with",
"name",
"and",
"arguments",
"corresponding",
"to",
"the",
"operation",
"causing",
"the",
"failure",
".",
"There",
"exists",
"a",
"constraint",
"that",
"as",
"shown",
"in",
"above",
"example",
"keys",
"in",
"`",
"kwargs",
"`",
"are",
"overwritten",
"by",
"following",
"operation",
"of",
"the",
"same",
"type",
"."
] |
class Variable:
"""
Instances of this class behave as variable of validated object in verifying functions.
A sequence of operations applied to the variable generates a function
which evaluates those operations to the validated object lazily in verification phase.
For exmaple,
>>> x.a.len * 3 > 5
is a function equivalent to
>>> lambda x: len(x.a) * 3 > 5
Available operations are:
- Operators and builtin functions whose behaviors can be overwritten by magic methods.
- `len()` should be represented with an attribute `.len`. This is because `__len__()` must be implemented to return `int`.
- `in_()` verifies that the variable equals to one item of the argument list.
- `has()` verifies that the variable contains the argument. `in` operator is not available because the returned value of `__contains__()` is evaluated as `bool`.
- Attribute and index access.
Additionally, `not_` property returns a variable which inversed the result logically.
The inversion is always evaluated after other operations. Use `inv()` instead to insert intermediate inversion.
Generated function as a result of those operations has `Verifier` which can produce `ValidationFailure`
with name and arguments corresponding to the operation causing the failure.
>>> f = (x.len > 5)._verifier.verify("abc")
>>> f.name, f.kwargs
('x.len.gt', {'gt.value': 5})
>>> class C:
... def __init__(self, a):
... self.a = a
...
>>> c = C("a")
>>> f = (x.a.len * 3 > 5)._verifier.verify(c)
>>> f.name, f.kwargs
('[email protected]', {'mul.value': 3, 'gt.value': 5})
There exists a constraint that, as shown in above example, keys in `kwargs` are overwritten by following operation of the same type.
"""
def __init__(self, f=lambda x:x, names=None, kwargs=None, not_=False):
self._id = f
self._names = names or ['x']
self._kwargs = kwargs or {}
self._not = not_
def _sync(self, f, name, **kwargs):
kw = {f"{name}.{k}":v for k, v in kwargs.items()}
return Variable(lambda x: f(self._id(x)), self._names+[name], dict(self._kwargs, **kw), self._not)
@property
def len(self):
return self._sync(lambda x: len(x), 'len')
def in_(self, *v):
return self._sync(lambda x: x in v, 'in', value=v)
def has(self, v):
return self._sync(lambda x: v in x, 'has', value=v)
def inv(self):
return self._sync(lambda x: not x, 'inv')
@property
def not_(self):
return Variable(self._id, self._names, self._kwargs, True)
@property
def _verifier(self):
func = lambda x: self(x)
names = [n for n in self._names if n]
if self._not:
names[1:1] = ['not']
return Verifier('.'.join(names), func, False, **self._kwargs)
def __call__(self, x, context:ValidationContext=None):
b = bool(self._id(x))
return not b if self._not else b
def __getattr__(self, key):
if key == '__name__':
return '.'.join(self._names)
elif key == '__annotations__':
return {}
else:
return self._sync(lambda x: getattr(x, key), f'@{key}')
def __getitem__(self, key):
return self._sync(lambda x: x[key], f'[{key}]')
def __eq__(self, v):
return self._sync(lambda x: x == v, 'eq', value=v)
def __ne__(self, v):
return self._sync(lambda x: x != v, 'ne', value=v)
def __lt__(self, th):
return self._sync(lambda x: x < th, 'lt', value=th)
def __le__(self, th):
return self._sync(lambda x: x <= th, 'le', value=th)
def __gt__(self, th):
return self._sync(lambda x: x > th, 'gt', value=th)
def __ge__(self, th):
return self._sync(lambda x: x >= th, 'ge', value=th)
def __add__(self, v):
return self._sync(lambda x: x + v, 'add', value=v)
def __sub__(self, v):
return self._sync(lambda x: x - v, 'sub', value=v)
def __mul__(self, v):
return self._sync(lambda x: x * v, 'mul', value=v)
def __matmul__(self, v):
return self._sync(lambda x: x @ v, 'matmul', value=v)
def __truediv__(self, v):
return self._sync(lambda x: x / v, 'truediv', value=v)
def __floordiv__(self, v):
return self._sync(lambda x: x // v, 'floordiv', value=v)
def __mod__(self, v):
return self._sync(lambda x: x % v, 'mod', value=v)
def __divmod__(self, v):
return self._sync(lambda x: divmod(x, v), 'divmod', value=v)
def __pow__(self, v):
return self._sync(lambda x: pow(x, v), 'pow', value=v)
def __lshift__(self, v):
return self._sync(lambda x: x << v, 'lshift', value=v)
def __rshift__(self, v):
return self._sync(lambda x: x >> v, 'rshift', value=v)
def __and__(self, v):
return self._sync(lambda x: x & v, 'and', value=v)
def __xor__(self, v):
return self._sync(lambda x: x ^ v, 'xor', value=v)
def __or__(self, v):
return self._sync(lambda x: x | v, 'or', value=v)
def __neg__(self):
return self._sync(lambda x: -x, 'neg')
def __pos__(self):
return self._sync(lambda x: +x, 'pos')
def __abs__(self):
return self._sync(lambda x: abs(x), 'abs')
def __invert__(self):
return self._sync(lambda x: ~x, 'invert')
def __round__(self):
return self._sync(lambda x: round(x), 'round')
def __trunc__(self):
return self._sync(lambda x: math.trunc(x), 'trunc')
def __floor__(self):
return self._sync(lambda x: math.floor(x), 'floor')
def __ceil__(self):
return self._sync(lambda x: math.ceil(x), 'ceil')
|
[
"class",
"Variable",
":",
"def",
"__init__",
"(",
"self",
",",
"f",
"=",
"lambda",
"x",
":",
"x",
",",
"names",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"not_",
"=",
"False",
")",
":",
"self",
".",
"_id",
"=",
"f",
"self",
".",
"_names",
"=",
"names",
"or",
"[",
"'x'",
"]",
"self",
".",
"_kwargs",
"=",
"kwargs",
"or",
"{",
"}",
"self",
".",
"_not",
"=",
"not_",
"def",
"_sync",
"(",
"self",
",",
"f",
",",
"name",
",",
"**",
"kwargs",
")",
":",
"kw",
"=",
"{",
"f\"{name}.{k}\"",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"}",
"return",
"Variable",
"(",
"lambda",
"x",
":",
"f",
"(",
"self",
".",
"_id",
"(",
"x",
")",
")",
",",
"self",
".",
"_names",
"+",
"[",
"name",
"]",
",",
"dict",
"(",
"self",
".",
"_kwargs",
",",
"**",
"kw",
")",
",",
"self",
".",
"_not",
")",
"@",
"property",
"def",
"len",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"len",
"(",
"x",
")",
",",
"'len'",
")",
"def",
"in_",
"(",
"self",
",",
"*",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"in",
"v",
",",
"'in'",
",",
"value",
"=",
"v",
")",
"def",
"has",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"v",
"in",
"x",
",",
"'has'",
",",
"value",
"=",
"v",
")",
"def",
"inv",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"not",
"x",
",",
"'inv'",
")",
"@",
"property",
"def",
"not_",
"(",
"self",
")",
":",
"return",
"Variable",
"(",
"self",
".",
"_id",
",",
"self",
".",
"_names",
",",
"self",
".",
"_kwargs",
",",
"True",
")",
"@",
"property",
"def",
"_verifier",
"(",
"self",
")",
":",
"func",
"=",
"lambda",
"x",
":",
"self",
"(",
"x",
")",
"names",
"=",
"[",
"n",
"for",
"n",
"in",
"self",
".",
"_names",
"if",
"n",
"]",
"if",
"self",
".",
"_not",
":",
"names",
"[",
"1",
":",
"1",
"]",
"=",
"[",
"'not'",
"]",
"return",
"Verifier",
"(",
"'.'",
".",
"join",
"(",
"names",
")",
",",
"func",
",",
"False",
",",
"**",
"self",
".",
"_kwargs",
")",
"def",
"__call__",
"(",
"self",
",",
"x",
",",
"context",
":",
"ValidationContext",
"=",
"None",
")",
":",
"b",
"=",
"bool",
"(",
"self",
".",
"_id",
"(",
"x",
")",
")",
"return",
"not",
"b",
"if",
"self",
".",
"_not",
"else",
"b",
"def",
"__getattr__",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"==",
"'__name__'",
":",
"return",
"'.'",
".",
"join",
"(",
"self",
".",
"_names",
")",
"elif",
"key",
"==",
"'__annotations__'",
":",
"return",
"{",
"}",
"else",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"getattr",
"(",
"x",
",",
"key",
")",
",",
"f'@{key}'",
")",
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"[",
"key",
"]",
",",
"f'[{key}]'",
")",
"def",
"__eq__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"==",
"v",
",",
"'eq'",
",",
"value",
"=",
"v",
")",
"def",
"__ne__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"!=",
"v",
",",
"'ne'",
",",
"value",
"=",
"v",
")",
"def",
"__lt__",
"(",
"self",
",",
"th",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"<",
"th",
",",
"'lt'",
",",
"value",
"=",
"th",
")",
"def",
"__le__",
"(",
"self",
",",
"th",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"<=",
"th",
",",
"'le'",
",",
"value",
"=",
"th",
")",
"def",
"__gt__",
"(",
"self",
",",
"th",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
">",
"th",
",",
"'gt'",
",",
"value",
"=",
"th",
")",
"def",
"__ge__",
"(",
"self",
",",
"th",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
">=",
"th",
",",
"'ge'",
",",
"value",
"=",
"th",
")",
"def",
"__add__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"+",
"v",
",",
"'add'",
",",
"value",
"=",
"v",
")",
"def",
"__sub__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"-",
"v",
",",
"'sub'",
",",
"value",
"=",
"v",
")",
"def",
"__mul__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"*",
"v",
",",
"'mul'",
",",
"value",
"=",
"v",
")",
"def",
"__matmul__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"@",
"v",
",",
"'matmul'",
",",
"value",
"=",
"v",
")",
"def",
"__truediv__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"/",
"v",
",",
"'truediv'",
",",
"value",
"=",
"v",
")",
"def",
"__floordiv__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"//",
"v",
",",
"'floordiv'",
",",
"value",
"=",
"v",
")",
"def",
"__mod__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"%",
"v",
",",
"'mod'",
",",
"value",
"=",
"v",
")",
"def",
"__divmod__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"divmod",
"(",
"x",
",",
"v",
")",
",",
"'divmod'",
",",
"value",
"=",
"v",
")",
"def",
"__pow__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"pow",
"(",
"x",
",",
"v",
")",
",",
"'pow'",
",",
"value",
"=",
"v",
")",
"def",
"__lshift__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"<<",
"v",
",",
"'lshift'",
",",
"value",
"=",
"v",
")",
"def",
"__rshift__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
">>",
"v",
",",
"'rshift'",
",",
"value",
"=",
"v",
")",
"def",
"__and__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"&",
"v",
",",
"'and'",
",",
"value",
"=",
"v",
")",
"def",
"__xor__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"^",
"v",
",",
"'xor'",
",",
"value",
"=",
"v",
")",
"def",
"__or__",
"(",
"self",
",",
"v",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"x",
"|",
"v",
",",
"'or'",
",",
"value",
"=",
"v",
")",
"def",
"__neg__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"-",
"x",
",",
"'neg'",
")",
"def",
"__pos__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"+",
"x",
",",
"'pos'",
")",
"def",
"__abs__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"abs",
"(",
"x",
")",
",",
"'abs'",
")",
"def",
"__invert__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"~",
"x",
",",
"'invert'",
")",
"def",
"__round__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"round",
"(",
"x",
")",
",",
"'round'",
")",
"def",
"__trunc__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"math",
".",
"trunc",
"(",
"x",
")",
",",
"'trunc'",
")",
"def",
"__floor__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"math",
".",
"floor",
"(",
"x",
")",
",",
"'floor'",
")",
"def",
"__ceil__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sync",
"(",
"lambda",
"x",
":",
"math",
".",
"ceil",
"(",
"x",
")",
",",
"'ceil'",
")"
] |
Instances of this class behave as variable of validated object in verifying functions.
|
[
"Instances",
"of",
"this",
"class",
"behave",
"as",
"variable",
"of",
"validated",
"object",
"in",
"verifying",
"functions",
"."
] |
[
"\"\"\"\r\n Instances of this class behave as variable of validated object in verifying functions.\r\n\r\n A sequence of operations applied to the variable generates a function\r\n which evaluates those operations to the validated object lazily in verification phase.\r\n\r\n For exmaple, \r\n \r\n >>> x.a.len * 3 > 5\r\n\r\n is a function equivalent to\r\n\r\n >>> lambda x: len(x.a) * 3 > 5\r\n\r\n Available operations are:\r\n\r\n - Operators and builtin functions whose behaviors can be overwritten by magic methods.\r\n - `len()` should be represented with an attribute `.len`. This is because `__len__()` must be implemented to return `int`.\r\n - `in_()` verifies that the variable equals to one item of the argument list.\r\n - `has()` verifies that the variable contains the argument. `in` operator is not available because the returned value of `__contains__()` is evaluated as `bool`.\r\n - Attribute and index access.\r\n\r\n Additionally, `not_` property returns a variable which inversed the result logically.\r\n The inversion is always evaluated after other operations. Use `inv()` instead to insert intermediate inversion. \r\n\r\n Generated function as a result of those operations has `Verifier` which can produce `ValidationFailure`\r\n with name and arguments corresponding to the operation causing the failure.\r\n\r\n >>> f = (x.len > 5)._verifier.verify(\"abc\")\r\n >>> f.name, f.kwargs\r\n ('x.len.gt', {'gt.value': 5})\r\n >>> class C:\r\n ... def __init__(self, a):\r\n ... self.a = a\r\n ...\r\n >>> c = C(\"a\")\r\n >>> f = (x.a.len * 3 > 5)._verifier.verify(c)\r\n >>> f.name, f.kwargs\r\n ('[email protected]', {'mul.value': 3, 'gt.value': 5})\r\n\r\n There exists a constraint that, as shown in above example, keys in `kwargs` are overwritten by following operation of the same type.\r\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 1,595
| 425
|
cb6abe07165c992f3295cd25ee94a0c26b469aef
|
lowercase00/clearly
|
clearly/server/streaming_dispatcher.py
|
[
"MIT"
] |
Python
|
StreamingDispatcher
|
Dispatch events to connected clients.
Server object, gets cleaned tasks and workers and send them to interested parties.
One instance takes care of only one of those, two instances are needed.
Attributes:
queue_input: to receive from event listener
observers: currently connected clients, interested in real time worker events
role: current role this dispatcher is running
|
Dispatch events to connected clients.
Server object, gets cleaned tasks and workers and send them to interested parties.
One instance takes care of only one of those, two instances are needed.
|
[
"Dispatch",
"events",
"to",
"connected",
"clients",
".",
"Server",
"object",
"gets",
"cleaned",
"tasks",
"and",
"workers",
"and",
"send",
"them",
"to",
"interested",
"parties",
".",
"One",
"instance",
"takes",
"care",
"of",
"only",
"one",
"of",
"those",
"two",
"instances",
"are",
"needed",
"."
] |
class StreamingDispatcher:
"""Dispatch events to connected clients.
Server object, gets cleaned tasks and workers and send them to interested parties.
One instance takes care of only one of those, two instances are needed.
Attributes:
queue_input: to receive from event listener
observers: currently connected clients, interested in real time worker events
role: current role this dispatcher is running
"""
def __init__(self, queue_input: Queue, role: Role):
"""Construct a client dispatcher instance.
Args:
queue_input: to receive from event listener
"""
logger.info('Creating %s', StreamingDispatcher.__name__)
self.queue_input, self.role = queue_input, role
self.observers: List[Tuple[Queue, Pattern, bool]] = []
# running engine (should be asyncio in the future)
self.dispatcher_thread: Optional[threading.Thread] = None
# detect shutdown.
def sigterm_handler(_signo, _stack_frame): # pragma: no cover
self.__stop()
signal.signal(signal.SIGTERM, sigterm_handler)
self.__start()
@contextmanager
def streaming_capture(self, capture: PatternFilter, queue: Queue) -> None:
"""Put a connected client in streaming capture mode, filtering all
incoming events in real time.
Args:
capture: the criteria for desired events
queue: where to put the matching events
"""
observer = queue, re.compile(capture.pattern), capture.negate
# should not need any locks, thanks to GIL
self.observers.append(observer)
try:
yield
finally:
self.observers.remove(observer)
def __start(self) -> None: # pragma: no cover
"""Start the real time engine that captures tasks."""
assert not self.dispatcher_thread
self.dispatcher_thread = threading.Thread(target=self.__run, name=self.role.thread_name)
self.dispatcher_thread.daemon = True
self.running = True # graceful shutdown
self.dispatcher_thread.start()
def __stop(self) -> None: # pragma: no cover
"""Stop the background engine."""
if not self.dispatcher_thread:
return
logger.info('Stopping %s', self.role.thread_name)
self.running = False # graceful shutdown
self.dispatcher_thread.join(1)
self.dispatcher_thread = None
def __run(self) -> None: # pragma: no cover
logger.info('Starting: %r', threading.current_thread())
while self.running:
try:
message = self.queue_input.get(timeout=1)
except Empty:
continue
self._dispatch(message)
logger.info('Stopped: %r', threading.current_thread())
def _dispatch(self, message: Union[TaskMessage, WorkerMessage]) -> None:
# let's see who's interested.
for q, pattern, negate in self.observers:
if self.role.func_accept(pattern, negate, message):
q.put(message)
|
[
"class",
"StreamingDispatcher",
":",
"def",
"__init__",
"(",
"self",
",",
"queue_input",
":",
"Queue",
",",
"role",
":",
"Role",
")",
":",
"\"\"\"Construct a client dispatcher instance.\n \n Args:\n queue_input: to receive from event listener\n\n \"\"\"",
"logger",
".",
"info",
"(",
"'Creating %s'",
",",
"StreamingDispatcher",
".",
"__name__",
")",
"self",
".",
"queue_input",
",",
"self",
".",
"role",
"=",
"queue_input",
",",
"role",
"self",
".",
"observers",
":",
"List",
"[",
"Tuple",
"[",
"Queue",
",",
"Pattern",
",",
"bool",
"]",
"]",
"=",
"[",
"]",
"self",
".",
"dispatcher_thread",
":",
"Optional",
"[",
"threading",
".",
"Thread",
"]",
"=",
"None",
"def",
"sigterm_handler",
"(",
"_signo",
",",
"_stack_frame",
")",
":",
"self",
".",
"__stop",
"(",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"sigterm_handler",
")",
"self",
".",
"__start",
"(",
")",
"@",
"contextmanager",
"def",
"streaming_capture",
"(",
"self",
",",
"capture",
":",
"PatternFilter",
",",
"queue",
":",
"Queue",
")",
"->",
"None",
":",
"\"\"\"Put a connected client in streaming capture mode, filtering all\n incoming events in real time.\n\n Args:\n capture: the criteria for desired events\n queue: where to put the matching events\n\n \"\"\"",
"observer",
"=",
"queue",
",",
"re",
".",
"compile",
"(",
"capture",
".",
"pattern",
")",
",",
"capture",
".",
"negate",
"self",
".",
"observers",
".",
"append",
"(",
"observer",
")",
"try",
":",
"yield",
"finally",
":",
"self",
".",
"observers",
".",
"remove",
"(",
"observer",
")",
"def",
"__start",
"(",
"self",
")",
"->",
"None",
":",
"\"\"\"Start the real time engine that captures tasks.\"\"\"",
"assert",
"not",
"self",
".",
"dispatcher_thread",
"self",
".",
"dispatcher_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"__run",
",",
"name",
"=",
"self",
".",
"role",
".",
"thread_name",
")",
"self",
".",
"dispatcher_thread",
".",
"daemon",
"=",
"True",
"self",
".",
"running",
"=",
"True",
"self",
".",
"dispatcher_thread",
".",
"start",
"(",
")",
"def",
"__stop",
"(",
"self",
")",
"->",
"None",
":",
"\"\"\"Stop the background engine.\"\"\"",
"if",
"not",
"self",
".",
"dispatcher_thread",
":",
"return",
"logger",
".",
"info",
"(",
"'Stopping %s'",
",",
"self",
".",
"role",
".",
"thread_name",
")",
"self",
".",
"running",
"=",
"False",
"self",
".",
"dispatcher_thread",
".",
"join",
"(",
"1",
")",
"self",
".",
"dispatcher_thread",
"=",
"None",
"def",
"__run",
"(",
"self",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"'Starting: %r'",
",",
"threading",
".",
"current_thread",
"(",
")",
")",
"while",
"self",
".",
"running",
":",
"try",
":",
"message",
"=",
"self",
".",
"queue_input",
".",
"get",
"(",
"timeout",
"=",
"1",
")",
"except",
"Empty",
":",
"continue",
"self",
".",
"_dispatch",
"(",
"message",
")",
"logger",
".",
"info",
"(",
"'Stopped: %r'",
",",
"threading",
".",
"current_thread",
"(",
")",
")",
"def",
"_dispatch",
"(",
"self",
",",
"message",
":",
"Union",
"[",
"TaskMessage",
",",
"WorkerMessage",
"]",
")",
"->",
"None",
":",
"for",
"q",
",",
"pattern",
",",
"negate",
"in",
"self",
".",
"observers",
":",
"if",
"self",
".",
"role",
".",
"func_accept",
"(",
"pattern",
",",
"negate",
",",
"message",
")",
":",
"q",
".",
"put",
"(",
"message",
")"
] |
Dispatch events to connected clients.
|
[
"Dispatch",
"events",
"to",
"connected",
"clients",
"."
] |
[
"\"\"\"Dispatch events to connected clients.\n\n Server object, gets cleaned tasks and workers and send them to interested parties.\n One instance takes care of only one of those, two instances are needed.\n \n Attributes:\n queue_input: to receive from event listener\n observers: currently connected clients, interested in real time worker events\n role: current role this dispatcher is running\n\n \"\"\"",
"\"\"\"Construct a client dispatcher instance.\n \n Args:\n queue_input: to receive from event listener\n\n \"\"\"",
"# running engine (should be asyncio in the future)",
"# detect shutdown.",
"# pragma: no cover",
"\"\"\"Put a connected client in streaming capture mode, filtering all\n incoming events in real time.\n\n Args:\n capture: the criteria for desired events\n queue: where to put the matching events\n\n \"\"\"",
"# should not need any locks, thanks to GIL",
"# pragma: no cover",
"\"\"\"Start the real time engine that captures tasks.\"\"\"",
"# graceful shutdown",
"# pragma: no cover",
"\"\"\"Stop the background engine.\"\"\"",
"# graceful shutdown",
"# pragma: no cover",
"# let's see who's interested."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "queue_input",
"type": null,
"docstring": "to receive from event listener",
"docstring_tokens": [
"to",
"receive",
"from",
"event",
"listener"
],
"default": null,
"is_optional": null
},
{
"identifier": "observers",
"type": null,
"docstring": "currently connected clients, interested in real time worker events",
"docstring_tokens": [
"currently",
"connected",
"clients",
"interested",
"in",
"real",
"time",
"worker",
"events"
],
"default": null,
"is_optional": null
},
{
"identifier": "role",
"type": null,
"docstring": "current role this dispatcher is running",
"docstring_tokens": [
"current",
"role",
"this",
"dispatcher",
"is",
"running"
],
"default": null,
"is_optional": null
}
],
"others": []
}
| false
| 14
| 636
| 77
|
963ffaed34d80bb1249f8dfbf6ac44f9be9141fc
|
VSChina/azure-iot-sdk-csharp
|
service/Microsoft.Azure.Devices/ApiResources.Designer.cs
|
[
"MIT"
] |
C#
|
ApiResources
|
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
|
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class ApiResources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal ApiResources() {
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Azure.Devices.ApiResources", typeof(ApiResources).GetTypeInfo().Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static string ArgumentMustBeNonNegative {
get {
return ResourceManager.GetString("ArgumentMustBeNonNegative", resourceCulture);
}
}
internal static string ArgumentMustBePositive {
get {
return ResourceManager.GetString("ArgumentMustBePositive", resourceCulture);
}
}
internal static string ConnectionStringIsNotWellFormed {
get {
return ResourceManager.GetString("ConnectionStringIsNotWellFormed", resourceCulture);
}
}
internal static string DeviceAuthenticationInvalid {
get {
return ResourceManager.GetString("DeviceAuthenticationInvalid", resourceCulture);
}
}
internal static string DeviceIdInvalid {
get {
return ResourceManager.GetString("DeviceIdInvalid", resourceCulture);
}
}
internal static string DeviceIdNotSet {
get {
return ResourceManager.GetString("DeviceIdNotSet", resourceCulture);
}
}
internal static string DeviceJobParametersNullOrEmptyDeviceList {
get {
return ResourceManager.GetString("DeviceJobParametersNullOrEmptyDeviceList", resourceCulture);
}
}
internal static string DeviceJobParametersNullOrEmptyDeviceListEntries {
get {
return ResourceManager.GetString("DeviceJobParametersNullOrEmptyDeviceListEntries", resourceCulture);
}
}
internal static string DeviceKeysInvalid {
get {
return ResourceManager.GetString("DeviceKeysInvalid", resourceCulture);
}
}
internal static string ETagNotSetWhileDeletingDevice {
get {
return ResourceManager.GetString("ETagNotSetWhileDeletingDevice", resourceCulture);
}
}
internal static string ETagNotSetWhileUpdatingDevice {
get {
return ResourceManager.GetString("ETagNotSetWhileUpdatingDevice", resourceCulture);
}
}
internal static string ETagNotSetWhileUpdatingTwin {
get {
return ResourceManager.GetString("ETagNotSetWhileUpdatingTwin", resourceCulture);
}
}
internal static string ETagSetWhileRegisteringDevice {
get {
return ResourceManager.GetString("ETagSetWhileRegisteringDevice", resourceCulture);
}
}
internal static string FailedToSerializeUnsupportedType {
get {
return ResourceManager.GetString("FailedToSerializeUnsupportedType", resourceCulture);
}
}
internal static string HostNameIsNull {
get {
return ResourceManager.GetString("HostNameIsNull", resourceCulture);
}
}
internal static string InvalidConnectionStringEndpoint {
get {
return ResourceManager.GetString("InvalidConnectionStringEndpoint", resourceCulture);
}
}
internal static string InvalidImportMode {
get {
return ResourceManager.GetString("InvalidImportMode", resourceCulture);
}
}
internal static string InvalidPassword {
get {
return ResourceManager.GetString("InvalidPassword", resourceCulture);
}
}
internal static string InvalidPropertyInConnectionString {
get {
return ResourceManager.GetString("InvalidPropertyInConnectionString", resourceCulture);
}
}
internal static string InvalidUser {
get {
return ResourceManager.GetString("InvalidUser", resourceCulture);
}
}
internal static string JobClientInstanceAlreadyClosed {
get {
return ResourceManager.GetString("JobClientInstanceAlreadyClosed", resourceCulture);
}
}
internal static string MessageBodyConsumed {
get {
return ResourceManager.GetString("MessageBodyConsumed", resourceCulture);
}
}
internal static string MessageDisposed {
get {
return ResourceManager.GetString("MessageDisposed", resourceCulture);
}
}
internal static string MissingPropertyInConnectionString {
get {
return ResourceManager.GetString("MissingPropertyInConnectionString", resourceCulture);
}
}
internal static string OffsetExceedsBufferSize {
get {
return ResourceManager.GetString("OffsetExceedsBufferSize", resourceCulture);
}
}
internal static string ParameterCannotBeNullOrEmpty {
get {
return ResourceManager.GetString("ParameterCannotBeNullOrEmpty", resourceCulture);
}
}
internal static string ParameterCannotBeNullOrWhitespace {
get {
return ResourceManager.GetString("ParameterCannotBeNullOrWhitespace", resourceCulture);
}
}
internal static string PropertyIsNotValidUri {
get {
return ResourceManager.GetString("PropertyIsNotValidUri", resourceCulture);
}
}
internal static string RegistryManagerInstanceAlreadyClosed {
get {
return ResourceManager.GetString("RegistryManagerInstanceAlreadyClosed", resourceCulture);
}
}
internal static string SizeExceedsRemainingBufferSpace {
get {
return ResourceManager.GetString("SizeExceedsRemainingBufferSpace", resourceCulture);
}
}
internal static string StringIsNotThumbprint {
get {
return ResourceManager.GetString("StringIsNotThumbprint", resourceCulture);
}
}
}
|
[
"[",
"global",
"::",
"System",
".",
"CodeDom",
".",
"Compiler",
".",
"GeneratedCodeAttribute",
"(",
"\"",
"System.Resources.Tools.StronglyTypedResourceBuilder",
"\"",
",",
"\"",
"4.0.0.0",
"\"",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"DebuggerNonUserCodeAttribute",
"(",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Runtime",
".",
"CompilerServices",
".",
"CompilerGeneratedAttribute",
"(",
")",
"]",
"internal",
"class",
"ApiResources",
"{",
"private",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"resourceMan",
";",
"private",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"resourceCulture",
";",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"CodeAnalysis",
".",
"SuppressMessageAttribute",
"(",
"\"",
"Microsoft.Performance",
"\"",
",",
"\"",
"CA1811:AvoidUncalledPrivateCode",
"\"",
")",
"]",
"internal",
"ApiResources",
"(",
")",
"{",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"ResourceManager",
"{",
"get",
"{",
"if",
"(",
"object",
".",
"ReferenceEquals",
"(",
"resourceMan",
",",
"null",
")",
")",
"{",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"temp",
"=",
"new",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"(",
"\"",
"Microsoft.Azure.Devices.ApiResources",
"\"",
",",
"typeof",
"(",
"ApiResources",
")",
".",
"GetTypeInfo",
"(",
")",
".",
"Assembly",
")",
";",
"resourceMan",
"=",
"temp",
";",
"}",
"return",
"resourceMan",
";",
"}",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"Culture",
"{",
"get",
"{",
"return",
"resourceCulture",
";",
"}",
"set",
"{",
"resourceCulture",
"=",
"value",
";",
"}",
"}",
"internal",
"static",
"string",
"ArgumentMustBeNonNegative",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ArgumentMustBeNonNegative",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"ArgumentMustBePositive",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ArgumentMustBePositive",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"ConnectionStringIsNotWellFormed",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ConnectionStringIsNotWellFormed",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"DeviceAuthenticationInvalid",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"DeviceAuthenticationInvalid",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"DeviceIdInvalid",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"DeviceIdInvalid",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"DeviceIdNotSet",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"DeviceIdNotSet",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"DeviceJobParametersNullOrEmptyDeviceList",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"DeviceJobParametersNullOrEmptyDeviceList",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"DeviceJobParametersNullOrEmptyDeviceListEntries",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"DeviceJobParametersNullOrEmptyDeviceListEntries",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"DeviceKeysInvalid",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"DeviceKeysInvalid",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"ETagNotSetWhileDeletingDevice",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ETagNotSetWhileDeletingDevice",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"ETagNotSetWhileUpdatingDevice",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ETagNotSetWhileUpdatingDevice",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"ETagNotSetWhileUpdatingTwin",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ETagNotSetWhileUpdatingTwin",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"ETagSetWhileRegisteringDevice",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ETagSetWhileRegisteringDevice",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"FailedToSerializeUnsupportedType",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"FailedToSerializeUnsupportedType",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"HostNameIsNull",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"HostNameIsNull",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"InvalidConnectionStringEndpoint",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"InvalidConnectionStringEndpoint",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"InvalidImportMode",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"InvalidImportMode",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"InvalidPassword",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"InvalidPassword",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"InvalidPropertyInConnectionString",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"InvalidPropertyInConnectionString",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"InvalidUser",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"InvalidUser",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"JobClientInstanceAlreadyClosed",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"JobClientInstanceAlreadyClosed",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MessageBodyConsumed",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MessageBodyConsumed",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MessageDisposed",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MessageDisposed",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"MissingPropertyInConnectionString",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"MissingPropertyInConnectionString",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"OffsetExceedsBufferSize",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"OffsetExceedsBufferSize",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"ParameterCannotBeNullOrEmpty",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ParameterCannotBeNullOrEmpty",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"ParameterCannotBeNullOrWhitespace",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"ParameterCannotBeNullOrWhitespace",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"PropertyIsNotValidUri",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"PropertyIsNotValidUri",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"RegistryManagerInstanceAlreadyClosed",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"RegistryManagerInstanceAlreadyClosed",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"SizeExceedsRemainingBufferSpace",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"SizeExceedsRemainingBufferSpace",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"StringIsNotThumbprint",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"StringIsNotThumbprint",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"}"
] |
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[
"/// <summary>",
"/// Returns the cached ResourceManager instance used by this class.",
"/// </summary>",
"/// <summary>",
"/// Overrides the current thread's CurrentUICulture property for all",
"/// resource lookups using this strongly typed resource class.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The value of this argument must be non-negative..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The value of this argument must be positive..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The connection string is not well formed..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Device {0} cannot specify both symmetric keys and thumbprints..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The device identifier {0} is invalid..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The id of the device was not set..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to null or empty deviceIds.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to null or empty deviceId entries specified.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Either both primary and secondary keys must be specified or neither one to auto generate on service side..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The ETag should be set while deleting the device..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The ETag should be set while updating the device..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The ETag should be set while updating the Twin..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The ETag should not be set while registering the device..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Serialization operation failed due to unsupported type {0}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The HostName is null..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The endpoint in the connection string is invalid..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to ImportMode not handled: {0}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The password is not valid..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The connection string has an invalid value for property: {0}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The User is not valid..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The JobClient instance was already closed..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The message body cannot be read multiple times. To reuse it store the value after reading..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to This messaging entity has already been closed, aborted, or disposed..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The connection string is missing the property: {0}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The specified offset exceeds the buffer size ({0} bytes)..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The parameter {0} cannot be null or empty..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The parameter {0} cannot be null, empty or whitespace..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The {0} property is not a valid Uri.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The RegistryManager instance was already closed..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The specified size exceeds the remaining buffer space ({0} bytes)..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to '{0}' is not a valid X.509 thumbprint.",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 1,205
| 84
|
138b3cd2532183577514c390c0c57ff11688c2e3
|
larryshamalama/pymc
|
pymc/distributions/distribution.py
|
[
"Apache-2.0"
] |
Python
|
SymbolicDistribution
|
Symbolic statistical distribution
While traditional PyMC distributions are represented by a single RandomVariable
graph, Symbolic distributions correspond to a larger graph that contains one or
more RandomVariables and an arbitrary number of deterministic operations, which
represent their own kind of distribution.
The graphs returned by symbolic distributions can be evaluated directly to
obtain valid draws and can further be parsed by Aeppl to derive the
corresponding logp at runtime.
Check pymc.distributions.Censored for an example of a symbolic distribution.
Symbolic distributions must implement the following classmethods:
cls.dist
Performs input validation and converts optional alternative parametrizations
to a canonical parametrization. It should call `super().dist()`, passing a
list with the default parameters as the first and only non keyword argument,
followed by other keyword arguments like size and rngs, and return the result
cls.num_rngs
Returns the number of rngs given the same arguments passed by the user when
calling the distribution
cls.ndim_supp
Returns the support of the symbolic distribution, given the default set of
parameters. This may not always be constant, for instance if the symbolic
distribution can be defined based on an arbitrary base distribution.
cls.rv_op
Returns a TensorVariable that represents the symbolic distribution
parametrized by a default set of parameters and a size and rngs arguments
cls.change_size
Returns an equivalent symbolic distribution with a different size. This is
analogous to `pymc.aesaraf.change_rv_size` for `RandomVariable`s.
|
Symbolic statistical distribution
While traditional PyMC distributions are represented by a single RandomVariable
graph, Symbolic distributions correspond to a larger graph that contains one or
more RandomVariables and an arbitrary number of deterministic operations, which
represent their own kind of distribution.
The graphs returned by symbolic distributions can be evaluated directly to
obtain valid draws and can further be parsed by Aeppl to derive the
corresponding logp at runtime.
Check pymc.distributions.Censored for an example of a symbolic distribution.
Symbolic distributions must implement the following classmethods:
cls.dist
Performs input validation and converts optional alternative parametrizations
to a canonical parametrization. It should call `super().dist()`, passing a
list with the default parameters as the first and only non keyword argument,
followed by other keyword arguments like size and rngs, and return the result
cls.num_rngs
Returns the number of rngs given the same arguments passed by the user when
calling the distribution
cls.ndim_supp
Returns the support of the symbolic distribution, given the default set of
parameters. This may not always be constant, for instance if the symbolic
distribution can be defined based on an arbitrary base distribution.
cls.rv_op
Returns a TensorVariable that represents the symbolic distribution
parametrized by a default set of parameters and a size and rngs arguments
cls.change_size
Returns an equivalent symbolic distribution with a different size. This is
analogous to `pymc.aesaraf.change_rv_size` for `RandomVariable`s.
|
[
"Symbolic",
"statistical",
"distribution",
"While",
"traditional",
"PyMC",
"distributions",
"are",
"represented",
"by",
"a",
"single",
"RandomVariable",
"graph",
"Symbolic",
"distributions",
"correspond",
"to",
"a",
"larger",
"graph",
"that",
"contains",
"one",
"or",
"more",
"RandomVariables",
"and",
"an",
"arbitrary",
"number",
"of",
"deterministic",
"operations",
"which",
"represent",
"their",
"own",
"kind",
"of",
"distribution",
".",
"The",
"graphs",
"returned",
"by",
"symbolic",
"distributions",
"can",
"be",
"evaluated",
"directly",
"to",
"obtain",
"valid",
"draws",
"and",
"can",
"further",
"be",
"parsed",
"by",
"Aeppl",
"to",
"derive",
"the",
"corresponding",
"logp",
"at",
"runtime",
".",
"Check",
"pymc",
".",
"distributions",
".",
"Censored",
"for",
"an",
"example",
"of",
"a",
"symbolic",
"distribution",
".",
"Symbolic",
"distributions",
"must",
"implement",
"the",
"following",
"classmethods",
":",
"cls",
".",
"dist",
"Performs",
"input",
"validation",
"and",
"converts",
"optional",
"alternative",
"parametrizations",
"to",
"a",
"canonical",
"parametrization",
".",
"It",
"should",
"call",
"`",
"super",
"()",
".",
"dist",
"()",
"`",
"passing",
"a",
"list",
"with",
"the",
"default",
"parameters",
"as",
"the",
"first",
"and",
"only",
"non",
"keyword",
"argument",
"followed",
"by",
"other",
"keyword",
"arguments",
"like",
"size",
"and",
"rngs",
"and",
"return",
"the",
"result",
"cls",
".",
"num_rngs",
"Returns",
"the",
"number",
"of",
"rngs",
"given",
"the",
"same",
"arguments",
"passed",
"by",
"the",
"user",
"when",
"calling",
"the",
"distribution",
"cls",
".",
"ndim_supp",
"Returns",
"the",
"support",
"of",
"the",
"symbolic",
"distribution",
"given",
"the",
"default",
"set",
"of",
"parameters",
".",
"This",
"may",
"not",
"always",
"be",
"constant",
"for",
"instance",
"if",
"the",
"symbolic",
"distribution",
"can",
"be",
"defined",
"based",
"on",
"an",
"arbitrary",
"base",
"distribution",
".",
"cls",
".",
"rv_op",
"Returns",
"a",
"TensorVariable",
"that",
"represents",
"the",
"symbolic",
"distribution",
"parametrized",
"by",
"a",
"default",
"set",
"of",
"parameters",
"and",
"a",
"size",
"and",
"rngs",
"arguments",
"cls",
".",
"change_size",
"Returns",
"an",
"equivalent",
"symbolic",
"distribution",
"with",
"a",
"different",
"size",
".",
"This",
"is",
"analogous",
"to",
"`",
"pymc",
".",
"aesaraf",
".",
"change_rv_size",
"`",
"for",
"`",
"RandomVariable",
"`",
"s",
"."
] |
class SymbolicDistribution:
"""Symbolic statistical distribution
While traditional PyMC distributions are represented by a single RandomVariable
graph, Symbolic distributions correspond to a larger graph that contains one or
more RandomVariables and an arbitrary number of deterministic operations, which
represent their own kind of distribution.
The graphs returned by symbolic distributions can be evaluated directly to
obtain valid draws and can further be parsed by Aeppl to derive the
corresponding logp at runtime.
Check pymc.distributions.Censored for an example of a symbolic distribution.
Symbolic distributions must implement the following classmethods:
cls.dist
Performs input validation and converts optional alternative parametrizations
to a canonical parametrization. It should call `super().dist()`, passing a
list with the default parameters as the first and only non keyword argument,
followed by other keyword arguments like size and rngs, and return the result
cls.num_rngs
Returns the number of rngs given the same arguments passed by the user when
calling the distribution
cls.ndim_supp
Returns the support of the symbolic distribution, given the default set of
parameters. This may not always be constant, for instance if the symbolic
distribution can be defined based on an arbitrary base distribution.
cls.rv_op
Returns a TensorVariable that represents the symbolic distribution
parametrized by a default set of parameters and a size and rngs arguments
cls.change_size
Returns an equivalent symbolic distribution with a different size. This is
analogous to `pymc.aesaraf.change_rv_size` for `RandomVariable`s.
"""
def __new__(
cls,
name: str,
*args,
rngs: Optional[Iterable] = None,
dims: Optional[Dims] = None,
initval=None,
observed=None,
total_size=None,
transform=UNSET,
**kwargs,
) -> TensorVariable:
"""Adds a TensorVariable corresponding to a PyMC symbolic distribution to the
current model.
Parameters
----------
cls : type
A distribution class that inherits from SymbolicDistribution.
name : str
Name for the new model variable.
rngs : optional
Random number generator to use for the RandomVariable(s) in the graph.
dims : tuple, optional
A tuple of dimension names known to the model.
initval : optional
Numeric or symbolic untransformed initial value of matching shape,
or one of the following initial value strategies: "moment", "prior".
Depending on the sampler's settings, a random jitter may be added to numeric,
symbolic or moment-based initial values in the transformed space.
observed : optional
Observed data to be passed when registering the random variable in the model.
See ``Model.register_rv``.
total_size : float, optional
See ``Model.register_rv``.
transform : optional
See ``Model.register_rv``.
**kwargs
Keyword arguments that will be forwarded to ``.dist()``.
Most prominently: ``shape`` and ``size``
Returns
-------
var : TensorVariable
The created variable, registered in the Model.
"""
try:
from pymc.model import Model
model = Model.get_context()
except TypeError:
raise TypeError(
"No model on context stack, which is needed to "
"instantiate distributions. Add variable inside "
"a 'with model:' block, or use the '.dist' syntax "
"for a standalone distribution."
)
if "testval" in kwargs:
initval = kwargs.pop("testval")
warnings.warn(
"The `testval` argument is deprecated; use `initval`.",
FutureWarning,
stacklevel=2,
)
if not isinstance(name, string_types):
raise TypeError(f"Name needs to be a string but got: {name}")
if rngs is None:
# Instead of passing individual RNG variables we could pass a RandomStream
# and let the classes create as many RNGs as they need
rngs = [model.next_rng() for _ in range(cls.num_rngs(*args, **kwargs))]
elif not isinstance(rngs, (list, tuple)):
rngs = [rngs]
# Create the RV and process dims and observed to determine
# a shape by which the created RV may need to be resized.
rv_out, dims, observed, resize_shape = _make_rv_and_resize_shape(
cls=cls, dims=dims, model=model, observed=observed, args=args, rngs=rngs, **kwargs
)
if resize_shape:
# A batch size was specified through `dims`, or implied by `observed`.
rv_out = cls.change_size(
rv=rv_out,
new_size=resize_shape,
expand=True,
)
rv_out = model.register_rv(
rv_out,
name,
observed,
total_size,
dims=dims,
transform=transform,
initval=initval,
)
# TODO: Refactor this
# add in pretty-printing support
rv_out.str_repr = lambda *args, **kwargs: name
rv_out._repr_latex_ = f"\\text{name}"
# rv_out.str_repr = types.MethodType(str_for_dist, rv_out)
# rv_out._repr_latex_ = types.MethodType(
# functools.partial(str_for_dist, formatting="latex"), rv_out
# )
return rv_out
@classmethod
def dist(
cls,
dist_params,
*,
shape: Optional[Shape] = None,
size: Optional[Size] = None,
**kwargs,
) -> TensorVariable:
"""Creates a TensorVariable corresponding to the `cls` symbolic distribution.
Parameters
----------
dist_params : array-like
The inputs to the `RandomVariable` `Op`.
shape : int, tuple, Variable, optional
A tuple of sizes for each dimension of the new RV.
An Ellipsis (...) may be inserted in the last position to short-hand refer to
all the dimensions that the RV would get if no shape/size/dims were passed at all.
size : int, tuple, Variable, optional
For creating the RV like in Aesara/NumPy.
Returns
-------
var : TensorVariable
"""
if "testval" in kwargs:
kwargs.pop("testval")
warnings.warn(
"The `.dist(testval=...)` argument is deprecated and has no effect. "
"Initial values for sampling/optimization can be specified with `initval` in a modelcontext. "
"For using Aesara's test value features, you must assign the `.tag.test_value` yourself.",
FutureWarning,
stacklevel=2,
)
if "initval" in kwargs:
raise TypeError(
"Unexpected keyword argument `initval`. "
"This argument is not available for the `.dist()` API."
)
if "dims" in kwargs:
raise NotImplementedError("The use of a `.dist(dims=...)` API is not supported.")
if shape is not None and size is not None:
raise ValueError(
f"Passing both `shape` ({shape}) and `size` ({size}) is not supported!"
)
shape = convert_shape(shape)
size = convert_size(size)
create_size, ndim_expected, ndim_batch, ndim_supp = find_size(
shape=shape, size=size, ndim_supp=cls.ndim_supp(*dist_params)
)
# Create the RV with a `size` right away.
# This is not necessarily the final result.
graph = cls.rv_op(*dist_params, size=create_size, **kwargs)
# Replicate dimensions may be prepended via a shape with Ellipsis as the last element:
if shape is not None and Ellipsis in shape:
replicate_shape = cast(StrongShape, shape[:-1])
graph = cls.change_size(rv=graph, new_size=replicate_shape, expand=True)
# TODO: Create new attr error stating that these are not available for DerivedDistribution
# rv_out.logp = _make_nice_attr_error("rv.logp(x)", "pm.logp(rv, x)")
# rv_out.logcdf = _make_nice_attr_error("rv.logcdf(x)", "pm.logcdf(rv, x)")
# rv_out.random = _make_nice_attr_error("rv.random()", "rv.eval()")
return graph
|
[
"class",
"SymbolicDistribution",
":",
"def",
"__new__",
"(",
"cls",
",",
"name",
":",
"str",
",",
"*",
"args",
",",
"rngs",
":",
"Optional",
"[",
"Iterable",
"]",
"=",
"None",
",",
"dims",
":",
"Optional",
"[",
"Dims",
"]",
"=",
"None",
",",
"initval",
"=",
"None",
",",
"observed",
"=",
"None",
",",
"total_size",
"=",
"None",
",",
"transform",
"=",
"UNSET",
",",
"**",
"kwargs",
",",
")",
"->",
"TensorVariable",
":",
"\"\"\"Adds a TensorVariable corresponding to a PyMC symbolic distribution to the\n current model.\n\n Parameters\n ----------\n cls : type\n A distribution class that inherits from SymbolicDistribution.\n name : str\n Name for the new model variable.\n rngs : optional\n Random number generator to use for the RandomVariable(s) in the graph.\n dims : tuple, optional\n A tuple of dimension names known to the model.\n initval : optional\n Numeric or symbolic untransformed initial value of matching shape,\n or one of the following initial value strategies: \"moment\", \"prior\".\n Depending on the sampler's settings, a random jitter may be added to numeric,\n symbolic or moment-based initial values in the transformed space.\n observed : optional\n Observed data to be passed when registering the random variable in the model.\n See ``Model.register_rv``.\n total_size : float, optional\n See ``Model.register_rv``.\n transform : optional\n See ``Model.register_rv``.\n **kwargs\n Keyword arguments that will be forwarded to ``.dist()``.\n Most prominently: ``shape`` and ``size``\n\n Returns\n -------\n var : TensorVariable\n The created variable, registered in the Model.\n \"\"\"",
"try",
":",
"from",
"pymc",
".",
"model",
"import",
"Model",
"model",
"=",
"Model",
".",
"get_context",
"(",
")",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"\"No model on context stack, which is needed to \"",
"\"instantiate distributions. Add variable inside \"",
"\"a 'with model:' block, or use the '.dist' syntax \"",
"\"for a standalone distribution.\"",
")",
"if",
"\"testval\"",
"in",
"kwargs",
":",
"initval",
"=",
"kwargs",
".",
"pop",
"(",
"\"testval\"",
")",
"warnings",
".",
"warn",
"(",
"\"The `testval` argument is deprecated; use `initval`.\"",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"if",
"not",
"isinstance",
"(",
"name",
",",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"f\"Name needs to be a string but got: {name}\"",
")",
"if",
"rngs",
"is",
"None",
":",
"rngs",
"=",
"[",
"model",
".",
"next_rng",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"cls",
".",
"num_rngs",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
")",
"]",
"elif",
"not",
"isinstance",
"(",
"rngs",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"rngs",
"=",
"[",
"rngs",
"]",
"rv_out",
",",
"dims",
",",
"observed",
",",
"resize_shape",
"=",
"_make_rv_and_resize_shape",
"(",
"cls",
"=",
"cls",
",",
"dims",
"=",
"dims",
",",
"model",
"=",
"model",
",",
"observed",
"=",
"observed",
",",
"args",
"=",
"args",
",",
"rngs",
"=",
"rngs",
",",
"**",
"kwargs",
")",
"if",
"resize_shape",
":",
"rv_out",
"=",
"cls",
".",
"change_size",
"(",
"rv",
"=",
"rv_out",
",",
"new_size",
"=",
"resize_shape",
",",
"expand",
"=",
"True",
",",
")",
"rv_out",
"=",
"model",
".",
"register_rv",
"(",
"rv_out",
",",
"name",
",",
"observed",
",",
"total_size",
",",
"dims",
"=",
"dims",
",",
"transform",
"=",
"transform",
",",
"initval",
"=",
"initval",
",",
")",
"rv_out",
".",
"str_repr",
"=",
"lambda",
"*",
"args",
",",
"**",
"kwargs",
":",
"name",
"rv_out",
".",
"_repr_latex_",
"=",
"f\"\\\\text{name}\"",
"return",
"rv_out",
"@",
"classmethod",
"def",
"dist",
"(",
"cls",
",",
"dist_params",
",",
"*",
",",
"shape",
":",
"Optional",
"[",
"Shape",
"]",
"=",
"None",
",",
"size",
":",
"Optional",
"[",
"Size",
"]",
"=",
"None",
",",
"**",
"kwargs",
",",
")",
"->",
"TensorVariable",
":",
"\"\"\"Creates a TensorVariable corresponding to the `cls` symbolic distribution.\n\n Parameters\n ----------\n dist_params : array-like\n The inputs to the `RandomVariable` `Op`.\n shape : int, tuple, Variable, optional\n A tuple of sizes for each dimension of the new RV.\n An Ellipsis (...) may be inserted in the last position to short-hand refer to\n all the dimensions that the RV would get if no shape/size/dims were passed at all.\n size : int, tuple, Variable, optional\n For creating the RV like in Aesara/NumPy.\n\n Returns\n -------\n var : TensorVariable\n \"\"\"",
"if",
"\"testval\"",
"in",
"kwargs",
":",
"kwargs",
".",
"pop",
"(",
"\"testval\"",
")",
"warnings",
".",
"warn",
"(",
"\"The `.dist(testval=...)` argument is deprecated and has no effect. \"",
"\"Initial values for sampling/optimization can be specified with `initval` in a modelcontext. \"",
"\"For using Aesara's test value features, you must assign the `.tag.test_value` yourself.\"",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"if",
"\"initval\"",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"\"Unexpected keyword argument `initval`. \"",
"\"This argument is not available for the `.dist()` API.\"",
")",
"if",
"\"dims\"",
"in",
"kwargs",
":",
"raise",
"NotImplementedError",
"(",
"\"The use of a `.dist(dims=...)` API is not supported.\"",
")",
"if",
"shape",
"is",
"not",
"None",
"and",
"size",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"f\"Passing both `shape` ({shape}) and `size` ({size}) is not supported!\"",
")",
"shape",
"=",
"convert_shape",
"(",
"shape",
")",
"size",
"=",
"convert_size",
"(",
"size",
")",
"create_size",
",",
"ndim_expected",
",",
"ndim_batch",
",",
"ndim_supp",
"=",
"find_size",
"(",
"shape",
"=",
"shape",
",",
"size",
"=",
"size",
",",
"ndim_supp",
"=",
"cls",
".",
"ndim_supp",
"(",
"*",
"dist_params",
")",
")",
"graph",
"=",
"cls",
".",
"rv_op",
"(",
"*",
"dist_params",
",",
"size",
"=",
"create_size",
",",
"**",
"kwargs",
")",
"if",
"shape",
"is",
"not",
"None",
"and",
"Ellipsis",
"in",
"shape",
":",
"replicate_shape",
"=",
"cast",
"(",
"StrongShape",
",",
"shape",
"[",
":",
"-",
"1",
"]",
")",
"graph",
"=",
"cls",
".",
"change_size",
"(",
"rv",
"=",
"graph",
",",
"new_size",
"=",
"replicate_shape",
",",
"expand",
"=",
"True",
")",
"return",
"graph"
] |
Symbolic statistical distribution
While traditional PyMC distributions are represented by a single RandomVariable
graph, Symbolic distributions correspond to a larger graph that contains one or
more RandomVariables and an arbitrary number of deterministic operations, which
represent their own kind of distribution.
|
[
"Symbolic",
"statistical",
"distribution",
"While",
"traditional",
"PyMC",
"distributions",
"are",
"represented",
"by",
"a",
"single",
"RandomVariable",
"graph",
"Symbolic",
"distributions",
"correspond",
"to",
"a",
"larger",
"graph",
"that",
"contains",
"one",
"or",
"more",
"RandomVariables",
"and",
"an",
"arbitrary",
"number",
"of",
"deterministic",
"operations",
"which",
"represent",
"their",
"own",
"kind",
"of",
"distribution",
"."
] |
[
"\"\"\"Symbolic statistical distribution\n\n While traditional PyMC distributions are represented by a single RandomVariable\n graph, Symbolic distributions correspond to a larger graph that contains one or\n more RandomVariables and an arbitrary number of deterministic operations, which\n represent their own kind of distribution.\n\n The graphs returned by symbolic distributions can be evaluated directly to\n obtain valid draws and can further be parsed by Aeppl to derive the\n corresponding logp at runtime.\n\n Check pymc.distributions.Censored for an example of a symbolic distribution.\n\n Symbolic distributions must implement the following classmethods:\n cls.dist\n Performs input validation and converts optional alternative parametrizations\n to a canonical parametrization. It should call `super().dist()`, passing a\n list with the default parameters as the first and only non keyword argument,\n followed by other keyword arguments like size and rngs, and return the result\n cls.num_rngs\n Returns the number of rngs given the same arguments passed by the user when\n calling the distribution\n cls.ndim_supp\n Returns the support of the symbolic distribution, given the default set of\n parameters. This may not always be constant, for instance if the symbolic\n distribution can be defined based on an arbitrary base distribution.\n cls.rv_op\n Returns a TensorVariable that represents the symbolic distribution\n parametrized by a default set of parameters and a size and rngs arguments\n cls.change_size\n Returns an equivalent symbolic distribution with a different size. This is\n analogous to `pymc.aesaraf.change_rv_size` for `RandomVariable`s.\n \"\"\"",
"\"\"\"Adds a TensorVariable corresponding to a PyMC symbolic distribution to the\n current model.\n\n Parameters\n ----------\n cls : type\n A distribution class that inherits from SymbolicDistribution.\n name : str\n Name for the new model variable.\n rngs : optional\n Random number generator to use for the RandomVariable(s) in the graph.\n dims : tuple, optional\n A tuple of dimension names known to the model.\n initval : optional\n Numeric or symbolic untransformed initial value of matching shape,\n or one of the following initial value strategies: \"moment\", \"prior\".\n Depending on the sampler's settings, a random jitter may be added to numeric,\n symbolic or moment-based initial values in the transformed space.\n observed : optional\n Observed data to be passed when registering the random variable in the model.\n See ``Model.register_rv``.\n total_size : float, optional\n See ``Model.register_rv``.\n transform : optional\n See ``Model.register_rv``.\n **kwargs\n Keyword arguments that will be forwarded to ``.dist()``.\n Most prominently: ``shape`` and ``size``\n\n Returns\n -------\n var : TensorVariable\n The created variable, registered in the Model.\n \"\"\"",
"# Instead of passing individual RNG variables we could pass a RandomStream",
"# and let the classes create as many RNGs as they need",
"# Create the RV and process dims and observed to determine",
"# a shape by which the created RV may need to be resized.",
"# A batch size was specified through `dims`, or implied by `observed`.",
"# TODO: Refactor this",
"# add in pretty-printing support",
"# rv_out.str_repr = types.MethodType(str_for_dist, rv_out)",
"# rv_out._repr_latex_ = types.MethodType(",
"# functools.partial(str_for_dist, formatting=\"latex\"), rv_out",
"# )",
"\"\"\"Creates a TensorVariable corresponding to the `cls` symbolic distribution.\n\n Parameters\n ----------\n dist_params : array-like\n The inputs to the `RandomVariable` `Op`.\n shape : int, tuple, Variable, optional\n A tuple of sizes for each dimension of the new RV.\n An Ellipsis (...) may be inserted in the last position to short-hand refer to\n all the dimensions that the RV would get if no shape/size/dims were passed at all.\n size : int, tuple, Variable, optional\n For creating the RV like in Aesara/NumPy.\n\n Returns\n -------\n var : TensorVariable\n \"\"\"",
"# Create the RV with a `size` right away.",
"# This is not necessarily the final result.",
"# Replicate dimensions may be prepended via a shape with Ellipsis as the last element:",
"# TODO: Create new attr error stating that these are not available for DerivedDistribution",
"# rv_out.logp = _make_nice_attr_error(\"rv.logp(x)\", \"pm.logp(rv, x)\")",
"# rv_out.logcdf = _make_nice_attr_error(\"rv.logcdf(x)\", \"pm.logcdf(rv, x)\")",
"# rv_out.random = _make_nice_attr_error(\"rv.random()\", \"rv.eval()\")"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 1,841
| 341
|
3e076709b233ad1d754e6d29f6d5b04223535ff1
|
mosaicsys/MosaicLibCS
|
Base/Xtras/JsonDotNet/JsonDotNetPersist.cs
|
[
"ECL-2.0",
"Apache-2.0"
] |
C#
|
DataContractPersistentJsonDotNetTextFileRingStorageAdapter
|
/// <summary>
/// This class is the most commonly used type that implements the IPersistentStorage interface.
/// This class uses a JsonDotNet to attempt to load objects
/// from the configured ring of files and to write objects to the next file in the ring when requested.
/// This class is based on the PersistentObjectFileRingStorageAdapterBase class that implements most of the
/// ring specific logic.
/// </summary>
/// <typeparam name="ObjType">
/// Defines the ObjType on which the IPersistentStorage operates. Must be a class with default constructor that implements the IPersistSequenceable interface.
/// </typeparam>
|
This class is the most commonly used type that implements the IPersistentStorage interface.
This class uses a JsonDotNet to attempt to load objects
from the configured ring of files and to write objects to the next file in the ring when requested.
This class is based on the PersistentObjectFileRingStorageAdapterBase class that implements most of the
ring specific logic.
|
[
"This",
"class",
"is",
"the",
"most",
"commonly",
"used",
"type",
"that",
"implements",
"the",
"IPersistentStorage",
"interface",
".",
"This",
"class",
"uses",
"a",
"JsonDotNet",
"to",
"attempt",
"to",
"load",
"objects",
"from",
"the",
"configured",
"ring",
"of",
"files",
"and",
"to",
"write",
"objects",
"to",
"the",
"next",
"file",
"in",
"the",
"ring",
"when",
"requested",
".",
"This",
"class",
"is",
"based",
"on",
"the",
"PersistentObjectFileRingStorageAdapterBase",
"class",
"that",
"implements",
"most",
"of",
"the",
"ring",
"specific",
"logic",
"."
] |
public class DataContractPersistentJsonDotNetTextFileRingStorageAdapter<ObjType>
: PersistentObjectFileRingStorageAdapterBase<ObjType>
, IPersistentStorage<ObjType>
where ObjType : class, IPersistSequenceable, new()
{
public DataContractPersistentJsonDotNetTextFileRingStorageAdapter(string name, PersistentObjectFileRingConfig ringConfig)
: base(name, ringConfig)
{
JsonSerializerSettings jss = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Auto,
TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple,
ObjectCreationHandling = ObjectCreationHandling.Replace,
Formatting = Formatting.Indented,
};
js = JsonSerializer.CreateDefault(jss);
}
JsonSerializer js;
protected override void InnerClearObject()
{
Object = new ObjType();
}
protected override object InnerReadObject(System.IO.Stream readStream)
{
using (StreamReader sr = new StreamReader(readStream))
{
return js.Deserialize(sr, typeof(ObjType));
}
}
protected override void InnerWriteObject(ObjType obj, System.IO.Stream writeStream)
{
using (StreamWriter sw = new StreamWriter(writeStream))
{
js.Serialize(sw, obj);
sw.Flush();
}
}
}
|
[
"public",
"class",
"DataContractPersistentJsonDotNetTextFileRingStorageAdapter",
"<",
"ObjType",
">",
":",
"PersistentObjectFileRingStorageAdapterBase",
"<",
"ObjType",
">",
",",
"IPersistentStorage",
"<",
"ObjType",
">",
"where",
"ObjType",
":",
"class",
",",
"IPersistSequenceable",
",",
"new",
"(",
")",
"{",
"public",
"DataContractPersistentJsonDotNetTextFileRingStorageAdapter",
"(",
"string",
"name",
",",
"PersistentObjectFileRingConfig",
"ringConfig",
")",
":",
"base",
"(",
"name",
",",
"ringConfig",
")",
"{",
"JsonSerializerSettings",
"jss",
"=",
"new",
"JsonSerializerSettings",
"(",
")",
"{",
"TypeNameHandling",
"=",
"TypeNameHandling",
".",
"Auto",
",",
"TypeNameAssemblyFormat",
"=",
"System",
".",
"Runtime",
".",
"Serialization",
".",
"Formatters",
".",
"FormatterAssemblyStyle",
".",
"Simple",
",",
"ObjectCreationHandling",
"=",
"ObjectCreationHandling",
".",
"Replace",
",",
"Formatting",
"=",
"Formatting",
".",
"Indented",
",",
"}",
";",
"js",
"=",
"JsonSerializer",
".",
"CreateDefault",
"(",
"jss",
")",
";",
"}",
"JsonSerializer",
"js",
";",
"protected",
"override",
"void",
"InnerClearObject",
"(",
")",
"{",
"Object",
"=",
"new",
"ObjType",
"(",
")",
";",
"}",
"protected",
"override",
"object",
"InnerReadObject",
"(",
"System",
".",
"IO",
".",
"Stream",
"readStream",
")",
"{",
"using",
"(",
"StreamReader",
"sr",
"=",
"new",
"StreamReader",
"(",
"readStream",
")",
")",
"{",
"return",
"js",
".",
"Deserialize",
"(",
"sr",
",",
"typeof",
"(",
"ObjType",
")",
")",
";",
"}",
"}",
"protected",
"override",
"void",
"InnerWriteObject",
"(",
"ObjType",
"obj",
",",
"System",
".",
"IO",
".",
"Stream",
"writeStream",
")",
"{",
"using",
"(",
"StreamWriter",
"sw",
"=",
"new",
"StreamWriter",
"(",
"writeStream",
")",
")",
"{",
"js",
".",
"Serialize",
"(",
"sw",
",",
"obj",
")",
";",
"sw",
".",
"Flush",
"(",
")",
";",
"}",
"}",
"}"
] |
This class is the most commonly used type that implements the IPersistentStorage interface.
|
[
"This",
"class",
"is",
"the",
"most",
"commonly",
"used",
"type",
"that",
"implements",
"the",
"IPersistentStorage",
"interface",
"."
] |
[
"/// <summary>",
"/// Required constructor. Takes given name and ringConfig.",
"/// </summary>",
"// Otherwise ValueContainerEnvelope properties do not get re-assigned correctly during deserialization.",
"/// <summary>",
"/// Used to reset the last loaded object its default contents.",
"/// <para/>Sets Object = new ObjType();",
"/// </summary>",
"/// <summary>",
"/// Implementation for required abstract method. Asks the contained DataContractSerializer instance to read an object from the given readStream using the ReadObject method.",
"/// </summary>",
"/// <summary>",
"/// Implementation for required abstract method. Asks the contained DataContractSerializer instance to write the given object to the given writeStream using the WriteObject method.",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "typeparam",
"docstring": "Defines the ObjType on which the IPersistentStorage operates. Must be a class with default constructor that implements the IPersistSequenceable interface.",
"docstring_tokens": [
"Defines",
"the",
"ObjType",
"on",
"which",
"the",
"IPersistentStorage",
"operates",
".",
"Must",
"be",
"a",
"class",
"with",
"default",
"constructor",
"that",
"implements",
"the",
"IPersistSequenceable",
"interface",
"."
]
}
]
}
| false
| 16
| 271
| 128
|
ffd5b674fb0f2399d61c3920664d1a52149b3f9f
|
asikaria/PipedMemoryStream
|
PipedMemoryStream/ByteBufferUnidirectionalStream.cs
|
[
"MIT"
] |
C#
|
ByteBufferUnidirectionalStream
|
/// <summary>
/// A pair of unidirectional streams wrapped around a circular byte buffer; useful as a pipe
/// between two threads.
///
/// Thread safety: It is safe to call all methods of this class concurrently.
/// Caution: Do not try to use both streams on the same thread. Since
/// the streams are blocking streams, this will result in a deadlock of any pf the
/// calls blocks: there will be no other thread to unblock the call.
/// </summary>
|
A pair of unidirectional streams wrapped around a circular byte buffer; useful as a pipe
between two threads.
Thread safety: It is safe to call all methods of this class concurrently.
Caution: Do not try to use both streams on the same thread. Since
the streams are blocking streams, this will result in a deadlock of any pf the
calls blocks: there will be no other thread to unblock the call.
|
[
"A",
"pair",
"of",
"unidirectional",
"streams",
"wrapped",
"around",
"a",
"circular",
"byte",
"buffer",
";",
"useful",
"as",
"a",
"pipe",
"between",
"two",
"threads",
".",
"Thread",
"safety",
":",
"It",
"is",
"safe",
"to",
"call",
"all",
"methods",
"of",
"this",
"class",
"concurrently",
".",
"Caution",
":",
"Do",
"not",
"try",
"to",
"use",
"both",
"streams",
"on",
"the",
"same",
"thread",
".",
"Since",
"the",
"streams",
"are",
"blocking",
"streams",
"this",
"will",
"result",
"in",
"a",
"deadlock",
"of",
"any",
"pf",
"the",
"calls",
"blocks",
":",
"there",
"will",
"be",
"no",
"other",
"thread",
"to",
"unblock",
"the",
"call",
"."
] |
public class ByteBufferUnidirectionalStream
{
private const int DefaultMemoryBufferSize = 4 * 1024 * 1024;
private readonly PipedMemoryInputStream _inputStream;
private readonly PipedMemoryOutputStream _outputStream;
public ByteBufferUnidirectionalStream() : this(DefaultMemoryBufferSize) { }
public ByteBufferUnidirectionalStream(int pipeMemoryBufferSize)
{
var circularByteBuffer = new CircularByteBuffer(pipeMemoryBufferSize);
_inputStream = new PipedMemoryInputStream(circularByteBuffer);
_outputStream = new PipedMemoryOutputStream(circularByteBuffer);
}
public Stream GetSenderStream() => _outputStream;
public Stream GetReceiverStream() => _inputStream;
private class PipedMemoryInputStream : Stream
{
private readonly CircularByteBuffer _circularByteBuffer;
public PipedMemoryInputStream(CircularByteBuffer buffer)
{
_circularByteBuffer = buffer;
}
public override int Read(byte[] buffer, int offset, int count)
{
int actualRead = _circularByteBuffer.Get(buffer, offset, count);
return actualRead;
}
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException("Cannot write to Input Stream");
public override void Flush() => throw new NotSupportedException("Cannot flush Input Stream");
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException("Stream does not support Length property");
public override long Position
{
get => throw new NotSupportedException("Stream does not support Position property");
set => throw new NotSupportedException("Stream does not support Position property");
}
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException("Stream does not support Seek");
public override void SetLength(long value) => throw new NotSupportedException("Stream does not support SetLength");
}
private class PipedMemoryOutputStream : Stream
{
private readonly CircularByteBuffer _circularByteBuffer;
public PipedMemoryOutputStream(CircularByteBuffer buffer)
{
_circularByteBuffer = buffer;
}
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException("Cannot read from Input Stream");
public override void Write(byte[] buffer, int offset, int count)
{
int writeSize = _circularByteBuffer.TotalCapacity;
while (count > writeSize)
{
_circularByteBuffer.Put(buffer, offset, writeSize);
offset += writeSize;
count -= writeSize;
}
_circularByteBuffer.Put(buffer, offset, count);
}
public override void Flush()
{
}
protected override void Dispose(Boolean disposing)
{
_circularByteBuffer.Close();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException("Stream does not support Length property");
public override long Position
{
get => throw new NotSupportedException("Stream does not support Position property");
set => throw new NotSupportedException("Stream does not support Position property");
}
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException("Stream does not support Seek");
public override void SetLength(long value) => throw new NotSupportedException("Stream does not support SetLength");
}
}
|
[
"public",
"class",
"ByteBufferUnidirectionalStream",
"{",
"private",
"const",
"int",
"DefaultMemoryBufferSize",
"=",
"4",
"*",
"1024",
"*",
"1024",
";",
"private",
"readonly",
"PipedMemoryInputStream",
"_inputStream",
";",
"private",
"readonly",
"PipedMemoryOutputStream",
"_outputStream",
";",
"public",
"ByteBufferUnidirectionalStream",
"(",
")",
":",
"this",
"(",
"DefaultMemoryBufferSize",
")",
"{",
"}",
"public",
"ByteBufferUnidirectionalStream",
"(",
"int",
"pipeMemoryBufferSize",
")",
"{",
"var",
"circularByteBuffer",
"=",
"new",
"CircularByteBuffer",
"(",
"pipeMemoryBufferSize",
")",
";",
"_inputStream",
"=",
"new",
"PipedMemoryInputStream",
"(",
"circularByteBuffer",
")",
";",
"_outputStream",
"=",
"new",
"PipedMemoryOutputStream",
"(",
"circularByteBuffer",
")",
";",
"}",
"public",
"Stream",
"GetSenderStream",
"(",
")",
"=>",
"_outputStream",
";",
"public",
"Stream",
"GetReceiverStream",
"(",
")",
"=>",
"_inputStream",
";",
"private",
"class",
"PipedMemoryInputStream",
":",
"Stream",
"{",
"private",
"readonly",
"CircularByteBuffer",
"_circularByteBuffer",
";",
"public",
"PipedMemoryInputStream",
"(",
"CircularByteBuffer",
"buffer",
")",
"{",
"_circularByteBuffer",
"=",
"buffer",
";",
"}",
"public",
"override",
"int",
"Read",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"offset",
",",
"int",
"count",
")",
"{",
"int",
"actualRead",
"=",
"_circularByteBuffer",
".",
"Get",
"(",
"buffer",
",",
"offset",
",",
"count",
")",
";",
"return",
"actualRead",
";",
"}",
"public",
"override",
"void",
"Write",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"offset",
",",
"int",
"count",
")",
"=>",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Cannot write to Input Stream",
"\"",
")",
";",
"public",
"override",
"void",
"Flush",
"(",
")",
"=>",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Cannot flush Input Stream",
"\"",
")",
";",
"public",
"override",
"bool",
"CanRead",
"=>",
"true",
";",
"public",
"override",
"bool",
"CanSeek",
"=>",
"false",
";",
"public",
"override",
"bool",
"CanWrite",
"=>",
"false",
";",
"public",
"override",
"long",
"Length",
"=>",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Stream does not support Length property",
"\"",
")",
";",
"public",
"override",
"long",
"Position",
"{",
"get",
"=>",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Stream does not support Position property",
"\"",
")",
";",
"set",
"=>",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Stream does not support Position property",
"\"",
")",
";",
"}",
"public",
"override",
"long",
"Seek",
"(",
"long",
"offset",
",",
"SeekOrigin",
"origin",
")",
"=>",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Stream does not support Seek",
"\"",
")",
";",
"public",
"override",
"void",
"SetLength",
"(",
"long",
"value",
")",
"=>",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Stream does not support SetLength",
"\"",
")",
";",
"}",
"private",
"class",
"PipedMemoryOutputStream",
":",
"Stream",
"{",
"private",
"readonly",
"CircularByteBuffer",
"_circularByteBuffer",
";",
"public",
"PipedMemoryOutputStream",
"(",
"CircularByteBuffer",
"buffer",
")",
"{",
"_circularByteBuffer",
"=",
"buffer",
";",
"}",
"public",
"override",
"int",
"Read",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"offset",
",",
"int",
"count",
")",
"=>",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Cannot read from Input Stream",
"\"",
")",
";",
"public",
"override",
"void",
"Write",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"offset",
",",
"int",
"count",
")",
"{",
"int",
"writeSize",
"=",
"_circularByteBuffer",
".",
"TotalCapacity",
";",
"while",
"(",
"count",
">",
"writeSize",
")",
"{",
"_circularByteBuffer",
".",
"Put",
"(",
"buffer",
",",
"offset",
",",
"writeSize",
")",
";",
"offset",
"+=",
"writeSize",
";",
"count",
"-=",
"writeSize",
";",
"}",
"_circularByteBuffer",
".",
"Put",
"(",
"buffer",
",",
"offset",
",",
"count",
")",
";",
"}",
"public",
"override",
"void",
"Flush",
"(",
")",
"{",
"}",
"protected",
"override",
"void",
"Dispose",
"(",
"Boolean",
"disposing",
")",
"{",
"_circularByteBuffer",
".",
"Close",
"(",
")",
";",
"}",
"public",
"override",
"Task",
"FlushAsync",
"(",
"CancellationToken",
"cancellationToken",
")",
"{",
"return",
"Task",
".",
"CompletedTask",
";",
"}",
"public",
"override",
"bool",
"CanRead",
"=>",
"false",
";",
"public",
"override",
"bool",
"CanSeek",
"=>",
"false",
";",
"public",
"override",
"bool",
"CanWrite",
"=>",
"true",
";",
"public",
"override",
"long",
"Length",
"=>",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Stream does not support Length property",
"\"",
")",
";",
"public",
"override",
"long",
"Position",
"{",
"get",
"=>",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Stream does not support Position property",
"\"",
")",
";",
"set",
"=>",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Stream does not support Position property",
"\"",
")",
";",
"}",
"public",
"override",
"long",
"Seek",
"(",
"long",
"offset",
",",
"SeekOrigin",
"origin",
")",
"=>",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Stream does not support Seek",
"\"",
")",
";",
"public",
"override",
"void",
"SetLength",
"(",
"long",
"value",
")",
"=>",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Stream does not support SetLength",
"\"",
")",
";",
"}",
"}"
] |
A pair of unidirectional streams wrapped around a circular byte buffer; useful as a pipe
between two threads.
|
[
"A",
"pair",
"of",
"unidirectional",
"streams",
"wrapped",
"around",
"a",
"circular",
"byte",
"buffer",
";",
"useful",
"as",
"a",
"pipe",
"between",
"two",
"threads",
"."
] |
[
"/// <summary>",
"/// Create the streams with underlying byte buffer of default size (4MB)",
"/// </summary>",
"/// <summary>",
"/// Create the streams with underlying byte buffer of specified size",
"/// </summary>",
"/// <param name=\"pipeMemoryBufferSize\"></param>",
"/// <summary>",
"/// Gets the sender stream of the pipe. You can only write to this stream, not read from it.",
"/// </summary>",
"/// <returns></returns>",
"/// <summary>",
"/// Gets the receiver stream of the pipe. You can only read from this stream, not write to it.",
"/// </summary>",
"/// <returns></returns>",
"// no-op",
"// async version of no-op"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 737
| 103
|
07f7a7feabd697753a871819ffe139ad427939c9
|
jgorgolewski/cookbook-cq
|
libraries/_healthcheck_helper.rb
|
[
"Apache-2.0"
] |
Ruby
|
Cq
|
#
# Cookbook:: cq
# Libraries:: HealthcheckHelper
#
# Copyright:: (C) 2018 Jakub Wadolowski
#
# 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.
#
|
: cq
Libraries:: HealthcheckHelper
: (C) 2018 Jakub Wadolowski
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
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.
|
[
":",
"cq",
"Libraries",
"::",
"HealthcheckHelper",
":",
"(",
"C",
")",
"2018",
"Jakub",
"Wadolowski",
"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",
"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",
"."
] |
module Cq
module HealthcheckHelper
include Cq::HttpHelper
def healthcheck_params(rescue_mode, same_state_barrier,
error_state_barrier, max_attempts, sleep_time)
{
'rescue_mode' => rescue_mode,
'same_state_barrier' => same_state_barrier,
'error_state_barrier' => error_state_barrier,
'max_attempts' => max_attempts,
'sleep_time' => sleep_time,
}
end
def path_desc(path)
case path
when '/system/console/bundles/.json'
'bundles'
when '/system/console/components/.json'
'components'
end
end
def stability_check(addr, path, user, password, hc_params)
Chef::Log.info("Waiting for stable state of OSGi #{path_desc(path)}...")
# Save current net read timeout value
current_timeout = node['cq']['http_read_timeout']
# Previous state (start with empty)
previous_state = ''
# How many times the state hasn't changed in a row
same_state_counter = 0
# How many times an error occurred in a row
error_state_counter = 0
(1..hc_params['max_attempts']).each do |i|
begin
# Reduce net read time value to speed up OSGi healthcheck procedure
# when instance is running but stopped accepting HTTP requests
node.default['cq']['http_read_timeout'] = 5
state = http_get(addr, path, user, password)
# Handle response errors
raise(Net::HTTPUnknownResponse) unless state.is_a?(Net::HTTPResponse)
raise(Net::HTTPBadResponse) unless state.code == '200'
# Reset error counter whenever request ended successfully
error_state_counter = 0
if state.body == previous_state
same_state_counter += 1
else
same_state_counter = 0
end
Chef::Log.info("Same state counter: #{same_state_counter}")
# Assign current state to previous state
previous_state = state.body
# Move on if the same state occurred N times in a row
if same_state_counter == hc_params['same_state_barrier']
Chef::Log.info(
"OSGi #{path_desc(path)} seem to be stable. Moving on..."
)
break
end
rescue => e
Chef::Log.warn(
"Unable to get OSGi #{path_desc(path)} state: #{e}. Retrying..."
)
# Let's start over in case of an error (clear indicator of flapping
# OSGi bundles/component)
previous_state = ''
same_state_counter = 0
# Increment error_state_counter in case of an error
error_state_counter += 1
Chef::Log.info("Error state counter: #{error_state_counter}")
# If error occurred N times in a row and rescue_mode is active then
# log such event and break the loop
if hc_params['rescue_mode'] &&
error_state_counter == hc_params['error_state_barrier']
Chef::Log.error(
"#{hc_params['error_state_barrier']} recent attempts to get "\
"OSGi #{path_desc(path)} state have failed! Rescuing, as "\
'rescue_mode is active...'
)
break
end
ensure
# Restore original timeout
node.default['cq']['http_read_timeout'] = current_timeout
end
Chef::Application.fatal!(
"Cannot detect stable state after #{hc_params['max_attempts']} "\
'attempts!'
) if i == hc_params['max_attempts']
Chef::Log.info(
"[#{i}/#{hc_params['max_attempts']}] Next check of OSGi "\
"#{path_desc(path)} in #{hc_params['sleep_time']}s..."
)
sleep hc_params['sleep_time']
end
end
end
end
|
[
"module",
"Cq",
"module",
"HealthcheckHelper",
"include",
"Cq",
"::",
"HttpHelper",
"def",
"healthcheck_params",
"(",
"rescue_mode",
",",
"same_state_barrier",
",",
"error_state_barrier",
",",
"max_attempts",
",",
"sleep_time",
")",
"{",
"'rescue_mode'",
"=>",
"rescue_mode",
",",
"'same_state_barrier'",
"=>",
"same_state_barrier",
",",
"'error_state_barrier'",
"=>",
"error_state_barrier",
",",
"'max_attempts'",
"=>",
"max_attempts",
",",
"'sleep_time'",
"=>",
"sleep_time",
",",
"}",
"end",
"def",
"path_desc",
"(",
"path",
")",
"case",
"path",
"when",
"'/system/console/bundles/.json'",
"'bundles'",
"when",
"'/system/console/components/.json'",
"'components'",
"end",
"end",
"def",
"stability_check",
"(",
"addr",
",",
"path",
",",
"user",
",",
"password",
",",
"hc_params",
")",
"Chef",
"::",
"Log",
".",
"info",
"(",
"\"Waiting for stable state of OSGi #{path_desc(path)}...\"",
")",
"current_timeout",
"=",
"node",
"[",
"'cq'",
"]",
"[",
"'http_read_timeout'",
"]",
"previous_state",
"=",
"''",
"same_state_counter",
"=",
"0",
"error_state_counter",
"=",
"0",
"(",
"1",
"..",
"hc_params",
"[",
"'max_attempts'",
"]",
")",
".",
"each",
"do",
"|",
"i",
"|",
"begin",
"node",
".",
"default",
"[",
"'cq'",
"]",
"[",
"'http_read_timeout'",
"]",
"=",
"5",
"state",
"=",
"http_get",
"(",
"addr",
",",
"path",
",",
"user",
",",
"password",
")",
"raise",
"(",
"Net",
"::",
"HTTPUnknownResponse",
")",
"unless",
"state",
".",
"is_a?",
"(",
"Net",
"::",
"HTTPResponse",
")",
"raise",
"(",
"Net",
"::",
"HTTPBadResponse",
")",
"unless",
"state",
".",
"code",
"==",
"'200'",
"error_state_counter",
"=",
"0",
"if",
"state",
".",
"body",
"==",
"previous_state",
"same_state_counter",
"+=",
"1",
"else",
"same_state_counter",
"=",
"0",
"end",
"Chef",
"::",
"Log",
".",
"info",
"(",
"\"Same state counter: #{same_state_counter}\"",
")",
"previous_state",
"=",
"state",
".",
"body",
"if",
"same_state_counter",
"==",
"hc_params",
"[",
"'same_state_barrier'",
"]",
"Chef",
"::",
"Log",
".",
"info",
"(",
"\"OSGi #{path_desc(path)} seem to be stable. Moving on...\"",
")",
"break",
"end",
"rescue",
"=>",
"e",
"Chef",
"::",
"Log",
".",
"warn",
"(",
"\"Unable to get OSGi #{path_desc(path)} state: #{e}. Retrying...\"",
")",
"previous_state",
"=",
"''",
"same_state_counter",
"=",
"0",
"error_state_counter",
"+=",
"1",
"Chef",
"::",
"Log",
".",
"info",
"(",
"\"Error state counter: #{error_state_counter}\"",
")",
"if",
"hc_params",
"[",
"'rescue_mode'",
"]",
"&&",
"error_state_counter",
"==",
"hc_params",
"[",
"'error_state_barrier'",
"]",
"Chef",
"::",
"Log",
".",
"error",
"(",
"\"#{hc_params['error_state_barrier']} recent attempts to get \"",
"\"OSGi #{path_desc(path)} state have failed! Rescuing, as \"",
"'rescue_mode is active...'",
")",
"break",
"end",
"ensure",
"node",
".",
"default",
"[",
"'cq'",
"]",
"[",
"'http_read_timeout'",
"]",
"=",
"current_timeout",
"end",
"Chef",
"::",
"Application",
".",
"fatal!",
"(",
"\"Cannot detect stable state after #{hc_params['max_attempts']} \"",
"'attempts!'",
")",
"if",
"i",
"==",
"hc_params",
"[",
"'max_attempts'",
"]",
"Chef",
"::",
"Log",
".",
"info",
"(",
"\"[#{i}/#{hc_params['max_attempts']}] Next check of OSGi \"",
"\"#{path_desc(path)} in #{hc_params['sleep_time']}s...\"",
")",
"sleep",
"hc_params",
"[",
"'sleep_time'",
"]",
"end",
"end",
"end",
"end"
] |
Cookbook:: cq
Libraries:: HealthcheckHelper
|
[
"Cookbook",
"::",
"cq",
"Libraries",
"::",
"HealthcheckHelper"
] |
[
"# Save current net read timeout value",
"# Previous state (start with empty)",
"# How many times the state hasn't changed in a row",
"# How many times an error occurred in a row",
"# Reduce net read time value to speed up OSGi healthcheck procedure",
"# when instance is running but stopped accepting HTTP requests",
"# Handle response errors",
"# Reset error counter whenever request ended successfully",
"# Assign current state to previous state",
"# Move on if the same state occurred N times in a row",
"# Let's start over in case of an error (clear indicator of flapping",
"# OSGi bundles/component)",
"# Increment error_state_counter in case of an error",
"# If error occurred N times in a row and rescue_mode is active then",
"# log such event and break the loop",
"# Restore original timeout"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 22
| 847
| 152
|
3406ab277f3361541b326c5476bc645160e42e4a
|
tzwickl/NumProg
|
Assignment1/src/assignment1/Plotter.java
|
[
"MIT"
] |
Java
|
Plotter
|
/**
* @author Christoph Riesinger ([email protected])
* @since November 06, 2011
* @version 1.0
*
* This class is a simple implementation of a plotter. It accepts two
* arrays of float values which represent the x- and y-coordinates of
* points which should be plotted in a carthesian coordinate system. x-
* and y-axis are scaled logarithmically. No interpolation between the
* dots is done!
*/
|
@author Christoph Riesinger ([email protected])
@since November 06, 2011
@version 1.0
This class is a simple implementation of a plotter. It accepts two
arrays of float values which represent the x- and y-coordinates of
points which should be plotted in a carthesian coordinate system. x
and y-axis are scaled logarithmically. No interpolation between the
dots is done!
|
[
"@author",
"Christoph",
"Riesinger",
"(",
"riesinge@in",
".",
"tum",
".",
"de",
")",
"@since",
"November",
"06",
"2011",
"@version",
"1",
".",
"0",
"This",
"class",
"is",
"a",
"simple",
"implementation",
"of",
"a",
"plotter",
".",
"It",
"accepts",
"two",
"arrays",
"of",
"float",
"values",
"which",
"represent",
"the",
"x",
"-",
"and",
"y",
"-",
"coordinates",
"of",
"points",
"which",
"should",
"be",
"plotted",
"in",
"a",
"carthesian",
"coordinate",
"system",
".",
"x",
"and",
"y",
"-",
"axis",
"are",
"scaled",
"logarithmically",
".",
"No",
"interpolation",
"between",
"the",
"dots",
"is",
"done!"
] |
public class Plotter extends JPanel {
/* Just to avoid compiler warning. */
private static final long serialVersionUID = -8725968470735352529L;
/* Top, bottom, left and right margin of the coordinate system in the plot. */
private final int PADDING = 20;
/* Class members. Are set in class constructor. */
private float[] xData = null;
private float[] yData = null;
private float minX = Float.MAX_VALUE;
private float minY = Float.MAX_VALUE;
private float maxX = -Float.MAX_VALUE;
private float maxY = -Float.MAX_VALUE;
/**
* Constructor of this class. Assigns the passed x- and y-values of the
* points to plot to the internal private member variables.
*
* @param xData
* x-values of the points which should be plotted by this class.
* @param yData
* y-values of the points which should be plotted by this class.
* @throws InstantiationException
* The lengths of the x- and y-coorinates arrays have to be
* equal. Elsewise an exception is thrown.
*/
public Plotter(float[] xData, float[] yData) throws InstantiationException {
/*
* Make sure the arrays which contain the x- and y-ccordinates which
* should be plotted by this class have the same length.
*/
if (xData.length != yData.length) {
throw (new InstantiationException(
"The arrays for the x- and y-components of the "
+ "coordinates have to be of the same length."));
}
this.xData = xData;
this.yData = yData;
/*
* Determine the smallest and largest value which should be plotted by
* this class. These values are the boundaries of the axes of the
* coordinate system which will be plotted.
*/
for (int i = 0; i < xData.length; i++) {
if (xData[i] < minX) {
minX = xData[i];
}
if (xData[i] > maxX) {
maxX = xData[i];
}
if (yData[i] < minY) {
minY = yData[i];
}
if (yData[i] > maxY) {
maxY = yData[i];
}
}
if (1.0d / Math.sqrt(maxX) < minY) {
minY = (float) (1.0d / Math.sqrt(maxX));
}
if (1.0d / Math.sqrt(minX) < minY) {
minY = (float) (1.0d / Math.sqrt(minX));
}
if (1.0d / Math.sqrt(maxX) > maxY) {
maxY = (float) (1.0d / Math.sqrt(maxX));
}
if (1.0d / Math.sqrt(minX) > maxY) {
maxY = (float) (1.0d / Math.sqrt(minX));
}
}
/*
* (non-Javadoc)
*
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*/
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D graphics = (Graphics2D) g;
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int height = getHeight();
int width = getWidth();
float x, y;
/* draw x-axis */
graphics.draw(new Line2D.Double(PADDING, PADDING, PADDING, height
- PADDING));
graphics.draw(new Line2D.Double(
PADDING + 0.25f * (width - 2 * PADDING), height - PADDING - 5,
PADDING + 0.25f * (width - 2 * PADDING), height - PADDING + 5));
graphics.draw(new Line2D.Double(0.5f * width, height - PADDING - 5,
0.5f * width, height - PADDING + 5));
graphics.draw(new Line2D.Double(
PADDING + 0.75f * (width - 2 * PADDING), height - PADDING - 5,
PADDING + 0.75f * (width - 2 * PADDING), height - PADDING + 5));
graphics.draw(new Line2D.Double(width - PADDING, height - PADDING - 5,
width - PADDING, height - PADDING + 5));
/* draw x-axis caption */
graphics.drawString((new Float(minX)).toString(), PADDING + 2, height
- PADDING + 12);
graphics.drawString(
(new Float(Math.pow(10.0d, 0.25f * Math.log10(maxX) + 0.75f
* Math.log10(minX)))).toString(), PADDING + 0.25f
* (width - 2 * PADDING) + 2, height - PADDING + 12);
graphics.drawString(
(new Float(Math.pow(10.0d,
0.5f * (Math.log10(maxX) + Math.log10(minX)))))
.toString(), 0.5f * width + 2, height - PADDING + 12);
graphics.drawString(
(new Float(Math.pow(10.0d, 0.75f * Math.log10(maxX) + 0.25f
* Math.log10(minX)))).toString(), PADDING + 0.75f
* (width - 2 * PADDING) + 2, height - PADDING + 12);
graphics.drawString((new Float(maxX)).toString(), width - PADDING + 2,
height - PADDING + 12);
/* draw y-axis */
graphics.draw(new Line2D.Double(PADDING, height - PADDING, width
- PADDING, height - PADDING));
graphics.draw(new Line2D.Double(PADDING - 5, height
- (PADDING + 0.25f * (height - 2 * PADDING)), PADDING + 5,
height - (PADDING + 0.25f * (height - 2 * PADDING))));
graphics.draw(new Line2D.Double(PADDING - 5, 0.5f * height,
PADDING + 5, 0.5f * height));
graphics.draw(new Line2D.Double(PADDING - 5, height
- (PADDING + 0.75f * (height - 2 * PADDING)), PADDING + 5,
height - (PADDING + 0.75f * (height - 2 * PADDING))));
graphics.draw(new Line2D.Double(PADDING - 5, height
- (PADDING + (height - 2 * PADDING)), PADDING + 5, height
- (PADDING + (height - 2 * PADDING))));
/* draw y-axis caption */
graphics.drawString((new Float(minY)).toString(), PADDING + 2,
(height - 2 * PADDING) + PADDING - 2);
graphics.drawString(
(new Float(Math.pow(10.0d, 0.25f * Math.log10(maxY) + 0.75f
* Math.log10(minY)))).toString(), PADDING + 2, height
- (PADDING + 0.25f * (height - 2 * PADDING)) - 2);
graphics.drawString(
(new Float(Math.pow(10.0d,
0.5f * (Math.log10(maxY) + Math.log10(minY)))))
.toString(), PADDING + 2, 0.5f * height - 2);
graphics.drawString(
(new Float(Math.pow(10.0d, 0.75f * Math.log10(maxY) + 0.25f
* Math.log10(minY)))).toString(), PADDING + 2, height
- (PADDING + 0.75f * (height - 2 * PADDING)) - 2);
graphics.drawString((new Float(maxY)).toString(), PADDING + 2,
PADDING - 2);
/* draw "exact" solution */
graphics.setPaint(Color.GREEN);
for (int i = 0; i < xData.length; i++) {
x = scaleX(xData[i], width);
y = scaleY((float) (1.0d / Math.sqrt(xData[i])), height);
graphics.fill(new Ellipse2D.Float(x - 1.0f, y - 1.0f, 2.0f, 2.0f));
}
/* draw assigned values */
graphics.setPaint(Color.red);
for (int i = 0; i < xData.length; i++) {
x = scaleX(xData[i], width);
y = scaleY(yData[i], height);
graphics.fill(new Ellipse2D.Float(x - 1.0f, y - 1.0f, 2.0f, 2.0f));
}
}
/**
* The x-values are logarithmically scaled before they are drawn. This is
* done by this method. The padding of the coordinate system is respected.
*
* @param x
* Value which should be scaled logarithmically.
* @param width
* Width of the plottable area.
* @return Logarithmically scaled value of x.
*/
private float scaleX(float x, float width) {
float xScale = (float) (width - 2 * PADDING)
/ (float) (Math.log10(maxX) - Math.log10(minX));
float xOffset = (float) -Math.log10(minX);
float result = PADDING + xScale * (xOffset + (float) Math.log10(x));
return result;
}
/**
* The y-values are logarithmically scaled before they are drawn. This is
* done by this method. The padding of the coordinate system is respected.
*
* @param y
* Value which should be scaled logarithmically.
* @param height
* Height of the plottable area.
* @return Logarithmically scaled value of y.
*/
private float scaleY(float y, float height) {
float yScale = (float) (height - 2 * PADDING)
/ (float) (Math.log10(maxY) - Math.log10(minY));
float yOffset = (float) -Math.log10(minY);
float result = height
- (PADDING + yScale * (yOffset + (float) Math.log10(y)));
return result;
}
}
|
[
"public",
"class",
"Plotter",
"extends",
"JPanel",
"{",
"/* Just to avoid compiler warning. */",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"-",
"8725968470735352529L",
";",
"/* Top, bottom, left and right margin of the coordinate system in the plot. */",
"private",
"final",
"int",
"PADDING",
"=",
"20",
";",
"/* Class members. Are set in class constructor. */",
"private",
"float",
"[",
"]",
"xData",
"=",
"null",
";",
"private",
"float",
"[",
"]",
"yData",
"=",
"null",
";",
"private",
"float",
"minX",
"=",
"Float",
".",
"MAX_VALUE",
";",
"private",
"float",
"minY",
"=",
"Float",
".",
"MAX_VALUE",
";",
"private",
"float",
"maxX",
"=",
"-",
"Float",
".",
"MAX_VALUE",
";",
"private",
"float",
"maxY",
"=",
"-",
"Float",
".",
"MAX_VALUE",
";",
"/**\n\t * Constructor of this class. Assigns the passed x- and y-values of the\n\t * points to plot to the internal private member variables.\n\t * \n\t * @param xData\n\t * x-values of the points which should be plotted by this class.\n\t * @param yData\n\t * y-values of the points which should be plotted by this class.\n\t * @throws InstantiationException\n\t * The lengths of the x- and y-coorinates arrays have to be\n\t * equal. Elsewise an exception is thrown.\n\t */",
"public",
"Plotter",
"(",
"float",
"[",
"]",
"xData",
",",
"float",
"[",
"]",
"yData",
")",
"throws",
"InstantiationException",
"{",
"/*\n\t\t * Make sure the arrays which contain the x- and y-ccordinates which\n\t\t * should be plotted by this class have the same length.\n\t\t */",
"if",
"(",
"xData",
".",
"length",
"!=",
"yData",
".",
"length",
")",
"{",
"throw",
"(",
"new",
"InstantiationException",
"(",
"\"",
"The arrays for the x- and y-components of the ",
"\"",
"+",
"\"",
"coordinates have to be of the same length.",
"\"",
")",
")",
";",
"}",
"this",
".",
"xData",
"=",
"xData",
";",
"this",
".",
"yData",
"=",
"yData",
";",
"/*\n\t\t * Determine the smallest and largest value which should be plotted by\n\t\t * this class. These values are the boundaries of the axes of the\n\t\t * coordinate system which will be plotted.\n\t\t */",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"xData",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"xData",
"[",
"i",
"]",
"<",
"minX",
")",
"{",
"minX",
"=",
"xData",
"[",
"i",
"]",
";",
"}",
"if",
"(",
"xData",
"[",
"i",
"]",
">",
"maxX",
")",
"{",
"maxX",
"=",
"xData",
"[",
"i",
"]",
";",
"}",
"if",
"(",
"yData",
"[",
"i",
"]",
"<",
"minY",
")",
"{",
"minY",
"=",
"yData",
"[",
"i",
"]",
";",
"}",
"if",
"(",
"yData",
"[",
"i",
"]",
">",
"maxY",
")",
"{",
"maxY",
"=",
"yData",
"[",
"i",
"]",
";",
"}",
"}",
"if",
"(",
"1.0d",
"/",
"Math",
".",
"sqrt",
"(",
"maxX",
")",
"<",
"minY",
")",
"{",
"minY",
"=",
"(",
"float",
")",
"(",
"1.0d",
"/",
"Math",
".",
"sqrt",
"(",
"maxX",
")",
")",
";",
"}",
"if",
"(",
"1.0d",
"/",
"Math",
".",
"sqrt",
"(",
"minX",
")",
"<",
"minY",
")",
"{",
"minY",
"=",
"(",
"float",
")",
"(",
"1.0d",
"/",
"Math",
".",
"sqrt",
"(",
"minX",
")",
")",
";",
"}",
"if",
"(",
"1.0d",
"/",
"Math",
".",
"sqrt",
"(",
"maxX",
")",
">",
"maxY",
")",
"{",
"maxY",
"=",
"(",
"float",
")",
"(",
"1.0d",
"/",
"Math",
".",
"sqrt",
"(",
"maxX",
")",
")",
";",
"}",
"if",
"(",
"1.0d",
"/",
"Math",
".",
"sqrt",
"(",
"minX",
")",
">",
"maxY",
")",
"{",
"maxY",
"=",
"(",
"float",
")",
"(",
"1.0d",
"/",
"Math",
".",
"sqrt",
"(",
"minX",
")",
")",
";",
"}",
"}",
"/*\n\t * (non-Javadoc)\n\t * \n\t * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)\n\t */",
"protected",
"void",
"paintComponent",
"(",
"Graphics",
"g",
")",
"{",
"super",
".",
"paintComponent",
"(",
"g",
")",
";",
"Graphics2D",
"graphics",
"=",
"(",
"Graphics2D",
")",
"g",
";",
"graphics",
".",
"setRenderingHint",
"(",
"RenderingHints",
".",
"KEY_ANTIALIASING",
",",
"RenderingHints",
".",
"VALUE_ANTIALIAS_ON",
")",
";",
"int",
"height",
"=",
"getHeight",
"(",
")",
";",
"int",
"width",
"=",
"getWidth",
"(",
")",
";",
"float",
"x",
",",
"y",
";",
"/* draw x-axis */",
"graphics",
".",
"draw",
"(",
"new",
"Line2D",
".",
"Double",
"(",
"PADDING",
",",
"PADDING",
",",
"PADDING",
",",
"height",
"-",
"PADDING",
")",
")",
";",
"graphics",
".",
"draw",
"(",
"new",
"Line2D",
".",
"Double",
"(",
"PADDING",
"+",
"0.25f",
"*",
"(",
"width",
"-",
"2",
"*",
"PADDING",
")",
",",
"height",
"-",
"PADDING",
"-",
"5",
",",
"PADDING",
"+",
"0.25f",
"*",
"(",
"width",
"-",
"2",
"*",
"PADDING",
")",
",",
"height",
"-",
"PADDING",
"+",
"5",
")",
")",
";",
"graphics",
".",
"draw",
"(",
"new",
"Line2D",
".",
"Double",
"(",
"0.5f",
"*",
"width",
",",
"height",
"-",
"PADDING",
"-",
"5",
",",
"0.5f",
"*",
"width",
",",
"height",
"-",
"PADDING",
"+",
"5",
")",
")",
";",
"graphics",
".",
"draw",
"(",
"new",
"Line2D",
".",
"Double",
"(",
"PADDING",
"+",
"0.75f",
"*",
"(",
"width",
"-",
"2",
"*",
"PADDING",
")",
",",
"height",
"-",
"PADDING",
"-",
"5",
",",
"PADDING",
"+",
"0.75f",
"*",
"(",
"width",
"-",
"2",
"*",
"PADDING",
")",
",",
"height",
"-",
"PADDING",
"+",
"5",
")",
")",
";",
"graphics",
".",
"draw",
"(",
"new",
"Line2D",
".",
"Double",
"(",
"width",
"-",
"PADDING",
",",
"height",
"-",
"PADDING",
"-",
"5",
",",
"width",
"-",
"PADDING",
",",
"height",
"-",
"PADDING",
"+",
"5",
")",
")",
";",
"/* draw x-axis caption */",
"graphics",
".",
"drawString",
"(",
"(",
"new",
"Float",
"(",
"minX",
")",
")",
".",
"toString",
"(",
")",
",",
"PADDING",
"+",
"2",
",",
"height",
"-",
"PADDING",
"+",
"12",
")",
";",
"graphics",
".",
"drawString",
"(",
"(",
"new",
"Float",
"(",
"Math",
".",
"pow",
"(",
"10.0d",
",",
"0.25f",
"*",
"Math",
".",
"log10",
"(",
"maxX",
")",
"+",
"0.75f",
"*",
"Math",
".",
"log10",
"(",
"minX",
")",
")",
")",
")",
".",
"toString",
"(",
")",
",",
"PADDING",
"+",
"0.25f",
"*",
"(",
"width",
"-",
"2",
"*",
"PADDING",
")",
"+",
"2",
",",
"height",
"-",
"PADDING",
"+",
"12",
")",
";",
"graphics",
".",
"drawString",
"(",
"(",
"new",
"Float",
"(",
"Math",
".",
"pow",
"(",
"10.0d",
",",
"0.5f",
"*",
"(",
"Math",
".",
"log10",
"(",
"maxX",
")",
"+",
"Math",
".",
"log10",
"(",
"minX",
")",
")",
")",
")",
")",
".",
"toString",
"(",
")",
",",
"0.5f",
"*",
"width",
"+",
"2",
",",
"height",
"-",
"PADDING",
"+",
"12",
")",
";",
"graphics",
".",
"drawString",
"(",
"(",
"new",
"Float",
"(",
"Math",
".",
"pow",
"(",
"10.0d",
",",
"0.75f",
"*",
"Math",
".",
"log10",
"(",
"maxX",
")",
"+",
"0.25f",
"*",
"Math",
".",
"log10",
"(",
"minX",
")",
")",
")",
")",
".",
"toString",
"(",
")",
",",
"PADDING",
"+",
"0.75f",
"*",
"(",
"width",
"-",
"2",
"*",
"PADDING",
")",
"+",
"2",
",",
"height",
"-",
"PADDING",
"+",
"12",
")",
";",
"graphics",
".",
"drawString",
"(",
"(",
"new",
"Float",
"(",
"maxX",
")",
")",
".",
"toString",
"(",
")",
",",
"width",
"-",
"PADDING",
"+",
"2",
",",
"height",
"-",
"PADDING",
"+",
"12",
")",
";",
"/* draw y-axis */",
"graphics",
".",
"draw",
"(",
"new",
"Line2D",
".",
"Double",
"(",
"PADDING",
",",
"height",
"-",
"PADDING",
",",
"width",
"-",
"PADDING",
",",
"height",
"-",
"PADDING",
")",
")",
";",
"graphics",
".",
"draw",
"(",
"new",
"Line2D",
".",
"Double",
"(",
"PADDING",
"-",
"5",
",",
"height",
"-",
"(",
"PADDING",
"+",
"0.25f",
"*",
"(",
"height",
"-",
"2",
"*",
"PADDING",
")",
")",
",",
"PADDING",
"+",
"5",
",",
"height",
"-",
"(",
"PADDING",
"+",
"0.25f",
"*",
"(",
"height",
"-",
"2",
"*",
"PADDING",
")",
")",
")",
")",
";",
"graphics",
".",
"draw",
"(",
"new",
"Line2D",
".",
"Double",
"(",
"PADDING",
"-",
"5",
",",
"0.5f",
"*",
"height",
",",
"PADDING",
"+",
"5",
",",
"0.5f",
"*",
"height",
")",
")",
";",
"graphics",
".",
"draw",
"(",
"new",
"Line2D",
".",
"Double",
"(",
"PADDING",
"-",
"5",
",",
"height",
"-",
"(",
"PADDING",
"+",
"0.75f",
"*",
"(",
"height",
"-",
"2",
"*",
"PADDING",
")",
")",
",",
"PADDING",
"+",
"5",
",",
"height",
"-",
"(",
"PADDING",
"+",
"0.75f",
"*",
"(",
"height",
"-",
"2",
"*",
"PADDING",
")",
")",
")",
")",
";",
"graphics",
".",
"draw",
"(",
"new",
"Line2D",
".",
"Double",
"(",
"PADDING",
"-",
"5",
",",
"height",
"-",
"(",
"PADDING",
"+",
"(",
"height",
"-",
"2",
"*",
"PADDING",
")",
")",
",",
"PADDING",
"+",
"5",
",",
"height",
"-",
"(",
"PADDING",
"+",
"(",
"height",
"-",
"2",
"*",
"PADDING",
")",
")",
")",
")",
";",
"/* draw y-axis caption */",
"graphics",
".",
"drawString",
"(",
"(",
"new",
"Float",
"(",
"minY",
")",
")",
".",
"toString",
"(",
")",
",",
"PADDING",
"+",
"2",
",",
"(",
"height",
"-",
"2",
"*",
"PADDING",
")",
"+",
"PADDING",
"-",
"2",
")",
";",
"graphics",
".",
"drawString",
"(",
"(",
"new",
"Float",
"(",
"Math",
".",
"pow",
"(",
"10.0d",
",",
"0.25f",
"*",
"Math",
".",
"log10",
"(",
"maxY",
")",
"+",
"0.75f",
"*",
"Math",
".",
"log10",
"(",
"minY",
")",
")",
")",
")",
".",
"toString",
"(",
")",
",",
"PADDING",
"+",
"2",
",",
"height",
"-",
"(",
"PADDING",
"+",
"0.25f",
"*",
"(",
"height",
"-",
"2",
"*",
"PADDING",
")",
")",
"-",
"2",
")",
";",
"graphics",
".",
"drawString",
"(",
"(",
"new",
"Float",
"(",
"Math",
".",
"pow",
"(",
"10.0d",
",",
"0.5f",
"*",
"(",
"Math",
".",
"log10",
"(",
"maxY",
")",
"+",
"Math",
".",
"log10",
"(",
"minY",
")",
")",
")",
")",
")",
".",
"toString",
"(",
")",
",",
"PADDING",
"+",
"2",
",",
"0.5f",
"*",
"height",
"-",
"2",
")",
";",
"graphics",
".",
"drawString",
"(",
"(",
"new",
"Float",
"(",
"Math",
".",
"pow",
"(",
"10.0d",
",",
"0.75f",
"*",
"Math",
".",
"log10",
"(",
"maxY",
")",
"+",
"0.25f",
"*",
"Math",
".",
"log10",
"(",
"minY",
")",
")",
")",
")",
".",
"toString",
"(",
")",
",",
"PADDING",
"+",
"2",
",",
"height",
"-",
"(",
"PADDING",
"+",
"0.75f",
"*",
"(",
"height",
"-",
"2",
"*",
"PADDING",
")",
")",
"-",
"2",
")",
";",
"graphics",
".",
"drawString",
"(",
"(",
"new",
"Float",
"(",
"maxY",
")",
")",
".",
"toString",
"(",
")",
",",
"PADDING",
"+",
"2",
",",
"PADDING",
"-",
"2",
")",
";",
"/* draw \"exact\" solution */",
"graphics",
".",
"setPaint",
"(",
"Color",
".",
"GREEN",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"xData",
".",
"length",
";",
"i",
"++",
")",
"{",
"x",
"=",
"scaleX",
"(",
"xData",
"[",
"i",
"]",
",",
"width",
")",
";",
"y",
"=",
"scaleY",
"(",
"(",
"float",
")",
"(",
"1.0d",
"/",
"Math",
".",
"sqrt",
"(",
"xData",
"[",
"i",
"]",
")",
")",
",",
"height",
")",
";",
"graphics",
".",
"fill",
"(",
"new",
"Ellipse2D",
".",
"Float",
"(",
"x",
"-",
"1.0f",
",",
"y",
"-",
"1.0f",
",",
"2.0f",
",",
"2.0f",
")",
")",
";",
"}",
"/* draw assigned values */",
"graphics",
".",
"setPaint",
"(",
"Color",
".",
"red",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"xData",
".",
"length",
";",
"i",
"++",
")",
"{",
"x",
"=",
"scaleX",
"(",
"xData",
"[",
"i",
"]",
",",
"width",
")",
";",
"y",
"=",
"scaleY",
"(",
"yData",
"[",
"i",
"]",
",",
"height",
")",
";",
"graphics",
".",
"fill",
"(",
"new",
"Ellipse2D",
".",
"Float",
"(",
"x",
"-",
"1.0f",
",",
"y",
"-",
"1.0f",
",",
"2.0f",
",",
"2.0f",
")",
")",
";",
"}",
"}",
"/**\n\t * The x-values are logarithmically scaled before they are drawn. This is\n\t * done by this method. The padding of the coordinate system is respected.\n\t * \n\t * @param x\n\t * Value which should be scaled logarithmically.\n\t * @param width\n\t * Width of the plottable area.\n\t * @return Logarithmically scaled value of x.\n\t */",
"private",
"float",
"scaleX",
"(",
"float",
"x",
",",
"float",
"width",
")",
"{",
"float",
"xScale",
"=",
"(",
"float",
")",
"(",
"width",
"-",
"2",
"*",
"PADDING",
")",
"/",
"(",
"float",
")",
"(",
"Math",
".",
"log10",
"(",
"maxX",
")",
"-",
"Math",
".",
"log10",
"(",
"minX",
")",
")",
";",
"float",
"xOffset",
"=",
"(",
"float",
")",
"-",
"Math",
".",
"log10",
"(",
"minX",
")",
";",
"float",
"result",
"=",
"PADDING",
"+",
"xScale",
"*",
"(",
"xOffset",
"+",
"(",
"float",
")",
"Math",
".",
"log10",
"(",
"x",
")",
")",
";",
"return",
"result",
";",
"}",
"/**\n\t * The y-values are logarithmically scaled before they are drawn. This is\n\t * done by this method. The padding of the coordinate system is respected.\n\t * \n\t * @param y\n\t * Value which should be scaled logarithmically.\n\t * @param height\n\t * Height of the plottable area.\n\t * @return Logarithmically scaled value of y.\n\t */",
"private",
"float",
"scaleY",
"(",
"float",
"y",
",",
"float",
"height",
")",
"{",
"float",
"yScale",
"=",
"(",
"float",
")",
"(",
"height",
"-",
"2",
"*",
"PADDING",
")",
"/",
"(",
"float",
")",
"(",
"Math",
".",
"log10",
"(",
"maxY",
")",
"-",
"Math",
".",
"log10",
"(",
"minY",
")",
")",
";",
"float",
"yOffset",
"=",
"(",
"float",
")",
"-",
"Math",
".",
"log10",
"(",
"minY",
")",
";",
"float",
"result",
"=",
"height",
"-",
"(",
"PADDING",
"+",
"yScale",
"*",
"(",
"yOffset",
"+",
"(",
"float",
")",
"Math",
".",
"log10",
"(",
"y",
")",
")",
")",
";",
"return",
"result",
";",
"}",
"}"
] |
@author Christoph Riesinger ([email protected])
@since November 06, 2011
@version 1.0
|
[
"@author",
"Christoph",
"Riesinger",
"(",
"riesinge@in",
".",
"tum",
".",
"de",
")",
"@since",
"November",
"06",
"2011",
"@version",
"1",
".",
"0"
] |
[] |
[
{
"param": "JPanel",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "JPanel",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 19
| 2,485
| 115
|
e5c15ec6e220a8a92ce70ba008ec796d10a8aa1d
|
ElyKar/Tools
|
Ruby/sorting/heap.rb
|
[
"MIT"
] |
Ruby
|
HeapHalf
|
# HeapHalf sorts an array using heapsort with half exchanges.
# It uses the standard heapify operation before sorting.
# It provides two methods, one for sorting the array in parameter and
# the other to return a sorted copy of the array.
# The items of the array must support the <=> operator
#
# Author:: Tristan Claverie
# License:: MIT
|
HeapHalf sorts an array using heapsort with half exchanges.
It uses the standard heapify operation before sorting.
It provides two methods, one for sorting the array in parameter and
the other to return a sorted copy of the array.
The items of the array must support the <=> operator
: Tristan Claverie
License:: MIT
|
[
"HeapHalf",
"sorts",
"an",
"array",
"using",
"heapsort",
"with",
"half",
"exchanges",
".",
"It",
"uses",
"the",
"standard",
"heapify",
"operation",
"before",
"sorting",
".",
"It",
"provides",
"two",
"methods",
"one",
"for",
"sorting",
"the",
"array",
"in",
"parameter",
"and",
"the",
"other",
"to",
"return",
"a",
"sorted",
"copy",
"of",
"the",
"array",
".",
"The",
"items",
"of",
"the",
"array",
"must",
"support",
"the",
"<",
"=",
">",
"operator",
":",
"Tristan",
"Claverie",
"License",
"::",
"MIT"
] |
class HeapHalf
# Sink the item in position k up to position n
def self.sink(a, k, n)
current = a[k]
while k*2 + 1 <= n
child = k*2 + 1
if child + 1 <= n and (a[child] <=> a[child + 1]) < 0 then
child += 1
end
break if not (current <=> a[child]) < 0
a[k] = a[child]
k = child
end
a[k] = current
end
private_class_method :sink
# Sort the given array in parameter using
# heapsort
def self.sort!(a)
n = a.size
# Heapify the array
((n-2)/2).downto(0) do |k|
sink(a, k, n-1)
end
# Sort the array
(n - 1).downto(1) do |last|
a[0], a[last] = a[last], a[0]
sink(a, 0, last - 1)
end
end
# Returns a sorted copy of the array in parameter
# using insertion sort
def self.sort(a)
sorted = a.dup
self.sort!(sorted)
return sorted
end
end
|
[
"class",
"HeapHalf",
"def",
"self",
".",
"sink",
"(",
"a",
",",
"k",
",",
"n",
")",
"current",
"=",
"a",
"[",
"k",
"]",
"while",
"k",
"*",
"2",
"+",
"1",
"<=",
"n",
"child",
"=",
"k",
"*",
"2",
"+",
"1",
"if",
"child",
"+",
"1",
"<=",
"n",
"and",
"(",
"a",
"[",
"child",
"]",
"<=>",
"a",
"[",
"child",
"+",
"1",
"]",
")",
"<",
"0",
"then",
"child",
"+=",
"1",
"end",
"break",
"if",
"not",
"(",
"current",
"<=>",
"a",
"[",
"child",
"]",
")",
"<",
"0",
"a",
"[",
"k",
"]",
"=",
"a",
"[",
"child",
"]",
"k",
"=",
"child",
"end",
"a",
"[",
"k",
"]",
"=",
"current",
"end",
"private_class_method",
":sink",
"def",
"self",
".",
"sort!",
"(",
"a",
")",
"n",
"=",
"a",
".",
"size",
"(",
"(",
"n",
"-",
"2",
")",
"/",
"2",
")",
".",
"downto",
"(",
"0",
")",
"do",
"|",
"k",
"|",
"sink",
"(",
"a",
",",
"k",
",",
"n",
"-",
"1",
")",
"end",
"(",
"n",
"-",
"1",
")",
".",
"downto",
"(",
"1",
")",
"do",
"|",
"last",
"|",
"a",
"[",
"0",
"]",
",",
"a",
"[",
"last",
"]",
"=",
"a",
"[",
"last",
"]",
",",
"a",
"[",
"0",
"]",
"sink",
"(",
"a",
",",
"0",
",",
"last",
"-",
"1",
")",
"end",
"end",
"def",
"self",
".",
"sort",
"(",
"a",
")",
"sorted",
"=",
"a",
".",
"dup",
"self",
".",
"sort!",
"(",
"sorted",
")",
"return",
"sorted",
"end",
"end"
] |
HeapHalf sorts an array using heapsort with half exchanges.
|
[
"HeapHalf",
"sorts",
"an",
"array",
"using",
"heapsort",
"with",
"half",
"exchanges",
"."
] |
[
"# Sink the item in position k up to position n",
"# Sort the given array in parameter using",
"# heapsort",
"# Heapify the array",
"# Sort the array",
"# Returns a sorted copy of the array in parameter",
"# using insertion sort"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 303
| 76
|
00d52bce7ce906cd2f396507f440af168b10c38d
|
xirzec/gdata-ruby-util
|
lib/gdata/client/youtube.rb
|
[
"Apache-2.0"
] |
Ruby
|
GData
|
# Copyright (C) 2008 Google Inc.
#
# 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.
|
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.
|
[
"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",
"."
] |
module GData
module Client
# Client class to wrap working with the YouTube API. Sets some
# YouTube-specific options.
class YouTube < Base
# The YouTube developer key being used.
attr_accessor :developer_key
# The YouTube ClientID being used.
attr_accessor :client_id
def initialize(options = {})
options[:clientlogin_service] ||= 'youtube'
options[:clientlogin_url] ||= 'https://www.google.com/youtube/accounts/ClientLogin'
options[:authsub_scope] ||= 'http://gdata.youtube.com'
options[:version] ||= '2'
super(options)
end
# Custom prepare_headers to include the developer key and clientID
def prepare_headers
if @client_id
@headers['X-GData-Client'] = @client_id
end
if @developer_key
@headers['X-GData-Key'] = "key=#{@developer_key}"
end
super
end
end
end
end
|
[
"module",
"GData",
"module",
"Client",
"class",
"YouTube",
"<",
"Base",
"attr_accessor",
":developer_key",
"attr_accessor",
":client_id",
"def",
"initialize",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":clientlogin_service",
"]",
"||=",
"'youtube'",
"options",
"[",
":clientlogin_url",
"]",
"||=",
"'https://www.google.com/youtube/accounts/ClientLogin'",
"options",
"[",
":authsub_scope",
"]",
"||=",
"'http://gdata.youtube.com'",
"options",
"[",
":version",
"]",
"||=",
"'2'",
"super",
"(",
"options",
")",
"end",
"def",
"prepare_headers",
"if",
"@client_id",
"@headers",
"[",
"'X-GData-Client'",
"]",
"=",
"@client_id",
"end",
"if",
"@developer_key",
"@headers",
"[",
"'X-GData-Key'",
"]",
"=",
"\"key=#{@developer_key}\"",
"end",
"super",
"end",
"end",
"end",
"end"
] |
Copyright (C) 2008 Google Inc.
|
[
"Copyright",
"(",
"C",
")",
"2008",
"Google",
"Inc",
"."
] |
[
"# Client class to wrap working with the YouTube API. Sets some ",
"# YouTube-specific options.",
"# The YouTube developer key being used.",
"# The YouTube ClientID being used.",
"# Custom prepare_headers to include the developer key and clientID"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 219
| 133
|
31b48be6d4a400f372bca78aa792e6e50a88fb07
|
yob/puma-plugin-systemd
|
lib/puma/plugin/systemd.rb
|
[
"MIT"
] |
Ruby
|
Systemd
|
# Give us a way to talk to systemd.
#
# It'd be great to use systemd-notify for the whole shebang, but there's a
# critical error introducing a race condition:
#
# https://github.com/systemd/systemd/issues/2739
#
# systemd-notify docs:
#
# https://www.freedesktop.org/software/systemd/man/systemd-notify.html
#
# We could use sd-daemon (sd_notify and friends) but they require a C
# extension, and are really just fancy wrappers for blatting datagrams at a
# socket advertised via ENV. See the docs:
#
# https://www.freedesktop.org/software/systemd/man/sd-daemon.html
#
|
Give us a way to talk to systemd.
It'd be great to use systemd-notify for the whole shebang, but there's a
critical error introducing a race condition.
systemd-notify docs.
We could use sd-daemon (sd_notify and friends) but they require a C
extension, and are really just fancy wrappers for blatting datagrams at a
socket advertised via ENV. See the docs.
|
[
"Give",
"us",
"a",
"way",
"to",
"talk",
"to",
"systemd",
".",
"It",
"'",
"d",
"be",
"great",
"to",
"use",
"systemd",
"-",
"notify",
"for",
"the",
"whole",
"shebang",
"but",
"there",
"'",
"s",
"a",
"critical",
"error",
"introducing",
"a",
"race",
"condition",
".",
"systemd",
"-",
"notify",
"docs",
".",
"We",
"could",
"use",
"sd",
"-",
"daemon",
"(",
"sd_notify",
"and",
"friends",
")",
"but",
"they",
"require",
"a",
"C",
"extension",
"and",
"are",
"really",
"just",
"fancy",
"wrappers",
"for",
"blatting",
"datagrams",
"at",
"a",
"socket",
"advertised",
"via",
"ENV",
".",
"See",
"the",
"docs",
"."
] |
class Systemd
# Do we have a systemctl binary? This is a good indicator whether systemd
# is installed at all.
def present?
ENV["PATH"].split(":").any? { |dir| File.exists?(File.join(dir, "systemctl")) }
end
# Is the system currently booted with systemd?
#
# We could check for the systemd run directory directly, but we can't be
# absolutely sure of it's location and breaks encapsulation. We can be sure
# that systemctl is present on a systemd system and understand whether
# systemd is running. The systemd-notify binary actually recommends this.
#
# An alternate way to check for this state is to call systemctl(1) with
# the is-system-running command. It will return "offline" if the system
# was not booted with systemd.
#
# See also sd_booted:
#
# https://www.freedesktop.org/software/systemd/man/sd_booted.html
#
def booted?
IO.popen(["systemctl", "is-system-running"], &:read).chomp != "offline"
end
# Are we running within a systemd unit that expects us to notify?
def notify?
ENV.include?("NOTIFY_SOCKET")
end
# Open a persistent notify socket.
#
# Ruby doesn't have a nicer way to open a unix socket as a datagram.
#
private def notify_socket
@notify_socket ||= Socket.new(Socket::AF_UNIX, Socket::SOCK_DGRAM, 0).tap do |socket|
socket.connect(Socket.pack_sockaddr_un(ENV["NOTIFY_SOCKET"]))
socket.close_on_exec = true
end
end
# Send a raw notify message.
#
# https://www.freedesktop.org/software/systemd/man/sd_notify.html
#
private def notify(message)
notify_socket.sendmsg(message, Socket::MSG_NOSIGNAL)
end
# Tell systemd we are now the main pid
def notify_pid
notify("MAINPID=#{$$}")
end
# Tell systemd we're fully started and ready to handle requests
def notify_ready
notify("READY=1")
end
# Tell systemd our status
def notify_status(status)
notify("STATUS=#{status}")
end
# Tell systemd we're restarting
def notify_reloading
notify("RELOADING=1")
end
# Tell systemd we're still alive
def notify_watchdog
notify("WATCHDOG=1")
end
# Has systemd asked us to watchdog?
#
# https://www.freedesktop.org/software/systemd/man/sd_watchdog_enabled.html
#
def watchdog?
ENV.include?("WATCHDOG_USEC") &&
(!ENV.include?("WATCHDOG_PID") || ENV["WATCHDOG_PID"].to_i == $$)
end
# How long between pings until the watchdog will think we're unhealthy?
def watchdog_usec
ENV["WATCHDOG_USEC"].to_i
end
end
|
[
"class",
"Systemd",
"def",
"present?",
"ENV",
"[",
"\"PATH\"",
"]",
".",
"split",
"(",
"\":\"",
")",
".",
"any?",
"{",
"|",
"dir",
"|",
"File",
".",
"exists?",
"(",
"File",
".",
"join",
"(",
"dir",
",",
"\"systemctl\"",
")",
")",
"}",
"end",
"def",
"booted?",
"IO",
".",
"popen",
"(",
"[",
"\"systemctl\"",
",",
"\"is-system-running\"",
"]",
",",
"&",
":read",
")",
".",
"chomp",
"!=",
"\"offline\"",
"end",
"def",
"notify?",
"ENV",
".",
"include?",
"(",
"\"NOTIFY_SOCKET\"",
")",
"end",
"private",
"def",
"notify_socket",
"@notify_socket",
"||=",
"Socket",
".",
"new",
"(",
"Socket",
"::",
"AF_UNIX",
",",
"Socket",
"::",
"SOCK_DGRAM",
",",
"0",
")",
".",
"tap",
"do",
"|",
"socket",
"|",
"socket",
".",
"connect",
"(",
"Socket",
".",
"pack_sockaddr_un",
"(",
"ENV",
"[",
"\"NOTIFY_SOCKET\"",
"]",
")",
")",
"socket",
".",
"close_on_exec",
"=",
"true",
"end",
"end",
"private",
"def",
"notify",
"(",
"message",
")",
"notify_socket",
".",
"sendmsg",
"(",
"message",
",",
"Socket",
"::",
"MSG_NOSIGNAL",
")",
"end",
"def",
"notify_pid",
"notify",
"(",
"\"MAINPID=#{$$}\"",
")",
"end",
"def",
"notify_ready",
"notify",
"(",
"\"READY=1\"",
")",
"end",
"def",
"notify_status",
"(",
"status",
")",
"notify",
"(",
"\"STATUS=#{status}\"",
")",
"end",
"def",
"notify_reloading",
"notify",
"(",
"\"RELOADING=1\"",
")",
"end",
"def",
"notify_watchdog",
"notify",
"(",
"\"WATCHDOG=1\"",
")",
"end",
"def",
"watchdog?",
"ENV",
".",
"include?",
"(",
"\"WATCHDOG_USEC\"",
")",
"&&",
"(",
"!",
"ENV",
".",
"include?",
"(",
"\"WATCHDOG_PID\"",
")",
"||",
"ENV",
"[",
"\"WATCHDOG_PID\"",
"]",
".",
"to_i",
"==",
"$$",
")",
"end",
"def",
"watchdog_usec",
"ENV",
"[",
"\"WATCHDOG_USEC\"",
"]",
".",
"to_i",
"end",
"end"
] |
Give us a way to talk to systemd.
|
[
"Give",
"us",
"a",
"way",
"to",
"talk",
"to",
"systemd",
"."
] |
[
"# Do we have a systemctl binary? This is a good indicator whether systemd",
"# is installed at all.",
"# Is the system currently booted with systemd?",
"#",
"# We could check for the systemd run directory directly, but we can't be",
"# absolutely sure of it's location and breaks encapsulation. We can be sure",
"# that systemctl is present on a systemd system and understand whether",
"# systemd is running. The systemd-notify binary actually recommends this.",
"#",
"# An alternate way to check for this state is to call systemctl(1) with",
"# the is-system-running command. It will return \"offline\" if the system",
"# was not booted with systemd.",
"#",
"# See also sd_booted:",
"#",
"# https://www.freedesktop.org/software/systemd/man/sd_booted.html",
"#",
"# Are we running within a systemd unit that expects us to notify?",
"# Open a persistent notify socket.",
"#",
"# Ruby doesn't have a nicer way to open a unix socket as a datagram.",
"#",
"# Send a raw notify message.",
"#",
"# https://www.freedesktop.org/software/systemd/man/sd_notify.html",
"#",
"# Tell systemd we are now the main pid",
"# Tell systemd we're fully started and ready to handle requests",
"# Tell systemd our status",
"# Tell systemd we're restarting",
"# Tell systemd we're still alive",
"# Has systemd asked us to watchdog?",
"#",
"# https://www.freedesktop.org/software/systemd/man/sd_watchdog_enabled.html",
"#",
"# How long between pings until the watchdog will think we're unhealthy?"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 670
| 153
|
a39b0964b5fa1996d2a2eb3d74f41dd0ea2a877b
|
murashovzhen/serilog-sinks-syslog
|
src/Serilog.Sinks.Syslog/Sinks/Formatters/SyslogFormatterBase.cs
|
[
"Apache-2.0"
] |
C#
|
SyslogFormatterBase
|
/// <summary>
/// Base class for formatters that output Serilog events in syslog formats
/// </summary>
/// <remarks>
/// We purposely don't use Serilog's ITextFormatter to format syslog messages, so that users of this library
/// can use their own ITextFormatter instances to control the format of the 'body' part of each message
/// </remarks>
|
Base class for formatters that output Serilog events in syslog formats
|
[
"Base",
"class",
"for",
"formatters",
"that",
"output",
"Serilog",
"events",
"in",
"syslog",
"formats"
] |
public abstract class SyslogFormatterBase : ISyslogFormatter
{
private readonly Facility facility;
private readonly ITextFormatter templateFormatter;
protected static readonly string Host = Environment.MachineName.WithMaxLength(255);
protected static readonly string ProcessId = Process.GetCurrentProcess().Id.ToString();
protected static readonly string ProcessName = Process.GetCurrentProcess().ProcessName;
protected SyslogFormatterBase(Facility facility, ITextFormatter templateFormatter)
{
this.facility = facility;
this.templateFormatter = templateFormatter;
}
public abstract string FormatMessage(LogEvent logEvent);
public int CalculatePriority(LogEventLevel level)
{
var severity = MapLogLevelToSeverity(level);
return ((int)this.facility * 8) + (int)severity;
}
private static Severity MapLogLevelToSeverity(LogEventLevel logEventLevel)
{
switch (logEventLevel)
{
case LogEventLevel.Debug: return Severity.Debug;
case LogEventLevel.Error: return Severity.Error;
case LogEventLevel.Fatal: return Severity.Emergency;
case LogEventLevel.Information: return Severity.Informational;
case LogEventLevel.Warning: return Severity.Warning;
default: return Severity.Notice;
}
}
protected string RenderMessage(LogEvent logEvent)
{
if (templateFormatter == null)
{
return logEvent.RenderMessage();
}
using (var sw = new StringWriter())
{
if (templateFormatter is JsonFormatter)
{
sw.Write("@cee:");
}
this.templateFormatter.Format(logEvent, sw);
return sw.ToString();
}
}
}
|
[
"public",
"abstract",
"class",
"SyslogFormatterBase",
":",
"ISyslogFormatter",
"{",
"private",
"readonly",
"Facility",
"facility",
";",
"private",
"readonly",
"ITextFormatter",
"templateFormatter",
";",
"protected",
"static",
"readonly",
"string",
"Host",
"=",
"Environment",
".",
"MachineName",
".",
"WithMaxLength",
"(",
"255",
")",
";",
"protected",
"static",
"readonly",
"string",
"ProcessId",
"=",
"Process",
".",
"GetCurrentProcess",
"(",
")",
".",
"Id",
".",
"ToString",
"(",
")",
";",
"protected",
"static",
"readonly",
"string",
"ProcessName",
"=",
"Process",
".",
"GetCurrentProcess",
"(",
")",
".",
"ProcessName",
";",
"protected",
"SyslogFormatterBase",
"(",
"Facility",
"facility",
",",
"ITextFormatter",
"templateFormatter",
")",
"{",
"this",
".",
"facility",
"=",
"facility",
";",
"this",
".",
"templateFormatter",
"=",
"templateFormatter",
";",
"}",
"public",
"abstract",
"string",
"FormatMessage",
"(",
"LogEvent",
"logEvent",
")",
";",
"public",
"int",
"CalculatePriority",
"(",
"LogEventLevel",
"level",
")",
"{",
"var",
"severity",
"=",
"MapLogLevelToSeverity",
"(",
"level",
")",
";",
"return",
"(",
"(",
"int",
")",
"this",
".",
"facility",
"*",
"8",
")",
"+",
"(",
"int",
")",
"severity",
";",
"}",
"private",
"static",
"Severity",
"MapLogLevelToSeverity",
"(",
"LogEventLevel",
"logEventLevel",
")",
"{",
"switch",
"(",
"logEventLevel",
")",
"{",
"case",
"LogEventLevel",
".",
"Debug",
":",
"return",
"Severity",
".",
"Debug",
";",
"case",
"LogEventLevel",
".",
"Error",
":",
"return",
"Severity",
".",
"Error",
";",
"case",
"LogEventLevel",
".",
"Fatal",
":",
"return",
"Severity",
".",
"Emergency",
";",
"case",
"LogEventLevel",
".",
"Information",
":",
"return",
"Severity",
".",
"Informational",
";",
"case",
"LogEventLevel",
".",
"Warning",
":",
"return",
"Severity",
".",
"Warning",
";",
"default",
":",
"return",
"Severity",
".",
"Notice",
";",
"}",
"}",
"protected",
"string",
"RenderMessage",
"(",
"LogEvent",
"logEvent",
")",
"{",
"if",
"(",
"templateFormatter",
"==",
"null",
")",
"{",
"return",
"logEvent",
".",
"RenderMessage",
"(",
")",
";",
"}",
"using",
"(",
"var",
"sw",
"=",
"new",
"StringWriter",
"(",
")",
")",
"{",
"if",
"(",
"templateFormatter",
"is",
"JsonFormatter",
")",
"{",
"sw",
".",
"Write",
"(",
"\"",
"@cee:",
"\"",
")",
";",
"}",
"this",
".",
"templateFormatter",
".",
"Format",
"(",
"logEvent",
",",
"sw",
")",
";",
"return",
"sw",
".",
"ToString",
"(",
")",
";",
"}",
"}",
"}"
] |
Base class for formatters that output Serilog events in syslog formats
|
[
"Base",
"class",
"for",
"formatters",
"that",
"output",
"Serilog",
"events",
"in",
"syslog",
"formats"
] |
[] |
[
{
"param": "ISyslogFormatter",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ISyslogFormatter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "We purposely don't use Serilog's ITextFormatter to format syslog messages, so that users of this library\ncan use their own ITextFormatter instances to control the format of the 'body' part of each message",
"docstring_tokens": [
"We",
"purposely",
"don",
"'",
"t",
"use",
"Serilog",
"'",
"s",
"ITextFormatter",
"to",
"format",
"syslog",
"messages",
"so",
"that",
"users",
"of",
"this",
"library",
"can",
"use",
"their",
"own",
"ITextFormatter",
"instances",
"to",
"control",
"the",
"format",
"of",
"the",
"'",
"body",
"'",
"part",
"of",
"each",
"message"
]
}
]
}
| false
| 14
| 344
| 78
|
75d5da77abd1fffcf0c20be63c1075e31fe1b795
|
googlegenomics/utils-java
|
src/main/java/com/google/cloud/genomics/utils/grpc/GenomicsStreamIterator.java
|
[
"Apache-2.0"
] |
Java
|
GenomicsStreamIterator
|
/**
* An iterator for streaming genomic data via gRPC with support for retries.
*
* Includes complex retry logic to upon failure resume the stream at the last known good start
* position without returning duplicate data.
*
* TODO: refactor this further to simplify the generic signature.
*
* @param <RequestT> Streaming request type.
* @param <ResponseT> Streaming response type.
* @param <ItemT> Genomic data type returned by stream.
* @param <StubT> Blocking stub type.
*/
|
An iterator for streaming genomic data via gRPC with support for retries.
Includes complex retry logic to upon failure resume the stream at the last known good start
position without returning duplicate data.
refactor this further to simplify the generic signature.
@param Streaming request type.
@param Streaming response type.
@param Genomic data type returned by stream.
@param Blocking stub type.
|
[
"An",
"iterator",
"for",
"streaming",
"genomic",
"data",
"via",
"gRPC",
"with",
"support",
"for",
"retries",
".",
"Includes",
"complex",
"retry",
"logic",
"to",
"upon",
"failure",
"resume",
"the",
"stream",
"at",
"the",
"last",
"known",
"good",
"start",
"position",
"without",
"returning",
"duplicate",
"data",
".",
"refactor",
"this",
"further",
"to",
"simplify",
"the",
"generic",
"signature",
".",
"@param",
"Streaming",
"request",
"type",
".",
"@param",
"Streaming",
"response",
"type",
".",
"@param",
"Genomic",
"data",
"type",
"returned",
"by",
"stream",
".",
"@param",
"Blocking",
"stub",
"type",
"."
] |
public abstract class GenomicsStreamIterator<RequestT, ResponseT, ItemT, StubT extends io.grpc.stub.AbstractStub<StubT>>
implements Iterator<ResponseT> {
private static final Logger LOG = Logger.getLogger(GenomicsStreamIterator.class.getName());
protected final ManagedChannel genomicsChannel;
protected final Predicate<ItemT> shardPredicate;
protected final StubT stub;
protected final RequestT originalRequest;
protected ExponentialBackOff backoff;
// Stateful members used to facilitate complex retry behavior for gRPC streams.
private Iterator<ResponseT> delegate;
private ItemT lastSuccessfulDataItem;
private String idSentinel;
/**
* Create a stream iterator that will filter shard data using the predicate, if supplied.
*
* @param channel The channel.
* @param request The request for the shard of data.
* @param shardPredicate A predicate used to client-side filter results returned (e.g., enforce a
* shard boundary and/or limit to SNPs only) or null for no filtering.
*/
protected GenomicsStreamIterator(ManagedChannel channel, RequestT request,
Predicate<ItemT> shardPredicate) {
this.originalRequest = request;
this.shardPredicate = shardPredicate;
this.genomicsChannel = channel;
stub = createStub(genomicsChannel);
// Using default backoff settings. For details, see
// https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.19.0/com/google/api/client/util/ExponentialBackOff
backoff = new ExponentialBackOff.Builder().build();
// RETRY STATE: Initialize settings.
delegate = createIterator(originalRequest);
lastSuccessfulDataItem = null;
idSentinel = null;
}
abstract StubT createStub(ManagedChannel channel);
abstract Iterator<ResponseT> createIteratorFromStub(RequestT request);
abstract long getRequestStart(RequestT streamRequest);
abstract long getDataItemStart(ItemT dataItem);
abstract String getDataItemId(ItemT dataItem);
abstract RequestT getRevisedRequest(long updatedStart);
abstract List<ItemT> getDataList(ResponseT response);
abstract ResponseT buildResponse(ResponseT response, Iterable<ItemT> dataList);
private Iterator<ResponseT> createIterator(RequestT request) {
while (true) {
try {
return createIteratorFromStub(request);
} catch (Exception e) {
if (shouldRetryNow()) {
LOG.log(Level.WARNING, "Retrying after failure to create iterator", e);
} else {
LOG.log(Level.WARNING, "All retries to create iterator consumed, re-throwing exception",
e);
throw e;
}
}
}
}
private boolean shouldRetryNow() {
long backOffMillis;
try {
backOffMillis = backoff.nextBackOffMillis();
} catch (IOException e1) {
// Something strange happened, just give up.
backOffMillis = BackOff.STOP;
}
if (backOffMillis == BackOff.STOP) {
backoff.reset();
return false;
}
try {
Thread.sleep(backOffMillis);
} catch (InterruptedException e) {
LOG.log(Level.WARNING, "Backoff sleep interrupted", e);
}
return true;
}
/**
* @see java.util.Iterator#hasNext()
*/
@Override
public boolean hasNext() {
boolean hasNext;
while (true) {
try {
hasNext = delegate.hasNext();
break;
} catch (Exception e) {
if (shouldRetryNow()) {
LOG.log(Level.WARNING, "Retrying after failing to get next item from stream: ", e);
setStreamStateForRetry();
} else {
LOG.log(Level.WARNING, "All retries to get next item from stream consumed, throwing: ", e);
genomicsChannel.shutdownNow();
throw e;
}
}
}
if (!hasNext) {
genomicsChannel.shutdownNow();
}
return hasNext;
}
private void setStreamStateForRetry() {
if (null == lastSuccessfulDataItem) {
// We have never returned any data. No need to set up state needed to filter previously
// returned results.
delegate = createIterator(originalRequest);
return;
}
if (getRequestStart(originalRequest) < getDataItemStart(lastSuccessfulDataItem)) {
// Create a new iterator at the revised start position.
delegate = createIterator(getRevisedRequest(getDataItemStart(lastSuccessfulDataItem)));
} else {
// The point at which the retry occurred was still within data overlapping the start of our
// original request but not beyond it yet.
delegate = createIterator(originalRequest);
}
// RETRY STATE: Enable the filtering of repeated data in next().
idSentinel = getDataItemId(lastSuccessfulDataItem);
}
/**
* @see java.util.Iterator#next()
*/
@Override
public ResponseT next() {
ResponseT response = delegate.next();
// TODO: Its more clean conceptually to do the same thing for all responses, but this could be a
// place where we're wasting a lot of time rebuilding response objects when nothing has actually
// changed.
return buildResponse(response, enforceShardPredicate(removeRepeatedData(getDataList(response))));
}
private List<ItemT> removeRepeatedData(List<ItemT> dataList) {
List<ItemT> filteredDataList = null;
if (null == idSentinel) {
filteredDataList = dataList;
} else {
// Filter out previously returned data items.
filteredDataList = Lists.newArrayList();
boolean sentinelFound = false;
for (ItemT dataItem : dataList) {
if (sentinelFound) {
filteredDataList.add(dataItem);
} else {
if (idSentinel.equals(getDataItemId(dataItem))) {
// RETRY STATE: We're at the end of the repeated data. Unset the sentinel and proceed.
idSentinel = null;
sentinelFound = true;
}
}
}
}
// RETRY STATE: Keep our last successfully returned data item in memory, just in case we need to
// retry.
if (filteredDataList.size() > 0) {
lastSuccessfulDataItem = filteredDataList.get(filteredDataList.size() - 1);
}
return filteredDataList;
}
private Iterable<ItemT> enforceShardPredicate(Iterable<ItemT> dataList) {
if (null == shardPredicate) {
return dataList;
}
return Iterables.filter(dataList, shardPredicate);
}
/**
* @see java.util.Iterator#remove()
*/
@Override
public void remove() {
delegate.remove();
}
}
|
[
"public",
"abstract",
"class",
"GenomicsStreamIterator",
"<",
"RequestT",
",",
"ResponseT",
",",
"ItemT",
",",
"StubT",
"extends",
"io",
".",
"grpc",
".",
"stub",
".",
"AbstractStub",
"<",
"StubT",
">",
">",
"implements",
"Iterator",
"<",
"ResponseT",
">",
"{",
"private",
"static",
"final",
"Logger",
"LOG",
"=",
"Logger",
".",
"getLogger",
"(",
"GenomicsStreamIterator",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"protected",
"final",
"ManagedChannel",
"genomicsChannel",
";",
"protected",
"final",
"Predicate",
"<",
"ItemT",
">",
"shardPredicate",
";",
"protected",
"final",
"StubT",
"stub",
";",
"protected",
"final",
"RequestT",
"originalRequest",
";",
"protected",
"ExponentialBackOff",
"backoff",
";",
"private",
"Iterator",
"<",
"ResponseT",
">",
"delegate",
";",
"private",
"ItemT",
"lastSuccessfulDataItem",
";",
"private",
"String",
"idSentinel",
";",
"/**\n * Create a stream iterator that will filter shard data using the predicate, if supplied.\n *\n * @param channel The channel.\n * @param request The request for the shard of data.\n * @param shardPredicate A predicate used to client-side filter results returned (e.g., enforce a\n * shard boundary and/or limit to SNPs only) or null for no filtering.\n */",
"protected",
"GenomicsStreamIterator",
"(",
"ManagedChannel",
"channel",
",",
"RequestT",
"request",
",",
"Predicate",
"<",
"ItemT",
">",
"shardPredicate",
")",
"{",
"this",
".",
"originalRequest",
"=",
"request",
";",
"this",
".",
"shardPredicate",
"=",
"shardPredicate",
";",
"this",
".",
"genomicsChannel",
"=",
"channel",
";",
"stub",
"=",
"createStub",
"(",
"genomicsChannel",
")",
";",
"backoff",
"=",
"new",
"ExponentialBackOff",
".",
"Builder",
"(",
")",
".",
"build",
"(",
")",
";",
"delegate",
"=",
"createIterator",
"(",
"originalRequest",
")",
";",
"lastSuccessfulDataItem",
"=",
"null",
";",
"idSentinel",
"=",
"null",
";",
"}",
"abstract",
"StubT",
"createStub",
"(",
"ManagedChannel",
"channel",
")",
";",
"abstract",
"Iterator",
"<",
"ResponseT",
">",
"createIteratorFromStub",
"(",
"RequestT",
"request",
")",
";",
"abstract",
"long",
"getRequestStart",
"(",
"RequestT",
"streamRequest",
")",
";",
"abstract",
"long",
"getDataItemStart",
"(",
"ItemT",
"dataItem",
")",
";",
"abstract",
"String",
"getDataItemId",
"(",
"ItemT",
"dataItem",
")",
";",
"abstract",
"RequestT",
"getRevisedRequest",
"(",
"long",
"updatedStart",
")",
";",
"abstract",
"List",
"<",
"ItemT",
">",
"getDataList",
"(",
"ResponseT",
"response",
")",
";",
"abstract",
"ResponseT",
"buildResponse",
"(",
"ResponseT",
"response",
",",
"Iterable",
"<",
"ItemT",
">",
"dataList",
")",
";",
"private",
"Iterator",
"<",
"ResponseT",
">",
"createIterator",
"(",
"RequestT",
"request",
")",
"{",
"while",
"(",
"true",
")",
"{",
"try",
"{",
"return",
"createIteratorFromStub",
"(",
"request",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"if",
"(",
"shouldRetryNow",
"(",
")",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"",
"Retrying after failure to create iterator",
"\"",
",",
"e",
")",
";",
"}",
"else",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"",
"All retries to create iterator consumed, re-throwing exception",
"\"",
",",
"e",
")",
";",
"throw",
"e",
";",
"}",
"}",
"}",
"}",
"private",
"boolean",
"shouldRetryNow",
"(",
")",
"{",
"long",
"backOffMillis",
";",
"try",
"{",
"backOffMillis",
"=",
"backoff",
".",
"nextBackOffMillis",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e1",
")",
"{",
"backOffMillis",
"=",
"BackOff",
".",
"STOP",
";",
"}",
"if",
"(",
"backOffMillis",
"==",
"BackOff",
".",
"STOP",
")",
"{",
"backoff",
".",
"reset",
"(",
")",
";",
"return",
"false",
";",
"}",
"try",
"{",
"Thread",
".",
"sleep",
"(",
"backOffMillis",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"",
"Backoff sleep interrupted",
"\"",
",",
"e",
")",
";",
"}",
"return",
"true",
";",
"}",
"/**\n * @see java.util.Iterator#hasNext()\n */",
"@",
"Override",
"public",
"boolean",
"hasNext",
"(",
")",
"{",
"boolean",
"hasNext",
";",
"while",
"(",
"true",
")",
"{",
"try",
"{",
"hasNext",
"=",
"delegate",
".",
"hasNext",
"(",
")",
";",
"break",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"if",
"(",
"shouldRetryNow",
"(",
")",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"",
"Retrying after failing to get next item from stream: ",
"\"",
",",
"e",
")",
";",
"setStreamStateForRetry",
"(",
")",
";",
"}",
"else",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"",
"All retries to get next item from stream consumed, throwing: ",
"\"",
",",
"e",
")",
";",
"genomicsChannel",
".",
"shutdownNow",
"(",
")",
";",
"throw",
"e",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"hasNext",
")",
"{",
"genomicsChannel",
".",
"shutdownNow",
"(",
")",
";",
"}",
"return",
"hasNext",
";",
"}",
"private",
"void",
"setStreamStateForRetry",
"(",
")",
"{",
"if",
"(",
"null",
"==",
"lastSuccessfulDataItem",
")",
"{",
"delegate",
"=",
"createIterator",
"(",
"originalRequest",
")",
";",
"return",
";",
"}",
"if",
"(",
"getRequestStart",
"(",
"originalRequest",
")",
"<",
"getDataItemStart",
"(",
"lastSuccessfulDataItem",
")",
")",
"{",
"delegate",
"=",
"createIterator",
"(",
"getRevisedRequest",
"(",
"getDataItemStart",
"(",
"lastSuccessfulDataItem",
")",
")",
")",
";",
"}",
"else",
"{",
"delegate",
"=",
"createIterator",
"(",
"originalRequest",
")",
";",
"}",
"idSentinel",
"=",
"getDataItemId",
"(",
"lastSuccessfulDataItem",
")",
";",
"}",
"/**\n * @see java.util.Iterator#next()\n */",
"@",
"Override",
"public",
"ResponseT",
"next",
"(",
")",
"{",
"ResponseT",
"response",
"=",
"delegate",
".",
"next",
"(",
")",
";",
"return",
"buildResponse",
"(",
"response",
",",
"enforceShardPredicate",
"(",
"removeRepeatedData",
"(",
"getDataList",
"(",
"response",
")",
")",
")",
")",
";",
"}",
"private",
"List",
"<",
"ItemT",
">",
"removeRepeatedData",
"(",
"List",
"<",
"ItemT",
">",
"dataList",
")",
"{",
"List",
"<",
"ItemT",
">",
"filteredDataList",
"=",
"null",
";",
"if",
"(",
"null",
"==",
"idSentinel",
")",
"{",
"filteredDataList",
"=",
"dataList",
";",
"}",
"else",
"{",
"filteredDataList",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"boolean",
"sentinelFound",
"=",
"false",
";",
"for",
"(",
"ItemT",
"dataItem",
":",
"dataList",
")",
"{",
"if",
"(",
"sentinelFound",
")",
"{",
"filteredDataList",
".",
"add",
"(",
"dataItem",
")",
";",
"}",
"else",
"{",
"if",
"(",
"idSentinel",
".",
"equals",
"(",
"getDataItemId",
"(",
"dataItem",
")",
")",
")",
"{",
"idSentinel",
"=",
"null",
";",
"sentinelFound",
"=",
"true",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"filteredDataList",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"lastSuccessfulDataItem",
"=",
"filteredDataList",
".",
"get",
"(",
"filteredDataList",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"}",
"return",
"filteredDataList",
";",
"}",
"private",
"Iterable",
"<",
"ItemT",
">",
"enforceShardPredicate",
"(",
"Iterable",
"<",
"ItemT",
">",
"dataList",
")",
"{",
"if",
"(",
"null",
"==",
"shardPredicate",
")",
"{",
"return",
"dataList",
";",
"}",
"return",
"Iterables",
".",
"filter",
"(",
"dataList",
",",
"shardPredicate",
")",
";",
"}",
"/**\n * @see java.util.Iterator#remove()\n */",
"@",
"Override",
"public",
"void",
"remove",
"(",
")",
"{",
"delegate",
".",
"remove",
"(",
")",
";",
"}",
"}"
] |
An iterator for streaming genomic data via gRPC with support for retries.
|
[
"An",
"iterator",
"for",
"streaming",
"genomic",
"data",
"via",
"gRPC",
"with",
"support",
"for",
"retries",
"."
] |
[
"// Stateful members used to facilitate complex retry behavior for gRPC streams.",
"// Using default backoff settings. For details, see",
"// https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.19.0/com/google/api/client/util/ExponentialBackOff",
"// RETRY STATE: Initialize settings.",
"// Something strange happened, just give up.",
"// We have never returned any data. No need to set up state needed to filter previously",
"// returned results.",
"// Create a new iterator at the revised start position.",
"// The point at which the retry occurred was still within data overlapping the start of our",
"// original request but not beyond it yet.",
"// RETRY STATE: Enable the filtering of repeated data in next().",
"// TODO: Its more clean conceptually to do the same thing for all responses, but this could be a",
"// place where we're wasting a lot of time rebuilding response objects when nothing has actually",
"// changed.",
"// Filter out previously returned data items.",
"// RETRY STATE: We're at the end of the repeated data. Unset the sentinel and proceed.",
"// RETRY STATE: Keep our last successfully returned data item in memory, just in case we need to",
"// retry."
] |
[
{
"param": "Iterator<ResponseT>",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Iterator<ResponseT>",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 17
| 1,437
| 105
|
a5335e3f1b6ace3558139f36b6b71519b14ed288
|
jephbayf1986/DrSproc
|
src/DrSproc.App/EntityMapping/CustomMapper.cs
|
[
"MIT"
] |
C#
|
CustomMapper
|
/// <summary>
/// <b>Custom Mapper</b> <br />
/// Inherit from this class to create a custom mapping from a stored procedure query result to an entity model
/// <para>
/// Declare the return type in the map using the in-built Read**** methods.<br/><br/>
/// <i>Example:</i> <br />
/// <code xml:space="preserve">
/// public override MyClass Map()
/// {
/// return new MyClass()
/// {
/// Id = ReadInt(Id_Lookup, allowNull: false),
/// FirstName = ReadString(FirstName_Loookup),
/// LastName = ReadString(LastName_Loookup),
/// Description = ReadString(Description_Lookup),
/// Height = ReadDecimal(Height_Lookup, allowNull: true, defaultIfNull: Height_DefaultIfNull),
/// Width = ReadNullableDecimal(Width_Lookup),
/// DateOfBirth = ReadNullableDateTime(Dob_Lookup),
/// };
/// }
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">Entity Model to map to</typeparam>
|
Custom Mapper
Inherit from this class to create a custom mapping from a stored procedure query result to an entity model
|
[
"Custom",
"Mapper",
"Inherit",
"from",
"this",
"class",
"to",
"create",
"a",
"custom",
"mapping",
"from",
"a",
"stored",
"procedure",
"query",
"result",
"to",
"an",
"entity",
"model"
] |
public abstract class CustomMapper<T> : IDisposable
{
private IDataReader _dataReader;
private string _storedProcName;
internal void SetReader(IDataReader dataReader)
{
_dataReader = dataReader;
}
internal void SetStoredProcName(string storedProcName)
{
_storedProcName = storedProcName;
}
public abstract T Map();
internal T MapSingle()
{
if (_dataReader.Read())
{
return Map();
}
return default;
}
internal IEnumerable<T> MapMulti()
{
var mappedItems = new List<T>();
while (_dataReader.Read())
{
mappedItems.Add(Map());
}
return mappedItems;
}
protected string ReadString(string fieldName, bool allowNull = true, string defaultIfNull = null)
{
var value = GetField(fieldName);
if (!allowNull && value.IsNull())
ThrowNullError(fieldName);
return value?.ToString() ?? defaultIfNull;
}
protected long ReadLong(string fieldName, bool allowNull = false, long defaultIfNull = default)
{
var value = GetField(fieldName);
if (!allowNull && value.IsNull())
ThrowNullError(fieldName);
if (value.IsNull())
return defaultIfNull;
var isValidType = long.TryParse(value.ToString(), out long result);
if (!isValidType)
throw DrSprocEntityMappingException.FieldOfWrongDataType(_storedProcName, fieldName, typeof(Guid), value.GetType(), value);
return result;
}
protected long? ReadNullableLong(string fieldName)
{
var value = GetField(fieldName);
if (value.IsNull())
return null;
return ReadLong(fieldName);
}
protected int ReadInt(string fieldName, bool allowNull = false, int defaultIfNull = default)
{
var value = GetField(fieldName);
if (!allowNull && value.IsNull())
ThrowNullError(fieldName);
if (value.IsNull())
return defaultIfNull;
var isValidType = int.TryParse(value.ToString(), out int result);
if (!isValidType)
throw DrSprocEntityMappingException.FieldOfWrongDataType(_storedProcName, fieldName, typeof(Guid), value.GetType(), value);
return result;
}
protected int? ReadNullableInt(string fieldName)
{
var value = GetField(fieldName);
if (value.IsNull())
return null;
return ReadInt(fieldName);
}
protected short ReadShort(string fieldName, bool allowNull = false, short defaultIfNull = default)
{
var value = GetField(fieldName);
if (!allowNull && value.IsNull())
ThrowNullError(fieldName);
if (value.IsNull())
return defaultIfNull;
var isValidType = short.TryParse(value.ToString(), out short result);
if (!isValidType)
throw DrSprocEntityMappingException.FieldOfWrongDataType(_storedProcName, fieldName, typeof(Guid), value.GetType(), value);
return result;
}
protected short? ReadNullableShort(string fieldName)
{
var value = GetField(fieldName);
if (value.IsNull())
return null;
return ReadShort(fieldName);
}
protected byte ReadByte(string fieldName, bool allowNull = false, byte defaultIfNull = default)
{
var value = GetField(fieldName);
if (!allowNull && value.IsNull())
ThrowNullError(fieldName);
if (value.IsNull())
return defaultIfNull;
var isValidType = byte.TryParse(value.ToString(), out byte result);
if (!isValidType)
throw DrSprocEntityMappingException.FieldOfWrongDataType(_storedProcName, fieldName, typeof(Guid), value.GetType(), value);
return result;
}
protected byte? ReadNullableByte(string fieldName)
{
var value = GetField(fieldName);
if (value.IsNull())
return null;
return ReadByte(fieldName);
}
protected double ReadDouble(string fieldName, bool allowNull = false, double defaultIfNull = default)
{
var value = GetField(fieldName);
if (!allowNull && value.IsNull())
ThrowNullError(fieldName);
if (value.IsNull())
return defaultIfNull;
var isValidType = double.TryParse(value.ToString(), out double result);
if (!isValidType)
throw DrSprocEntityMappingException.FieldOfWrongDataType(_storedProcName, fieldName, typeof(Guid), value.GetType(), value);
return result;
}
protected double? ReadNullableDouble(string fieldName)
{
var value = GetField(fieldName);
if (value.IsNull())
return null;
return ReadDouble(fieldName);
}
protected decimal ReadDecimal(string fieldName, bool allowNull = false, decimal defaultIfNull = default)
{
var value = GetField(fieldName);
if (!allowNull && value.IsNull())
ThrowNullError(fieldName);
if (value.IsNull())
return defaultIfNull;
var isValidType = decimal.TryParse(value.ToString(), out decimal result);
if (!isValidType)
throw DrSprocEntityMappingException.FieldOfWrongDataType(_storedProcName, fieldName, typeof(Guid), value.GetType(), value);
return result;
}
protected decimal? ReadNullableDecimal(string fieldName)
{
var value = GetField(fieldName);
if (value.IsNull())
return null;
return ReadDecimal(fieldName);
}
protected bool ReadBoolean(string fieldName, bool allowNull = false, bool defaultIfNull = false)
{
var value = GetField(fieldName);
if (!allowNull && value.IsNull())
ThrowNullError(fieldName);
if (value.IsNull())
return defaultIfNull;
var stringVal = value.ToString()
.ToLower()
.Replace("yes", "true")
.Replace("y", "true")
.Replace("no", "false")
.Replace("n", "false");
var isValidType = bool.TryParse(stringVal, out bool result);
if (!isValidType)
throw DrSprocEntityMappingException.FieldOfWrongDataType(_storedProcName, fieldName, typeof(Guid), value.GetType(), value);
return result;
}
protected bool? ReadNullableBoolean(string fieldName)
{
var value = GetField(fieldName);
if (value.IsNull())
return null;
return ReadBoolean(fieldName);
}
protected DateTime ReadDateTime(string fieldName, bool allowNull = false, DateTime defaultIfNull = default)
{
var value = GetField(fieldName);
if (!allowNull && value.IsNull())
ThrowNullError(fieldName);
if (value.IsNull())
return defaultIfNull;
var isValidType = DateTime.TryParse(value.ToString(), out DateTime result);
if (!isValidType)
throw DrSprocEntityMappingException.FieldOfWrongDataType(_storedProcName, fieldName, typeof(Guid), value.GetType(), value);
return result;
}
protected DateTime? ReadNullableDateTime(string fieldName)
{
var value = GetField(fieldName);
if (value.IsNull())
return null;
return ReadDateTime(fieldName);
}
protected Guid ReadGuid(string fieldName, bool generateNewIfNull = false)
{
var value = GetField(fieldName);
if (!generateNewIfNull && value.IsNull())
ThrowNullError(fieldName);
if (value.IsNull())
return new Guid();
var isValidType = Guid.TryParse(value.ToString(), out Guid result);
if (!isValidType)
throw DrSprocEntityMappingException.FieldOfWrongDataType(_storedProcName, fieldName, typeof(Guid), value.GetType(), value);
return result;
}
protected Guid? ReadNullableGuid(string fieldName)
{
var value = GetField(fieldName);
if (value.IsNull())
return null;
return ReadGuid(fieldName);
}
private object GetField(string fieldName)
{
var fieldFound = _dataReader.TryGetField(fieldName, out object value);
if (!fieldFound)
throw DrSprocEntityMappingException.FieldDoesntExist(_storedProcName, fieldName);
return value;
}
private void ThrowNullError(string fieldName)
{
throw DrSprocEntityMappingException.RequiredFieldIsNull(_storedProcName, fieldName);
}
public void Dispose()
{
if (_dataReader != null)
_dataReader.Dispose();
}
}
|
[
"public",
"abstract",
"class",
"CustomMapper",
"<",
"T",
">",
":",
"IDisposable",
"{",
"private",
"IDataReader",
"_dataReader",
";",
"private",
"string",
"_storedProcName",
";",
"internal",
"void",
"SetReader",
"(",
"IDataReader",
"dataReader",
")",
"{",
"_dataReader",
"=",
"dataReader",
";",
"}",
"internal",
"void",
"SetStoredProcName",
"(",
"string",
"storedProcName",
")",
"{",
"_storedProcName",
"=",
"storedProcName",
";",
"}",
"public",
"abstract",
"T",
"Map",
"(",
")",
";",
"internal",
"T",
"MapSingle",
"(",
")",
"{",
"if",
"(",
"_dataReader",
".",
"Read",
"(",
")",
")",
"{",
"return",
"Map",
"(",
")",
";",
"}",
"return",
"default",
";",
"}",
"internal",
"IEnumerable",
"<",
"T",
">",
"MapMulti",
"(",
")",
"{",
"var",
"mappedItems",
"=",
"new",
"List",
"<",
"T",
">",
"(",
")",
";",
"while",
"(",
"_dataReader",
".",
"Read",
"(",
")",
")",
"{",
"mappedItems",
".",
"Add",
"(",
"Map",
"(",
")",
")",
";",
"}",
"return",
"mappedItems",
";",
"}",
"protected",
"string",
"ReadString",
"(",
"string",
"fieldName",
",",
"bool",
"allowNull",
"=",
"true",
",",
"string",
"defaultIfNull",
"=",
"null",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"!",
"allowNull",
"&&",
"value",
".",
"IsNull",
"(",
")",
")",
"ThrowNullError",
"(",
"fieldName",
")",
";",
"return",
"value",
"?",
".",
"ToString",
"(",
")",
"??",
"defaultIfNull",
";",
"}",
"protected",
"long",
"ReadLong",
"(",
"string",
"fieldName",
",",
"bool",
"allowNull",
"=",
"false",
",",
"long",
"defaultIfNull",
"=",
"default",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"!",
"allowNull",
"&&",
"value",
".",
"IsNull",
"(",
")",
")",
"ThrowNullError",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"defaultIfNull",
";",
"var",
"isValidType",
"=",
"long",
".",
"TryParse",
"(",
"value",
".",
"ToString",
"(",
")",
",",
"out",
"long",
"result",
")",
";",
"if",
"(",
"!",
"isValidType",
")",
"throw",
"DrSprocEntityMappingException",
".",
"FieldOfWrongDataType",
"(",
"_storedProcName",
",",
"fieldName",
",",
"typeof",
"(",
"Guid",
")",
",",
"value",
".",
"GetType",
"(",
")",
",",
"value",
")",
";",
"return",
"result",
";",
"}",
"protected",
"long",
"?",
"ReadNullableLong",
"(",
"string",
"fieldName",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"null",
";",
"return",
"ReadLong",
"(",
"fieldName",
")",
";",
"}",
"protected",
"int",
"ReadInt",
"(",
"string",
"fieldName",
",",
"bool",
"allowNull",
"=",
"false",
",",
"int",
"defaultIfNull",
"=",
"default",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"!",
"allowNull",
"&&",
"value",
".",
"IsNull",
"(",
")",
")",
"ThrowNullError",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"defaultIfNull",
";",
"var",
"isValidType",
"=",
"int",
".",
"TryParse",
"(",
"value",
".",
"ToString",
"(",
")",
",",
"out",
"int",
"result",
")",
";",
"if",
"(",
"!",
"isValidType",
")",
"throw",
"DrSprocEntityMappingException",
".",
"FieldOfWrongDataType",
"(",
"_storedProcName",
",",
"fieldName",
",",
"typeof",
"(",
"Guid",
")",
",",
"value",
".",
"GetType",
"(",
")",
",",
"value",
")",
";",
"return",
"result",
";",
"}",
"protected",
"int",
"?",
"ReadNullableInt",
"(",
"string",
"fieldName",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"null",
";",
"return",
"ReadInt",
"(",
"fieldName",
")",
";",
"}",
"protected",
"short",
"ReadShort",
"(",
"string",
"fieldName",
",",
"bool",
"allowNull",
"=",
"false",
",",
"short",
"defaultIfNull",
"=",
"default",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"!",
"allowNull",
"&&",
"value",
".",
"IsNull",
"(",
")",
")",
"ThrowNullError",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"defaultIfNull",
";",
"var",
"isValidType",
"=",
"short",
".",
"TryParse",
"(",
"value",
".",
"ToString",
"(",
")",
",",
"out",
"short",
"result",
")",
";",
"if",
"(",
"!",
"isValidType",
")",
"throw",
"DrSprocEntityMappingException",
".",
"FieldOfWrongDataType",
"(",
"_storedProcName",
",",
"fieldName",
",",
"typeof",
"(",
"Guid",
")",
",",
"value",
".",
"GetType",
"(",
")",
",",
"value",
")",
";",
"return",
"result",
";",
"}",
"protected",
"short",
"?",
"ReadNullableShort",
"(",
"string",
"fieldName",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"null",
";",
"return",
"ReadShort",
"(",
"fieldName",
")",
";",
"}",
"protected",
"byte",
"ReadByte",
"(",
"string",
"fieldName",
",",
"bool",
"allowNull",
"=",
"false",
",",
"byte",
"defaultIfNull",
"=",
"default",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"!",
"allowNull",
"&&",
"value",
".",
"IsNull",
"(",
")",
")",
"ThrowNullError",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"defaultIfNull",
";",
"var",
"isValidType",
"=",
"byte",
".",
"TryParse",
"(",
"value",
".",
"ToString",
"(",
")",
",",
"out",
"byte",
"result",
")",
";",
"if",
"(",
"!",
"isValidType",
")",
"throw",
"DrSprocEntityMappingException",
".",
"FieldOfWrongDataType",
"(",
"_storedProcName",
",",
"fieldName",
",",
"typeof",
"(",
"Guid",
")",
",",
"value",
".",
"GetType",
"(",
")",
",",
"value",
")",
";",
"return",
"result",
";",
"}",
"protected",
"byte",
"?",
"ReadNullableByte",
"(",
"string",
"fieldName",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"null",
";",
"return",
"ReadByte",
"(",
"fieldName",
")",
";",
"}",
"protected",
"double",
"ReadDouble",
"(",
"string",
"fieldName",
",",
"bool",
"allowNull",
"=",
"false",
",",
"double",
"defaultIfNull",
"=",
"default",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"!",
"allowNull",
"&&",
"value",
".",
"IsNull",
"(",
")",
")",
"ThrowNullError",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"defaultIfNull",
";",
"var",
"isValidType",
"=",
"double",
".",
"TryParse",
"(",
"value",
".",
"ToString",
"(",
")",
",",
"out",
"double",
"result",
")",
";",
"if",
"(",
"!",
"isValidType",
")",
"throw",
"DrSprocEntityMappingException",
".",
"FieldOfWrongDataType",
"(",
"_storedProcName",
",",
"fieldName",
",",
"typeof",
"(",
"Guid",
")",
",",
"value",
".",
"GetType",
"(",
")",
",",
"value",
")",
";",
"return",
"result",
";",
"}",
"protected",
"double",
"?",
"ReadNullableDouble",
"(",
"string",
"fieldName",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"null",
";",
"return",
"ReadDouble",
"(",
"fieldName",
")",
";",
"}",
"protected",
"decimal",
"ReadDecimal",
"(",
"string",
"fieldName",
",",
"bool",
"allowNull",
"=",
"false",
",",
"decimal",
"defaultIfNull",
"=",
"default",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"!",
"allowNull",
"&&",
"value",
".",
"IsNull",
"(",
")",
")",
"ThrowNullError",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"defaultIfNull",
";",
"var",
"isValidType",
"=",
"decimal",
".",
"TryParse",
"(",
"value",
".",
"ToString",
"(",
")",
",",
"out",
"decimal",
"result",
")",
";",
"if",
"(",
"!",
"isValidType",
")",
"throw",
"DrSprocEntityMappingException",
".",
"FieldOfWrongDataType",
"(",
"_storedProcName",
",",
"fieldName",
",",
"typeof",
"(",
"Guid",
")",
",",
"value",
".",
"GetType",
"(",
")",
",",
"value",
")",
";",
"return",
"result",
";",
"}",
"protected",
"decimal",
"?",
"ReadNullableDecimal",
"(",
"string",
"fieldName",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"null",
";",
"return",
"ReadDecimal",
"(",
"fieldName",
")",
";",
"}",
"protected",
"bool",
"ReadBoolean",
"(",
"string",
"fieldName",
",",
"bool",
"allowNull",
"=",
"false",
",",
"bool",
"defaultIfNull",
"=",
"false",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"!",
"allowNull",
"&&",
"value",
".",
"IsNull",
"(",
")",
")",
"ThrowNullError",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"defaultIfNull",
";",
"var",
"stringVal",
"=",
"value",
".",
"ToString",
"(",
")",
".",
"ToLower",
"(",
")",
".",
"Replace",
"(",
"\"",
"yes",
"\"",
",",
"\"",
"true",
"\"",
")",
".",
"Replace",
"(",
"\"",
"y",
"\"",
",",
"\"",
"true",
"\"",
")",
".",
"Replace",
"(",
"\"",
"no",
"\"",
",",
"\"",
"false",
"\"",
")",
".",
"Replace",
"(",
"\"",
"n",
"\"",
",",
"\"",
"false",
"\"",
")",
";",
"var",
"isValidType",
"=",
"bool",
".",
"TryParse",
"(",
"stringVal",
",",
"out",
"bool",
"result",
")",
";",
"if",
"(",
"!",
"isValidType",
")",
"throw",
"DrSprocEntityMappingException",
".",
"FieldOfWrongDataType",
"(",
"_storedProcName",
",",
"fieldName",
",",
"typeof",
"(",
"Guid",
")",
",",
"value",
".",
"GetType",
"(",
")",
",",
"value",
")",
";",
"return",
"result",
";",
"}",
"protected",
"bool",
"?",
"ReadNullableBoolean",
"(",
"string",
"fieldName",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"null",
";",
"return",
"ReadBoolean",
"(",
"fieldName",
")",
";",
"}",
"protected",
"DateTime",
"ReadDateTime",
"(",
"string",
"fieldName",
",",
"bool",
"allowNull",
"=",
"false",
",",
"DateTime",
"defaultIfNull",
"=",
"default",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"!",
"allowNull",
"&&",
"value",
".",
"IsNull",
"(",
")",
")",
"ThrowNullError",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"defaultIfNull",
";",
"var",
"isValidType",
"=",
"DateTime",
".",
"TryParse",
"(",
"value",
".",
"ToString",
"(",
")",
",",
"out",
"DateTime",
"result",
")",
";",
"if",
"(",
"!",
"isValidType",
")",
"throw",
"DrSprocEntityMappingException",
".",
"FieldOfWrongDataType",
"(",
"_storedProcName",
",",
"fieldName",
",",
"typeof",
"(",
"Guid",
")",
",",
"value",
".",
"GetType",
"(",
")",
",",
"value",
")",
";",
"return",
"result",
";",
"}",
"protected",
"DateTime",
"?",
"ReadNullableDateTime",
"(",
"string",
"fieldName",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"null",
";",
"return",
"ReadDateTime",
"(",
"fieldName",
")",
";",
"}",
"protected",
"Guid",
"ReadGuid",
"(",
"string",
"fieldName",
",",
"bool",
"generateNewIfNull",
"=",
"false",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"!",
"generateNewIfNull",
"&&",
"value",
".",
"IsNull",
"(",
")",
")",
"ThrowNullError",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"new",
"Guid",
"(",
")",
";",
"var",
"isValidType",
"=",
"Guid",
".",
"TryParse",
"(",
"value",
".",
"ToString",
"(",
")",
",",
"out",
"Guid",
"result",
")",
";",
"if",
"(",
"!",
"isValidType",
")",
"throw",
"DrSprocEntityMappingException",
".",
"FieldOfWrongDataType",
"(",
"_storedProcName",
",",
"fieldName",
",",
"typeof",
"(",
"Guid",
")",
",",
"value",
".",
"GetType",
"(",
")",
",",
"value",
")",
";",
"return",
"result",
";",
"}",
"protected",
"Guid",
"?",
"ReadNullableGuid",
"(",
"string",
"fieldName",
")",
"{",
"var",
"value",
"=",
"GetField",
"(",
"fieldName",
")",
";",
"if",
"(",
"value",
".",
"IsNull",
"(",
")",
")",
"return",
"null",
";",
"return",
"ReadGuid",
"(",
"fieldName",
")",
";",
"}",
"private",
"object",
"GetField",
"(",
"string",
"fieldName",
")",
"{",
"var",
"fieldFound",
"=",
"_dataReader",
".",
"TryGetField",
"(",
"fieldName",
",",
"out",
"object",
"value",
")",
";",
"if",
"(",
"!",
"fieldFound",
")",
"throw",
"DrSprocEntityMappingException",
".",
"FieldDoesntExist",
"(",
"_storedProcName",
",",
"fieldName",
")",
";",
"return",
"value",
";",
"}",
"private",
"void",
"ThrowNullError",
"(",
"string",
"fieldName",
")",
"{",
"throw",
"DrSprocEntityMappingException",
".",
"RequiredFieldIsNull",
"(",
"_storedProcName",
",",
"fieldName",
")",
";",
"}",
"public",
"void",
"Dispose",
"(",
")",
"{",
"if",
"(",
"_dataReader",
"!=",
"null",
")",
"_dataReader",
".",
"Dispose",
"(",
")",
";",
"}",
"}"
] |
Custom Mapper
Inherit from this class to create a custom mapping from a stored procedure query result to an entity model
|
[
"Custom",
"Mapper",
"Inherit",
"from",
"this",
"class",
"to",
"create",
"a",
"custom",
"mapping",
"from",
"a",
"stored",
"procedure",
"query",
"result",
"to",
"an",
"entity",
"model"
] |
[
"/// <summary>",
"/// Map",
"/// </summary>",
"/// <returns>The Entity Desired from Mapping</returns>",
"/// <summary>",
"/// Read a String from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <param name=\"allowNull\">Allow a null value to be used if found</param>",
"/// <param name=\"defaultIfNull\">If nulls found, value to use instead</param>",
"/// <returns>String Generated from Read</returns>",
"/// <summary>",
"/// Read an Long from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <param name=\"allowNull\">Allow a null value to be read if found; value from defaultIfNull is used</param>",
"/// <param name=\"defaultIfNull\">If nulls found, value to use instead</param>",
"/// <returns>Long Generated from Read</returns>",
"/// <summary>",
"/// Read a Nullable Long from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <returns>Nullable Long Generated from Read</returns>",
"/// <summary>",
"/// Read an Int from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <param name=\"allowNull\">Allow a null value to be read if found; value from defaultIfNull is used</param>",
"/// <param name=\"defaultIfNull\">If nulls found, value to use instead</param>",
"/// <returns>Int Generated from Read</returns>",
"/// <summary>",
"/// Read a Nullable Int from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <returns>Nullable Int Generated from Read</returns>",
"/// <summary>",
"/// Read an Short from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <param name=\"allowNull\">Allow a null value to be read if found; value from defaultIfNull is used</param>",
"/// <param name=\"defaultIfNull\">If nulls found, value to use instead</param>",
"/// <returns>Short Generated from Read</returns>",
"/// <summary>",
"/// Read a Nullable Short from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <returns>Nullable Short Generated from Read</returns>",
"/// <summary>",
"/// Read an Byte from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <param name=\"allowNull\">Allow a null value to be read if found; value from defaultIfNull is used</param>",
"/// <param name=\"defaultIfNull\">If nulls found, value to use instead</param>",
"/// <returns>Byte Generated from Read</returns>",
"/// <summary>",
"/// Read a Nullable Byte from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <returns>Nullable Byte Generated from Read</returns>",
"/// <summary>",
"/// Read an Double from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <param name=\"allowNull\">Allow a null value to be read if found; value from defaultIfNull is used</param>",
"/// <param name=\"defaultIfNull\">If nulls found, value to use instead</param>",
"/// <returns>Double Generated from Read</returns>",
"/// <summary>",
"/// Read a Nullable Double from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <returns>Nullable Double Generated from Read</returns>",
"/// <summary>",
"/// Read an Decimal from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <param name=\"allowNull\">Allow a null value to be read if found; value from defaultIfNull is used</param>",
"/// <param name=\"defaultIfNull\">If nulls found, value to use instead</param>",
"/// <returns>Decimal Generated from Read</returns>",
"/// <summary>",
"/// Read a Nullable Decimal from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <returns>Nullable Decimal Generated from Read</returns>",
"/// <summary>",
"/// Read an Boolean from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <param name=\"allowNull\">Allow a null value to be read if found; value from defaultIfNull is used</param>",
"/// <param name=\"defaultIfNull\">If nulls found, value to use instead</param>",
"/// <returns>Boolean Generated from Read</returns>",
"/// <summary>",
"/// Read a Nullable Boolean from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <returns>Nullable Boolean Generated from Read</returns>",
"/// <summary>",
"/// Read an DateTime from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <param name=\"allowNull\">Allow a null value to be read if found; value from defaultIfNull is used</param>",
"/// <param name=\"defaultIfNull\">If nulls found, value to use instead</param>",
"/// <returns>DateTime Generated from Read</returns>",
"/// <summary>",
"/// Read a Nullable DateTime from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <returns>Nullable DateTime Generated from Read</returns>",
"/// <summary>",
"/// Read an Guid from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <param name=\"generateNewIfNull\">Allow Null and generate a new Guid if Null is read</param>",
"/// <returns>Guid Generated from Read</returns>",
"/// <summary>",
"/// Read a Nullable Guid from the Query Result",
"/// </summary>",
"/// <param name=\"fieldName\">The name of the column received</param>",
"/// <returns>Nullable Guid Generated from Read</returns>",
"/// <summary>",
"/// Dispose the Mapper",
"/// </summary>"
] |
[
{
"param": "IDisposable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IDisposable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "typeparam",
"docstring": "Entity Model to map to",
"docstring_tokens": [
"Entity",
"Model",
"to",
"map",
"to"
]
}
]
}
| false
| 20
| 1,704
| 237
|
60ebb03da92903b0dbb829cebdb1e2d8e602b968
|
lapfelix/brew
|
Library/Homebrew/cmd/analytics.rb
|
[
"BSD-2-Clause"
] |
Ruby
|
Homebrew
|
#: * `analytics` [`state`]:
#: Display anonymous user behaviour analytics state.
#: Read more at <https://docs.brew.sh/Analytics>.
#:
#: * `analytics` (`on`|`off`):
#: Turn on/off Homebrew's analytics.
#:
#: * `analytics` `regenerate-uuid`:
#: Regenerate UUID used in Homebrew's analytics.
|
: * `analytics` [`state`]:
: Display anonymous user behaviour analytics state.
: Read more at .
|
[
":",
"*",
"`",
"analytics",
"`",
"[",
"`",
"state",
"`",
"]",
":",
":",
"Display",
"anonymous",
"user",
"behaviour",
"analytics",
"state",
".",
":",
"Read",
"more",
"at",
"."
] |
module Homebrew
module_function
def analytics
config_file = HOMEBREW_REPOSITORY/".git/config"
raise UsageError if ARGV.named.size > 1
case ARGV.named.first
when nil, "state"
analyticsdisabled =
Utils.popen_read("git config --file=#{config_file} --get homebrew.analyticsdisabled").chomp
uuid =
Utils.popen_read("git config --file=#{config_file} --get homebrew.analyticsuuid").chomp
if ENV["HOMEBREW_NO_ANALYTICS"]
puts "Analytics is disabled (by HOMEBREW_NO_ANALYTICS)."
elsif analyticsdisabled == "true"
puts "Analytics is disabled."
else
puts "Analytics is enabled."
puts "UUID: #{uuid}" if uuid.present?
end
when "on"
safe_system "git", "config", "--file=#{config_file}",
"--replace-all", "homebrew.analyticsdisabled", "false"
safe_system "git", "config", "--file=#{config_file}",
"--replace-all", "homebrew.analyticsmessage", "true"
when "off"
safe_system "git", "config", "--file=#{config_file}",
"--replace-all", "homebrew.analyticsdisabled", "true"
system "git", "config", "--file=#{config_file}", "--unset-all", "homebrew.analyticsuuid"
when "regenerate-uuid"
# it will be regenerated in next run.
system "git", "config", "--file=#{config_file}", "--unset-all", "homebrew.analyticsuuid"
else
raise UsageError
end
end
end
|
[
"module",
"Homebrew",
"module_function",
"def",
"analytics",
"config_file",
"=",
"HOMEBREW_REPOSITORY",
"/",
"\".git/config\"",
"raise",
"UsageError",
"if",
"ARGV",
".",
"named",
".",
"size",
">",
"1",
"case",
"ARGV",
".",
"named",
".",
"first",
"when",
"nil",
",",
"\"state\"",
"analyticsdisabled",
"=",
"Utils",
".",
"popen_read",
"(",
"\"git config --file=#{config_file} --get homebrew.analyticsdisabled\"",
")",
".",
"chomp",
"uuid",
"=",
"Utils",
".",
"popen_read",
"(",
"\"git config --file=#{config_file} --get homebrew.analyticsuuid\"",
")",
".",
"chomp",
"if",
"ENV",
"[",
"\"HOMEBREW_NO_ANALYTICS\"",
"]",
"puts",
"\"Analytics is disabled (by HOMEBREW_NO_ANALYTICS).\"",
"elsif",
"analyticsdisabled",
"==",
"\"true\"",
"puts",
"\"Analytics is disabled.\"",
"else",
"puts",
"\"Analytics is enabled.\"",
"puts",
"\"UUID: #{uuid}\"",
"if",
"uuid",
".",
"present?",
"end",
"when",
"\"on\"",
"safe_system",
"\"git\"",
",",
"\"config\"",
",",
"\"--file=#{config_file}\"",
",",
"\"--replace-all\"",
",",
"\"homebrew.analyticsdisabled\"",
",",
"\"false\"",
"safe_system",
"\"git\"",
",",
"\"config\"",
",",
"\"--file=#{config_file}\"",
",",
"\"--replace-all\"",
",",
"\"homebrew.analyticsmessage\"",
",",
"\"true\"",
"when",
"\"off\"",
"safe_system",
"\"git\"",
",",
"\"config\"",
",",
"\"--file=#{config_file}\"",
",",
"\"--replace-all\"",
",",
"\"homebrew.analyticsdisabled\"",
",",
"\"true\"",
"system",
"\"git\"",
",",
"\"config\"",
",",
"\"--file=#{config_file}\"",
",",
"\"--unset-all\"",
",",
"\"homebrew.analyticsuuid\"",
"when",
"\"regenerate-uuid\"",
"system",
"\"git\"",
",",
"\"config\"",
",",
"\"--file=#{config_file}\"",
",",
"\"--unset-all\"",
",",
"\"homebrew.analyticsuuid\"",
"else",
"raise",
"UsageError",
"end",
"end",
"end"
] |
: * `analytics` [`state`]:
: Display anonymous user behaviour analytics state.
|
[
":",
"*",
"`",
"analytics",
"`",
"[",
"`",
"state",
"`",
"]",
":",
":",
"Display",
"anonymous",
"user",
"behaviour",
"analytics",
"state",
"."
] |
[
"# it will be regenerated in next run."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 358
| 87
|
39f1cc2e03f1e8d4a4cbcea5957c96172ced046a
|
moyamo/polygon2square
|
geometry.py
|
[
"MIT"
] |
Python
|
Triangle
|
A class structure for storing and minipulating a triangle.
The trianlge is represented as a 3-tuple of points. Each point is
represented as a 2-tuple of floats, the first element being the
x-coordinate and the second element being the y-coordinate.
Several useful operations can be applied to a triangle such as, rotate,
translate, split across altitude, and rectanglify.
The Triangle (and underlying tuple) should be treated as an immutable
data structure. All methods return a new triangle and do not modify the
existing one.
|
A class structure for storing and minipulating a triangle.
The trianlge is represented as a 3-tuple of points. Each point is
represented as a 2-tuple of floats, the first element being the
x-coordinate and the second element being the y-coordinate.
Several useful operations can be applied to a triangle such as, rotate,
translate, split across altitude, and rectanglify.
The Triangle (and underlying tuple) should be treated as an immutable
data structure. All methods return a new triangle and do not modify the
existing one.
|
[
"A",
"class",
"structure",
"for",
"storing",
"and",
"minipulating",
"a",
"triangle",
".",
"The",
"trianlge",
"is",
"represented",
"as",
"a",
"3",
"-",
"tuple",
"of",
"points",
".",
"Each",
"point",
"is",
"represented",
"as",
"a",
"2",
"-",
"tuple",
"of",
"floats",
"the",
"first",
"element",
"being",
"the",
"x",
"-",
"coordinate",
"and",
"the",
"second",
"element",
"being",
"the",
"y",
"-",
"coordinate",
".",
"Several",
"useful",
"operations",
"can",
"be",
"applied",
"to",
"a",
"triangle",
"such",
"as",
"rotate",
"translate",
"split",
"across",
"altitude",
"and",
"rectanglify",
".",
"The",
"Triangle",
"(",
"and",
"underlying",
"tuple",
")",
"should",
"be",
"treated",
"as",
"an",
"immutable",
"data",
"structure",
".",
"All",
"methods",
"return",
"a",
"new",
"triangle",
"and",
"do",
"not",
"modify",
"the",
"existing",
"one",
"."
] |
class Triangle:
"""A class structure for storing and minipulating a triangle.
The trianlge is represented as a 3-tuple of points. Each point is
represented as a 2-tuple of floats, the first element being the
x-coordinate and the second element being the y-coordinate.
Several useful operations can be applied to a triangle such as, rotate,
translate, split across altitude, and rectanglify.
The Triangle (and underlying tuple) should be treated as an immutable
data structure. All methods return a new triangle and do not modify the
existing one."""
def __init__(self, tpl):
"""tpl is a 3-tuple of coordinates"""
self.points = tpl
def __iter__(self):
"""Returns the tuple of points"""
return iter(self.points)
@property
def segments(self):
"""A list of segments representing the sides of the line.
The ith line will be opposite the ith point
"""
return [LineSegment(self.points[1], self.points[2]),
LineSegment(self.points[0], self.points[2]),
LineSegment(self.points[0], self.points[1])
]
def angle(self, i):
"""Return the angle at the ith point"""
segs = self.segments
a = segs[i].length()
b = segs[(i + 1) % 3].length()
c = segs[(i + 2) % 3].length()
thing = (a**2 - b**2 - c**2)/(-2*b*c)
# Get rid of rounding errors for boundry values
if float_eq(thing, -1):
thing = -1
elif float_eq(thing, 1):
thing = 1
return math.acos(thing)
def largest_angle(self):
"""Return the the number of the point at the largest angle"""
cur_max = 0
big_ang = None
for i in range(len(self.points)):
ang = self.angle(i)
if ang > cur_max:
cur_max = ang
big_ang = i
return big_ang
def area(self):
"""Return area of triangle"""
x0, y0 = self.points[0]
x1, y1 = self.points[1]
x2, y2 = self.points[2]
area = abs(0.5 * ((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)))
return area
def rotate(self, pivot, rangle):
"""Return a new triangle rotate clockwise (by angle) around pivot.
pivot -- A coordinate pair
rangle -- The angle to rotate by in radians"""
new_points = list()
px, py = pivot
for x, y in self.points:
dx, dy = x - px, y - py
current_angle = math.atan2(dy, dx)
total_angle = current_angle - rangle
r = math.hypot(dx, dy)
nx = r*math.cos(total_angle) + px
ny = r*math.sin(total_angle) + py
new_points.append((nx, ny))
return Triangle(tuple(new_points))
def translate(self, translation):
"""Return a new triangle translated by 'translation'"""
tx, ty = translation
new_points = [(x + tx, y + ty) for x, y in self.points]
return Triangle(tuple(new_points))
def to_rightangle(self):
"""Splits the triangle into two right-angled triangles"""
# We need to cut the triangle across the largest angle (in case it's
# obtuse)
p = self.points
big_point = self.largest_angle()
other_points = [(big_point + 1) % 3, (big_point + 2) % 3]
cut = self.segments[big_point].to_line().perpendicular(p[big_point])
new_point = line_intersects_segment(cut, self.segments[big_point])
t1 = Triangle((p[big_point], new_point, p[other_points[0]]))
t2 = Triangle((p[big_point], new_point, p[other_points[1]]))
return (t1, t2)
def split(self, line):
"""Splits the Triangle into two shapes separated by line.
All the points of the first shape will be on the non-negative side of
line. All the points of the second shape will be on the non-positive
side of the line.
"""
sides = [line.side_of_line(p) for p in self.points]
# The whole triangle is on the same side of the line
if sides[0] == sides[1] == sides[2]:
if sides[0] == 1:
return (Shape([self]), Shape([]))
else:
return (Shape([]), Shape([self]))
# The triangle is cut into two, on one vertex
elif sorted(sides) == [-1, 0, 1]:
inverse = [None for i in range(3)]
for i, s in enumerate(sides):
inverse[s % 3] = self.points[i]
base = LineSegment(inverse[1], inverse[2])
basepoint = line_intersects_segment(line, base)
pos_shape = Triangle((basepoint, inverse[0], inverse[1]))
neg_shape = Triangle((basepoint, inverse[0], inverse[2]))
return (Shape([pos_shape]), Shape([neg_shape]))
# Line is "tangent" to triangle
elif 0 in sides:
if 1 in sides:
return (Shape([self]), Shape([]))
elif -1 in sides:
return (Shape([]), Shape([self]))
# Line intersects two segments
else:
segs = self.segments
intersects = (line_intersects_segment(line, s) for s in segs)
intersects = [i for i in intersects if i != None]
assert len(intersects) == 2
sided_points = [[], []]
for i, s in enumerate(sides):
if s == 1:
sided_points[1].append(self.points[i])
elif s == -1:
sided_points[0].append(self.points[i])
if len(sided_points[0]) == 1:
t1 = Triangle((sided_points[0][0], intersects[0], intersects[1]))
t2 = Triangle((sided_points[1][0], intersects[0], intersects[1]))
t3 = Triangle((sided_points[1][0], sided_points[1][1], intersects[0]))
return (Shape([t2, t3]), Shape([t1]))
elif len(sided_points[1]) == 1:
t1 = Triangle((sided_points[1][0], intersects[0], intersects[1]))
t2 = Triangle((sided_points[0][0], intersects[0], intersects[1]))
t3 = Triangle((sided_points[0][0], sided_points[0][1], intersects[0]))
return (Shape([t1]), Shape([t2, t3]))
else:
raise Exception("Segments missing")
|
[
"class",
"Triangle",
":",
"def",
"__init__",
"(",
"self",
",",
"tpl",
")",
":",
"\"\"\"tpl is a 3-tuple of coordinates\"\"\"",
"self",
".",
"points",
"=",
"tpl",
"def",
"__iter__",
"(",
"self",
")",
":",
"\"\"\"Returns the tuple of points\"\"\"",
"return",
"iter",
"(",
"self",
".",
"points",
")",
"@",
"property",
"def",
"segments",
"(",
"self",
")",
":",
"\"\"\"A list of segments representing the sides of the line.\n \n The ith line will be opposite the ith point\n \"\"\"",
"return",
"[",
"LineSegment",
"(",
"self",
".",
"points",
"[",
"1",
"]",
",",
"self",
".",
"points",
"[",
"2",
"]",
")",
",",
"LineSegment",
"(",
"self",
".",
"points",
"[",
"0",
"]",
",",
"self",
".",
"points",
"[",
"2",
"]",
")",
",",
"LineSegment",
"(",
"self",
".",
"points",
"[",
"0",
"]",
",",
"self",
".",
"points",
"[",
"1",
"]",
")",
"]",
"def",
"angle",
"(",
"self",
",",
"i",
")",
":",
"\"\"\"Return the angle at the ith point\"\"\"",
"segs",
"=",
"self",
".",
"segments",
"a",
"=",
"segs",
"[",
"i",
"]",
".",
"length",
"(",
")",
"b",
"=",
"segs",
"[",
"(",
"i",
"+",
"1",
")",
"%",
"3",
"]",
".",
"length",
"(",
")",
"c",
"=",
"segs",
"[",
"(",
"i",
"+",
"2",
")",
"%",
"3",
"]",
".",
"length",
"(",
")",
"thing",
"=",
"(",
"a",
"**",
"2",
"-",
"b",
"**",
"2",
"-",
"c",
"**",
"2",
")",
"/",
"(",
"-",
"2",
"*",
"b",
"*",
"c",
")",
"if",
"float_eq",
"(",
"thing",
",",
"-",
"1",
")",
":",
"thing",
"=",
"-",
"1",
"elif",
"float_eq",
"(",
"thing",
",",
"1",
")",
":",
"thing",
"=",
"1",
"return",
"math",
".",
"acos",
"(",
"thing",
")",
"def",
"largest_angle",
"(",
"self",
")",
":",
"\"\"\"Return the the number of the point at the largest angle\"\"\"",
"cur_max",
"=",
"0",
"big_ang",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"points",
")",
")",
":",
"ang",
"=",
"self",
".",
"angle",
"(",
"i",
")",
"if",
"ang",
">",
"cur_max",
":",
"cur_max",
"=",
"ang",
"big_ang",
"=",
"i",
"return",
"big_ang",
"def",
"area",
"(",
"self",
")",
":",
"\"\"\"Return area of triangle\"\"\"",
"x0",
",",
"y0",
"=",
"self",
".",
"points",
"[",
"0",
"]",
"x1",
",",
"y1",
"=",
"self",
".",
"points",
"[",
"1",
"]",
"x2",
",",
"y2",
"=",
"self",
".",
"points",
"[",
"2",
"]",
"area",
"=",
"abs",
"(",
"0.5",
"*",
"(",
"(",
"x1",
"-",
"x0",
")",
"*",
"(",
"y2",
"-",
"y0",
")",
"-",
"(",
"x2",
"-",
"x0",
")",
"*",
"(",
"y1",
"-",
"y0",
")",
")",
")",
"return",
"area",
"def",
"rotate",
"(",
"self",
",",
"pivot",
",",
"rangle",
")",
":",
"\"\"\"Return a new triangle rotate clockwise (by angle) around pivot.\n \n pivot -- A coordinate pair\n rangle -- The angle to rotate by in radians\"\"\"",
"new_points",
"=",
"list",
"(",
")",
"px",
",",
"py",
"=",
"pivot",
"for",
"x",
",",
"y",
"in",
"self",
".",
"points",
":",
"dx",
",",
"dy",
"=",
"x",
"-",
"px",
",",
"y",
"-",
"py",
"current_angle",
"=",
"math",
".",
"atan2",
"(",
"dy",
",",
"dx",
")",
"total_angle",
"=",
"current_angle",
"-",
"rangle",
"r",
"=",
"math",
".",
"hypot",
"(",
"dx",
",",
"dy",
")",
"nx",
"=",
"r",
"*",
"math",
".",
"cos",
"(",
"total_angle",
")",
"+",
"px",
"ny",
"=",
"r",
"*",
"math",
".",
"sin",
"(",
"total_angle",
")",
"+",
"py",
"new_points",
".",
"append",
"(",
"(",
"nx",
",",
"ny",
")",
")",
"return",
"Triangle",
"(",
"tuple",
"(",
"new_points",
")",
")",
"def",
"translate",
"(",
"self",
",",
"translation",
")",
":",
"\"\"\"Return a new triangle translated by 'translation'\"\"\"",
"tx",
",",
"ty",
"=",
"translation",
"new_points",
"=",
"[",
"(",
"x",
"+",
"tx",
",",
"y",
"+",
"ty",
")",
"for",
"x",
",",
"y",
"in",
"self",
".",
"points",
"]",
"return",
"Triangle",
"(",
"tuple",
"(",
"new_points",
")",
")",
"def",
"to_rightangle",
"(",
"self",
")",
":",
"\"\"\"Splits the triangle into two right-angled triangles\"\"\"",
"p",
"=",
"self",
".",
"points",
"big_point",
"=",
"self",
".",
"largest_angle",
"(",
")",
"other_points",
"=",
"[",
"(",
"big_point",
"+",
"1",
")",
"%",
"3",
",",
"(",
"big_point",
"+",
"2",
")",
"%",
"3",
"]",
"cut",
"=",
"self",
".",
"segments",
"[",
"big_point",
"]",
".",
"to_line",
"(",
")",
".",
"perpendicular",
"(",
"p",
"[",
"big_point",
"]",
")",
"new_point",
"=",
"line_intersects_segment",
"(",
"cut",
",",
"self",
".",
"segments",
"[",
"big_point",
"]",
")",
"t1",
"=",
"Triangle",
"(",
"(",
"p",
"[",
"big_point",
"]",
",",
"new_point",
",",
"p",
"[",
"other_points",
"[",
"0",
"]",
"]",
")",
")",
"t2",
"=",
"Triangle",
"(",
"(",
"p",
"[",
"big_point",
"]",
",",
"new_point",
",",
"p",
"[",
"other_points",
"[",
"1",
"]",
"]",
")",
")",
"return",
"(",
"t1",
",",
"t2",
")",
"def",
"split",
"(",
"self",
",",
"line",
")",
":",
"\"\"\"Splits the Triangle into two shapes separated by line.\n\n All the points of the first shape will be on the non-negative side of\n line. All the points of the second shape will be on the non-positive\n side of the line.\n \"\"\"",
"sides",
"=",
"[",
"line",
".",
"side_of_line",
"(",
"p",
")",
"for",
"p",
"in",
"self",
".",
"points",
"]",
"if",
"sides",
"[",
"0",
"]",
"==",
"sides",
"[",
"1",
"]",
"==",
"sides",
"[",
"2",
"]",
":",
"if",
"sides",
"[",
"0",
"]",
"==",
"1",
":",
"return",
"(",
"Shape",
"(",
"[",
"self",
"]",
")",
",",
"Shape",
"(",
"[",
"]",
")",
")",
"else",
":",
"return",
"(",
"Shape",
"(",
"[",
"]",
")",
",",
"Shape",
"(",
"[",
"self",
"]",
")",
")",
"elif",
"sorted",
"(",
"sides",
")",
"==",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
":",
"inverse",
"=",
"[",
"None",
"for",
"i",
"in",
"range",
"(",
"3",
")",
"]",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"sides",
")",
":",
"inverse",
"[",
"s",
"%",
"3",
"]",
"=",
"self",
".",
"points",
"[",
"i",
"]",
"base",
"=",
"LineSegment",
"(",
"inverse",
"[",
"1",
"]",
",",
"inverse",
"[",
"2",
"]",
")",
"basepoint",
"=",
"line_intersects_segment",
"(",
"line",
",",
"base",
")",
"pos_shape",
"=",
"Triangle",
"(",
"(",
"basepoint",
",",
"inverse",
"[",
"0",
"]",
",",
"inverse",
"[",
"1",
"]",
")",
")",
"neg_shape",
"=",
"Triangle",
"(",
"(",
"basepoint",
",",
"inverse",
"[",
"0",
"]",
",",
"inverse",
"[",
"2",
"]",
")",
")",
"return",
"(",
"Shape",
"(",
"[",
"pos_shape",
"]",
")",
",",
"Shape",
"(",
"[",
"neg_shape",
"]",
")",
")",
"elif",
"0",
"in",
"sides",
":",
"if",
"1",
"in",
"sides",
":",
"return",
"(",
"Shape",
"(",
"[",
"self",
"]",
")",
",",
"Shape",
"(",
"[",
"]",
")",
")",
"elif",
"-",
"1",
"in",
"sides",
":",
"return",
"(",
"Shape",
"(",
"[",
"]",
")",
",",
"Shape",
"(",
"[",
"self",
"]",
")",
")",
"else",
":",
"segs",
"=",
"self",
".",
"segments",
"intersects",
"=",
"(",
"line_intersects_segment",
"(",
"line",
",",
"s",
")",
"for",
"s",
"in",
"segs",
")",
"intersects",
"=",
"[",
"i",
"for",
"i",
"in",
"intersects",
"if",
"i",
"!=",
"None",
"]",
"assert",
"len",
"(",
"intersects",
")",
"==",
"2",
"sided_points",
"=",
"[",
"[",
"]",
",",
"[",
"]",
"]",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"sides",
")",
":",
"if",
"s",
"==",
"1",
":",
"sided_points",
"[",
"1",
"]",
".",
"append",
"(",
"self",
".",
"points",
"[",
"i",
"]",
")",
"elif",
"s",
"==",
"-",
"1",
":",
"sided_points",
"[",
"0",
"]",
".",
"append",
"(",
"self",
".",
"points",
"[",
"i",
"]",
")",
"if",
"len",
"(",
"sided_points",
"[",
"0",
"]",
")",
"==",
"1",
":",
"t1",
"=",
"Triangle",
"(",
"(",
"sided_points",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"intersects",
"[",
"0",
"]",
",",
"intersects",
"[",
"1",
"]",
")",
")",
"t2",
"=",
"Triangle",
"(",
"(",
"sided_points",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"intersects",
"[",
"0",
"]",
",",
"intersects",
"[",
"1",
"]",
")",
")",
"t3",
"=",
"Triangle",
"(",
"(",
"sided_points",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"sided_points",
"[",
"1",
"]",
"[",
"1",
"]",
",",
"intersects",
"[",
"0",
"]",
")",
")",
"return",
"(",
"Shape",
"(",
"[",
"t2",
",",
"t3",
"]",
")",
",",
"Shape",
"(",
"[",
"t1",
"]",
")",
")",
"elif",
"len",
"(",
"sided_points",
"[",
"1",
"]",
")",
"==",
"1",
":",
"t1",
"=",
"Triangle",
"(",
"(",
"sided_points",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"intersects",
"[",
"0",
"]",
",",
"intersects",
"[",
"1",
"]",
")",
")",
"t2",
"=",
"Triangle",
"(",
"(",
"sided_points",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"intersects",
"[",
"0",
"]",
",",
"intersects",
"[",
"1",
"]",
")",
")",
"t3",
"=",
"Triangle",
"(",
"(",
"sided_points",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"sided_points",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"intersects",
"[",
"0",
"]",
")",
")",
"return",
"(",
"Shape",
"(",
"[",
"t1",
"]",
")",
",",
"Shape",
"(",
"[",
"t2",
",",
"t3",
"]",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Segments missing\"",
")"
] |
A class structure for storing and minipulating a triangle.
|
[
"A",
"class",
"structure",
"for",
"storing",
"and",
"minipulating",
"a",
"triangle",
"."
] |
[
"\"\"\"A class structure for storing and minipulating a triangle.\n\n The trianlge is represented as a 3-tuple of points. Each point is\n represented as a 2-tuple of floats, the first element being the\n x-coordinate and the second element being the y-coordinate.\n\n Several useful operations can be applied to a triangle such as, rotate,\n translate, split across altitude, and rectanglify.\n\n The Triangle (and underlying tuple) should be treated as an immutable\n data structure. All methods return a new triangle and do not modify the\n existing one.\"\"\"",
"\"\"\"tpl is a 3-tuple of coordinates\"\"\"",
"\"\"\"Returns the tuple of points\"\"\"",
"\"\"\"A list of segments representing the sides of the line.\n \n The ith line will be opposite the ith point\n \"\"\"",
"\"\"\"Return the angle at the ith point\"\"\"",
"# Get rid of rounding errors for boundry values",
"\"\"\"Return the the number of the point at the largest angle\"\"\"",
"\"\"\"Return area of triangle\"\"\"",
"\"\"\"Return a new triangle rotate clockwise (by angle) around pivot.\n \n pivot -- A coordinate pair\n rangle -- The angle to rotate by in radians\"\"\"",
"\"\"\"Return a new triangle translated by 'translation'\"\"\"",
"\"\"\"Splits the triangle into two right-angled triangles\"\"\"",
"# We need to cut the triangle across the largest angle (in case it's",
"# obtuse)",
"\"\"\"Splits the Triangle into two shapes separated by line.\n\n All the points of the first shape will be on the non-negative side of\n line. All the points of the second shape will be on the non-positive\n side of the line.\n \"\"\"",
"# The whole triangle is on the same side of the line",
"# The triangle is cut into two, on one vertex",
"# Line is \"tangent\" to triangle",
"# Line intersects two segments"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 18
| 1,589
| 124
|
aac2f6b2c27a6c1a4990ba1cbfc0c060ea1f9b6a
|
maptube/Harmony
|
QUANT/GTFSFile.py
|
[
"MIT"
] |
Python
|
GTFSFile
|
Splits a string containing comma separated data and returns the elements as an array of strings.
Quotes can be used around items containing a comma.
These quotes are removed from the string array that is returned.
<param name="line">The CSV line string to be split</param>
<returns>Array of strings containing the comma separated elements in the CSV file line</returns>
|
Splits a string containing comma separated data and returns the elements as an array of strings.
Quotes can be used around items containing a comma.
These quotes are removed from the string array that is returned.
The CSV line string to be split
Array of strings containing the comma separated elements in the CSV file line
|
[
"Splits",
"a",
"string",
"containing",
"comma",
"separated",
"data",
"and",
"returns",
"the",
"elements",
"as",
"an",
"array",
"of",
"strings",
".",
"Quotes",
"can",
"be",
"used",
"around",
"items",
"containing",
"a",
"comma",
".",
"These",
"quotes",
"are",
"removed",
"from",
"the",
"string",
"array",
"that",
"is",
"returned",
".",
"The",
"CSV",
"line",
"string",
"to",
"be",
"split",
"Array",
"of",
"strings",
"containing",
"the",
"comma",
"separated",
"elements",
"in",
"the",
"CSV",
"file",
"line"
] |
class GTFSFile:
# <summary>
# Load a GTFS file. Filename must be a zip file.
# </summary>
# <param name="Filename"></param>
def __init__(self, Filename):
self.CurrentFilename = Filename
self.Routes = {} #from routes.txt
self.Stops = {} #from stops.txt
self.Trips = {} #from trips.txt
self.StopTimes = {} #from stop_times.txt
with zipfile.ZipFile(Filename,'r') as zip:
#load routes from routes.txt inside zip file
with zip.open('routes.txt') as routestxt:
self.ParseRoutes(routestxt)
#load stop points from stops.txt inside zip file
with zip.open('stops.txt') as stopstxt:
self.ParseStops(stopstxt)
#trips
with zip.open('trips.txt') as tripstxt:
self.ParseTrips(tripstxt)
#stop_times
with zip.open('stop_times.txt') as stoptimestxt:
self.ParseStopTimes(stoptimestxt)
#with ZipFile
################################################################################
"""
Splits a string containing comma separated data and returns the elements as an array of strings.
Quotes can be used around items containing a comma.
These quotes are removed from the string array that is returned.
<param name="line">The CSV line string to be split</param>
<returns>Array of strings containing the comma separated elements in the CSV file line</returns>
"""
def ParseCSVLine(self, line):
Items = []
Current = ""
Quote = False
for ch in line:
if ch==',':
if not Quote:
Items.append(Current.strip())
Current = ""
else:
Current += "," #comma inside a quote
elif ch=='"':
Quote = not Quote
else:
Current += ch
#end if ch==','
#end for ch in line
Items.append(Current.strip()) #add trailing item - even if last char was a comma, we still want a null on the end
return Items
################################################################################
# <summary>
# routes.txt
# NOTE: defaults to rail if no route_type found
# </summary>
# <param name="reader"></param>
def ParseRoutes(self, reader):
#route_id,agency_id,route_short_name,route_long_name,route_desc,route_type,route_url,route_color,route_text_color
#1-BAK-_-y05-400122,OId_LUL,Bakerloo,,Elephant & Castle - Queen's Park - Harrow & Wealdstone,1,,,
self.Routes = {}
Line = reader.readline().decode('utf-8') #skip header
Headers = self.ParseCSVLine(Line)
HeaderLookup = {}
for idx, Header in enumerate(Headers):
HeaderLookup[Header]=idx
for Line in reader:
Line = Line.decode('utf-8') #this is nasty - the weakly typed language returns a byte array, which it then tries to parse as a string, including the leading b' meaning bytes!
Fields = self.ParseCSVLine(Line)
RouteId = Fields[HeaderLookup['route_id']]
#AgencyId = Fields[HeaderLookup['agency_id']] #not in OASA data
AgencyId = "OASA" #HACK!
RouteShortName = Fields[HeaderLookup['route_short_name']]
RouteLongName = Fields[HeaderLookup['route_long_name']]
if 'route_desc' in HeaderLookup:
RouteDesc = Fields[HeaderLookup['route_desc']]
else:
RouteDesc=''
try:
RouteType = int(Fields[HeaderLookup['route_type']])
except ValueError as verr:
RouteType = GTFSRouteType.Rail
try:
self.Routes[RouteId] = GTFSRoute(RouteId, AgencyId, RouteShortName, RouteLongName, RouteDesc, RouteType)
except Exception as e:
print('Error: routes.txt ' + self.CurrentFilename + ', ' + Line + ' ' + e)
#end for
################################################################################
# <summary>
# reader points to a stops.txt file, which is read to extract stop locations and populate this.StopPoints.
# </summary>
# <param name="reader"></param>
def ParseStops(self, reader):
#stops.txt
#stop_id,stop_name,stop_desc,stop_lat,stop_lon,zone_id,stop_url
#9400ZZLUHAW1,"Wealdstone, Harrow & Wealdstone Station",,51.5923316813,-0.3354040827,,
#9400ZZLUKEN2,"Kenton (London), Kenton",,51.5822158642,-0.3171684662,,
#self.Stops = {}
#Line = reader.readline() #skip header
#for Line in reader:
# Line = Line.decode('utf-8')
# Fields = self.ParseCSVLine(Line)
# Code = Fields[0]
# Name = Fields[1]
# try:
# Lat = float(Fields[3])
# Lon = float(Fields[4])
# if not Code in self.Stops:
# self.Stops[Code] = GTFSStop(Code,Name,Lat, Lon)
# except Exception as e:
# print('Error: stops.txt ' + self.CurrentFilename + ', ' + str(Line) + ', ' + str(e))
# #end try except
##end for
#
#better code (python)
dfStops = pd.read_csv(reader, dtype={'stop_id': str, 'stop_name': str})
for index, row in dfStops.iterrows():
#NOTE: MUST have the str() on the Code and Name for Python as they can use numbers! Weak typing mess!
Code = row["stop_id"] #or stop_code?
Name = row["stop_name"]
try:
Lat = float(row["stop_lat"])
Lon = float(row["stop_lon"])
if not Code in self.Stops:
self.Stops[Code] = GTFSStop(Code, Name, Lat, Lon)
except Exception as e:
Line = row[:].to_string(header=False, index=False)
print('Error: stops.txt ' + self.CurrentFilename + ', ' + Line + ', ' + str(e))
#end try except
#end for iterrows
print("ParseStops loaded "+str(len(self.Stops))+" stops")
################################################################################
# <summary>
# Reader points to a trips.txt file.
# </summary>
# <param name="reader"></param>
def ParseTrips(self, reader):
#route_id,service_id,trip_id,trip_headsign,direction_id,block_id,shape_id
#3-E10-_-y05-41620,3-E10-_-y05-41620,VJ_3-E10-_-y05-41620-1-MF@05:20:00,Islip Manor Road - Ealing Broadway Station / Haven Green,0,,
#3-E10-_-y05-41620,3-E10-_-y05-41620,VJ_3-E10-_-y05-41620-2-MF@05:22:00,Haven Green / Ealing Broadway - Islip Manor Road,1,,
self.Trips = {}
Line = reader.readline() #skip header
for Line in reader:
Line = Line.decode('utf-8')
Fields = self.ParseCSVLine(Line)
RouteId = Fields[0]
ServiceId = Fields[1]
TripId = Fields[2]
TripHeadsign = Fields[3]
try:
if not TripId in self.Trips:
self.Trips[TripId] = GTFSTrip(RouteId,ServiceId,TripId,TripHeadsign)
except Exception as e:
print('Error: trips.txt ' + self.CurrentFilename + ', ' + Line + ', ' + e)
#end for
################################################################################
# <summary>
# Parses a GTFS time code string, taking into account the fact that it might be of the form 24:49:00.
# Arbitrarily sets all times to have a base date of 1 Jan 1970, so any hours>=24 will be set to the 2nd Jan.
# </summary>
# <param name="strTime"></param>
# <returns></returns>
def ParseGTFSTime(self, strTime):
Fields = strTime.split(':')
HH = int(Fields[0])
MM = int(Fields[1])
SS = int(Fields[2])
Over24 = False
if (HH >= 24):
Over24 = True
HH -= 24
#end
DT = datetime(1970,1,1,HH,MM,SS)
if Over24:
DT = DT + timedelta(hours=24)
return DT
################################################################################
def ParseStopTimes(self, reader):
#trip_id,arrival_time,departure_time,stop_id,stop_sequence,stop_headsign,pickup_type,drop_off_type,shape_dist_traveled
#VJ_3-E10-_-y05-41620-1-MF@05:20:00,05:20:00,05:20:00,490008519N,1,,0,0,
#VJ_3-E10-_-y05-41620-1-MF@05:20:00,05:20:00,05:20:00,490009557N,2,,0,0,
self.StopTimes = {}
Line = reader.readline() #skip header
for Line in reader:
Line = Line.decode('utf-8')
Fields = self.ParseCSVLine(Line)
try:
TripId = Fields[0]
#Annoyingly, you get some times recorded as 24:49:00, which is obviously over 24 hours. This is on services that run across midnight so you can tell it's not going backwards in time.
#Need to filter this out though.
#DateTime ArrivalTime = DateTime.Parse(Fields[1]); //DateTime - only the time is used, Date defaults to today
#DateTime DepartureTime = DateTime.Parse(Fields[2]); //DateTime
ArrivalTime = self.ParseGTFSTime(Fields[1])
DepartureTime = self.ParseGTFSTime(Fields[2])
StopId = Fields[3]
StopSequence = int(Fields[4])
if not TripId in self.StopTimes: #create a new TripId sequence
self.StopTimes[TripId] = []
#end if
#push new stop onto end of TripId sequence
self.StopTimes[TripId].append(GTFSStopTime(TripId, ArrivalTime, DepartureTime, StopId, StopSequence))
except Exception as e:
print('Error: stop_times.txt ' + self.CurrentFilename + ', ' + Line + ', ' + e)
#end try except
#end for
|
[
"class",
"GTFSFile",
":",
"def",
"__init__",
"(",
"self",
",",
"Filename",
")",
":",
"self",
".",
"CurrentFilename",
"=",
"Filename",
"self",
".",
"Routes",
"=",
"{",
"}",
"self",
".",
"Stops",
"=",
"{",
"}",
"self",
".",
"Trips",
"=",
"{",
"}",
"self",
".",
"StopTimes",
"=",
"{",
"}",
"with",
"zipfile",
".",
"ZipFile",
"(",
"Filename",
",",
"'r'",
")",
"as",
"zip",
":",
"with",
"zip",
".",
"open",
"(",
"'routes.txt'",
")",
"as",
"routestxt",
":",
"self",
".",
"ParseRoutes",
"(",
"routestxt",
")",
"with",
"zip",
".",
"open",
"(",
"'stops.txt'",
")",
"as",
"stopstxt",
":",
"self",
".",
"ParseStops",
"(",
"stopstxt",
")",
"with",
"zip",
".",
"open",
"(",
"'trips.txt'",
")",
"as",
"tripstxt",
":",
"self",
".",
"ParseTrips",
"(",
"tripstxt",
")",
"with",
"zip",
".",
"open",
"(",
"'stop_times.txt'",
")",
"as",
"stoptimestxt",
":",
"self",
".",
"ParseStopTimes",
"(",
"stoptimestxt",
")",
"def",
"ParseCSVLine",
"(",
"self",
",",
"line",
")",
":",
"Items",
"=",
"[",
"]",
"Current",
"=",
"\"\"",
"Quote",
"=",
"False",
"for",
"ch",
"in",
"line",
":",
"if",
"ch",
"==",
"','",
":",
"if",
"not",
"Quote",
":",
"Items",
".",
"append",
"(",
"Current",
".",
"strip",
"(",
")",
")",
"Current",
"=",
"\"\"",
"else",
":",
"Current",
"+=",
"\",\"",
"elif",
"ch",
"==",
"'\"'",
":",
"Quote",
"=",
"not",
"Quote",
"else",
":",
"Current",
"+=",
"ch",
"Items",
".",
"append",
"(",
"Current",
".",
"strip",
"(",
")",
")",
"return",
"Items",
"def",
"ParseRoutes",
"(",
"self",
",",
"reader",
")",
":",
"self",
".",
"Routes",
"=",
"{",
"}",
"Line",
"=",
"reader",
".",
"readline",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"Headers",
"=",
"self",
".",
"ParseCSVLine",
"(",
"Line",
")",
"HeaderLookup",
"=",
"{",
"}",
"for",
"idx",
",",
"Header",
"in",
"enumerate",
"(",
"Headers",
")",
":",
"HeaderLookup",
"[",
"Header",
"]",
"=",
"idx",
"for",
"Line",
"in",
"reader",
":",
"Line",
"=",
"Line",
".",
"decode",
"(",
"'utf-8'",
")",
"Fields",
"=",
"self",
".",
"ParseCSVLine",
"(",
"Line",
")",
"RouteId",
"=",
"Fields",
"[",
"HeaderLookup",
"[",
"'route_id'",
"]",
"]",
"AgencyId",
"=",
"\"OASA\"",
"RouteShortName",
"=",
"Fields",
"[",
"HeaderLookup",
"[",
"'route_short_name'",
"]",
"]",
"RouteLongName",
"=",
"Fields",
"[",
"HeaderLookup",
"[",
"'route_long_name'",
"]",
"]",
"if",
"'route_desc'",
"in",
"HeaderLookup",
":",
"RouteDesc",
"=",
"Fields",
"[",
"HeaderLookup",
"[",
"'route_desc'",
"]",
"]",
"else",
":",
"RouteDesc",
"=",
"''",
"try",
":",
"RouteType",
"=",
"int",
"(",
"Fields",
"[",
"HeaderLookup",
"[",
"'route_type'",
"]",
"]",
")",
"except",
"ValueError",
"as",
"verr",
":",
"RouteType",
"=",
"GTFSRouteType",
".",
"Rail",
"try",
":",
"self",
".",
"Routes",
"[",
"RouteId",
"]",
"=",
"GTFSRoute",
"(",
"RouteId",
",",
"AgencyId",
",",
"RouteShortName",
",",
"RouteLongName",
",",
"RouteDesc",
",",
"RouteType",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"'Error: routes.txt '",
"+",
"self",
".",
"CurrentFilename",
"+",
"', '",
"+",
"Line",
"+",
"' '",
"+",
"e",
")",
"def",
"ParseStops",
"(",
"self",
",",
"reader",
")",
":",
"dfStops",
"=",
"pd",
".",
"read_csv",
"(",
"reader",
",",
"dtype",
"=",
"{",
"'stop_id'",
":",
"str",
",",
"'stop_name'",
":",
"str",
"}",
")",
"for",
"index",
",",
"row",
"in",
"dfStops",
".",
"iterrows",
"(",
")",
":",
"Code",
"=",
"row",
"[",
"\"stop_id\"",
"]",
"Name",
"=",
"row",
"[",
"\"stop_name\"",
"]",
"try",
":",
"Lat",
"=",
"float",
"(",
"row",
"[",
"\"stop_lat\"",
"]",
")",
"Lon",
"=",
"float",
"(",
"row",
"[",
"\"stop_lon\"",
"]",
")",
"if",
"not",
"Code",
"in",
"self",
".",
"Stops",
":",
"self",
".",
"Stops",
"[",
"Code",
"]",
"=",
"GTFSStop",
"(",
"Code",
",",
"Name",
",",
"Lat",
",",
"Lon",
")",
"except",
"Exception",
"as",
"e",
":",
"Line",
"=",
"row",
"[",
":",
"]",
".",
"to_string",
"(",
"header",
"=",
"False",
",",
"index",
"=",
"False",
")",
"print",
"(",
"'Error: stops.txt '",
"+",
"self",
".",
"CurrentFilename",
"+",
"', '",
"+",
"Line",
"+",
"', '",
"+",
"str",
"(",
"e",
")",
")",
"print",
"(",
"\"ParseStops loaded \"",
"+",
"str",
"(",
"len",
"(",
"self",
".",
"Stops",
")",
")",
"+",
"\" stops\"",
")",
"def",
"ParseTrips",
"(",
"self",
",",
"reader",
")",
":",
"self",
".",
"Trips",
"=",
"{",
"}",
"Line",
"=",
"reader",
".",
"readline",
"(",
")",
"for",
"Line",
"in",
"reader",
":",
"Line",
"=",
"Line",
".",
"decode",
"(",
"'utf-8'",
")",
"Fields",
"=",
"self",
".",
"ParseCSVLine",
"(",
"Line",
")",
"RouteId",
"=",
"Fields",
"[",
"0",
"]",
"ServiceId",
"=",
"Fields",
"[",
"1",
"]",
"TripId",
"=",
"Fields",
"[",
"2",
"]",
"TripHeadsign",
"=",
"Fields",
"[",
"3",
"]",
"try",
":",
"if",
"not",
"TripId",
"in",
"self",
".",
"Trips",
":",
"self",
".",
"Trips",
"[",
"TripId",
"]",
"=",
"GTFSTrip",
"(",
"RouteId",
",",
"ServiceId",
",",
"TripId",
",",
"TripHeadsign",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"'Error: trips.txt '",
"+",
"self",
".",
"CurrentFilename",
"+",
"', '",
"+",
"Line",
"+",
"', '",
"+",
"e",
")",
"def",
"ParseGTFSTime",
"(",
"self",
",",
"strTime",
")",
":",
"Fields",
"=",
"strTime",
".",
"split",
"(",
"':'",
")",
"HH",
"=",
"int",
"(",
"Fields",
"[",
"0",
"]",
")",
"MM",
"=",
"int",
"(",
"Fields",
"[",
"1",
"]",
")",
"SS",
"=",
"int",
"(",
"Fields",
"[",
"2",
"]",
")",
"Over24",
"=",
"False",
"if",
"(",
"HH",
">=",
"24",
")",
":",
"Over24",
"=",
"True",
"HH",
"-=",
"24",
"DT",
"=",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"HH",
",",
"MM",
",",
"SS",
")",
"if",
"Over24",
":",
"DT",
"=",
"DT",
"+",
"timedelta",
"(",
"hours",
"=",
"24",
")",
"return",
"DT",
"def",
"ParseStopTimes",
"(",
"self",
",",
"reader",
")",
":",
"self",
".",
"StopTimes",
"=",
"{",
"}",
"Line",
"=",
"reader",
".",
"readline",
"(",
")",
"for",
"Line",
"in",
"reader",
":",
"Line",
"=",
"Line",
".",
"decode",
"(",
"'utf-8'",
")",
"Fields",
"=",
"self",
".",
"ParseCSVLine",
"(",
"Line",
")",
"try",
":",
"TripId",
"=",
"Fields",
"[",
"0",
"]",
"ArrivalTime",
"=",
"self",
".",
"ParseGTFSTime",
"(",
"Fields",
"[",
"1",
"]",
")",
"DepartureTime",
"=",
"self",
".",
"ParseGTFSTime",
"(",
"Fields",
"[",
"2",
"]",
")",
"StopId",
"=",
"Fields",
"[",
"3",
"]",
"StopSequence",
"=",
"int",
"(",
"Fields",
"[",
"4",
"]",
")",
"if",
"not",
"TripId",
"in",
"self",
".",
"StopTimes",
":",
"self",
".",
"StopTimes",
"[",
"TripId",
"]",
"=",
"[",
"]",
"self",
".",
"StopTimes",
"[",
"TripId",
"]",
".",
"append",
"(",
"GTFSStopTime",
"(",
"TripId",
",",
"ArrivalTime",
",",
"DepartureTime",
",",
"StopId",
",",
"StopSequence",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"'Error: stop_times.txt '",
"+",
"self",
".",
"CurrentFilename",
"+",
"', '",
"+",
"Line",
"+",
"', '",
"+",
"e",
")"
] |
Splits a string containing comma separated data and returns the elements as an array of strings.
|
[
"Splits",
"a",
"string",
"containing",
"comma",
"separated",
"data",
"and",
"returns",
"the",
"elements",
"as",
"an",
"array",
"of",
"strings",
"."
] |
[
"# <summary>",
"# Load a GTFS file. Filename must be a zip file.",
"# </summary>",
"# <param name=\"Filename\"></param>",
"#from routes.txt",
"#from stops.txt",
"#from trips.txt",
"#from stop_times.txt",
"#load routes from routes.txt inside zip file",
"#load stop points from stops.txt inside zip file",
"#trips",
"#stop_times",
"#with ZipFile",
"################################################################################",
"\"\"\"\n Splits a string containing comma separated data and returns the elements as an array of strings.\n Quotes can be used around items containing a comma.\n These quotes are removed from the string array that is returned.\n \n <param name=\"line\">The CSV line string to be split</param>\n <returns>Array of strings containing the comma separated elements in the CSV file line</returns>\n \"\"\"",
"#comma inside a quote",
"#end if ch==','",
"#end for ch in line",
"#add trailing item - even if last char was a comma, we still want a null on the end",
"################################################################################",
"# <summary>",
"# routes.txt",
"# NOTE: defaults to rail if no route_type found",
"# </summary>",
"# <param name=\"reader\"></param>",
"#route_id,agency_id,route_short_name,route_long_name,route_desc,route_type,route_url,route_color,route_text_color",
"#1-BAK-_-y05-400122,OId_LUL,Bakerloo,,Elephant & Castle - Queen's Park - Harrow & Wealdstone,1,,,",
"#skip header",
"#this is nasty - the weakly typed language returns a byte array, which it then tries to parse as a string, including the leading b' meaning bytes!",
"#AgencyId = Fields[HeaderLookup['agency_id']] #not in OASA data",
"#HACK!",
"#end for",
"################################################################################",
"# <summary>",
"# reader points to a stops.txt file, which is read to extract stop locations and populate this.StopPoints.",
"# </summary>",
"# <param name=\"reader\"></param>",
"#stops.txt",
"#stop_id,stop_name,stop_desc,stop_lat,stop_lon,zone_id,stop_url",
"#9400ZZLUHAW1,\"Wealdstone, Harrow & Wealdstone Station\",,51.5923316813,-0.3354040827,,",
"#9400ZZLUKEN2,\"Kenton (London), Kenton\",,51.5822158642,-0.3171684662,,",
"#self.Stops = {}",
"#Line = reader.readline() #skip header",
"#for Line in reader:",
"# Line = Line.decode('utf-8')",
"# Fields = self.ParseCSVLine(Line)",
"# Code = Fields[0]",
"# Name = Fields[1]",
"# try:",
"# Lat = float(Fields[3])",
"# Lon = float(Fields[4])",
"# if not Code in self.Stops:",
"# self.Stops[Code] = GTFSStop(Code,Name,Lat, Lon)",
"# except Exception as e:",
"# print('Error: stops.txt ' + self.CurrentFilename + ', ' + str(Line) + ', ' + str(e))",
"# #end try except",
"##end for",
"#",
"#better code (python)",
"#NOTE: MUST have the str() on the Code and Name for Python as they can use numbers! Weak typing mess!",
"#or stop_code?",
"#end try except",
"#end for iterrows",
"################################################################################",
"# <summary>",
"# Reader points to a trips.txt file.",
"# </summary>",
"# <param name=\"reader\"></param>",
"#route_id,service_id,trip_id,trip_headsign,direction_id,block_id,shape_id",
"#3-E10-_-y05-41620,3-E10-_-y05-41620,VJ_3-E10-_-y05-41620-1-MF@05:20:00,Islip Manor Road - Ealing Broadway Station / Haven Green,0,,",
"#3-E10-_-y05-41620,3-E10-_-y05-41620,VJ_3-E10-_-y05-41620-2-MF@05:22:00,Haven Green / Ealing Broadway - Islip Manor Road,1,,",
"#skip header",
"#end for",
"################################################################################",
"# <summary>",
"# Parses a GTFS time code string, taking into account the fact that it might be of the form 24:49:00.",
"# Arbitrarily sets all times to have a base date of 1 Jan 1970, so any hours>=24 will be set to the 2nd Jan.",
"# </summary>",
"# <param name=\"strTime\"></param>",
"# <returns></returns>",
"#end",
"################################################################################",
"#trip_id,arrival_time,departure_time,stop_id,stop_sequence,stop_headsign,pickup_type,drop_off_type,shape_dist_traveled",
"#VJ_3-E10-_-y05-41620-1-MF@05:20:00,05:20:00,05:20:00,490008519N,1,,0,0,",
"#VJ_3-E10-_-y05-41620-1-MF@05:20:00,05:20:00,05:20:00,490009557N,2,,0,0,",
"#skip header",
"#Annoyingly, you get some times recorded as 24:49:00, which is obviously over 24 hours. This is on services that run across midnight so you can tell it's not going backwards in time.",
"#Need to filter this out though.",
"#DateTime ArrivalTime = DateTime.Parse(Fields[1]); //DateTime - only the time is used, Date defaults to today",
"#DateTime DepartureTime = DateTime.Parse(Fields[2]); //DateTime",
"#create a new TripId sequence",
"#end if",
"#push new stop onto end of TripId sequence",
"#end try except",
"#end for"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 2,580
| 83
|
ebc8a32ce769be004c0f794e68f2227e68eac67c
|
nazish33/ifml-editor
|
plugins/IFMLEditor/src/IFML/Core/impl/ContentBindingImpl.java
|
[
"MIT"
] |
Java
|
ContentBindingImpl
|
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Content Binding</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link IFML.Core.impl.ContentBindingImpl#getUniformResourceIdentifier <em>Uniform Resource Identifier</em>}</li>
* </ul>
* </p>
*
* @generated
*/
|
An implementation of the model object 'Content Binding'.
The following features are implemented:
IFML.Core.impl.ContentBindingImpl#getUniformResourceIdentifier Uniform Resource Identifier
|
[
"An",
"implementation",
"of",
"the",
"model",
"object",
"'",
"Content",
"Binding",
"'",
".",
"The",
"following",
"features",
"are",
"implemented",
":",
"IFML",
".",
"Core",
".",
"impl",
".",
"ContentBindingImpl#getUniformResourceIdentifier",
"Uniform",
"Resource",
"Identifier"
] |
public abstract class ContentBindingImpl extends ViewComponentPartImpl implements ContentBinding {
/**
* The default value of the '{@link #getUniformResourceIdentifier() <em>Uniform Resource Identifier</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUniformResourceIdentifier()
* @generated
* @ordered
*/
protected static final String UNIFORM_RESOURCE_IDENTIFIER_EDEFAULT = null;
/**
* The cached value of the '{@link #getUniformResourceIdentifier() <em>Uniform Resource Identifier</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUniformResourceIdentifier()
* @generated
* @ordered
*/
protected String uniformResourceIdentifier = UNIFORM_RESOURCE_IDENTIFIER_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ContentBindingImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return CorePackage.Literals.CONTENT_BINDING;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getUniformResourceIdentifier() {
return uniformResourceIdentifier;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setUniformResourceIdentifier(String newUniformResourceIdentifier) {
String oldUniformResourceIdentifier = uniformResourceIdentifier;
uniformResourceIdentifier = newUniformResourceIdentifier;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, CorePackage.CONTENT_BINDING__UNIFORM_RESOURCE_IDENTIFIER, oldUniformResourceIdentifier, uniformResourceIdentifier));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case CorePackage.CONTENT_BINDING__UNIFORM_RESOURCE_IDENTIFIER:
return getUniformResourceIdentifier();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case CorePackage.CONTENT_BINDING__UNIFORM_RESOURCE_IDENTIFIER:
setUniformResourceIdentifier((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case CorePackage.CONTENT_BINDING__UNIFORM_RESOURCE_IDENTIFIER:
setUniformResourceIdentifier(UNIFORM_RESOURCE_IDENTIFIER_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case CorePackage.CONTENT_BINDING__UNIFORM_RESOURCE_IDENTIFIER:
return UNIFORM_RESOURCE_IDENTIFIER_EDEFAULT == null ? uniformResourceIdentifier != null : !UNIFORM_RESOURCE_IDENTIFIER_EDEFAULT.equals(uniformResourceIdentifier);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (uniformResourceIdentifier: ");
result.append(uniformResourceIdentifier);
result.append(')');
return result.toString();
}
}
|
[
"public",
"abstract",
"class",
"ContentBindingImpl",
"extends",
"ViewComponentPartImpl",
"implements",
"ContentBinding",
"{",
"/**\n\t * The default value of the '{@link #getUniformResourceIdentifier() <em>Uniform Resource Identifier</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @see #getUniformResourceIdentifier()\n\t * @generated\n\t * @ordered\n\t */",
"protected",
"static",
"final",
"String",
"UNIFORM_RESOURCE_IDENTIFIER_EDEFAULT",
"=",
"null",
";",
"/**\n\t * The cached value of the '{@link #getUniformResourceIdentifier() <em>Uniform Resource Identifier</em>}' attribute.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @see #getUniformResourceIdentifier()\n\t * @generated\n\t * @ordered\n\t */",
"protected",
"String",
"uniformResourceIdentifier",
"=",
"UNIFORM_RESOURCE_IDENTIFIER_EDEFAULT",
";",
"/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */",
"protected",
"ContentBindingImpl",
"(",
")",
"{",
"super",
"(",
")",
";",
"}",
"/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */",
"@",
"Override",
"protected",
"EClass",
"eStaticClass",
"(",
")",
"{",
"return",
"CorePackage",
".",
"Literals",
".",
"CONTENT_BINDING",
";",
"}",
"/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */",
"public",
"String",
"getUniformResourceIdentifier",
"(",
")",
"{",
"return",
"uniformResourceIdentifier",
";",
"}",
"/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */",
"public",
"void",
"setUniformResourceIdentifier",
"(",
"String",
"newUniformResourceIdentifier",
")",
"{",
"String",
"oldUniformResourceIdentifier",
"=",
"uniformResourceIdentifier",
";",
"uniformResourceIdentifier",
"=",
"newUniformResourceIdentifier",
";",
"if",
"(",
"eNotificationRequired",
"(",
")",
")",
"eNotify",
"(",
"new",
"ENotificationImpl",
"(",
"this",
",",
"Notification",
".",
"SET",
",",
"CorePackage",
".",
"CONTENT_BINDING__UNIFORM_RESOURCE_IDENTIFIER",
",",
"oldUniformResourceIdentifier",
",",
"uniformResourceIdentifier",
")",
")",
";",
"}",
"/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */",
"@",
"Override",
"public",
"Object",
"eGet",
"(",
"int",
"featureID",
",",
"boolean",
"resolve",
",",
"boolean",
"coreType",
")",
"{",
"switch",
"(",
"featureID",
")",
"{",
"case",
"CorePackage",
".",
"CONTENT_BINDING__UNIFORM_RESOURCE_IDENTIFIER",
":",
"return",
"getUniformResourceIdentifier",
"(",
")",
";",
"}",
"return",
"super",
".",
"eGet",
"(",
"featureID",
",",
"resolve",
",",
"coreType",
")",
";",
"}",
"/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */",
"@",
"Override",
"public",
"void",
"eSet",
"(",
"int",
"featureID",
",",
"Object",
"newValue",
")",
"{",
"switch",
"(",
"featureID",
")",
"{",
"case",
"CorePackage",
".",
"CONTENT_BINDING__UNIFORM_RESOURCE_IDENTIFIER",
":",
"setUniformResourceIdentifier",
"(",
"(",
"String",
")",
"newValue",
")",
";",
"return",
";",
"}",
"super",
".",
"eSet",
"(",
"featureID",
",",
"newValue",
")",
";",
"}",
"/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */",
"@",
"Override",
"public",
"void",
"eUnset",
"(",
"int",
"featureID",
")",
"{",
"switch",
"(",
"featureID",
")",
"{",
"case",
"CorePackage",
".",
"CONTENT_BINDING__UNIFORM_RESOURCE_IDENTIFIER",
":",
"setUniformResourceIdentifier",
"(",
"UNIFORM_RESOURCE_IDENTIFIER_EDEFAULT",
")",
";",
"return",
";",
"}",
"super",
".",
"eUnset",
"(",
"featureID",
")",
";",
"}",
"/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */",
"@",
"Override",
"public",
"boolean",
"eIsSet",
"(",
"int",
"featureID",
")",
"{",
"switch",
"(",
"featureID",
")",
"{",
"case",
"CorePackage",
".",
"CONTENT_BINDING__UNIFORM_RESOURCE_IDENTIFIER",
":",
"return",
"UNIFORM_RESOURCE_IDENTIFIER_EDEFAULT",
"==",
"null",
"?",
"uniformResourceIdentifier",
"!=",
"null",
":",
"!",
"UNIFORM_RESOURCE_IDENTIFIER_EDEFAULT",
".",
"equals",
"(",
"uniformResourceIdentifier",
")",
";",
"}",
"return",
"super",
".",
"eIsSet",
"(",
"featureID",
")",
";",
"}",
"/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"if",
"(",
"eIsProxy",
"(",
")",
")",
"return",
"super",
".",
"toString",
"(",
")",
";",
"StringBuffer",
"result",
"=",
"new",
"StringBuffer",
"(",
"super",
".",
"toString",
"(",
")",
")",
";",
"result",
".",
"append",
"(",
"\"",
" (uniformResourceIdentifier: ",
"\"",
")",
";",
"result",
".",
"append",
"(",
"uniformResourceIdentifier",
")",
";",
"result",
".",
"append",
"(",
"')'",
")",
";",
"return",
"result",
".",
"toString",
"(",
")",
";",
"}",
"}"
] |
<!-- begin-user-doc -->
An implementation of the model object '<em><b>Content Binding</b></em>'.
|
[
"<!",
"--",
"begin",
"-",
"user",
"-",
"doc",
"--",
">",
"An",
"implementation",
"of",
"the",
"model",
"object",
"'",
"<em",
">",
"<b",
">",
"Content",
"Binding<",
"/",
"b",
">",
"<",
"/",
"em",
">",
"'",
"."
] |
[] |
[
{
"param": "ViewComponentPartImpl",
"type": null
},
{
"param": "ContentBinding",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ViewComponentPartImpl",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ContentBinding",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 815
| 89
|
f3517b0af30385805686bc28d2811f7242274e61
|
miguel090/Proteus
|
org.xtext.agen/src-gen/org/xtext/agen/impl/RunConfigurationImpl.java
|
[
"Apache-2.0"
] |
Java
|
RunConfigurationImpl
|
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Run Configuration</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.xtext.agen.impl.RunConfigurationImpl#getRuntimePackage <em>Runtime Package</em>}</li>
* <li>{@link org.xtext.agen.impl.RunConfigurationImpl#getCoordinatorLocation <em>Coordinator Location</em>}</li>
* <li>{@link org.xtext.agen.impl.RunConfigurationImpl#getNodes <em>Nodes</em>}</li>
* </ul>
*
* @generated
*/
|
An implementation of the model object 'Run Configuration'.
|
[
"An",
"implementation",
"of",
"the",
"model",
"object",
"'",
"Run",
"Configuration",
"'",
"."
] |
public class RunConfigurationImpl extends TypesImpl implements RunConfiguration
{
/**
* The default value of the '{@link #getRuntimePackage() <em>Runtime Package</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRuntimePackage()
* @generated
* @ordered
*/
protected static final String RUNTIME_PACKAGE_EDEFAULT = null;
/**
* The cached value of the '{@link #getRuntimePackage() <em>Runtime Package</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRuntimePackage()
* @generated
* @ordered
*/
protected String runtimePackage = RUNTIME_PACKAGE_EDEFAULT;
/**
* The default value of the '{@link #getCoordinatorLocation() <em>Coordinator Location</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCoordinatorLocation()
* @generated
* @ordered
*/
protected static final String COORDINATOR_LOCATION_EDEFAULT = null;
/**
* The cached value of the '{@link #getCoordinatorLocation() <em>Coordinator Location</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCoordinatorLocation()
* @generated
* @ordered
*/
protected String coordinatorLocation = COORDINATOR_LOCATION_EDEFAULT;
/**
* The cached value of the '{@link #getNodes() <em>Nodes</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNodes()
* @generated
* @ordered
*/
protected EList<Node> nodes;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected RunConfigurationImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return AgenPackage.Literals.RUN_CONFIGURATION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getRuntimePackage()
{
return runtimePackage;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setRuntimePackage(String newRuntimePackage)
{
String oldRuntimePackage = runtimePackage;
runtimePackage = newRuntimePackage;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AgenPackage.RUN_CONFIGURATION__RUNTIME_PACKAGE, oldRuntimePackage, runtimePackage));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getCoordinatorLocation()
{
return coordinatorLocation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setCoordinatorLocation(String newCoordinatorLocation)
{
String oldCoordinatorLocation = coordinatorLocation;
coordinatorLocation = newCoordinatorLocation;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AgenPackage.RUN_CONFIGURATION__COORDINATOR_LOCATION, oldCoordinatorLocation, coordinatorLocation));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EList<Node> getNodes()
{
if (nodes == null)
{
nodes = new EObjectContainmentEList<Node>(Node.class, this, AgenPackage.RUN_CONFIGURATION__NODES);
}
return nodes;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case AgenPackage.RUN_CONFIGURATION__NODES:
return ((InternalEList<?>)getNodes()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case AgenPackage.RUN_CONFIGURATION__RUNTIME_PACKAGE:
return getRuntimePackage();
case AgenPackage.RUN_CONFIGURATION__COORDINATOR_LOCATION:
return getCoordinatorLocation();
case AgenPackage.RUN_CONFIGURATION__NODES:
return getNodes();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case AgenPackage.RUN_CONFIGURATION__RUNTIME_PACKAGE:
setRuntimePackage((String)newValue);
return;
case AgenPackage.RUN_CONFIGURATION__COORDINATOR_LOCATION:
setCoordinatorLocation((String)newValue);
return;
case AgenPackage.RUN_CONFIGURATION__NODES:
getNodes().clear();
getNodes().addAll((Collection<? extends Node>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case AgenPackage.RUN_CONFIGURATION__RUNTIME_PACKAGE:
setRuntimePackage(RUNTIME_PACKAGE_EDEFAULT);
return;
case AgenPackage.RUN_CONFIGURATION__COORDINATOR_LOCATION:
setCoordinatorLocation(COORDINATOR_LOCATION_EDEFAULT);
return;
case AgenPackage.RUN_CONFIGURATION__NODES:
getNodes().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case AgenPackage.RUN_CONFIGURATION__RUNTIME_PACKAGE:
return RUNTIME_PACKAGE_EDEFAULT == null ? runtimePackage != null : !RUNTIME_PACKAGE_EDEFAULT.equals(runtimePackage);
case AgenPackage.RUN_CONFIGURATION__COORDINATOR_LOCATION:
return COORDINATOR_LOCATION_EDEFAULT == null ? coordinatorLocation != null : !COORDINATOR_LOCATION_EDEFAULT.equals(coordinatorLocation);
case AgenPackage.RUN_CONFIGURATION__NODES:
return nodes != null && !nodes.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuilder result = new StringBuilder(super.toString());
result.append(" (runtimePackage: ");
result.append(runtimePackage);
result.append(", coordinatorLocation: ");
result.append(coordinatorLocation);
result.append(')');
return result.toString();
}
}
|
[
"public",
"class",
"RunConfigurationImpl",
"extends",
"TypesImpl",
"implements",
"RunConfiguration",
"{",
"/**\n * The default value of the '{@link #getRuntimePackage() <em>Runtime Package</em>}' attribute.\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @see #getRuntimePackage()\n * @generated\n * @ordered\n */",
"protected",
"static",
"final",
"String",
"RUNTIME_PACKAGE_EDEFAULT",
"=",
"null",
";",
"/**\n * The cached value of the '{@link #getRuntimePackage() <em>Runtime Package</em>}' attribute.\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @see #getRuntimePackage()\n * @generated\n * @ordered\n */",
"protected",
"String",
"runtimePackage",
"=",
"RUNTIME_PACKAGE_EDEFAULT",
";",
"/**\n * The default value of the '{@link #getCoordinatorLocation() <em>Coordinator Location</em>}' attribute.\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @see #getCoordinatorLocation()\n * @generated\n * @ordered\n */",
"protected",
"static",
"final",
"String",
"COORDINATOR_LOCATION_EDEFAULT",
"=",
"null",
";",
"/**\n * The cached value of the '{@link #getCoordinatorLocation() <em>Coordinator Location</em>}' attribute.\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @see #getCoordinatorLocation()\n * @generated\n * @ordered\n */",
"protected",
"String",
"coordinatorLocation",
"=",
"COORDINATOR_LOCATION_EDEFAULT",
";",
"/**\n * The cached value of the '{@link #getNodes() <em>Nodes</em>}' containment reference list.\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @see #getNodes()\n * @generated\n * @ordered\n */",
"protected",
"EList",
"<",
"Node",
">",
"nodes",
";",
"/**\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @generated\n */",
"protected",
"RunConfigurationImpl",
"(",
")",
"{",
"super",
"(",
")",
";",
"}",
"/**\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @generated\n */",
"@",
"Override",
"protected",
"EClass",
"eStaticClass",
"(",
")",
"{",
"return",
"AgenPackage",
".",
"Literals",
".",
"RUN_CONFIGURATION",
";",
"}",
"/**\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @generated\n */",
"@",
"Override",
"public",
"String",
"getRuntimePackage",
"(",
")",
"{",
"return",
"runtimePackage",
";",
"}",
"/**\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @generated\n */",
"@",
"Override",
"public",
"void",
"setRuntimePackage",
"(",
"String",
"newRuntimePackage",
")",
"{",
"String",
"oldRuntimePackage",
"=",
"runtimePackage",
";",
"runtimePackage",
"=",
"newRuntimePackage",
";",
"if",
"(",
"eNotificationRequired",
"(",
")",
")",
"eNotify",
"(",
"new",
"ENotificationImpl",
"(",
"this",
",",
"Notification",
".",
"SET",
",",
"AgenPackage",
".",
"RUN_CONFIGURATION__RUNTIME_PACKAGE",
",",
"oldRuntimePackage",
",",
"runtimePackage",
")",
")",
";",
"}",
"/**\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @generated\n */",
"@",
"Override",
"public",
"String",
"getCoordinatorLocation",
"(",
")",
"{",
"return",
"coordinatorLocation",
";",
"}",
"/**\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @generated\n */",
"@",
"Override",
"public",
"void",
"setCoordinatorLocation",
"(",
"String",
"newCoordinatorLocation",
")",
"{",
"String",
"oldCoordinatorLocation",
"=",
"coordinatorLocation",
";",
"coordinatorLocation",
"=",
"newCoordinatorLocation",
";",
"if",
"(",
"eNotificationRequired",
"(",
")",
")",
"eNotify",
"(",
"new",
"ENotificationImpl",
"(",
"this",
",",
"Notification",
".",
"SET",
",",
"AgenPackage",
".",
"RUN_CONFIGURATION__COORDINATOR_LOCATION",
",",
"oldCoordinatorLocation",
",",
"coordinatorLocation",
")",
")",
";",
"}",
"/**\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @generated\n */",
"@",
"Override",
"public",
"EList",
"<",
"Node",
">",
"getNodes",
"(",
")",
"{",
"if",
"(",
"nodes",
"==",
"null",
")",
"{",
"nodes",
"=",
"new",
"EObjectContainmentEList",
"<",
"Node",
">",
"(",
"Node",
".",
"class",
",",
"this",
",",
"AgenPackage",
".",
"RUN_CONFIGURATION__NODES",
")",
";",
"}",
"return",
"nodes",
";",
"}",
"/**\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @generated\n */",
"@",
"Override",
"public",
"NotificationChain",
"eInverseRemove",
"(",
"InternalEObject",
"otherEnd",
",",
"int",
"featureID",
",",
"NotificationChain",
"msgs",
")",
"{",
"switch",
"(",
"featureID",
")",
"{",
"case",
"AgenPackage",
".",
"RUN_CONFIGURATION__NODES",
":",
"return",
"(",
"(",
"InternalEList",
"<",
"?",
">",
")",
"getNodes",
"(",
")",
")",
".",
"basicRemove",
"(",
"otherEnd",
",",
"msgs",
")",
";",
"}",
"return",
"super",
".",
"eInverseRemove",
"(",
"otherEnd",
",",
"featureID",
",",
"msgs",
")",
";",
"}",
"/**\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @generated\n */",
"@",
"Override",
"public",
"Object",
"eGet",
"(",
"int",
"featureID",
",",
"boolean",
"resolve",
",",
"boolean",
"coreType",
")",
"{",
"switch",
"(",
"featureID",
")",
"{",
"case",
"AgenPackage",
".",
"RUN_CONFIGURATION__RUNTIME_PACKAGE",
":",
"return",
"getRuntimePackage",
"(",
")",
";",
"case",
"AgenPackage",
".",
"RUN_CONFIGURATION__COORDINATOR_LOCATION",
":",
"return",
"getCoordinatorLocation",
"(",
")",
";",
"case",
"AgenPackage",
".",
"RUN_CONFIGURATION__NODES",
":",
"return",
"getNodes",
"(",
")",
";",
"}",
"return",
"super",
".",
"eGet",
"(",
"featureID",
",",
"resolve",
",",
"coreType",
")",
";",
"}",
"/**\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @generated\n */",
"@",
"SuppressWarnings",
"(",
"\"",
"unchecked",
"\"",
")",
"@",
"Override",
"public",
"void",
"eSet",
"(",
"int",
"featureID",
",",
"Object",
"newValue",
")",
"{",
"switch",
"(",
"featureID",
")",
"{",
"case",
"AgenPackage",
".",
"RUN_CONFIGURATION__RUNTIME_PACKAGE",
":",
"setRuntimePackage",
"(",
"(",
"String",
")",
"newValue",
")",
";",
"return",
";",
"case",
"AgenPackage",
".",
"RUN_CONFIGURATION__COORDINATOR_LOCATION",
":",
"setCoordinatorLocation",
"(",
"(",
"String",
")",
"newValue",
")",
";",
"return",
";",
"case",
"AgenPackage",
".",
"RUN_CONFIGURATION__NODES",
":",
"getNodes",
"(",
")",
".",
"clear",
"(",
")",
";",
"getNodes",
"(",
")",
".",
"addAll",
"(",
"(",
"Collection",
"<",
"?",
"extends",
"Node",
">",
")",
"newValue",
")",
";",
"return",
";",
"}",
"super",
".",
"eSet",
"(",
"featureID",
",",
"newValue",
")",
";",
"}",
"/**\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @generated\n */",
"@",
"Override",
"public",
"void",
"eUnset",
"(",
"int",
"featureID",
")",
"{",
"switch",
"(",
"featureID",
")",
"{",
"case",
"AgenPackage",
".",
"RUN_CONFIGURATION__RUNTIME_PACKAGE",
":",
"setRuntimePackage",
"(",
"RUNTIME_PACKAGE_EDEFAULT",
")",
";",
"return",
";",
"case",
"AgenPackage",
".",
"RUN_CONFIGURATION__COORDINATOR_LOCATION",
":",
"setCoordinatorLocation",
"(",
"COORDINATOR_LOCATION_EDEFAULT",
")",
";",
"return",
";",
"case",
"AgenPackage",
".",
"RUN_CONFIGURATION__NODES",
":",
"getNodes",
"(",
")",
".",
"clear",
"(",
")",
";",
"return",
";",
"}",
"super",
".",
"eUnset",
"(",
"featureID",
")",
";",
"}",
"/**\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @generated\n */",
"@",
"Override",
"public",
"boolean",
"eIsSet",
"(",
"int",
"featureID",
")",
"{",
"switch",
"(",
"featureID",
")",
"{",
"case",
"AgenPackage",
".",
"RUN_CONFIGURATION__RUNTIME_PACKAGE",
":",
"return",
"RUNTIME_PACKAGE_EDEFAULT",
"==",
"null",
"?",
"runtimePackage",
"!=",
"null",
":",
"!",
"RUNTIME_PACKAGE_EDEFAULT",
".",
"equals",
"(",
"runtimePackage",
")",
";",
"case",
"AgenPackage",
".",
"RUN_CONFIGURATION__COORDINATOR_LOCATION",
":",
"return",
"COORDINATOR_LOCATION_EDEFAULT",
"==",
"null",
"?",
"coordinatorLocation",
"!=",
"null",
":",
"!",
"COORDINATOR_LOCATION_EDEFAULT",
".",
"equals",
"(",
"coordinatorLocation",
")",
";",
"case",
"AgenPackage",
".",
"RUN_CONFIGURATION__NODES",
":",
"return",
"nodes",
"!=",
"null",
"&&",
"!",
"nodes",
".",
"isEmpty",
"(",
")",
";",
"}",
"return",
"super",
".",
"eIsSet",
"(",
"featureID",
")",
";",
"}",
"/**\n * <!-- begin-user-doc -->\n * <!-- end-user-doc -->\n * @generated\n */",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"if",
"(",
"eIsProxy",
"(",
")",
")",
"return",
"super",
".",
"toString",
"(",
")",
";",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
"super",
".",
"toString",
"(",
")",
")",
";",
"result",
".",
"append",
"(",
"\"",
" (runtimePackage: ",
"\"",
")",
";",
"result",
".",
"append",
"(",
"runtimePackage",
")",
";",
"result",
".",
"append",
"(",
"\"",
", coordinatorLocation: ",
"\"",
")",
";",
"result",
".",
"append",
"(",
"coordinatorLocation",
")",
";",
"result",
".",
"append",
"(",
"')'",
")",
";",
"return",
"result",
".",
"toString",
"(",
")",
";",
"}",
"}"
] |
<!-- begin-user-doc -->
An implementation of the model object '<em><b>Run Configuration</b></em>'.
|
[
"<!",
"--",
"begin",
"-",
"user",
"-",
"doc",
"--",
">",
"An",
"implementation",
"of",
"the",
"model",
"object",
"'",
"<em",
">",
"<b",
">",
"Run",
"Configuration<",
"/",
"b",
">",
"<",
"/",
"em",
">",
"'",
"."
] |
[] |
[
{
"param": "TypesImpl",
"type": null
},
{
"param": "RunConfiguration",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "TypesImpl",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "RunConfiguration",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 15
| 1,581
| 140
|
4150553a101bab80eece49a646e38f98f5028764
|
PeteE/DReAM
|
src/mindtouch.dream/Collections/LockFreeWorkStealingDeque.cs
|
[
"Apache-2.0"
] |
C#
|
WorkStealingDeque
|
/// <summary>
/// Provides a queue that allows items to pushed and popped by a single thread while
/// other threads may attempt steal from it. The implementation is based on the work done by
/// Danny Hendler, Yossi Lev, Mark Moir, and Nir Shavit: "A dynamic-sized nonblocking work stealing deque",
/// Distributed Computing, Volume 18, Issue 3 (February 2006), pp189-207, ISSN:0178-2770
/// </summary>
/// <typeparam name="T">Collection item type.</typeparam>
|
Provides a queue that allows items to pushed and popped by a single thread while
other threads may attempt steal from it. The implementation is based on the work done by
Danny Hendler, Yossi Lev, Mark Moir, and Nir Shavit: "A dynamic-sized nonblocking work stealing deque",
Distributed Computing, Volume 18, Issue 3 (February 2006), pp189-207, ISSN:0178-2770
|
[
"Provides",
"a",
"queue",
"that",
"allows",
"items",
"to",
"pushed",
"and",
"popped",
"by",
"a",
"single",
"thread",
"while",
"other",
"threads",
"may",
"attempt",
"steal",
"from",
"it",
".",
"The",
"implementation",
"is",
"based",
"on",
"the",
"work",
"done",
"by",
"Danny",
"Hendler",
"Yossi",
"Lev",
"Mark",
"Moir",
"and",
"Nir",
"Shavit",
":",
"\"",
"A",
"dynamic",
"-",
"sized",
"nonblocking",
"work",
"stealing",
"deque",
"\"",
"Distributed",
"Computing",
"Volume",
"18",
"Issue",
"3",
"(",
"February",
"2006",
")",
"pp189",
"-",
"207",
"ISSN",
":",
"0178",
"-",
"2770"
] |
public sealed class WorkStealingDeque<T> where T: class {
private const int DEFAULT_CAPACITY = 32;
internal class BottomData {
internal readonly DequeNode Node;
internal readonly int Index;
internal BottomData(DequeNode node, int index) {
this.Node = node;
this.Index = index;
}
}
internal class TopData {
internal readonly int Tag;
internal readonly DequeNode Node;
internal readonly int Index;
internal TopData(int tag, DequeNode node, int index) {
this.Tag = tag;
this.Node = node;
this.Index = index;
}
}
internal class DequeNode {
internal readonly T[] Data;
internal DequeNode Next;
internal DequeNode Prev;
internal DequeNode(int capacity, DequeNode next) {
Data = new T[capacity];
if(next != null) {
this.Next = next;
next.Prev = this;
}
}
}
private static bool IsEmpty(BottomData bottom, TopData top, int capacity) {
if(ReferenceEquals(bottom.Node, top.Node) && ((bottom.Index == top.Index) || (bottom.Index == (top.Index + 1)))) {
return true;
} else if(ReferenceEquals(bottom.Node, top.Node.Next) && (bottom.Index == 0) && (top.Index == (capacity - 1))) {
return true;
}
return false;
}
private readonly int _capacity;
private BottomData _bottom;
private TopData _top;
public WorkStealingDeque() : this(DEFAULT_CAPACITY) { }
public WorkStealingDeque(int capacity) {
_capacity = capacity;
DequeNode nodeB = new DequeNode(_capacity, null);
DequeNode nodeA = new DequeNode(_capacity, nodeB);
_bottom = new BottomData(nodeA, _capacity - 1);
_top = new TopData(0, nodeA, _capacity - 1);
}
public int Count {
get {
BottomData curBottom = _bottom;
TopData curTop = _top;
int count;
if(ReferenceEquals(curBottom.Node, curTop.Node)) {
count = Math.Max(0, curTop.Index - curBottom.Index);
} else if(ReferenceEquals(curBottom.Node, curTop.Node.Next) && (curBottom.Index == 0) && (curTop.Index == (_capacity - 1))) {
count = 0;
} else {
count = _capacity - (curBottom.Index + 1);
for(var node = curBottom.Node.Next; (node != curTop.Node) && (node != null); node = node.Next) {
count += _capacity;
}
count += curTop.Index + 1;
}
return count;
}
}
public void Push(T data) {
BottomData curBottom = _bottom;
curBottom.Node.Data[curBottom.Index] = data;
BottomData newBottom;
if(curBottom.Index != 0) {
newBottom = new BottomData(curBottom.Node, curBottom.Index - 1);
} else {
DequeNode newNode = new DequeNode(_capacity, curBottom.Node);
newBottom = new BottomData(newNode, _capacity - 1);
}
_bottom = newBottom;
}
public bool TryPop(out T item) {
item = default(T);
BottomData curBottom = _bottom;
BottomData newBottom;
if(curBottom.Index != (_capacity - 1)) {
newBottom = new BottomData(curBottom.Node, curBottom.Index + 1);
} else {
newBottom = new BottomData(curBottom.Node.Next, 0);
}
_bottom = newBottom;
TopData curTop = _top;
T retVal = newBottom.Node.Data[newBottom.Index];
if(ReferenceEquals(curBottom.Node, curTop.Node) && (curBottom.Index == curTop.Index)) {
_bottom = curBottom;
return false;
}
if(ReferenceEquals(newBottom.Node, curTop.Node) && (newBottom.Index == curTop.Index)) {
TopData newTopVal = new TopData(curTop.Tag + 1, curTop.Node, curTop.Index);
if(SysUtil.CAS(ref _top, curTop, newTopVal)) {
newBottom.Node.Data[newBottom.Index] = default(T);
if(!ReferenceEquals(curBottom.Node, newBottom.Node)) {
newBottom.Node.Prev = null;
}
item = retVal;
return true;
} else {
_bottom = curBottom;
return false;
}
}
if(!ReferenceEquals(curBottom.Node, newBottom.Node)) {
newBottom.Node.Prev = null;
}
item = retVal;
return true;
}
public bool TrySteal(out T item) {
TopData curTop = _top;
BottomData curBottom = _bottom;
if(IsEmpty(curBottom, curTop, _capacity)) {
item = default(T);
if(ReferenceEquals(curTop, _top)) {
return false;
} else {
return false;
}
}
TopData newTop;
if(curTop.Index != 0) {
newTop = new TopData(curTop.Tag, curTop.Node, curTop.Index - 1);
} else {
newTop = new TopData(curTop.Tag + 1, curTop.Node.Prev, _capacity - 1);
}
T retVal = curTop.Node.Data[curTop.Index];
if(SysUtil.CAS(ref _top, curTop, newTop)) {
SysUtil.CAS(ref curTop.Node.Data[curTop.Index], retVal, default(T));
curTop.Node.Next = null;
item = retVal;
return true;
} else {
item = default(T);
return false;
}
}
}
|
[
"public",
"sealed",
"class",
"WorkStealingDeque",
"<",
"T",
">",
"where",
"T",
":",
"class",
"{",
"private",
"const",
"int",
"DEFAULT_CAPACITY",
"=",
"32",
";",
"internal",
"class",
"BottomData",
"{",
"internal",
"readonly",
"DequeNode",
"Node",
";",
"internal",
"readonly",
"int",
"Index",
";",
"internal",
"BottomData",
"(",
"DequeNode",
"node",
",",
"int",
"index",
")",
"{",
"this",
".",
"Node",
"=",
"node",
";",
"this",
".",
"Index",
"=",
"index",
";",
"}",
"}",
"internal",
"class",
"TopData",
"{",
"internal",
"readonly",
"int",
"Tag",
";",
"internal",
"readonly",
"DequeNode",
"Node",
";",
"internal",
"readonly",
"int",
"Index",
";",
"internal",
"TopData",
"(",
"int",
"tag",
",",
"DequeNode",
"node",
",",
"int",
"index",
")",
"{",
"this",
".",
"Tag",
"=",
"tag",
";",
"this",
".",
"Node",
"=",
"node",
";",
"this",
".",
"Index",
"=",
"index",
";",
"}",
"}",
"internal",
"class",
"DequeNode",
"{",
"internal",
"readonly",
"T",
"[",
"]",
"Data",
";",
"internal",
"DequeNode",
"Next",
";",
"internal",
"DequeNode",
"Prev",
";",
"internal",
"DequeNode",
"(",
"int",
"capacity",
",",
"DequeNode",
"next",
")",
"{",
"Data",
"=",
"new",
"T",
"[",
"capacity",
"]",
";",
"if",
"(",
"next",
"!=",
"null",
")",
"{",
"this",
".",
"Next",
"=",
"next",
";",
"next",
".",
"Prev",
"=",
"this",
";",
"}",
"}",
"}",
"private",
"static",
"bool",
"IsEmpty",
"(",
"BottomData",
"bottom",
",",
"TopData",
"top",
",",
"int",
"capacity",
")",
"{",
"if",
"(",
"ReferenceEquals",
"(",
"bottom",
".",
"Node",
",",
"top",
".",
"Node",
")",
"&&",
"(",
"(",
"bottom",
".",
"Index",
"==",
"top",
".",
"Index",
")",
"||",
"(",
"bottom",
".",
"Index",
"==",
"(",
"top",
".",
"Index",
"+",
"1",
")",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"ReferenceEquals",
"(",
"bottom",
".",
"Node",
",",
"top",
".",
"Node",
".",
"Next",
")",
"&&",
"(",
"bottom",
".",
"Index",
"==",
"0",
")",
"&&",
"(",
"top",
".",
"Index",
"==",
"(",
"capacity",
"-",
"1",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
"private",
"readonly",
"int",
"_capacity",
";",
"private",
"BottomData",
"_bottom",
";",
"private",
"TopData",
"_top",
";",
"public",
"WorkStealingDeque",
"(",
")",
":",
"this",
"(",
"DEFAULT_CAPACITY",
")",
"{",
"}",
"public",
"WorkStealingDeque",
"(",
"int",
"capacity",
")",
"{",
"_capacity",
"=",
"capacity",
";",
"DequeNode",
"nodeB",
"=",
"new",
"DequeNode",
"(",
"_capacity",
",",
"null",
")",
";",
"DequeNode",
"nodeA",
"=",
"new",
"DequeNode",
"(",
"_capacity",
",",
"nodeB",
")",
";",
"_bottom",
"=",
"new",
"BottomData",
"(",
"nodeA",
",",
"_capacity",
"-",
"1",
")",
";",
"_top",
"=",
"new",
"TopData",
"(",
"0",
",",
"nodeA",
",",
"_capacity",
"-",
"1",
")",
";",
"}",
"public",
"int",
"Count",
"{",
"get",
"{",
"BottomData",
"curBottom",
"=",
"_bottom",
";",
"TopData",
"curTop",
"=",
"_top",
";",
"int",
"count",
";",
"if",
"(",
"ReferenceEquals",
"(",
"curBottom",
".",
"Node",
",",
"curTop",
".",
"Node",
")",
")",
"{",
"count",
"=",
"Math",
".",
"Max",
"(",
"0",
",",
"curTop",
".",
"Index",
"-",
"curBottom",
".",
"Index",
")",
";",
"}",
"else",
"if",
"(",
"ReferenceEquals",
"(",
"curBottom",
".",
"Node",
",",
"curTop",
".",
"Node",
".",
"Next",
")",
"&&",
"(",
"curBottom",
".",
"Index",
"==",
"0",
")",
"&&",
"(",
"curTop",
".",
"Index",
"==",
"(",
"_capacity",
"-",
"1",
")",
")",
")",
"{",
"count",
"=",
"0",
";",
"}",
"else",
"{",
"count",
"=",
"_capacity",
"-",
"(",
"curBottom",
".",
"Index",
"+",
"1",
")",
";",
"for",
"(",
"var",
"node",
"=",
"curBottom",
".",
"Node",
".",
"Next",
";",
"(",
"node",
"!=",
"curTop",
".",
"Node",
")",
"&&",
"(",
"node",
"!=",
"null",
")",
";",
"node",
"=",
"node",
".",
"Next",
")",
"{",
"count",
"+=",
"_capacity",
";",
"}",
"count",
"+=",
"curTop",
".",
"Index",
"+",
"1",
";",
"}",
"return",
"count",
";",
"}",
"}",
"public",
"void",
"Push",
"(",
"T",
"data",
")",
"{",
"BottomData",
"curBottom",
"=",
"_bottom",
";",
"curBottom",
".",
"Node",
".",
"Data",
"[",
"curBottom",
".",
"Index",
"]",
"=",
"data",
";",
"BottomData",
"newBottom",
";",
"if",
"(",
"curBottom",
".",
"Index",
"!=",
"0",
")",
"{",
"newBottom",
"=",
"new",
"BottomData",
"(",
"curBottom",
".",
"Node",
",",
"curBottom",
".",
"Index",
"-",
"1",
")",
";",
"}",
"else",
"{",
"DequeNode",
"newNode",
"=",
"new",
"DequeNode",
"(",
"_capacity",
",",
"curBottom",
".",
"Node",
")",
";",
"newBottom",
"=",
"new",
"BottomData",
"(",
"newNode",
",",
"_capacity",
"-",
"1",
")",
";",
"}",
"_bottom",
"=",
"newBottom",
";",
"}",
"public",
"bool",
"TryPop",
"(",
"out",
"T",
"item",
")",
"{",
"item",
"=",
"default",
"(",
"T",
")",
";",
"BottomData",
"curBottom",
"=",
"_bottom",
";",
"BottomData",
"newBottom",
";",
"if",
"(",
"curBottom",
".",
"Index",
"!=",
"(",
"_capacity",
"-",
"1",
")",
")",
"{",
"newBottom",
"=",
"new",
"BottomData",
"(",
"curBottom",
".",
"Node",
",",
"curBottom",
".",
"Index",
"+",
"1",
")",
";",
"}",
"else",
"{",
"newBottom",
"=",
"new",
"BottomData",
"(",
"curBottom",
".",
"Node",
".",
"Next",
",",
"0",
")",
";",
"}",
"_bottom",
"=",
"newBottom",
";",
"TopData",
"curTop",
"=",
"_top",
";",
"T",
"retVal",
"=",
"newBottom",
".",
"Node",
".",
"Data",
"[",
"newBottom",
".",
"Index",
"]",
";",
"if",
"(",
"ReferenceEquals",
"(",
"curBottom",
".",
"Node",
",",
"curTop",
".",
"Node",
")",
"&&",
"(",
"curBottom",
".",
"Index",
"==",
"curTop",
".",
"Index",
")",
")",
"{",
"_bottom",
"=",
"curBottom",
";",
"return",
"false",
";",
"}",
"if",
"(",
"ReferenceEquals",
"(",
"newBottom",
".",
"Node",
",",
"curTop",
".",
"Node",
")",
"&&",
"(",
"newBottom",
".",
"Index",
"==",
"curTop",
".",
"Index",
")",
")",
"{",
"TopData",
"newTopVal",
"=",
"new",
"TopData",
"(",
"curTop",
".",
"Tag",
"+",
"1",
",",
"curTop",
".",
"Node",
",",
"curTop",
".",
"Index",
")",
";",
"if",
"(",
"SysUtil",
".",
"CAS",
"(",
"ref",
"_top",
",",
"curTop",
",",
"newTopVal",
")",
")",
"{",
"newBottom",
".",
"Node",
".",
"Data",
"[",
"newBottom",
".",
"Index",
"]",
"=",
"default",
"(",
"T",
")",
";",
"if",
"(",
"!",
"ReferenceEquals",
"(",
"curBottom",
".",
"Node",
",",
"newBottom",
".",
"Node",
")",
")",
"{",
"newBottom",
".",
"Node",
".",
"Prev",
"=",
"null",
";",
"}",
"item",
"=",
"retVal",
";",
"return",
"true",
";",
"}",
"else",
"{",
"_bottom",
"=",
"curBottom",
";",
"return",
"false",
";",
"}",
"}",
"if",
"(",
"!",
"ReferenceEquals",
"(",
"curBottom",
".",
"Node",
",",
"newBottom",
".",
"Node",
")",
")",
"{",
"newBottom",
".",
"Node",
".",
"Prev",
"=",
"null",
";",
"}",
"item",
"=",
"retVal",
";",
"return",
"true",
";",
"}",
"public",
"bool",
"TrySteal",
"(",
"out",
"T",
"item",
")",
"{",
"TopData",
"curTop",
"=",
"_top",
";",
"BottomData",
"curBottom",
"=",
"_bottom",
";",
"if",
"(",
"IsEmpty",
"(",
"curBottom",
",",
"curTop",
",",
"_capacity",
")",
")",
"{",
"item",
"=",
"default",
"(",
"T",
")",
";",
"if",
"(",
"ReferenceEquals",
"(",
"curTop",
",",
"_top",
")",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
"TopData",
"newTop",
";",
"if",
"(",
"curTop",
".",
"Index",
"!=",
"0",
")",
"{",
"newTop",
"=",
"new",
"TopData",
"(",
"curTop",
".",
"Tag",
",",
"curTop",
".",
"Node",
",",
"curTop",
".",
"Index",
"-",
"1",
")",
";",
"}",
"else",
"{",
"newTop",
"=",
"new",
"TopData",
"(",
"curTop",
".",
"Tag",
"+",
"1",
",",
"curTop",
".",
"Node",
".",
"Prev",
",",
"_capacity",
"-",
"1",
")",
";",
"}",
"T",
"retVal",
"=",
"curTop",
".",
"Node",
".",
"Data",
"[",
"curTop",
".",
"Index",
"]",
";",
"if",
"(",
"SysUtil",
".",
"CAS",
"(",
"ref",
"_top",
",",
"curTop",
",",
"newTop",
")",
")",
"{",
"SysUtil",
".",
"CAS",
"(",
"ref",
"curTop",
".",
"Node",
".",
"Data",
"[",
"curTop",
".",
"Index",
"]",
",",
"retVal",
",",
"default",
"(",
"T",
")",
")",
";",
"curTop",
".",
"Node",
".",
"Next",
"=",
"null",
";",
"item",
"=",
"retVal",
";",
"return",
"true",
";",
"}",
"else",
"{",
"item",
"=",
"default",
"(",
"T",
")",
";",
"return",
"false",
";",
"}",
"}",
"}"
] |
Provides a queue that allows items to pushed and popped by a single thread while
other threads may attempt steal from it.
|
[
"Provides",
"a",
"queue",
"that",
"allows",
"items",
"to",
"pushed",
"and",
"popped",
"by",
"a",
"single",
"thread",
"while",
"other",
"threads",
"may",
"attempt",
"steal",
"from",
"it",
"."
] |
[
"//--- Constants ---",
"//--- Types ---",
"//--- Fields ---",
"//--- Constructors ---",
"//--- Fields ---",
"//--- Constructors ---",
"//--- Fields ---",
"//--- Constructors ---",
"//--- Class Methods ---",
"//--- Fields ---",
"//--- Constructors ---",
"/// <summary>",
"/// Create a new instance.",
"/// </summary>",
"/// <summary>",
"/// Create a new instance.",
"/// </summary>",
"/// <param name=\"capacity\">Maximum number of items in the queue.</param>",
"//--- Properties ---",
"/// <summary>",
"/// Total number of items in queue.",
"/// </summary>",
"// check if top and bottom share the same node",
"//--- Methods ---",
"/// <summary>",
"/// Push an item onto the tail of the queue.",
"/// </summary>",
"/// <remarks>",
"/// NOTE: Push() and TryPop() <strong>MUST</strong> be called from the same thread.",
"/// </remarks>",
"/// <param name=\"data\">Item to push onto the tail of the queue.</param>",
"// read bottom data",
"// write data in current bottom cell",
"// allocate and link a new node",
"// update bottom",
"/// <summary>",
"/// Pop an item from the tail of the queue.",
"/// </summary>",
"/// <remarks>",
"/// NOTE: Push() and TryPop() <strong>MUST</strong> be called from the same thread.",
"/// </remarks>",
"/// <param name=\"item\">Tail item of the queue when operation is successful.</param>",
"/// <returns><see langword=\"True\"/> if operation was successful.</returns>",
"// read bottom data",
"// update bottom",
"// read top",
"// read data to be popped",
"// case 1: if _top has crossed _bottom",
"// return bottom to its old position",
"// case 2: when popping the last entry in the deque (i.e. deque is empty after the update of bottom)",
"// try to update _top's tag so no concurrent Steal operation will also pop the same entry",
"// clear out the entry we read, so the GC can reclaim it",
"// free old node if needed",
"// if CAS failed (i.e. a concurrent Steal operation alrady popped that last entry)",
"// return bottom to its old position",
"// case 3: regular case (i.e. there was a least one entry in the deque _after_ bottom's update)",
"// free old node if needed",
"/// <summary>",
"/// Pop an item from the head of the queue.",
"/// </summary>",
"/// <remarks>",
"/// NOTE: TrySteal() can be invoked from any thread.",
"/// </remarks>",
"/// <param name=\"item\">Head item of the queue when operation is successful.</param>",
"/// <returns><see langword=\"True\"/> if operation was successful.</returns>",
"// read top",
"// read bottom",
"// NOTE (steveb): this is contentious access case; we currently return 'false' but may want to differentiate in the future",
"// if deque isn't empty, calcuate next top pointer",
"// stay at current node",
"// move to next node and update tag",
"// read value",
"// try updating _top using CAS",
"// clear out the entry we read, so the GC can reclaim it",
"// free old node",
"// NOTE (steveb): this is contentious access case; we currently return 'false' but may want to differentiate in the future"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "typeparam",
"docstring": "Collection item type.",
"docstring_tokens": [
"Collection",
"item",
"type",
"."
]
}
]
}
| false
| 16
| 1,277
| 129
|
2294fc4ce2a7bd69c915e0e76d9bb6af86052646
|
jensparky83/reliability
|
reliability/Other_functions.py
|
[
"MIT"
] |
Python
|
similar_distributions
|
similar_distributions
This is a tool to find similar distributions when given an input distribution.
It is useful to see how similar one distribution is to another. For example, you may look at a Weibull distribution and think it looks like a Normal distribution.
Using this tool you can determine the parameters of the Normal distribution that most closely matches your Weibull distribution.
Inputs:
distribution - a distribution object created using the reliability.Distributions module
include_location_shifted - True/False. Default is True. When set to True it will include Weibull_3P, Lognormal_3P, Gamma_3P, Expon_2P
show_plot - True/False. Default is True
print_results - True/False. Default is True
number_of_distributions_to_show - the number of similar distributions to show. Default is 3. If the number specified exceeds the number available (typically 8), then the number specified will automatically be reduced.
Outputs:
results - an array of distributions objects ranked in order of best fit.
most_similar_distribution - a distribution object. This is the first item from results.
Example usage:
from reliability.Distributions import Weibull_Distribution
from reliability.Other_functions import similar_distributions
dist = Weibull_Distribution(alpha=50,beta=3.3)
similar_distributions(distribution=dist)
|
similar_distributions
This is a tool to find similar distributions when given an input distribution.
It is useful to see how similar one distribution is to another. For example, you may look at a Weibull distribution and think it looks like a Normal distribution.
Using this tool you can determine the parameters of the Normal distribution that most closely matches your Weibull distribution.
a distribution object created using the reliability.Distributions module
include_location_shifted - True/False. Default is True.
an array of distributions objects ranked in order of best fit.
most_similar_distribution - a distribution object. This is the first item from results.
|
[
"similar_distributions",
"This",
"is",
"a",
"tool",
"to",
"find",
"similar",
"distributions",
"when",
"given",
"an",
"input",
"distribution",
".",
"It",
"is",
"useful",
"to",
"see",
"how",
"similar",
"one",
"distribution",
"is",
"to",
"another",
".",
"For",
"example",
"you",
"may",
"look",
"at",
"a",
"Weibull",
"distribution",
"and",
"think",
"it",
"looks",
"like",
"a",
"Normal",
"distribution",
".",
"Using",
"this",
"tool",
"you",
"can",
"determine",
"the",
"parameters",
"of",
"the",
"Normal",
"distribution",
"that",
"most",
"closely",
"matches",
"your",
"Weibull",
"distribution",
".",
"a",
"distribution",
"object",
"created",
"using",
"the",
"reliability",
".",
"Distributions",
"module",
"include_location_shifted",
"-",
"True",
"/",
"False",
".",
"Default",
"is",
"True",
".",
"an",
"array",
"of",
"distributions",
"objects",
"ranked",
"in",
"order",
"of",
"best",
"fit",
".",
"most_similar_distribution",
"-",
"a",
"distribution",
"object",
".",
"This",
"is",
"the",
"first",
"item",
"from",
"results",
"."
] |
class similar_distributions:
'''
similar_distributions
This is a tool to find similar distributions when given an input distribution.
It is useful to see how similar one distribution is to another. For example, you may look at a Weibull distribution and think it looks like a Normal distribution.
Using this tool you can determine the parameters of the Normal distribution that most closely matches your Weibull distribution.
Inputs:
distribution - a distribution object created using the reliability.Distributions module
include_location_shifted - True/False. Default is True. When set to True it will include Weibull_3P, Lognormal_3P, Gamma_3P, Expon_2P
show_plot - True/False. Default is True
print_results - True/False. Default is True
number_of_distributions_to_show - the number of similar distributions to show. Default is 3. If the number specified exceeds the number available (typically 8), then the number specified will automatically be reduced.
Outputs:
results - an array of distributions objects ranked in order of best fit.
most_similar_distribution - a distribution object. This is the first item from results.
Example usage:
from reliability.Distributions import Weibull_Distribution
from reliability.Other_functions import similar_distributions
dist = Weibull_Distribution(alpha=50,beta=3.3)
similar_distributions(distribution=dist)
'''
def __init__(self, distribution, include_location_shifted=True, show_plot=True, print_results=True, number_of_distributions_to_show=3):
# ensure the input is a distribution object
if type(distribution) not in [Weibull_Distribution, Normal_Distribution, Lognormal_Distribution, Exponential_Distribution, Gamma_Distribution, Beta_Distribution]:
raise ValueError('distribution must be a probability distribution object from the reliability.Distributions module. First define the distribution using Reliability.Distributions.___')
# sample the CDF from 0.001 to 0.999. These samples will be used to fit all other distributions.
RVS = distribution.quantile(np.linspace(0.001, 0.999, 698)) # 698 samples is the ideal number for the points to align. Evidenced using plot_points.
# filter out negative values
RVS_filtered = []
negative_values_error = False
for item in RVS:
if item > 0:
RVS_filtered.append(item)
else:
negative_values_error = True
if negative_values_error is True:
print('WARNING: The input distribution has non-negligible area for x<0. Samples from this region have been discarded to enable other distributions to be fitted.')
fitted_results = Fit_Everything(failures=RVS_filtered, print_results=False, show_probability_plot=False, show_histogram_plot=False, show_PP_plot=False) # fit all distributions to the filtered samples
ranked_distributions = list(fitted_results.results.index.values)
ranked_distributions.remove(distribution.name2) # removes the fitted version of the original distribution
ranked_distributions_objects = []
ranked_distributions_labels = []
sigfig = 2
for dist_name in ranked_distributions:
if dist_name == 'Weibull_2P':
ranked_distributions_objects.append(Weibull_Distribution(alpha=fitted_results.Weibull_2P_alpha, beta=fitted_results.Weibull_2P_beta))
ranked_distributions_labels.append(str('Weibull_2P (α=' + str(round(fitted_results.Weibull_2P_alpha, sigfig)) + ',β=' + str(round(fitted_results.Weibull_2P_beta, sigfig)) + ')'))
elif dist_name == 'Gamma_2P':
ranked_distributions_objects.append(Gamma_Distribution(alpha=fitted_results.Gamma_2P_alpha, beta=fitted_results.Gamma_2P_beta))
ranked_distributions_labels.append(str('Gamma_2P (α=' + str(round(fitted_results.Gamma_2P_alpha, sigfig)) + ',β=' + str(round(fitted_results.Gamma_2P_beta, sigfig)) + ')'))
elif dist_name == 'Normal_2P':
ranked_distributions_objects.append(Normal_Distribution(mu=fitted_results.Normal_2P_mu, sigma=fitted_results.Normal_2P_sigma))
ranked_distributions_labels.append(str('Normal_2P (μ=' + str(round(fitted_results.Normal_2P_mu, sigfig)) + ',σ=' + str(round(fitted_results.Normal_2P_sigma, sigfig)) + ')'))
elif dist_name == 'Lognormal_2P':
ranked_distributions_objects.append(Lognormal_Distribution(mu=fitted_results.Lognormal_2P_mu, sigma=fitted_results.Lognormal_2P_sigma))
ranked_distributions_labels.append(str('Lognormal_2P (μ=' + str(round(fitted_results.Lognormal_2P_mu, sigfig)) + ',σ=' + str(round(fitted_results.Lognormal_2P_sigma, sigfig)) + ')'))
elif dist_name == 'Exponential_1P':
ranked_distributions_objects.append(Exponential_Distribution(Lambda=fitted_results.Expon_1P_lambda))
ranked_distributions_labels.append(str('Exponential_1P (lambda=' + str(round(fitted_results.Expon_1P_lambda, sigfig)) + ')'))
elif dist_name == 'Beta_2P':
ranked_distributions_objects.append(Beta_Distribution(alpha=fitted_results.Beta_2P_alpha, beta=fitted_results.Beta_2P_beta))
ranked_distributions_labels.append(str('Beta_2P (α=' + str(round(fitted_results.Beta_2P_alpha, sigfig)) + ',β=' + str(round(fitted_results.Beta_2P_beta, sigfig)) + ')'))
if include_location_shifted is True:
if dist_name == 'Weibull_3P':
ranked_distributions_objects.append(Weibull_Distribution(alpha=fitted_results.Weibull_3P_alpha, beta=fitted_results.Weibull_3P_beta, gamma=fitted_results.Weibull_3P_gamma))
ranked_distributions_labels.append(str('Weibull_3P (α=' + str(round(fitted_results.Weibull_3P_alpha, sigfig)) + ',β=' + str(round(fitted_results.Weibull_3P_beta, sigfig)) + ',γ=' + str(round(fitted_results.Weibull_3P_gamma, sigfig)) + ')'))
elif dist_name == 'Gamma_3P':
ranked_distributions_objects.append(Gamma_Distribution(alpha=fitted_results.Gamma_3P_alpha, beta=fitted_results.Gamma_3P_beta, gamma=fitted_results.Gamma_3P_gamma))
ranked_distributions_labels.append(str('Gamma_3P (α=' + str(round(fitted_results.Gamma_3P_alpha, sigfig)) + ',β=' + str(round(fitted_results.Gamma_3P_beta, sigfig)) + ',γ=' + str(round(fitted_results.Gamma_3P_gamma, sigfig)) + ')'))
elif dist_name == 'Lognormal_3P':
ranked_distributions_objects.append(Lognormal_Distribution(mu=fitted_results.Lognormal_3P_mu, sigma=fitted_results.Lognormal_3P_sigma, gamma=fitted_results.Lognormal_3P_gamma))
ranked_distributions_labels.append(str('Lognormal_3P (μ=' + str(round(fitted_results.Lognormal_3P_mu, sigfig)) + ',σ=' + str(round(fitted_results.Lognormal_3P_sigma, sigfig)) + ',γ=' + str(round(fitted_results.Lognormal_3P_gamma, sigfig)) + ')'))
elif dist_name == 'Exponential_2P':
ranked_distributions_objects.append(Exponential_Distribution(Lambda=fitted_results.Expon_1P_lambda, gamma=fitted_results.Expon_2P_gamma))
ranked_distributions_labels.append(str('Exponential_1P (lambda=' + str(round(fitted_results.Expon_1P_lambda, sigfig)) + ',γ=' + str(round(fitted_results.Expon_2P_gamma, sigfig)) + ')'))
number_of_distributions_fitted = len(ranked_distributions_objects)
self.results = ranked_distributions_objects
self.most_similar_distribution = ranked_distributions_objects[0]
if print_results is True:
print('The input distribution was:')
print(distribution.param_title_long)
if number_of_distributions_fitted < number_of_distributions_to_show:
number_of_distributions_to_show = number_of_distributions_fitted
print('\nThe top', number_of_distributions_to_show, 'most similar distributions are:')
counter = 0
while counter < number_of_distributions_to_show and counter < number_of_distributions_fitted:
dist = ranked_distributions_objects[counter]
print(dist.param_title_long)
counter += 1
if show_plot is True:
plt.figure(figsize=(14, 6))
plt.suptitle(str('Plot of similar distributions to ' + distribution.param_title_long))
counter = 0
xlower = distribution.quantile(0.001)
xupper = distribution.quantile(0.999)
x_delta = xupper - xlower
plt.subplot(121)
distribution.PDF(label=str('Input distribution [' + distribution.name2 + ']'), linestyle='--')
while counter < number_of_distributions_to_show and counter < number_of_distributions_fitted:
ranked_distributions_objects[counter].PDF(label=ranked_distributions_labels[counter])
counter += 1
plt.xlim([xlower - x_delta * 0.1, xupper + x_delta * 0.1])
plt.legend()
plt.title('PDF')
counter = 0
plt.subplot(122)
distribution.CDF(label=str('Input distribution [' + distribution.name2 + ']'), linestyle='--')
while counter < number_of_distributions_to_show and counter < number_of_distributions_fitted:
ranked_distributions_objects[counter].CDF(label=ranked_distributions_labels[counter])
counter += 1
plt.xlim([xlower - x_delta * 0.1, xupper + x_delta * 0.1])
plt.legend()
plt.title('CDF')
plt.subplots_adjust(left=0.08, right=0.95)
plt.show()
|
[
"class",
"similar_distributions",
":",
"def",
"__init__",
"(",
"self",
",",
"distribution",
",",
"include_location_shifted",
"=",
"True",
",",
"show_plot",
"=",
"True",
",",
"print_results",
"=",
"True",
",",
"number_of_distributions_to_show",
"=",
"3",
")",
":",
"if",
"type",
"(",
"distribution",
")",
"not",
"in",
"[",
"Weibull_Distribution",
",",
"Normal_Distribution",
",",
"Lognormal_Distribution",
",",
"Exponential_Distribution",
",",
"Gamma_Distribution",
",",
"Beta_Distribution",
"]",
":",
"raise",
"ValueError",
"(",
"'distribution must be a probability distribution object from the reliability.Distributions module. First define the distribution using Reliability.Distributions.___'",
")",
"RVS",
"=",
"distribution",
".",
"quantile",
"(",
"np",
".",
"linspace",
"(",
"0.001",
",",
"0.999",
",",
"698",
")",
")",
"RVS_filtered",
"=",
"[",
"]",
"negative_values_error",
"=",
"False",
"for",
"item",
"in",
"RVS",
":",
"if",
"item",
">",
"0",
":",
"RVS_filtered",
".",
"append",
"(",
"item",
")",
"else",
":",
"negative_values_error",
"=",
"True",
"if",
"negative_values_error",
"is",
"True",
":",
"print",
"(",
"'WARNING: The input distribution has non-negligible area for x<0. Samples from this region have been discarded to enable other distributions to be fitted.'",
")",
"fitted_results",
"=",
"Fit_Everything",
"(",
"failures",
"=",
"RVS_filtered",
",",
"print_results",
"=",
"False",
",",
"show_probability_plot",
"=",
"False",
",",
"show_histogram_plot",
"=",
"False",
",",
"show_PP_plot",
"=",
"False",
")",
"ranked_distributions",
"=",
"list",
"(",
"fitted_results",
".",
"results",
".",
"index",
".",
"values",
")",
"ranked_distributions",
".",
"remove",
"(",
"distribution",
".",
"name2",
")",
"ranked_distributions_objects",
"=",
"[",
"]",
"ranked_distributions_labels",
"=",
"[",
"]",
"sigfig",
"=",
"2",
"for",
"dist_name",
"in",
"ranked_distributions",
":",
"if",
"dist_name",
"==",
"'Weibull_2P'",
":",
"ranked_distributions_objects",
".",
"append",
"(",
"Weibull_Distribution",
"(",
"alpha",
"=",
"fitted_results",
".",
"Weibull_2P_alpha",
",",
"beta",
"=",
"fitted_results",
".",
"Weibull_2P_beta",
")",
")",
"ranked_distributions_labels",
".",
"append",
"(",
"str",
"(",
"'Weibull_2P (α=' ",
" ",
"tr(",
"r",
"ound(",
"f",
"itted_results.",
"W",
"eibull_2P_alpha,",
" ",
"igfig)",
")",
" ",
" ",
",β=' +",
"s",
"r(r",
"o",
"und(f",
"i",
"tted_results.W",
"e",
"ibull_2P_beta, ",
"s",
"gfig))",
" ",
"+",
"'",
"'))",
"",
"",
"elif",
"dist_name",
"==",
"'Gamma_2P'",
":",
"ranked_distributions_objects",
".",
"append",
"(",
"Gamma_Distribution",
"(",
"alpha",
"=",
"fitted_results",
".",
"Gamma_2P_alpha",
",",
"beta",
"=",
"fitted_results",
".",
"Gamma_2P_beta",
")",
")",
"ranked_distributions_labels",
".",
"append",
"(",
"str",
"(",
"'Gamma_2P (α=' ",
" ",
"tr(",
"r",
"ound(",
"f",
"itted_results.",
"G",
"amma_2P_alpha,",
" ",
"igfig)",
")",
" ",
" ",
",β=' +",
"s",
"r(r",
"o",
"und(f",
"i",
"tted_results.G",
"a",
"mma_2P_beta, ",
"s",
"gfig))",
" ",
"+",
"'",
"'))",
"",
"",
"elif",
"dist_name",
"==",
"'Normal_2P'",
":",
"ranked_distributions_objects",
".",
"append",
"(",
"Normal_Distribution",
"(",
"mu",
"=",
"fitted_results",
".",
"Normal_2P_mu",
",",
"sigma",
"=",
"fitted_results",
".",
"Normal_2P_sigma",
")",
")",
"ranked_distributions_labels",
".",
"append",
"(",
"str",
"(",
"'Normal_2P (μ=' ",
" ",
"tr(",
"r",
"ound(",
"f",
"itted_results.",
"N",
"ormal_2P_mu,",
" ",
"igfig)",
")",
" ",
" ",
",σ=' +",
"s",
"r(r",
"o",
"und(f",
"i",
"tted_results.N",
"o",
"rmal_2P_sigma, ",
"s",
"gfig))",
" ",
"+",
"'",
"'))",
"",
"",
"elif",
"dist_name",
"==",
"'Lognormal_2P'",
":",
"ranked_distributions_objects",
".",
"append",
"(",
"Lognormal_Distribution",
"(",
"mu",
"=",
"fitted_results",
".",
"Lognormal_2P_mu",
",",
"sigma",
"=",
"fitted_results",
".",
"Lognormal_2P_sigma",
")",
")",
"ranked_distributions_labels",
".",
"append",
"(",
"str",
"(",
"'Lognormal_2P (μ=' ",
" ",
"tr(",
"r",
"ound(",
"f",
"itted_results.",
"L",
"ognormal_2P_mu,",
" ",
"igfig)",
")",
" ",
" ",
",σ=' +",
"s",
"r(r",
"o",
"und(f",
"i",
"tted_results.L",
"o",
"gnormal_2P_sigma, ",
"s",
"gfig))",
" ",
"+",
"'",
"'))",
"",
"",
"elif",
"dist_name",
"==",
"'Exponential_1P'",
":",
"ranked_distributions_objects",
".",
"append",
"(",
"Exponential_Distribution",
"(",
"Lambda",
"=",
"fitted_results",
".",
"Expon_1P_lambda",
")",
")",
"ranked_distributions_labels",
".",
"append",
"(",
"str",
"(",
"'Exponential_1P (lambda='",
"+",
"str",
"(",
"round",
"(",
"fitted_results",
".",
"Expon_1P_lambda",
",",
"sigfig",
")",
")",
"+",
"')'",
")",
")",
"elif",
"dist_name",
"==",
"'Beta_2P'",
":",
"ranked_distributions_objects",
".",
"append",
"(",
"Beta_Distribution",
"(",
"alpha",
"=",
"fitted_results",
".",
"Beta_2P_alpha",
",",
"beta",
"=",
"fitted_results",
".",
"Beta_2P_beta",
")",
")",
"ranked_distributions_labels",
".",
"append",
"(",
"str",
"(",
"'Beta_2P (α=' ",
" ",
"tr(",
"r",
"ound(",
"f",
"itted_results.",
"B",
"eta_2P_alpha,",
" ",
"igfig)",
")",
" ",
" ",
",β=' +",
"s",
"r(r",
"o",
"und(f",
"i",
"tted_results.B",
"e",
"ta_2P_beta, ",
"s",
"gfig))",
" ",
"+",
"'",
"'))",
"",
"",
"if",
"include_location_shifted",
"is",
"True",
":",
"if",
"dist_name",
"==",
"'Weibull_3P'",
":",
"ranked_distributions_objects",
".",
"append",
"(",
"Weibull_Distribution",
"(",
"alpha",
"=",
"fitted_results",
".",
"Weibull_3P_alpha",
",",
"beta",
"=",
"fitted_results",
".",
"Weibull_3P_beta",
",",
"gamma",
"=",
"fitted_results",
".",
"Weibull_3P_gamma",
")",
")",
"ranked_distributions_labels",
".",
"append",
"(",
"str",
"(",
"'Weibull_3P (α=' ",
" ",
"tr(",
"r",
"ound(",
"f",
"itted_results.",
"W",
"eibull_3P_alpha,",
" ",
"igfig)",
")",
" ",
" ",
",β=' +",
"s",
"r(r",
"o",
"und(f",
"i",
"tted_results.W",
"e",
"ibull_3P_beta, ",
"s",
"gfig))",
" ",
"+",
"'",
"γ=' + ",
"t",
"(ro",
"u",
"nd(fi",
"t",
"ted_results.We",
"i",
"bull_3P_gamma, s",
"i",
"fig)) ",
"+",
" ",
")",
"))",
"",
"",
"elif",
"dist_name",
"==",
"'Gamma_3P'",
":",
"ranked_distributions_objects",
".",
"append",
"(",
"Gamma_Distribution",
"(",
"alpha",
"=",
"fitted_results",
".",
"Gamma_3P_alpha",
",",
"beta",
"=",
"fitted_results",
".",
"Gamma_3P_beta",
",",
"gamma",
"=",
"fitted_results",
".",
"Gamma_3P_gamma",
")",
")",
"ranked_distributions_labels",
".",
"append",
"(",
"str",
"(",
"'Gamma_3P (α=' ",
" ",
"tr(",
"r",
"ound(",
"f",
"itted_results.",
"G",
"amma_3P_alpha,",
" ",
"igfig)",
")",
" ",
" ",
",β=' +",
"s",
"r(r",
"o",
"und(f",
"i",
"tted_results.G",
"a",
"mma_3P_beta, ",
"s",
"gfig))",
" ",
"+",
"'",
"γ=' + ",
"t",
"(ro",
"u",
"nd(fi",
"t",
"ted_results.Ga",
"m",
"ma_3P_gamma, s",
"i",
"fig)) ",
"+",
" ",
")",
"))",
"",
"",
"elif",
"dist_name",
"==",
"'Lognormal_3P'",
":",
"ranked_distributions_objects",
".",
"append",
"(",
"Lognormal_Distribution",
"(",
"mu",
"=",
"fitted_results",
".",
"Lognormal_3P_mu",
",",
"sigma",
"=",
"fitted_results",
".",
"Lognormal_3P_sigma",
",",
"gamma",
"=",
"fitted_results",
".",
"Lognormal_3P_gamma",
")",
")",
"ranked_distributions_labels",
".",
"append",
"(",
"str",
"(",
"'Lognormal_3P (μ=' ",
" ",
"tr(",
"r",
"ound(",
"f",
"itted_results.",
"L",
"ognormal_3P_mu,",
" ",
"igfig)",
")",
" ",
" ",
",σ=' +",
"s",
"r(r",
"o",
"und(f",
"i",
"tted_results.L",
"o",
"gnormal_3P_sigma, ",
"s",
"gfig))",
" ",
"+",
"'",
"γ=' + ",
"t",
"(ro",
"u",
"nd(fi",
"t",
"ted_results.Lo",
"g",
"normal_3P_gamma, s",
"i",
"fig)) ",
"+",
" ",
")",
"))",
"",
"",
"elif",
"dist_name",
"==",
"'Exponential_2P'",
":",
"ranked_distributions_objects",
".",
"append",
"(",
"Exponential_Distribution",
"(",
"Lambda",
"=",
"fitted_results",
".",
"Expon_1P_lambda",
",",
"gamma",
"=",
"fitted_results",
".",
"Expon_2P_gamma",
")",
")",
"ranked_distributions_labels",
".",
"append",
"(",
"str",
"(",
"'Exponential_1P (lambda='",
"+",
"str",
"(",
"round",
"(",
"fitted_results",
".",
"Expon_1P_lambda",
",",
"sigfig",
")",
")",
"+",
"',γ=' ",
" ",
"tr(",
"r",
"ound(",
"f",
"itted_results.",
"E",
"xpon_2P_gamma,",
" ",
"igfig)",
")",
" ",
" ",
")')",
")",
"",
"number_of_distributions_fitted",
"=",
"len",
"(",
"ranked_distributions_objects",
")",
"self",
".",
"results",
"=",
"ranked_distributions_objects",
"self",
".",
"most_similar_distribution",
"=",
"ranked_distributions_objects",
"[",
"0",
"]",
"if",
"print_results",
"is",
"True",
":",
"print",
"(",
"'The input distribution was:'",
")",
"print",
"(",
"distribution",
".",
"param_title_long",
")",
"if",
"number_of_distributions_fitted",
"<",
"number_of_distributions_to_show",
":",
"number_of_distributions_to_show",
"=",
"number_of_distributions_fitted",
"print",
"(",
"'\\nThe top'",
",",
"number_of_distributions_to_show",
",",
"'most similar distributions are:'",
")",
"counter",
"=",
"0",
"while",
"counter",
"<",
"number_of_distributions_to_show",
"and",
"counter",
"<",
"number_of_distributions_fitted",
":",
"dist",
"=",
"ranked_distributions_objects",
"[",
"counter",
"]",
"print",
"(",
"dist",
".",
"param_title_long",
")",
"counter",
"+=",
"1",
"if",
"show_plot",
"is",
"True",
":",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"14",
",",
"6",
")",
")",
"plt",
".",
"suptitle",
"(",
"str",
"(",
"'Plot of similar distributions to '",
"+",
"distribution",
".",
"param_title_long",
")",
")",
"counter",
"=",
"0",
"xlower",
"=",
"distribution",
".",
"quantile",
"(",
"0.001",
")",
"xupper",
"=",
"distribution",
".",
"quantile",
"(",
"0.999",
")",
"x_delta",
"=",
"xupper",
"-",
"xlower",
"plt",
".",
"subplot",
"(",
"121",
")",
"distribution",
".",
"PDF",
"(",
"label",
"=",
"str",
"(",
"'Input distribution ['",
"+",
"distribution",
".",
"name2",
"+",
"']'",
")",
",",
"linestyle",
"=",
"'--'",
")",
"while",
"counter",
"<",
"number_of_distributions_to_show",
"and",
"counter",
"<",
"number_of_distributions_fitted",
":",
"ranked_distributions_objects",
"[",
"counter",
"]",
".",
"PDF",
"(",
"label",
"=",
"ranked_distributions_labels",
"[",
"counter",
"]",
")",
"counter",
"+=",
"1",
"plt",
".",
"xlim",
"(",
"[",
"xlower",
"-",
"x_delta",
"*",
"0.1",
",",
"xupper",
"+",
"x_delta",
"*",
"0.1",
"]",
")",
"plt",
".",
"legend",
"(",
")",
"plt",
".",
"title",
"(",
"'PDF'",
")",
"counter",
"=",
"0",
"plt",
".",
"subplot",
"(",
"122",
")",
"distribution",
".",
"CDF",
"(",
"label",
"=",
"str",
"(",
"'Input distribution ['",
"+",
"distribution",
".",
"name2",
"+",
"']'",
")",
",",
"linestyle",
"=",
"'--'",
")",
"while",
"counter",
"<",
"number_of_distributions_to_show",
"and",
"counter",
"<",
"number_of_distributions_fitted",
":",
"ranked_distributions_objects",
"[",
"counter",
"]",
".",
"CDF",
"(",
"label",
"=",
"ranked_distributions_labels",
"[",
"counter",
"]",
")",
"counter",
"+=",
"1",
"plt",
".",
"xlim",
"(",
"[",
"xlower",
"-",
"x_delta",
"*",
"0.1",
",",
"xupper",
"+",
"x_delta",
"*",
"0.1",
"]",
")",
"plt",
".",
"legend",
"(",
")",
"plt",
".",
"title",
"(",
"'CDF'",
")",
"plt",
".",
"subplots_adjust",
"(",
"left",
"=",
"0.08",
",",
"right",
"=",
"0.95",
")",
"plt",
".",
"show",
"(",
")"
] |
similar_distributions
This is a tool to find similar distributions when given an input distribution.
|
[
"similar_distributions",
"This",
"is",
"a",
"tool",
"to",
"find",
"similar",
"distributions",
"when",
"given",
"an",
"input",
"distribution",
"."
] |
[
"'''\n similar_distributions\n\n This is a tool to find similar distributions when given an input distribution.\n It is useful to see how similar one distribution is to another. For example, you may look at a Weibull distribution and think it looks like a Normal distribution.\n Using this tool you can determine the parameters of the Normal distribution that most closely matches your Weibull distribution.\n\n Inputs:\n distribution - a distribution object created using the reliability.Distributions module\n include_location_shifted - True/False. Default is True. When set to True it will include Weibull_3P, Lognormal_3P, Gamma_3P, Expon_2P\n show_plot - True/False. Default is True\n print_results - True/False. Default is True\n number_of_distributions_to_show - the number of similar distributions to show. Default is 3. If the number specified exceeds the number available (typically 8), then the number specified will automatically be reduced.\n\n Outputs:\n results - an array of distributions objects ranked in order of best fit.\n most_similar_distribution - a distribution object. This is the first item from results.\n\n Example usage:\n from reliability.Distributions import Weibull_Distribution\n from reliability.Other_functions import similar_distributions\n dist = Weibull_Distribution(alpha=50,beta=3.3)\n similar_distributions(distribution=dist)\n '''",
"# ensure the input is a distribution object",
"# sample the CDF from 0.001 to 0.999. These samples will be used to fit all other distributions.",
"# 698 samples is the ideal number for the points to align. Evidenced using plot_points.",
"# filter out negative values",
"# fit all distributions to the filtered samples",
"# removes the fitted version of the original distribution"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 28
| 2,267
| 299
|
ead9932f8cda3b67f3e060dfb10daef4e7058ebd
|
KarimLUCCIN/ChromeCast-Desktop-Audio-Streamer
|
Source/MiniCast.Client/ViewModel/MainViewModel.cs
|
[
"MIT"
] |
C#
|
MainViewModel
|
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
|
This class contains properties that the main View can data bind to.
Use the mvvminpc
You can also use Blend to data bind with the tool's support.
|
[
"This",
"class",
"contains",
"properties",
"that",
"the",
"main",
"View",
"can",
"data",
"bind",
"to",
".",
"Use",
"the",
"mvvminpc",
"You",
"can",
"also",
"use",
"Blend",
"to",
"data",
"bind",
"with",
"the",
"tool",
"'",
"s",
"support",
"."
] |
public class MainViewModel : ViewModelBase
{
private HamburgerMenuItemCollection _menuItems;
private HamburgerMenuItemCollection _menuOptionItems;
public MainViewModel()
{
this.CreateMenuItems();
ViewModelLocator.Instance.Hue.BeginUpdateEveryFrame();
}
public void CreateMenuItems()
{
MenuItems = new HamburgerMenuItemCollection
{
new HamburgerMenuIconItem()
{
Icon = new PackIconMaterial() {Kind = PackIconMaterialKind.Cast},
Label = "Chromecast",
ToolTip = "Chromecast Settings.",
Tag = ViewModelLocator.Instance.Chromecast
},
new HamburgerMenuIconItem()
{
Icon = new PackIconMaterial() {Kind = PackIconMaterialKind.LightbulbOn},
Label = "Hue",
ToolTip = "Philips Hue.",
Tag = ViewModelLocator.Instance.Hue
},
new HamburgerMenuIconItem()
{
Icon = new PackIconMaterial() {Kind = PackIconMaterialKind.Music},
Label = "Music Colors",
ToolTip = "Music Color Setup",
Tag = ViewModelLocator.Instance.MusicColor
}
};
MenuOptionItems = new HamburgerMenuItemCollection
{
new HamburgerMenuIconItem()
{
Icon = new PackIconMaterial() {Kind = PackIconMaterialKind.Settings},
Label = "Settings",
ToolTip = "General Settings.",
Tag = ViewModelLocator.Instance.Settings
}
};
}
public HamburgerMenuItemCollection MenuItems
{
get { return _menuItems; }
set
{
if (Equals(value, _menuItems)) return;
_menuItems = value;
RaisePropertyChanged();
}
}
public HamburgerMenuItemCollection MenuOptionItems
{
get { return _menuOptionItems; }
set
{
if (Equals(value, _menuOptionItems)) return;
_menuOptionItems = value;
RaisePropertyChanged();
}
}
}
|
[
"public",
"class",
"MainViewModel",
":",
"ViewModelBase",
"{",
"private",
"HamburgerMenuItemCollection",
"_menuItems",
";",
"private",
"HamburgerMenuItemCollection",
"_menuOptionItems",
";",
"public",
"MainViewModel",
"(",
")",
"{",
"this",
".",
"CreateMenuItems",
"(",
")",
";",
"ViewModelLocator",
".",
"Instance",
".",
"Hue",
".",
"BeginUpdateEveryFrame",
"(",
")",
";",
"}",
"public",
"void",
"CreateMenuItems",
"(",
")",
"{",
"MenuItems",
"=",
"new",
"HamburgerMenuItemCollection",
"{",
"new",
"HamburgerMenuIconItem",
"(",
")",
"{",
"Icon",
"=",
"new",
"PackIconMaterial",
"(",
")",
"{",
"Kind",
"=",
"PackIconMaterialKind",
".",
"Cast",
"}",
",",
"Label",
"=",
"\"",
"Chromecast",
"\"",
",",
"ToolTip",
"=",
"\"",
"Chromecast Settings.",
"\"",
",",
"Tag",
"=",
"ViewModelLocator",
".",
"Instance",
".",
"Chromecast",
"}",
",",
"new",
"HamburgerMenuIconItem",
"(",
")",
"{",
"Icon",
"=",
"new",
"PackIconMaterial",
"(",
")",
"{",
"Kind",
"=",
"PackIconMaterialKind",
".",
"LightbulbOn",
"}",
",",
"Label",
"=",
"\"",
"Hue",
"\"",
",",
"ToolTip",
"=",
"\"",
"Philips Hue.",
"\"",
",",
"Tag",
"=",
"ViewModelLocator",
".",
"Instance",
".",
"Hue",
"}",
",",
"new",
"HamburgerMenuIconItem",
"(",
")",
"{",
"Icon",
"=",
"new",
"PackIconMaterial",
"(",
")",
"{",
"Kind",
"=",
"PackIconMaterialKind",
".",
"Music",
"}",
",",
"Label",
"=",
"\"",
"Music Colors",
"\"",
",",
"ToolTip",
"=",
"\"",
"Music Color Setup",
"\"",
",",
"Tag",
"=",
"ViewModelLocator",
".",
"Instance",
".",
"MusicColor",
"}",
"}",
";",
"MenuOptionItems",
"=",
"new",
"HamburgerMenuItemCollection",
"{",
"new",
"HamburgerMenuIconItem",
"(",
")",
"{",
"Icon",
"=",
"new",
"PackIconMaterial",
"(",
")",
"{",
"Kind",
"=",
"PackIconMaterialKind",
".",
"Settings",
"}",
",",
"Label",
"=",
"\"",
"Settings",
"\"",
",",
"ToolTip",
"=",
"\"",
"General Settings.",
"\"",
",",
"Tag",
"=",
"ViewModelLocator",
".",
"Instance",
".",
"Settings",
"}",
"}",
";",
"}",
"public",
"HamburgerMenuItemCollection",
"MenuItems",
"{",
"get",
"{",
"return",
"_menuItems",
";",
"}",
"set",
"{",
"if",
"(",
"Equals",
"(",
"value",
",",
"_menuItems",
")",
")",
"return",
";",
"_menuItems",
"=",
"value",
";",
"RaisePropertyChanged",
"(",
")",
";",
"}",
"}",
"public",
"HamburgerMenuItemCollection",
"MenuOptionItems",
"{",
"get",
"{",
"return",
"_menuOptionItems",
";",
"}",
"set",
"{",
"if",
"(",
"Equals",
"(",
"value",
",",
"_menuOptionItems",
")",
")",
"return",
";",
"_menuOptionItems",
"=",
"value",
";",
"RaisePropertyChanged",
"(",
")",
";",
"}",
"}",
"}"
] |
This class contains properties that the main View can data bind to.
|
[
"This",
"class",
"contains",
"properties",
"that",
"the",
"main",
"View",
"can",
"data",
"bind",
"to",
"."
] |
[] |
[
{
"param": "ViewModelBase",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ViewModelBase",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 16
| 428
| 97
|
3e6cba57ab5c56d5bdf4a9034dfeff11a5948cec
|
belav/roslyn
|
src/Workspaces/Core/Portable/Options/DocumentOptionSet.cs
|
[
"MIT"
] |
C#
|
DocumentOptionSet
|
/// <summary>
/// An <see cref="OptionSet"/> that comes from <see cref="Document.GetOptionsAsync(System.Threading.CancellationToken)"/>. It behaves just like a normal
/// <see cref="OptionSet"/> but remembers which language the <see cref="Document"/> is, so you don't have to
/// pass that information redundantly when calling <see cref="GetOption{T}(PerLanguageOption{T})"/>.
/// </summary>
|
An that comes from . It behaves just like a normal
but remembers which language the is, so you don't have to
pass that information redundantly when calling .
|
[
"An",
"that",
"comes",
"from",
".",
"It",
"behaves",
"just",
"like",
"a",
"normal",
"but",
"remembers",
"which",
"language",
"the",
"is",
"so",
"you",
"don",
"'",
"t",
"have",
"to",
"pass",
"that",
"information",
"redundantly",
"when",
"calling",
"."
] |
public sealed class DocumentOptionSet : OptionSet
{
private readonly OptionSet _backingOptionSet;
private readonly string _language;
internal DocumentOptionSet(OptionSet backingOptionSet, string language)
{
_backingOptionSet = backingOptionSet;
_language = language;
}
private protected override object? GetOptionCore(OptionKey optionKey) =>
_backingOptionSet.GetOption(optionKey);
public T GetOption<T>(PerLanguageOption<T> option) =>
_backingOptionSet.GetOption(option, _language);
internal T GetOption<T>(PerLanguageOption2<T> option) =>
_backingOptionSet.GetOption(option, _language);
public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value) =>
new DocumentOptionSet(
_backingOptionSet.WithChangedOption(optionAndLanguage, value),
_language
);
public DocumentOptionSet WithChangedOption<T>(PerLanguageOption<T> option, T value) =>
(DocumentOptionSet)WithChangedOption(option, _language, value);
internal DocumentOptionSet WithChangedOption<T>(PerLanguageOption2<T> option, T value) =>
(DocumentOptionSet)WithChangedOption(option, _language, value);
private protected override AnalyzerConfigOptions CreateAnalyzerConfigOptions(
IOptionService optionService,
string? language
)
{
Debug.Assert(
(language ?? _language) == _language,
$"Use of a {nameof(DocumentOptionSet)} is not expected to differ from the language it was constructed with."
);
return _backingOptionSet.AsAnalyzerConfigOptions(optionService, language ?? _language);
}
internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet) =>
_backingOptionSet.GetChangedOptions(optionSet);
}
|
[
"public",
"sealed",
"class",
"DocumentOptionSet",
":",
"OptionSet",
"{",
"private",
"readonly",
"OptionSet",
"_backingOptionSet",
";",
"private",
"readonly",
"string",
"_language",
";",
"internal",
"DocumentOptionSet",
"(",
"OptionSet",
"backingOptionSet",
",",
"string",
"language",
")",
"{",
"_backingOptionSet",
"=",
"backingOptionSet",
";",
"_language",
"=",
"language",
";",
"}",
"private",
"protected",
"override",
"object",
"?",
"GetOptionCore",
"(",
"OptionKey",
"optionKey",
")",
"=>",
"_backingOptionSet",
".",
"GetOption",
"(",
"optionKey",
")",
";",
"public",
"T",
"GetOption",
"<",
"T",
">",
"(",
"PerLanguageOption",
"<",
"T",
">",
"option",
")",
"=>",
"_backingOptionSet",
".",
"GetOption",
"(",
"option",
",",
"_language",
")",
";",
"internal",
"T",
"GetOption",
"<",
"T",
">",
"(",
"PerLanguageOption2",
"<",
"T",
">",
"option",
")",
"=>",
"_backingOptionSet",
".",
"GetOption",
"(",
"option",
",",
"_language",
")",
";",
"public",
"override",
"OptionSet",
"WithChangedOption",
"(",
"OptionKey",
"optionAndLanguage",
",",
"object",
"?",
"value",
")",
"=>",
"new",
"DocumentOptionSet",
"(",
"_backingOptionSet",
".",
"WithChangedOption",
"(",
"optionAndLanguage",
",",
"value",
")",
",",
"_language",
")",
";",
"public",
"DocumentOptionSet",
"WithChangedOption",
"<",
"T",
">",
"(",
"PerLanguageOption",
"<",
"T",
">",
"option",
",",
"T",
"value",
")",
"=>",
"(",
"DocumentOptionSet",
")",
"WithChangedOption",
"(",
"option",
",",
"_language",
",",
"value",
")",
";",
"internal",
"DocumentOptionSet",
"WithChangedOption",
"<",
"T",
">",
"(",
"PerLanguageOption2",
"<",
"T",
">",
"option",
",",
"T",
"value",
")",
"=>",
"(",
"DocumentOptionSet",
")",
"WithChangedOption",
"(",
"option",
",",
"_language",
",",
"value",
")",
";",
"private",
"protected",
"override",
"AnalyzerConfigOptions",
"CreateAnalyzerConfigOptions",
"(",
"IOptionService",
"optionService",
",",
"string",
"?",
"language",
")",
"{",
"Debug",
".",
"Assert",
"(",
"(",
"language",
"??",
"_language",
")",
"==",
"_language",
",",
"$\"",
"Use of a ",
"{",
"nameof",
"(",
"DocumentOptionSet",
")",
"}",
" is not expected to differ from the language it was constructed with.",
"\"",
")",
";",
"return",
"_backingOptionSet",
".",
"AsAnalyzerConfigOptions",
"(",
"optionService",
",",
"language",
"??",
"_language",
")",
";",
"}",
"internal",
"override",
"IEnumerable",
"<",
"OptionKey",
">",
"GetChangedOptions",
"(",
"OptionSet",
"optionSet",
")",
"=>",
"_backingOptionSet",
".",
"GetChangedOptions",
"(",
"optionSet",
")",
";",
"}"
] |
An that comes from .
|
[
"An",
"that",
"comes",
"from",
"."
] |
[
"/// <summary>",
"/// Creates a new <see cref=\"DocumentOptionSet\" /> that contains the changed value.",
"/// </summary>",
"/// <summary>",
"/// Creates a new <see cref=\"DocumentOptionSet\" /> that contains the changed value.",
"/// </summary>"
] |
[
{
"param": "OptionSet",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "OptionSet",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 393
| 92
|
41e0ab3c25e858bfc6f2a8a389be28466b0d8995
|
pswietojanski/pyroomacoustics
|
pyroomacoustics/recognition.py
|
[
"MIT"
] |
Python
|
HMM
|
Hidden Markov Model with Gaussian emissions
Attributes
----------
K : int
Number of states in the model
O : int
Number of dimensions of the Gaussian emission distribution
A : ndarray
KxK transition matrix of the Markov chain
pi : ndarray
K dim vector of the initial probabilities of the Markov chain
emission : (GaussianEmission or CircularGaussianEmission)
An instance of emission_class
model : string, optional
The model used for the chain, can be 'full' or 'left-right'
leftright_jum_max : int, optional
The number of non-zero upper diagonals in a 'left-right' model
|
Hidden Markov Model with Gaussian emissions
Attributes
|
[
"Hidden",
"Markov",
"Model",
"with",
"Gaussian",
"emissions",
"Attributes"
] |
class HMM:
'''
Hidden Markov Model with Gaussian emissions
Attributes
----------
K : int
Number of states in the model
O : int
Number of dimensions of the Gaussian emission distribution
A : ndarray
KxK transition matrix of the Markov chain
pi : ndarray
K dim vector of the initial probabilities of the Markov chain
emission : (GaussianEmission or CircularGaussianEmission)
An instance of emission_class
model : string, optional
The model used for the chain, can be 'full' or 'left-right'
leftright_jum_max : int, optional
The number of non-zero upper diagonals in a 'left-right' model
'''
def __init__(self, nstates, emission, model='full', leftright_jump_max=3):
'''
Initialize a Hidden Markov Model with nstates and Gaussian observations
nstates: int
The number of states in the Markov chain
emission : emission object, optional
The emission object (CircularGaussianEmission or GaussianEmission)
model : string, optional
The model used for the chain, can be 'full' or 'left-right'
leftright_jump_max : int
The maximum jump length in the Left-Right chain model
'''
self.K = nstates # number of states
self.emission = emission # The observation parameters
# The Markov chain parameters
self.model = model
self.leftright_jump_max = leftright_jump_max
self.A = np.zeros((self.K, self.K)) # the state transition matrix
self.pi = np.zeros((self.K)) # the initial distribution
# Initialize the HMM parameters to some random values
if self.model == 'full':
self.A = np.random.uniform(size=(self.K,self.K))
self.pi = np.random.uniform(size=(self.K))
elif self.model == 'left-right':
self.A = np.triu(np.tril(np.random.uniform(size=(self.K,self.K)), k=self.leftright_jump_max))
self.A += np.diag(np.sum(self.A[:,:], axis=1)*2)
self.pi = np.zeros(self.K)
self.pi[0] = 1
# Normalize the distributions
for row in self.A:
row /= row.sum()
self.pi /= self.pi.sum()
def fit(self, examples, tol=0.1, max_iter=10, verbose=False):
'''
Training of the HMM using the EM algorithm
Parameters
----------
examples : (list)
A list of examples used to train the model. Each example is
an array of feature vectors, each row is a feature vector,
the sequence runs on axis 0
tol : (float)
The training stops when the progress between to steps is less than
this number (default 0.1)
max_iter : (int)
Alternatively the algorithm stops when a maximum number of
iterations is reached (default 10)
verbose : bool, optional
When True, prints extra information about convergence
'''
# Make sure to normalize parameters that should be...
for row in self.A:
row[:] /= row.sum()
self.pi[:] /= self.pi.sum()
# Run the EM algorithm
loglikelihood_old = -np.inf # log-likelihood
n_iter = 0
while True:
# Initialize new parameters value for accumulation
loglikelihood = 0.
# We need to run the forward/backward algorithm for each example and
# and combine the result to form the new estimates
gamma = []
xhi = []
p_x_given_z = self.emission.prob_x_given_state(examples)
# Expectation-step
#-----------------
for X,pxz in zip(examples, p_x_given_z):
# check dimension of emission
if X.shape[1] != self.emission.O:
raise ValueError("Error: Emission vectors of all examples should have the same size")
# First compute alpha and beta using forward/backward algo
alpha, c = self.forward(X, pxz)
beta = self.backward(X, pxz, c)
# Recompute the likelihood of the sequence
# (Bishop 13.63)
loglikelihood += np.sum(np.log(c))
# Now the more interesting quantities
# gamma(z_n) = p(z_n | X, theta_old)
# xhi(z_{n-1}, z_n) = p(z_{n-1}, z_n | X, theta_old)
gamma.append(alpha * beta)
xhi.append(np.zeros((X.shape[0]-1, self.K, self.K)))
for n in range(1,X.shape[0]):
xhi[-1][n-1] = np.outer(alpha[n-1], beta[n]*pxz[n])*self.A/c[n]
# Maximization-step
#------------------
# update the Markov Chain parameters
self.update_parameters(examples, gamma, xhi)
# Update the emission distribution parameters
self.emission.update_parameters(examples, gamma)
# Now check for convergence
#--------------------------
n_iter += 1
epsilon = loglikelihood - loglikelihood_old
if verbose:
print('Iterations:', n_iter, 'epsilon:', epsilon, 'LL_new:', loglikelihood)
# some checks here
if epsilon < tol:
if verbose:
print('Tolerance reached: stopping.')
break
if n_iter == max_iter:
if verbose:
print('Maximum iterations reached: stopping.')
break
loglikelihood_old = loglikelihood
# return the number of iterations performed
return n_iter
def update_parameters(self, examples, gamma, xhi):
''' Update the parameters of the Markov Chain '''
X = np.concatenate(examples, axis=0)
x = np.concatenate(xhi, axis=0)
self.pi[:] = np.sum([g[0,:] for g in gamma], axis=0)
self.A = x.sum(axis=0)
# normalize to enforce distribution constraints
self.pi /= np.sum(self.pi)
for k in range(self.K):
den = np.sum(self.A[k,:])
if den < 1e-15:
self.A[k,:] = 0.
else:
self.A[k,:] /= den
def generate(self, N):
''' Generate a random sample of length N using the model '''
X = np.zeros((N, self.emission.O))
distributions = self.emission.get_pdfs()
# pick initial state
state = np.random.choice(self.K, p=self.pi)
# now run the chain
for n in range(0,N):
# produce emission vector according to current state
X[n,:] = distributions[state].rvs()
# pick next state
state = np.random.choice(self.K, p=self.A[state,:])
return X
def loglikelihood(self, X):
'''
Compute the log-likelihood of a sample vector using the sum-product algorithm
'''
p_x_given_z = self.emission.prob_x_given_state([X])[0]
alpha, c = self.forward(X, p_x_given_z)
return np.sum(np.log(c))
def forward(self, X, p_x_given_z):
''' The forward recursion for HMM as described in Bishop Ch. 13 '''
# initialize the alpha vector
alpha = np.zeros((X.shape[0], self.K))
c = np.zeros(X.shape[0])
# initialize the recursion as
# p(X | z_k) pi_k
alpha[0] = p_x_given_z[0]*self.pi
c[0] = np.sum(alpha[0])
alpha[0] /= c[0]
# Run the forward recursion
for n in range(1,X.shape[0]):
alpha[n] = p_x_given_z[n]*np.dot(self.A.T, alpha[n-1])
c[n] = np.sum(alpha[n])
alpha[n] /= c[n]
return alpha, c
def backward(self, X, p_x_given_z, c):
''' The backward recursion for HMM as described in Bishop Ch. 13 '''
# intialize the beta vectors
beta = np.zeros((X.shape[0], self.K))
# initialize the recursion
beta[-1,:] = 1
# Run the backward recursion
for n in range(X.shape[0]-2,-1,-1):
beta[n] = np.dot(self.A, p_x_given_z[n+1]*beta[n+1])/c[n+1]
return beta
def viterbi(self):
x=1
|
[
"class",
"HMM",
":",
"def",
"__init__",
"(",
"self",
",",
"nstates",
",",
"emission",
",",
"model",
"=",
"'full'",
",",
"leftright_jump_max",
"=",
"3",
")",
":",
"'''\n Initialize a Hidden Markov Model with nstates and Gaussian observations \n \n nstates: int\n The number of states in the Markov chain\n emission : emission object, optional\n The emission object (CircularGaussianEmission or GaussianEmission)\n model : string, optional\n The model used for the chain, can be 'full' or 'left-right'\n leftright_jump_max : int\n The maximum jump length in the Left-Right chain model\n '''",
"self",
".",
"K",
"=",
"nstates",
"self",
".",
"emission",
"=",
"emission",
"self",
".",
"model",
"=",
"model",
"self",
".",
"leftright_jump_max",
"=",
"leftright_jump_max",
"self",
".",
"A",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"K",
",",
"self",
".",
"K",
")",
")",
"self",
".",
"pi",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"K",
")",
")",
"if",
"self",
".",
"model",
"==",
"'full'",
":",
"self",
".",
"A",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"size",
"=",
"(",
"self",
".",
"K",
",",
"self",
".",
"K",
")",
")",
"self",
".",
"pi",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"size",
"=",
"(",
"self",
".",
"K",
")",
")",
"elif",
"self",
".",
"model",
"==",
"'left-right'",
":",
"self",
".",
"A",
"=",
"np",
".",
"triu",
"(",
"np",
".",
"tril",
"(",
"np",
".",
"random",
".",
"uniform",
"(",
"size",
"=",
"(",
"self",
".",
"K",
",",
"self",
".",
"K",
")",
")",
",",
"k",
"=",
"self",
".",
"leftright_jump_max",
")",
")",
"self",
".",
"A",
"+=",
"np",
".",
"diag",
"(",
"np",
".",
"sum",
"(",
"self",
".",
"A",
"[",
":",
",",
":",
"]",
",",
"axis",
"=",
"1",
")",
"*",
"2",
")",
"self",
".",
"pi",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"K",
")",
"self",
".",
"pi",
"[",
"0",
"]",
"=",
"1",
"for",
"row",
"in",
"self",
".",
"A",
":",
"row",
"/=",
"row",
".",
"sum",
"(",
")",
"self",
".",
"pi",
"/=",
"self",
".",
"pi",
".",
"sum",
"(",
")",
"def",
"fit",
"(",
"self",
",",
"examples",
",",
"tol",
"=",
"0.1",
",",
"max_iter",
"=",
"10",
",",
"verbose",
"=",
"False",
")",
":",
"'''\n Training of the HMM using the EM algorithm\n\n Parameters\n ----------\n examples : (list)\n A list of examples used to train the model. Each example is\n an array of feature vectors, each row is a feature vector,\n the sequence runs on axis 0\n tol : (float)\n The training stops when the progress between to steps is less than\n this number (default 0.1)\n max_iter : (int)\n Alternatively the algorithm stops when a maximum number of\n iterations is reached (default 10)\n verbose : bool, optional\n When True, prints extra information about convergence\n '''",
"for",
"row",
"in",
"self",
".",
"A",
":",
"row",
"[",
":",
"]",
"/=",
"row",
".",
"sum",
"(",
")",
"self",
".",
"pi",
"[",
":",
"]",
"/=",
"self",
".",
"pi",
".",
"sum",
"(",
")",
"loglikelihood_old",
"=",
"-",
"np",
".",
"inf",
"n_iter",
"=",
"0",
"while",
"True",
":",
"loglikelihood",
"=",
"0.",
"gamma",
"=",
"[",
"]",
"xhi",
"=",
"[",
"]",
"p_x_given_z",
"=",
"self",
".",
"emission",
".",
"prob_x_given_state",
"(",
"examples",
")",
"for",
"X",
",",
"pxz",
"in",
"zip",
"(",
"examples",
",",
"p_x_given_z",
")",
":",
"if",
"X",
".",
"shape",
"[",
"1",
"]",
"!=",
"self",
".",
"emission",
".",
"O",
":",
"raise",
"ValueError",
"(",
"\"Error: Emission vectors of all examples should have the same size\"",
")",
"alpha",
",",
"c",
"=",
"self",
".",
"forward",
"(",
"X",
",",
"pxz",
")",
"beta",
"=",
"self",
".",
"backward",
"(",
"X",
",",
"pxz",
",",
"c",
")",
"loglikelihood",
"+=",
"np",
".",
"sum",
"(",
"np",
".",
"log",
"(",
"c",
")",
")",
"gamma",
".",
"append",
"(",
"alpha",
"*",
"beta",
")",
"xhi",
".",
"append",
"(",
"np",
".",
"zeros",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
"-",
"1",
",",
"self",
".",
"K",
",",
"self",
".",
"K",
")",
")",
")",
"for",
"n",
"in",
"range",
"(",
"1",
",",
"X",
".",
"shape",
"[",
"0",
"]",
")",
":",
"xhi",
"[",
"-",
"1",
"]",
"[",
"n",
"-",
"1",
"]",
"=",
"np",
".",
"outer",
"(",
"alpha",
"[",
"n",
"-",
"1",
"]",
",",
"beta",
"[",
"n",
"]",
"*",
"pxz",
"[",
"n",
"]",
")",
"*",
"self",
".",
"A",
"/",
"c",
"[",
"n",
"]",
"self",
".",
"update_parameters",
"(",
"examples",
",",
"gamma",
",",
"xhi",
")",
"self",
".",
"emission",
".",
"update_parameters",
"(",
"examples",
",",
"gamma",
")",
"n_iter",
"+=",
"1",
"epsilon",
"=",
"loglikelihood",
"-",
"loglikelihood_old",
"if",
"verbose",
":",
"print",
"(",
"'Iterations:'",
",",
"n_iter",
",",
"'epsilon:'",
",",
"epsilon",
",",
"'LL_new:'",
",",
"loglikelihood",
")",
"if",
"epsilon",
"<",
"tol",
":",
"if",
"verbose",
":",
"print",
"(",
"'Tolerance reached: stopping.'",
")",
"break",
"if",
"n_iter",
"==",
"max_iter",
":",
"if",
"verbose",
":",
"print",
"(",
"'Maximum iterations reached: stopping.'",
")",
"break",
"loglikelihood_old",
"=",
"loglikelihood",
"return",
"n_iter",
"def",
"update_parameters",
"(",
"self",
",",
"examples",
",",
"gamma",
",",
"xhi",
")",
":",
"''' Update the parameters of the Markov Chain '''",
"X",
"=",
"np",
".",
"concatenate",
"(",
"examples",
",",
"axis",
"=",
"0",
")",
"x",
"=",
"np",
".",
"concatenate",
"(",
"xhi",
",",
"axis",
"=",
"0",
")",
"self",
".",
"pi",
"[",
":",
"]",
"=",
"np",
".",
"sum",
"(",
"[",
"g",
"[",
"0",
",",
":",
"]",
"for",
"g",
"in",
"gamma",
"]",
",",
"axis",
"=",
"0",
")",
"self",
".",
"A",
"=",
"x",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"self",
".",
"pi",
"/=",
"np",
".",
"sum",
"(",
"self",
".",
"pi",
")",
"for",
"k",
"in",
"range",
"(",
"self",
".",
"K",
")",
":",
"den",
"=",
"np",
".",
"sum",
"(",
"self",
".",
"A",
"[",
"k",
",",
":",
"]",
")",
"if",
"den",
"<",
"1e-15",
":",
"self",
".",
"A",
"[",
"k",
",",
":",
"]",
"=",
"0.",
"else",
":",
"self",
".",
"A",
"[",
"k",
",",
":",
"]",
"/=",
"den",
"def",
"generate",
"(",
"self",
",",
"N",
")",
":",
"''' Generate a random sample of length N using the model '''",
"X",
"=",
"np",
".",
"zeros",
"(",
"(",
"N",
",",
"self",
".",
"emission",
".",
"O",
")",
")",
"distributions",
"=",
"self",
".",
"emission",
".",
"get_pdfs",
"(",
")",
"state",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"self",
".",
"K",
",",
"p",
"=",
"self",
".",
"pi",
")",
"for",
"n",
"in",
"range",
"(",
"0",
",",
"N",
")",
":",
"X",
"[",
"n",
",",
":",
"]",
"=",
"distributions",
"[",
"state",
"]",
".",
"rvs",
"(",
")",
"state",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"self",
".",
"K",
",",
"p",
"=",
"self",
".",
"A",
"[",
"state",
",",
":",
"]",
")",
"return",
"X",
"def",
"loglikelihood",
"(",
"self",
",",
"X",
")",
":",
"'''\n Compute the log-likelihood of a sample vector using the sum-product algorithm\n '''",
"p_x_given_z",
"=",
"self",
".",
"emission",
".",
"prob_x_given_state",
"(",
"[",
"X",
"]",
")",
"[",
"0",
"]",
"alpha",
",",
"c",
"=",
"self",
".",
"forward",
"(",
"X",
",",
"p_x_given_z",
")",
"return",
"np",
".",
"sum",
"(",
"np",
".",
"log",
"(",
"c",
")",
")",
"def",
"forward",
"(",
"self",
",",
"X",
",",
"p_x_given_z",
")",
":",
"''' The forward recursion for HMM as described in Bishop Ch. 13 '''",
"alpha",
"=",
"np",
".",
"zeros",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"self",
".",
"K",
")",
")",
"c",
"=",
"np",
".",
"zeros",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
")",
"alpha",
"[",
"0",
"]",
"=",
"p_x_given_z",
"[",
"0",
"]",
"*",
"self",
".",
"pi",
"c",
"[",
"0",
"]",
"=",
"np",
".",
"sum",
"(",
"alpha",
"[",
"0",
"]",
")",
"alpha",
"[",
"0",
"]",
"/=",
"c",
"[",
"0",
"]",
"for",
"n",
"in",
"range",
"(",
"1",
",",
"X",
".",
"shape",
"[",
"0",
"]",
")",
":",
"alpha",
"[",
"n",
"]",
"=",
"p_x_given_z",
"[",
"n",
"]",
"*",
"np",
".",
"dot",
"(",
"self",
".",
"A",
".",
"T",
",",
"alpha",
"[",
"n",
"-",
"1",
"]",
")",
"c",
"[",
"n",
"]",
"=",
"np",
".",
"sum",
"(",
"alpha",
"[",
"n",
"]",
")",
"alpha",
"[",
"n",
"]",
"/=",
"c",
"[",
"n",
"]",
"return",
"alpha",
",",
"c",
"def",
"backward",
"(",
"self",
",",
"X",
",",
"p_x_given_z",
",",
"c",
")",
":",
"''' The backward recursion for HMM as described in Bishop Ch. 13 '''",
"beta",
"=",
"np",
".",
"zeros",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"self",
".",
"K",
")",
")",
"beta",
"[",
"-",
"1",
",",
":",
"]",
"=",
"1",
"for",
"n",
"in",
"range",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
"-",
"2",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"beta",
"[",
"n",
"]",
"=",
"np",
".",
"dot",
"(",
"self",
".",
"A",
",",
"p_x_given_z",
"[",
"n",
"+",
"1",
"]",
"*",
"beta",
"[",
"n",
"+",
"1",
"]",
")",
"/",
"c",
"[",
"n",
"+",
"1",
"]",
"return",
"beta",
"def",
"viterbi",
"(",
"self",
")",
":",
"x",
"=",
"1"
] |
Hidden Markov Model with Gaussian emissions
Attributes
|
[
"Hidden",
"Markov",
"Model",
"with",
"Gaussian",
"emissions",
"Attributes"
] |
[
"'''\n Hidden Markov Model with Gaussian emissions\n\n Attributes\n ----------\n K : int\n Number of states in the model\n O : int\n Number of dimensions of the Gaussian emission distribution\n A : ndarray\n KxK transition matrix of the Markov chain\n pi : ndarray\n K dim vector of the initial probabilities of the Markov chain\n emission : (GaussianEmission or CircularGaussianEmission)\n An instance of emission_class\n model : string, optional\n The model used for the chain, can be 'full' or 'left-right'\n leftright_jum_max : int, optional\n The number of non-zero upper diagonals in a 'left-right' model\n '''",
"'''\n Initialize a Hidden Markov Model with nstates and Gaussian observations \n \n nstates: int\n The number of states in the Markov chain\n emission : emission object, optional\n The emission object (CircularGaussianEmission or GaussianEmission)\n model : string, optional\n The model used for the chain, can be 'full' or 'left-right'\n leftright_jump_max : int\n The maximum jump length in the Left-Right chain model\n '''",
"# number of states",
"# The observation parameters",
"# The Markov chain parameters",
"# the state transition matrix",
"# the initial distribution",
"# Initialize the HMM parameters to some random values",
"# Normalize the distributions",
"'''\n Training of the HMM using the EM algorithm\n\n Parameters\n ----------\n examples : (list)\n A list of examples used to train the model. Each example is\n an array of feature vectors, each row is a feature vector,\n the sequence runs on axis 0\n tol : (float)\n The training stops when the progress between to steps is less than\n this number (default 0.1)\n max_iter : (int)\n Alternatively the algorithm stops when a maximum number of\n iterations is reached (default 10)\n verbose : bool, optional\n When True, prints extra information about convergence\n '''",
"# Make sure to normalize parameters that should be...",
"# Run the EM algorithm",
"# log-likelihood",
"# Initialize new parameters value for accumulation",
"# We need to run the forward/backward algorithm for each example and",
"# and combine the result to form the new estimates",
"# Expectation-step",
"#-----------------",
"# check dimension of emission",
"# First compute alpha and beta using forward/backward algo",
"# Recompute the likelihood of the sequence",
"# (Bishop 13.63)",
"# Now the more interesting quantities",
"# gamma(z_n) = p(z_n | X, theta_old) ",
"# xhi(z_{n-1}, z_n) = p(z_{n-1}, z_n | X, theta_old)",
"# Maximization-step",
"#------------------",
"# update the Markov Chain parameters",
"# Update the emission distribution parameters",
"# Now check for convergence",
"#--------------------------",
"# some checks here",
"# return the number of iterations performed",
"''' Update the parameters of the Markov Chain '''",
"# normalize to enforce distribution constraints",
"''' Generate a random sample of length N using the model '''",
"# pick initial state",
"# now run the chain",
"# produce emission vector according to current state",
"# pick next state",
"'''\n Compute the log-likelihood of a sample vector using the sum-product algorithm\n '''",
"''' The forward recursion for HMM as described in Bishop Ch. 13 '''",
"# initialize the alpha vector",
"# initialize the recursion as",
"# p(X | z_k) pi_k",
"# Run the forward recursion",
"''' The backward recursion for HMM as described in Bishop Ch. 13 '''",
"# intialize the beta vectors",
"# initialize the recursion",
"# Run the backward recursion"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 1,909
| 156
|
3408406619b13ae3b7cc066fc959b3a1721fd93b
|
aTiKhan/openproject
|
modules/bim/spec/support/components/xeokit_model_tree.rb
|
[
"CC-BY-3.0"
] |
Ruby
|
Components
|
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2013 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
|
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 3.
OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
Copyright (C) 2006-2013 Jean-Philippe Lang
Copyright (C) 2010-2013 the ChiliProject Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
See docs/COPYRIGHT.rdoc for more details.
|
[
"This",
"program",
"is",
"free",
"software",
";",
"you",
"can",
"redistribute",
"it",
"and",
"/",
"or",
"modify",
"it",
"under",
"the",
"terms",
"of",
"the",
"GNU",
"General",
"Public",
"License",
"version",
"3",
".",
"OpenProject",
"is",
"a",
"fork",
"of",
"ChiliProject",
"which",
"is",
"a",
"fork",
"of",
"Redmine",
".",
"The",
"copyright",
"follows",
":",
"Copyright",
"(",
"C",
")",
"2006",
"-",
"2013",
"Jean",
"-",
"Philippe",
"Lang",
"Copyright",
"(",
"C",
")",
"2010",
"-",
"2013",
"the",
"ChiliProject",
"Team",
"This",
"program",
"is",
"free",
"software",
";",
"you",
"can",
"redistribute",
"it",
"and",
"/",
"or",
"modify",
"it",
"under",
"the",
"terms",
"of",
"the",
"GNU",
"General",
"Public",
"License",
"as",
"published",
"by",
"the",
"Free",
"Software",
"Foundation",
";",
"either",
"version",
"2",
"of",
"the",
"License",
"or",
"(",
"at",
"your",
"option",
")",
"any",
"later",
"version",
".",
"This",
"program",
"is",
"distributed",
"in",
"the",
"hope",
"that",
"it",
"will",
"be",
"useful",
"but",
"WITHOUT",
"ANY",
"WARRANTY",
";",
"without",
"even",
"the",
"implied",
"warranty",
"of",
"MERCHANTABILITY",
"or",
"FITNESS",
"FOR",
"A",
"PARTICULAR",
"PURPOSE",
".",
"See",
"the",
"GNU",
"General",
"Public",
"License",
"for",
"more",
"details",
".",
"You",
"should",
"have",
"received",
"a",
"copy",
"of",
"the",
"GNU",
"General",
"Public",
"License",
"along",
"with",
"this",
"program",
";",
"if",
"not",
"write",
"to",
"the",
"Free",
"Software",
"Foundation",
"Inc",
".",
"51",
"Franklin",
"Street",
"Fifth",
"Floor",
"Boston",
"MA",
"02110",
"-",
"1301",
"USA",
".",
"See",
"docs",
"/",
"COPYRIGHT",
".",
"rdoc",
"for",
"more",
"details",
"."
] |
module Components
class XeokitModelTree
include Capybara::DSL
include RSpec::Matchers
def initialize; end
def sidebar_shows_viewer_menu(visible)
selector = '.xeokit-tab'
tabs = ['Models', 'Objects', 'Classes', 'Storeys']
tabs.each do |tab|
expect(page).to have_conditional_selector(visible, selector, text: tab)
end
end
def expect_model_management_available(visible: true)
selector = '.xeokit-btn.xeokit-addModel'
expect(page).to have_conditional_selector(visible, selector)
end
def click_add_model
selector = '.xeokit-btn.xeokit-addModel'
page.find(selector).click
end
def select_model_menu_item(model_name, item_label)
page.find('.xeokit-form-check span', text: model_name).right_click
page.find('.xeokit-context-menu-item', text: item_label).click
end
def select_sidebar_tab(tab)
selector = '.xeokit-tab'
page.find(selector, text: tab).click
end
def expand_tree
page.all('.xeokit-tree-panel a.plus').map(&:click)
end
def expect_checked(label)
page
.find('.xeokit-tree-panel li span', text: label, wait: 10)
.sibling('input[type=checkbox]:checked')
end
def expect_unchecked(label)
page
.find('.xeokit-tree-panel li span', text: label, wait: 10)
.sibling('input[type=checkbox]:not(:checked)')
end
def all_checkboxes
page
.all('.xeokit-tree-panel li span')
.map { |item| [item, item.sibling('input[type=checkbox]')] }
end
def expect_tree_panel_selected(selected, tab = 'Models')
within (".xeokit-#{tab.downcase}.xeokit-tree-panel") do
if selected
expect(page.find('input', match: :first)).to be_checked
else
expect(page.find('input', match: :first)).not_to be_checked
end
end
end
end
end
|
[
"module",
"Components",
"class",
"XeokitModelTree",
"include",
"Capybara",
"::",
"DSL",
"include",
"RSpec",
"::",
"Matchers",
"def",
"initialize",
";",
"end",
"def",
"sidebar_shows_viewer_menu",
"(",
"visible",
")",
"selector",
"=",
"'.xeokit-tab'",
"tabs",
"=",
"[",
"'Models'",
",",
"'Objects'",
",",
"'Classes'",
",",
"'Storeys'",
"]",
"tabs",
".",
"each",
"do",
"|",
"tab",
"|",
"expect",
"(",
"page",
")",
".",
"to",
"have_conditional_selector",
"(",
"visible",
",",
"selector",
",",
"text",
":",
"tab",
")",
"end",
"end",
"def",
"expect_model_management_available",
"(",
"visible",
":",
"true",
")",
"selector",
"=",
"'.xeokit-btn.xeokit-addModel'",
"expect",
"(",
"page",
")",
".",
"to",
"have_conditional_selector",
"(",
"visible",
",",
"selector",
")",
"end",
"def",
"click_add_model",
"selector",
"=",
"'.xeokit-btn.xeokit-addModel'",
"page",
".",
"find",
"(",
"selector",
")",
".",
"click",
"end",
"def",
"select_model_menu_item",
"(",
"model_name",
",",
"item_label",
")",
"page",
".",
"find",
"(",
"'.xeokit-form-check span'",
",",
"text",
":",
"model_name",
")",
".",
"right_click",
"page",
".",
"find",
"(",
"'.xeokit-context-menu-item'",
",",
"text",
":",
"item_label",
")",
".",
"click",
"end",
"def",
"select_sidebar_tab",
"(",
"tab",
")",
"selector",
"=",
"'.xeokit-tab'",
"page",
".",
"find",
"(",
"selector",
",",
"text",
":",
"tab",
")",
".",
"click",
"end",
"def",
"expand_tree",
"page",
".",
"all",
"(",
"'.xeokit-tree-panel a.plus'",
")",
".",
"map",
"(",
"&",
":click",
")",
"end",
"def",
"expect_checked",
"(",
"label",
")",
"page",
".",
"find",
"(",
"'.xeokit-tree-panel li span'",
",",
"text",
":",
"label",
",",
"wait",
":",
"10",
")",
".",
"sibling",
"(",
"'input[type=checkbox]:checked'",
")",
"end",
"def",
"expect_unchecked",
"(",
"label",
")",
"page",
".",
"find",
"(",
"'.xeokit-tree-panel li span'",
",",
"text",
":",
"label",
",",
"wait",
":",
"10",
")",
".",
"sibling",
"(",
"'input[type=checkbox]:not(:checked)'",
")",
"end",
"def",
"all_checkboxes",
"page",
".",
"all",
"(",
"'.xeokit-tree-panel li span'",
")",
".",
"map",
"{",
"|",
"item",
"|",
"[",
"item",
",",
"item",
".",
"sibling",
"(",
"'input[type=checkbox]'",
")",
"]",
"}",
"end",
"def",
"expect_tree_panel_selected",
"(",
"selected",
",",
"tab",
"=",
"'Models'",
")",
"within",
"(",
"\".xeokit-#{tab.downcase}.xeokit-tree-panel\"",
")",
"do",
"if",
"selected",
"expect",
"(",
"page",
".",
"find",
"(",
"'input'",
",",
"match",
":",
":first",
")",
")",
".",
"to",
"be_checked",
"else",
"expect",
"(",
"page",
".",
"find",
"(",
"'input'",
",",
"match",
":",
":first",
")",
")",
".",
"not_to",
"be_checked",
"end",
"end",
"end",
"end",
"end"
] |
copyright
OpenProject is an open source project management software.
|
[
"copyright",
"OpenProject",
"is",
"an",
"open",
"source",
"project",
"management",
"software",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 18
| 486
| 314
|
18a11f845295f671f6f0910de9816d16bc760234
|
JAD-SVK/mono-tools
|
rules/Gendarme.Rules.Maintainability/AvoidComplexMethodsRule.cs
|
[
"MIT"
] |
C#
|
AvoidComplexMethodsRule
|
/// <summary>
/// This rule computes the cyclomatic complexity (CC) for every method and reports any method
/// with a CC over 25 (this limit is configurable). Large CC value often indicate complex
/// code that is hard to understand and maintain. It's likely that breaking the
/// method into several methods will help readability. This rule won't report any defects
/// on code generated by the compiler or by tools.
/// </summary>
/// <remarks>This rule is available since Gendarme 2.0</remarks>
|
This rule computes the cyclomatic complexity (CC) for every method and reports any method
with a CC over 25 (this limit is configurable). Large CC value often indicate complex
code that is hard to understand and maintain. It's likely that breaking the
method into several methods will help readability. This rule won't report any defects
on code generated by the compiler or by tools.
|
[
"This",
"rule",
"computes",
"the",
"cyclomatic",
"complexity",
"(",
"CC",
")",
"for",
"every",
"method",
"and",
"reports",
"any",
"method",
"with",
"a",
"CC",
"over",
"25",
"(",
"this",
"limit",
"is",
"configurable",
")",
".",
"Large",
"CC",
"value",
"often",
"indicate",
"complex",
"code",
"that",
"is",
"hard",
"to",
"understand",
"and",
"maintain",
".",
"It",
"'",
"s",
"likely",
"that",
"breaking",
"the",
"method",
"into",
"several",
"methods",
"will",
"help",
"readability",
".",
"This",
"rule",
"won",
"'",
"t",
"report",
"any",
"defects",
"on",
"code",
"generated",
"by",
"the",
"compiler",
"or",
"by",
"tools",
"."
] |
[Problem ("Methods with a large cyclomatic complexity are hard to understand and maintain.")]
[Solution ("Simplify the method using refactors like Extract Method.")]
[FxCopCompatibility ("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[EngineDependency (typeof (OpCodeEngine))]
public class AvoidComplexMethodsRule : Rule, IMethodRule {
private const int DefaultSuccessThreshold = 25;
static OpCodeBitmask ld = new OpCodeBitmask (0xFFFF6C3FC, 0x1B0300000000FFE0, 0x400100FFF800, 0xDE0);
public AvoidComplexMethodsRule ()
{
SuccessThreshold = DefaultSuccessThreshold;
}
public override void Initialize (IRunner runner)
{
base.Initialize (runner);
if (LowThreshold == 0)
LowThreshold = SuccessThreshold * 2;
if (MediumThreshold == 0)
MediumThreshold = SuccessThreshold * 3;
if (HighThreshold == 0)
HighThreshold = SuccessThreshold * 4;
}
[DefaultValue (DefaultSuccessThreshold)]
[Description ("The cyclomatic complexity at which defects are reported.")]
public int SuccessThreshold { get; set; }
[DefaultValue (0)]
[Description ("Methods with cyclomatic complexity less than this will be reported as low severity.")]
public int LowThreshold { get; set; }
[DefaultValue (0)]
[Description ("Methods with cyclomatic complexity less than this will be reported as medium severity.")]
public int MediumThreshold { get; set; }
[DefaultValue (0)]
[Description ("Methods with cyclomatic complexity less than this will be reported as high severity.")]
public int HighThreshold { get; set; }
public RuleResult CheckMethod (MethodDefinition method)
{
if (!method.HasBody || method.IsGeneratedCode () || method.IsCompilerControlled)
return RuleResult.DoesNotApply;
if (method.Body.Instructions.Count < SuccessThreshold)
return RuleResult.Success;
int cc = GetCyclomaticComplexity (method);
if (cc < SuccessThreshold)
return RuleResult.Success;
Severity sev = GetCyclomaticComplexitySeverity(cc);
string msg = String.Format (CultureInfo.CurrentCulture, "Method's cyclomatic complexity : {0}.", cc);
Runner.Report (method, sev, Confidence.High, msg);
return RuleResult.Failure;
}
public bool SkipGeneratedGuiMethods
{
get
{
return true;
}
}
public Severity GetCyclomaticComplexitySeverity(int cc)
{
if (cc < LowThreshold)
return Severity.Low;
if (cc < MediumThreshold)
return Severity.Medium;
if (cc < HighThreshold)
return Severity.High;
return Severity.Critical;
}
static public int GetCyclomaticComplexity (MethodDefinition method)
{
if ((method == null) || !method.HasBody)
return 1;
if (OpCodeEngine.GetBitmask (method).Get (Code.Switch))
return GetSwitchCyclomaticComplexity (method);
else
return GetFastCyclomaticComplexity (method);
}
static private int GetFastCyclomaticComplexity (MethodDefinition method)
{
int cc = 1;
foreach (Instruction ins in method.Body.Instructions) {
switch (ins.OpCode.FlowControl) {
case FlowControl.Branch:
Instruction previous = ins.Previous;
if ((previous != null) && ld.Get (previous.OpCode.Code))
cc++;
break;
case FlowControl.Cond_Branch:
cc++;
break;
}
}
return cc;
}
static private int GetSwitchCyclomaticComplexity (MethodDefinition method)
{
Instruction previous = null;
Instruction branch = null;
int cc = 1;
foreach (Instruction ins in method.Body.Instructions) {
switch (ins.OpCode.FlowControl) {
case FlowControl.Branch:
if (previous == null)
continue;
previous = ins.Previous;
if (ld.Get (previous.OpCode.Code))
cc++;
if (previous.OpCode.FlowControl == FlowControl.Cond_Branch) {
branch = (previous.Operand as Instruction);
if ((branch != null) && targets.Contains (branch))
targets.AddIfNew (ins);
}
break;
case FlowControl.Cond_Branch:
if (ins.OpCode.Code == Code.Switch) {
AccumulateSwitchTargets (ins);
} else {
branch = (ins.Operand as Instruction);
previous = branch.Previous;
if ((previous != null) && !previous.Previous.Is (Code.Switch)) {
if (!targets.Contains (branch))
cc++;
}
}
break;
}
}
cc += targets.Count;
targets.Clear ();
return cc;
}
static List<Instruction> targets = new List<Instruction> ();
static private void AccumulateSwitchTargets (Instruction ins)
{
Instruction[] cases = (Instruction[]) ins.Operand;
foreach (Instruction target in cases) {
if (target != ins.Next)
targets.AddIfNew (target);
}
Instruction next = ins.Next;
if (next.OpCode.FlowControl == FlowControl.Branch) {
Instruction unc = FindFirstUnconditionalBranchTarget (cases [0]);
if (unc != next.Operand)
targets.AddIfNew (next.Operand as Instruction);
}
}
static private Instruction FindFirstUnconditionalBranchTarget (Instruction ins)
{
while (ins != null) {
if (FlowControl.Branch == ins.OpCode.FlowControl)
return ((Instruction) ins.Operand);
ins = ins.Next;
}
return null;
}
#if false
public void Bitmask ()
{
OpCodeBitmask mask = new OpCodeBitmask ();
mask.Set (Code.Ldarg);
mask.Set (Code.Ldarg_0);
mask.Set (Code.Ldarg_1);
mask.Set (Code.Ldarg_2);
mask.Set (Code.Ldarg_3);
mask.Set (Code.Ldarg_S);
mask.Set (Code.Ldarga);
mask.Set (Code.Ldarga_S);
mask.Set (Code.Ldc_I4);
mask.Set (Code.Ldc_I4_0);
mask.Set (Code.Ldc_I4_1);
mask.Set (Code.Ldc_I4_2);
mask.Set (Code.Ldc_I4_3);
mask.Set (Code.Ldc_I4_4);
mask.Set (Code.Ldc_I4_5);
mask.Set (Code.Ldc_I4_6);
mask.Set (Code.Ldc_I4_7);
mask.Set (Code.Ldc_I4_8);
mask.Set (Code.Ldc_I4_M1);
mask.Set (Code.Ldc_I4_S);
mask.Set (Code.Ldc_I8);
mask.Set (Code.Ldc_R4);
mask.Set (Code.Ldc_R8);
mask.Set (Code.Ldelem_Any);
mask.Set (Code.Ldelem_I);
mask.Set (Code.Ldelem_I1);
mask.Set (Code.Ldelem_I2);
mask.Set (Code.Ldelem_I4);
mask.Set (Code.Ldelem_I8);
mask.Set (Code.Ldelem_R4);
mask.Set (Code.Ldelem_R8);
mask.Set (Code.Ldelem_Ref);
mask.Set (Code.Ldelem_U1);
mask.Set (Code.Ldelem_U2);
mask.Set (Code.Ldelem_U4);
mask.Set (Code.Ldelema);
mask.Set (Code.Ldfld);
mask.Set (Code.Ldflda);
mask.Set (Code.Ldftn);
mask.Set (Code.Ldind_I);
mask.Set (Code.Ldind_I1);
mask.Set (Code.Ldind_I2);
mask.Set (Code.Ldind_I4);
mask.Set (Code.Ldind_I8);
mask.Set (Code.Ldind_R4);
mask.Set (Code.Ldind_R8);
mask.Set (Code.Ldind_Ref);
mask.Set (Code.Ldind_U1);
mask.Set (Code.Ldind_U2);
mask.Set (Code.Ldind_U4);
mask.Set (Code.Ldlen);
mask.Set (Code.Ldloc);
mask.Set (Code.Ldloc_0);
mask.Set (Code.Ldloc_1);
mask.Set (Code.Ldloc_2);
mask.Set (Code.Ldloc_3);
mask.Set (Code.Ldloc_S);
mask.Set (Code.Ldloca);
mask.Set (Code.Ldloca_S);
mask.Set (Code.Ldnull);
mask.Set (Code.Ldobj);
mask.Set (Code.Ldsfld);
mask.Set (Code.Ldsflda);
mask.Set (Code.Ldstr);
mask.Set (Code.Ldtoken);
mask.Set (Code.Ldvirtftn);
Console.WriteLine (mask);
}
#endif
}
|
[
"[",
"Problem",
"(",
"\"",
"Methods with a large cyclomatic complexity are hard to understand and maintain.",
"\"",
")",
"]",
"[",
"Solution",
"(",
"\"",
"Simplify the method using refactors like Extract Method.",
"\"",
")",
"]",
"[",
"FxCopCompatibility",
"(",
"\"",
"Microsoft.Maintainability",
"\"",
",",
"\"",
"CA1502:AvoidExcessiveComplexity",
"\"",
")",
"]",
"[",
"EngineDependency",
"(",
"typeof",
"(",
"OpCodeEngine",
")",
")",
"]",
"public",
"class",
"AvoidComplexMethodsRule",
":",
"Rule",
",",
"IMethodRule",
"{",
"private",
"const",
"int",
"DefaultSuccessThreshold",
"=",
"25",
";",
"static",
"OpCodeBitmask",
"ld",
"=",
"new",
"OpCodeBitmask",
"(",
"0xFFFF6C3FC",
",",
"0x1B0300000000FFE0",
",",
"0x400100FFF800",
",",
"0xDE0",
")",
";",
"public",
"AvoidComplexMethodsRule",
"(",
")",
"{",
"SuccessThreshold",
"=",
"DefaultSuccessThreshold",
";",
"}",
"public",
"override",
"void",
"Initialize",
"(",
"IRunner",
"runner",
")",
"{",
"base",
".",
"Initialize",
"(",
"runner",
")",
";",
"if",
"(",
"LowThreshold",
"==",
"0",
")",
"LowThreshold",
"=",
"SuccessThreshold",
"*",
"2",
";",
"if",
"(",
"MediumThreshold",
"==",
"0",
")",
"MediumThreshold",
"=",
"SuccessThreshold",
"*",
"3",
";",
"if",
"(",
"HighThreshold",
"==",
"0",
")",
"HighThreshold",
"=",
"SuccessThreshold",
"*",
"4",
";",
"}",
"[",
"DefaultValue",
"(",
"DefaultSuccessThreshold",
")",
"]",
"[",
"Description",
"(",
"\"",
"The cyclomatic complexity at which defects are reported.",
"\"",
")",
"]",
"public",
"int",
"SuccessThreshold",
"{",
"get",
";",
"set",
";",
"}",
"[",
"DefaultValue",
"(",
"0",
")",
"]",
"[",
"Description",
"(",
"\"",
"Methods with cyclomatic complexity less than this will be reported as low severity.",
"\"",
")",
"]",
"public",
"int",
"LowThreshold",
"{",
"get",
";",
"set",
";",
"}",
"[",
"DefaultValue",
"(",
"0",
")",
"]",
"[",
"Description",
"(",
"\"",
"Methods with cyclomatic complexity less than this will be reported as medium severity.",
"\"",
")",
"]",
"public",
"int",
"MediumThreshold",
"{",
"get",
";",
"set",
";",
"}",
"[",
"DefaultValue",
"(",
"0",
")",
"]",
"[",
"Description",
"(",
"\"",
"Methods with cyclomatic complexity less than this will be reported as high severity.",
"\"",
")",
"]",
"public",
"int",
"HighThreshold",
"{",
"get",
";",
"set",
";",
"}",
"public",
"RuleResult",
"CheckMethod",
"(",
"MethodDefinition",
"method",
")",
"{",
"if",
"(",
"!",
"method",
".",
"HasBody",
"||",
"method",
".",
"IsGeneratedCode",
"(",
")",
"||",
"method",
".",
"IsCompilerControlled",
")",
"return",
"RuleResult",
".",
"DoesNotApply",
";",
"if",
"(",
"method",
".",
"Body",
".",
"Instructions",
".",
"Count",
"<",
"SuccessThreshold",
")",
"return",
"RuleResult",
".",
"Success",
";",
"int",
"cc",
"=",
"GetCyclomaticComplexity",
"(",
"method",
")",
";",
"if",
"(",
"cc",
"<",
"SuccessThreshold",
")",
"return",
"RuleResult",
".",
"Success",
";",
"Severity",
"sev",
"=",
"GetCyclomaticComplexitySeverity",
"(",
"cc",
")",
";",
"string",
"msg",
"=",
"String",
".",
"Format",
"(",
"CultureInfo",
".",
"CurrentCulture",
",",
"\"",
"Method's cyclomatic complexity : {0}.",
"\"",
",",
"cc",
")",
";",
"Runner",
".",
"Report",
"(",
"method",
",",
"sev",
",",
"Confidence",
".",
"High",
",",
"msg",
")",
";",
"return",
"RuleResult",
".",
"Failure",
";",
"}",
"public",
"bool",
"SkipGeneratedGuiMethods",
"{",
"get",
"{",
"return",
"true",
";",
"}",
"}",
"public",
"Severity",
"GetCyclomaticComplexitySeverity",
"(",
"int",
"cc",
")",
"{",
"if",
"(",
"cc",
"<",
"LowThreshold",
")",
"return",
"Severity",
".",
"Low",
";",
"if",
"(",
"cc",
"<",
"MediumThreshold",
")",
"return",
"Severity",
".",
"Medium",
";",
"if",
"(",
"cc",
"<",
"HighThreshold",
")",
"return",
"Severity",
".",
"High",
";",
"return",
"Severity",
".",
"Critical",
";",
"}",
"static",
"public",
"int",
"GetCyclomaticComplexity",
"(",
"MethodDefinition",
"method",
")",
"{",
"if",
"(",
"(",
"method",
"==",
"null",
")",
"||",
"!",
"method",
".",
"HasBody",
")",
"return",
"1",
";",
"if",
"(",
"OpCodeEngine",
".",
"GetBitmask",
"(",
"method",
")",
".",
"Get",
"(",
"Code",
".",
"Switch",
")",
")",
"return",
"GetSwitchCyclomaticComplexity",
"(",
"method",
")",
";",
"else",
"return",
"GetFastCyclomaticComplexity",
"(",
"method",
")",
";",
"}",
"static",
"private",
"int",
"GetFastCyclomaticComplexity",
"(",
"MethodDefinition",
"method",
")",
"{",
"int",
"cc",
"=",
"1",
";",
"foreach",
"(",
"Instruction",
"ins",
"in",
"method",
".",
"Body",
".",
"Instructions",
")",
"{",
"switch",
"(",
"ins",
".",
"OpCode",
".",
"FlowControl",
")",
"{",
"case",
"FlowControl",
".",
"Branch",
":",
"Instruction",
"previous",
"=",
"ins",
".",
"Previous",
";",
"if",
"(",
"(",
"previous",
"!=",
"null",
")",
"&&",
"ld",
".",
"Get",
"(",
"previous",
".",
"OpCode",
".",
"Code",
")",
")",
"cc",
"++",
";",
"break",
";",
"case",
"FlowControl",
".",
"Cond_Branch",
":",
"cc",
"++",
";",
"break",
";",
"}",
"}",
"return",
"cc",
";",
"}",
"static",
"private",
"int",
"GetSwitchCyclomaticComplexity",
"(",
"MethodDefinition",
"method",
")",
"{",
"Instruction",
"previous",
"=",
"null",
";",
"Instruction",
"branch",
"=",
"null",
";",
"int",
"cc",
"=",
"1",
";",
"foreach",
"(",
"Instruction",
"ins",
"in",
"method",
".",
"Body",
".",
"Instructions",
")",
"{",
"switch",
"(",
"ins",
".",
"OpCode",
".",
"FlowControl",
")",
"{",
"case",
"FlowControl",
".",
"Branch",
":",
"if",
"(",
"previous",
"==",
"null",
")",
"continue",
";",
"previous",
"=",
"ins",
".",
"Previous",
";",
"if",
"(",
"ld",
".",
"Get",
"(",
"previous",
".",
"OpCode",
".",
"Code",
")",
")",
"cc",
"++",
";",
"if",
"(",
"previous",
".",
"OpCode",
".",
"FlowControl",
"==",
"FlowControl",
".",
"Cond_Branch",
")",
"{",
"branch",
"=",
"(",
"previous",
".",
"Operand",
"as",
"Instruction",
")",
";",
"if",
"(",
"(",
"branch",
"!=",
"null",
")",
"&&",
"targets",
".",
"Contains",
"(",
"branch",
")",
")",
"targets",
".",
"AddIfNew",
"(",
"ins",
")",
";",
"}",
"break",
";",
"case",
"FlowControl",
".",
"Cond_Branch",
":",
"if",
"(",
"ins",
".",
"OpCode",
".",
"Code",
"==",
"Code",
".",
"Switch",
")",
"{",
"AccumulateSwitchTargets",
"(",
"ins",
")",
";",
"}",
"else",
"{",
"branch",
"=",
"(",
"ins",
".",
"Operand",
"as",
"Instruction",
")",
";",
"previous",
"=",
"branch",
".",
"Previous",
";",
"if",
"(",
"(",
"previous",
"!=",
"null",
")",
"&&",
"!",
"previous",
".",
"Previous",
".",
"Is",
"(",
"Code",
".",
"Switch",
")",
")",
"{",
"if",
"(",
"!",
"targets",
".",
"Contains",
"(",
"branch",
")",
")",
"cc",
"++",
";",
"}",
"}",
"break",
";",
"}",
"}",
"cc",
"+=",
"targets",
".",
"Count",
";",
"targets",
".",
"Clear",
"(",
")",
";",
"return",
"cc",
";",
"}",
"static",
"List",
"<",
"Instruction",
">",
"targets",
"=",
"new",
"List",
"<",
"Instruction",
">",
"(",
")",
";",
"static",
"private",
"void",
"AccumulateSwitchTargets",
"(",
"Instruction",
"ins",
")",
"{",
"Instruction",
"[",
"]",
"cases",
"=",
"(",
"Instruction",
"[",
"]",
")",
"ins",
".",
"Operand",
";",
"foreach",
"(",
"Instruction",
"target",
"in",
"cases",
")",
"{",
"if",
"(",
"target",
"!=",
"ins",
".",
"Next",
")",
"targets",
".",
"AddIfNew",
"(",
"target",
")",
";",
"}",
"Instruction",
"next",
"=",
"ins",
".",
"Next",
";",
"if",
"(",
"next",
".",
"OpCode",
".",
"FlowControl",
"==",
"FlowControl",
".",
"Branch",
")",
"{",
"Instruction",
"unc",
"=",
"FindFirstUnconditionalBranchTarget",
"(",
"cases",
"[",
"0",
"]",
")",
";",
"if",
"(",
"unc",
"!=",
"next",
".",
"Operand",
")",
"targets",
".",
"AddIfNew",
"(",
"next",
".",
"Operand",
"as",
"Instruction",
")",
";",
"}",
"}",
"static",
"private",
"Instruction",
"FindFirstUnconditionalBranchTarget",
"(",
"Instruction",
"ins",
")",
"{",
"while",
"(",
"ins",
"!=",
"null",
")",
"{",
"if",
"(",
"FlowControl",
".",
"Branch",
"==",
"ins",
".",
"OpCode",
".",
"FlowControl",
")",
"return",
"(",
"(",
"Instruction",
")",
"ins",
".",
"Operand",
")",
";",
"ins",
"=",
"ins",
".",
"Next",
";",
"}",
"return",
"null",
";",
"}",
"if",
"false",
"public",
"void",
"Bitmask",
"(",
")",
"{",
"OpCodeBitmask",
"mask",
"=",
"new",
"OpCodeBitmask",
"(",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldarg",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldarg_0",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldarg_1",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldarg_2",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldarg_3",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldarg_S",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldarga",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldarga_S",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_I4",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_I4_0",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_I4_1",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_I4_2",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_I4_3",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_I4_4",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_I4_5",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_I4_6",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_I4_7",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_I4_8",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_I4_M1",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_I4_S",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_I8",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_R4",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldc_R8",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldelem_Any",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldelem_I",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldelem_I1",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldelem_I2",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldelem_I4",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldelem_I8",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldelem_R4",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldelem_R8",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldelem_Ref",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldelem_U1",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldelem_U2",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldelem_U4",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldelema",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldfld",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldflda",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldftn",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldind_I",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldind_I1",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldind_I2",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldind_I4",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldind_I8",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldind_R4",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldind_R8",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldind_Ref",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldind_U1",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldind_U2",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldind_U4",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldlen",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldloc",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldloc_0",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldloc_1",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldloc_2",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldloc_3",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldloc_S",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldloca",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldloca_S",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldnull",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldobj",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldsfld",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldsflda",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldstr",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldtoken",
")",
";",
"mask",
".",
"Set",
"(",
"Code",
".",
"Ldvirtftn",
")",
";",
"Console",
".",
"WriteLine",
"(",
"mask",
")",
";",
"}",
"endif",
"}"
] |
This rule computes the cyclomatic complexity (CC) for every method and reports any method
with a CC over 25 (this limit is configurable).
|
[
"This",
"rule",
"computes",
"the",
"cyclomatic",
"complexity",
"(",
"CC",
")",
"for",
"every",
"method",
"and",
"reports",
"any",
"method",
"with",
"a",
"CC",
"over",
"25",
"(",
"this",
"limit",
"is",
"configurable",
")",
"."
] |
[
"// defaults match fxcop rule http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1575061&SiteID=1",
"// so people using both tools should not see conflicting results",
"// works if only SuccessThreshold is configured in rules.xml",
"/// <summary>The cyclomatic complexity at which defects begin to be reported.</summary>",
"/// <remarks>This defaults to 25 and larger values will mean fewer reported defects.</remarks>",
"/// <summary>Methods with cyclomatic complexity less than this will be reported as low severity.</summary>",
"/// <remarks>If left as zero then the rule will initialize it to 2*SuccessThreshold.</remarks>",
"/// <summary>Methods with cyclomatic complexity less than this (but higher than LowThreshold) will be reported as medium severity.</summary>",
"/// <remarks>If left as zero then the rule will initialize it to 3*SuccessThreshold.</remarks>",
"/// <summary>Methods with cyclomatic complexity less than this (but higher than MediumThreshold) will be reported as high severity.</summary>",
"/// <remarks>Methods with cyclomatic complexity greater than this will be reported as critical severity.",
"/// If left as zero then the rule will initialize it to 4*SuccessThreshold.</remarks>",
"//does rule apply?",
"//yay! rule do apply!",
"// quick optimization: if the number of instructions is lower",
"// than our SuccessThreshold then it cannot be too complex",
"//how's severity?",
"// 25 <= CC < 50 is not good but not catastrophic either",
"// 50 <= CC < 75 this should be refactored asap",
"// 75 <= CC < 100 this SHOULD be refactored asap",
"// CC > 100, don't touch it since it may become a classic in textbooks ",
"// anyway probably no one can understand it ;-)",
"// the use of 'switch' requires a bit more code so we avoid it unless there are swicth instructions",
"// detect ternary pattern",
"// detect ternary pattern",
"// or 'default' (xmcs)",
"// branch can be null (e.g. switch -> Instruction[])",
"// note: a single switch (C#) with sparse values can be broken into several swicth (IL)",
"// that will use the same 'targets' and must be counted only once",
"// some conditional branch can be related to the sparse switch",
"// count all unique targets (and default if more than one C# switch is used)",
"// ignore targets that are the next instructions (xmcs)",
"// add 'default' branch (if one exists)"
] |
[
{
"param": "Rule",
"type": null
},
{
"param": "IMethodRule",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Rule",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "IMethodRule",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "This rule is available since Gendarme 2.0",
"docstring_tokens": [
"This",
"rule",
"is",
"available",
"since",
"Gendarme",
"2",
".",
"0"
]
}
]
}
| false
| 19
| 2,053
| 111
|
39e6d12af21466c7940a7807ad7e73f6e1859dd0
|
pavel-petrenko/nodejstools
|
Nodejs/Product/Nodejs/SharedProject/CommonProjectNode.DiskMerger.cs
|
[
"Apache-2.0"
] |
C#
|
DiskMerger
|
/// <summary>
/// Performs merging of the file system state with the current project hierarchy, bringing them
/// back into sync.
///
/// The class can be created, and ContinueMerge should be called until it returns false, at which
/// point the file system has been merged.
///
/// You can wait between calls to ContinueMerge to enable not blocking the UI.
///
/// If there were changes which came in while the DiskMerger was processing then those changes will still need
/// to be processed after the DiskMerger completes.
/// </summary>
|
Performs merging of the file system state with the current project hierarchy, bringing them
back into sync.
The class can be created, and ContinueMerge should be called until it returns false, at which
point the file system has been merged.
You can wait between calls to ContinueMerge to enable not blocking the UI.
If there were changes which came in while the DiskMerger was processing then those changes will still need
to be processed after the DiskMerger completes.
|
[
"Performs",
"merging",
"of",
"the",
"file",
"system",
"state",
"with",
"the",
"current",
"project",
"hierarchy",
"bringing",
"them",
"back",
"into",
"sync",
".",
"The",
"class",
"can",
"be",
"created",
"and",
"ContinueMerge",
"should",
"be",
"called",
"until",
"it",
"returns",
"false",
"at",
"which",
"point",
"the",
"file",
"system",
"has",
"been",
"merged",
".",
"You",
"can",
"wait",
"between",
"calls",
"to",
"ContinueMerge",
"to",
"enable",
"not",
"blocking",
"the",
"UI",
".",
"If",
"there",
"were",
"changes",
"which",
"came",
"in",
"while",
"the",
"DiskMerger",
"was",
"processing",
"then",
"those",
"changes",
"will",
"still",
"need",
"to",
"be",
"processed",
"after",
"the",
"DiskMerger",
"completes",
"."
] |
private sealed class DiskMerger
{
private readonly ConcurrentStack<(string Name, HierarchyNode Parent)> remainingDirs = new ConcurrentStack<(string, HierarchyNode)>();
private readonly CommonProjectNode project;
public DiskMerger(CommonProjectNode project, HierarchyNode parent, string dir)
{
this.project = project;
this.remainingDirs.Push((dir, parent));
}
public async Task<bool> ContinueMergeAsync(bool hierarchyCreated)
{
if (this.remainingDirs.Count == 0)
{
await this.InvokeOnUIThread(this.project.BoldStartupItem);
return false;
}
if (!this.remainingDirs.TryPop(out var dir) || !Directory.Exists(dir.Name))
{
return true;
}
return await this.InvokeOnUIThread(() => this.ContinueMergeAsyncWorker(dir, hierarchyCreated));
}
private async Task<bool> ContinueMergeAsyncWorker((string Name, HierarchyNode Parent) dir, bool hierarchyCreated)
{
var wasExpanded = hierarchyCreated ? dir.Parent.GetIsExpanded() : false;
var missingOnDisk = new HashSet<HierarchyNode>(dir.Parent.AllChildren);
var thread = this.project.Site.GetUIThread();
try
{
var folders = await Task.Run(() =>
{
thread.MustNotBeCalledFromUIThread();
return Directory.GetDirectories(dir.Name, "*", SearchOption.TopDirectoryOnly);
}).ConfigureAwait(true);
thread.MustBeCalledFromUIThread();
foreach (var curDir in folders)
{
if (this.project.IsFileHidden(curDir))
{
continue;
}
if (IsFileSymLink(curDir))
{
if (IsRecursiveSymLink(dir.Name, curDir))
{
continue;
}
this.project.CreateSymLinkWatcher(curDir);
}
var existing = this.project.AddAllFilesFolder(dir.Parent, curDir, hierarchyCreated);
missingOnDisk.Remove(existing);
this.remainingDirs.Push((curDir, existing));
}
}
catch
{
return true;
}
try
{
var newFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var files = await Task.Run(() =>
{
thread.MustNotBeCalledFromUIThread();
return Directory.GetFiles(dir.Name, "*", SearchOption.TopDirectoryOnly);
}).ConfigureAwait(true);
thread.MustBeCalledFromUIThread();
foreach (var file in files)
{
if (this.project.IsFileHidden(file))
{
continue;
}
var existing = this.project.FindNodeByFullPath(file);
if (existing == null)
{
newFiles.Add(file);
}
else
{
missingOnDisk.Remove(existing);
}
}
AddNewFiles(dir.Parent, newFiles);
}
catch
{
if (hierarchyCreated)
{
dir.Parent.ExpandItem(wasExpanded ? EXPANDFLAGS.EXPF_ExpandFolder : EXPANDFLAGS.EXPF_CollapseFolder);
}
return true;
}
this.RemoveMissingChildren(missingOnDisk);
if (hierarchyCreated)
{
dir.Parent.ExpandItem(wasExpanded ? EXPANDFLAGS.EXPF_ExpandFolder : EXPANDFLAGS.EXPF_CollapseFolder);
}
return true;
}
private void RemoveMissingChildren(HashSet<HierarchyNode> children)
{
this.project.Site.GetUIThread().MustBeCalledFromUIThread();
foreach (var child in children)
{
if (child.ItemNode.IsExcluded)
{
this.project.RemoveSubTree(child);
}
}
}
private void AddNewFiles(HierarchyNode parent, HashSet<string> newFiles)
{
this.project.Site.GetUIThread().MustBeCalledFromUIThread();
foreach (var file in newFiles)
{
this.project.AddAllFilesFile(parent, file);
}
}
private Task InvokeOnUIThread(Action action)
{
return this.project.Site.GetUIThread().InvokeAsync(action);
}
private Task<T> InvokeOnUIThread<T>(Func<Task<T>> func)
{
return this.project.Site.GetUIThread().InvokeTask(func);
}
}
|
[
"private",
"sealed",
"class",
"DiskMerger",
"{",
"private",
"readonly",
"ConcurrentStack",
"<",
"(",
"string",
"Name",
",",
"HierarchyNode",
"Parent",
")",
">",
"remainingDirs",
"=",
"new",
"ConcurrentStack",
"<",
"(",
"string",
",",
"HierarchyNode",
")",
">",
"(",
")",
";",
"private",
"readonly",
"CommonProjectNode",
"project",
";",
"public",
"DiskMerger",
"(",
"CommonProjectNode",
"project",
",",
"HierarchyNode",
"parent",
",",
"string",
"dir",
")",
"{",
"this",
".",
"project",
"=",
"project",
";",
"this",
".",
"remainingDirs",
".",
"Push",
"(",
"(",
"dir",
",",
"parent",
")",
")",
";",
"}",
"public",
"async",
"Task",
"<",
"bool",
">",
"ContinueMergeAsync",
"(",
"bool",
"hierarchyCreated",
")",
"{",
"if",
"(",
"this",
".",
"remainingDirs",
".",
"Count",
"==",
"0",
")",
"{",
"await",
"this",
".",
"InvokeOnUIThread",
"(",
"this",
".",
"project",
".",
"BoldStartupItem",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"this",
".",
"remainingDirs",
".",
"TryPop",
"(",
"out",
"var",
"dir",
")",
"||",
"!",
"Directory",
".",
"Exists",
"(",
"dir",
".",
"Name",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"await",
"this",
".",
"InvokeOnUIThread",
"(",
"(",
")",
"=>",
"this",
".",
"ContinueMergeAsyncWorker",
"(",
"dir",
",",
"hierarchyCreated",
")",
")",
";",
"}",
"private",
"async",
"Task",
"<",
"bool",
">",
"ContinueMergeAsyncWorker",
"(",
"(",
"string",
"Name",
",",
"HierarchyNode",
"Parent",
")",
"dir",
",",
"bool",
"hierarchyCreated",
")",
"{",
"var",
"wasExpanded",
"=",
"hierarchyCreated",
"?",
"dir",
".",
"Parent",
".",
"GetIsExpanded",
"(",
")",
":",
"false",
";",
"var",
"missingOnDisk",
"=",
"new",
"HashSet",
"<",
"HierarchyNode",
">",
"(",
"dir",
".",
"Parent",
".",
"AllChildren",
")",
";",
"var",
"thread",
"=",
"this",
".",
"project",
".",
"Site",
".",
"GetUIThread",
"(",
")",
";",
"try",
"{",
"var",
"folders",
"=",
"await",
"Task",
".",
"Run",
"(",
"(",
")",
"=>",
"{",
"thread",
".",
"MustNotBeCalledFromUIThread",
"(",
")",
";",
"return",
"Directory",
".",
"GetDirectories",
"(",
"dir",
".",
"Name",
",",
"\"",
"*",
"\"",
",",
"SearchOption",
".",
"TopDirectoryOnly",
")",
";",
"}",
")",
".",
"ConfigureAwait",
"(",
"true",
")",
";",
"thread",
".",
"MustBeCalledFromUIThread",
"(",
")",
";",
"foreach",
"(",
"var",
"curDir",
"in",
"folders",
")",
"{",
"if",
"(",
"this",
".",
"project",
".",
"IsFileHidden",
"(",
"curDir",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"IsFileSymLink",
"(",
"curDir",
")",
")",
"{",
"if",
"(",
"IsRecursiveSymLink",
"(",
"dir",
".",
"Name",
",",
"curDir",
")",
")",
"{",
"continue",
";",
"}",
"this",
".",
"project",
".",
"CreateSymLinkWatcher",
"(",
"curDir",
")",
";",
"}",
"var",
"existing",
"=",
"this",
".",
"project",
".",
"AddAllFilesFolder",
"(",
"dir",
".",
"Parent",
",",
"curDir",
",",
"hierarchyCreated",
")",
";",
"missingOnDisk",
".",
"Remove",
"(",
"existing",
")",
";",
"this",
".",
"remainingDirs",
".",
"Push",
"(",
"(",
"curDir",
",",
"existing",
")",
")",
";",
"}",
"}",
"catch",
"{",
"return",
"true",
";",
"}",
"try",
"{",
"var",
"newFiles",
"=",
"new",
"HashSet",
"<",
"string",
">",
"(",
"StringComparer",
".",
"OrdinalIgnoreCase",
")",
";",
"var",
"files",
"=",
"await",
"Task",
".",
"Run",
"(",
"(",
")",
"=>",
"{",
"thread",
".",
"MustNotBeCalledFromUIThread",
"(",
")",
";",
"return",
"Directory",
".",
"GetFiles",
"(",
"dir",
".",
"Name",
",",
"\"",
"*",
"\"",
",",
"SearchOption",
".",
"TopDirectoryOnly",
")",
";",
"}",
")",
".",
"ConfigureAwait",
"(",
"true",
")",
";",
"thread",
".",
"MustBeCalledFromUIThread",
"(",
")",
";",
"foreach",
"(",
"var",
"file",
"in",
"files",
")",
"{",
"if",
"(",
"this",
".",
"project",
".",
"IsFileHidden",
"(",
"file",
")",
")",
"{",
"continue",
";",
"}",
"var",
"existing",
"=",
"this",
".",
"project",
".",
"FindNodeByFullPath",
"(",
"file",
")",
";",
"if",
"(",
"existing",
"==",
"null",
")",
"{",
"newFiles",
".",
"Add",
"(",
"file",
")",
";",
"}",
"else",
"{",
"missingOnDisk",
".",
"Remove",
"(",
"existing",
")",
";",
"}",
"}",
"AddNewFiles",
"(",
"dir",
".",
"Parent",
",",
"newFiles",
")",
";",
"}",
"catch",
"{",
"if",
"(",
"hierarchyCreated",
")",
"{",
"dir",
".",
"Parent",
".",
"ExpandItem",
"(",
"wasExpanded",
"?",
"EXPANDFLAGS",
".",
"EXPF_ExpandFolder",
":",
"EXPANDFLAGS",
".",
"EXPF_CollapseFolder",
")",
";",
"}",
"return",
"true",
";",
"}",
"this",
".",
"RemoveMissingChildren",
"(",
"missingOnDisk",
")",
";",
"if",
"(",
"hierarchyCreated",
")",
"{",
"dir",
".",
"Parent",
".",
"ExpandItem",
"(",
"wasExpanded",
"?",
"EXPANDFLAGS",
".",
"EXPF_ExpandFolder",
":",
"EXPANDFLAGS",
".",
"EXPF_CollapseFolder",
")",
";",
"}",
"return",
"true",
";",
"}",
"private",
"void",
"RemoveMissingChildren",
"(",
"HashSet",
"<",
"HierarchyNode",
">",
"children",
")",
"{",
"this",
".",
"project",
".",
"Site",
".",
"GetUIThread",
"(",
")",
".",
"MustBeCalledFromUIThread",
"(",
")",
";",
"foreach",
"(",
"var",
"child",
"in",
"children",
")",
"{",
"if",
"(",
"child",
".",
"ItemNode",
".",
"IsExcluded",
")",
"{",
"this",
".",
"project",
".",
"RemoveSubTree",
"(",
"child",
")",
";",
"}",
"}",
"}",
"private",
"void",
"AddNewFiles",
"(",
"HierarchyNode",
"parent",
",",
"HashSet",
"<",
"string",
">",
"newFiles",
")",
"{",
"this",
".",
"project",
".",
"Site",
".",
"GetUIThread",
"(",
")",
".",
"MustBeCalledFromUIThread",
"(",
")",
";",
"foreach",
"(",
"var",
"file",
"in",
"newFiles",
")",
"{",
"this",
".",
"project",
".",
"AddAllFilesFile",
"(",
"parent",
",",
"file",
")",
";",
"}",
"}",
"private",
"Task",
"InvokeOnUIThread",
"(",
"Action",
"action",
")",
"{",
"return",
"this",
".",
"project",
".",
"Site",
".",
"GetUIThread",
"(",
")",
".",
"InvokeAsync",
"(",
"action",
")",
";",
"}",
"private",
"Task",
"<",
"T",
">",
"InvokeOnUIThread",
"<",
"T",
">",
"(",
"Func",
"<",
"Task",
"<",
"T",
">",
">",
"func",
")",
"{",
"return",
"this",
".",
"project",
".",
"Site",
".",
"GetUIThread",
"(",
")",
".",
"InvokeTask",
"(",
"func",
")",
";",
"}",
"}"
] |
Performs merging of the file system state with the current project hierarchy, bringing them
back into sync.
|
[
"Performs",
"merging",
"of",
"the",
"file",
"system",
"state",
"with",
"the",
"current",
"project",
"hierarchy",
"bringing",
"them",
"back",
"into",
"sync",
"."
] |
[
"/// <summary>",
"/// Continues processing the merge request, performing a portion of the full merge possibly",
"/// returning before the merge has completed.",
"/// </summary>",
"/// <returns>Returns true if the merge needs to continue, or false if the merge has completed.</returns>",
"// all done",
"// enumerate disk on worker thread ",
"// don't add recursive sym links",
"// track symlinks, we won't get events on the directory",
"// directory was deleted, we don't have access, etc...",
"// directory was deleted, we don't have access, etc...",
"// We are about to return and some of the previous operations may have affect the Parent's Expanded",
"// state. Set it back to what it was",
"// remove the excluded children which are no longer there"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 23
| 878
| 116
|
67efe49da5508c4d6b0d3e0d8ac87f6231ff4604
|
PolymerEl/multi-verse
|
web_modules/@preignition/multi-geo.js
|
[
"Apache-2.0"
] |
JavaScript
|
MultiDrawablePath
|
/**
* ## MultiDrawablePath
*
* `<multi-drawable-path>` draw a line from a geo path in a given projection
*
* ### Styling
* `<multi-drawable-feature>` provides the following custom properties and mixins
* for styling:
*
* Custom property | Description | Default
* ----------------|-------------|----------
* `--multi-drawable-feature-stroke-color` | stroke color for features | `--secondary-text-color` or grey
* `--multi-drawable-feature-fill-color` | fill color for features | none
* `--multi-drawable-feature` | Mixin applied to features | `{}`
*
* @memberof MultiChart
* @customElement
* @polymer
* @appliesMixin MultiChart.mixin.MultiGeoMixin
* @demo
**/
|
MultiDrawablePath
`` draw a line from a geo path in a given projection
Styling
`` provides the following custom properties and mixins
for styling.
|
[
"MultiDrawablePath",
"`",
"`",
"draw",
"a",
"line",
"from",
"a",
"geo",
"path",
"in",
"a",
"given",
"projection",
"Styling",
"`",
"`",
"provides",
"the",
"following",
"custom",
"properties",
"and",
"mixins",
"for",
"styling",
"."
] |
class MultiDrawablePath extends
MultiGeoDrawable(MultiDrawable) {
// Note(cg): style to add to svghost while dispatching SVG.
static get hostStyles() {
return css `
.multi-drawable-path {
stroke: var(--multi-drawable-path-stroke-color, var(--secondary-text-color, grey));
fill: var(--multi-drawable-path-fill-color, none);
}
`;
}
render() {
return this.html `
<svg>
<g id="drawable" slot-svg="slot-layer" part="path" class="multi-drawable-path"></g>
</svg>
`;
}
static get properties() {
return {
...super.properties,
/**
* `path` the [path](https://github.com/d3/d3-geo#geoPath) generator function
*/
path: {
type: Function
},
/**
* `attrs` default attributes to be set on the chart
*/
attrs: {
type: Object
}
};
}
/*
* `registerOrder` - registerable elements are sorted on the basis of this property.
*/
get registerOrder() {
return 50;
}
draw(data) {
if (!this.path) {
this.log && console.warn('trying to draw path but geo path is not yet set');
return false;
}
if (!this.drawableData) {
this.log && console.warn('data not yet set');
return false;
}
this.log && console.info('draw path');
const chart = select(this.targetElement);
chart.selectAll('*').remove();
return chart
.append('path')
.datum(this.drawableData)
.attrs(this.attrs)
.attr('d', this.path);
}
}
|
[
"class",
"MultiDrawablePath",
"extends",
"MultiGeoDrawable",
"(",
"MultiDrawable",
")",
"{",
"static",
"get",
"hostStyles",
"(",
")",
"{",
"return",
"css",
"`",
"`",
";",
"}",
"render",
"(",
")",
"{",
"return",
"this",
".",
"html",
"`",
"`",
";",
"}",
"static",
"get",
"properties",
"(",
")",
"{",
"return",
"{",
"...",
"super",
".",
"properties",
",",
"path",
":",
"{",
"type",
":",
"Function",
"}",
",",
"attrs",
":",
"{",
"type",
":",
"Object",
"}",
"}",
";",
"}",
"get",
"registerOrder",
"(",
")",
"{",
"return",
"50",
";",
"}",
"draw",
"(",
"data",
")",
"{",
"if",
"(",
"!",
"this",
".",
"path",
")",
"{",
"this",
".",
"log",
"&&",
"console",
".",
"warn",
"(",
"'trying to draw path but geo path is not yet set'",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"this",
".",
"drawableData",
")",
"{",
"this",
".",
"log",
"&&",
"console",
".",
"warn",
"(",
"'data not yet set'",
")",
";",
"return",
"false",
";",
"}",
"this",
".",
"log",
"&&",
"console",
".",
"info",
"(",
"'draw path'",
")",
";",
"const",
"chart",
"=",
"select",
"(",
"this",
".",
"targetElement",
")",
";",
"chart",
".",
"selectAll",
"(",
"'*'",
")",
".",
"remove",
"(",
")",
";",
"return",
"chart",
".",
"append",
"(",
"'path'",
")",
".",
"datum",
"(",
"this",
".",
"drawableData",
")",
".",
"attrs",
"(",
"this",
".",
"attrs",
")",
".",
"attr",
"(",
"'d'",
",",
"this",
".",
"path",
")",
";",
"}",
"}"
] |
## MultiDrawablePath
`<multi-drawable-path>` draw a line from a geo path in a given projection
|
[
"##",
"MultiDrawablePath",
"`",
"<multi",
"-",
"drawable",
"-",
"path",
">",
"`",
"draw",
"a",
"line",
"from",
"a",
"geo",
"path",
"in",
"a",
"given",
"projection"
] |
[
"// Note(cg): style to add to svghost while dispatching SVG.",
"/**\n * `path` the [path](https://github.com/d3/d3-geo#geoPath) generator function\n */",
"/**\n * `attrs` default attributes to be set on the chart\n */",
"/*\n * `registerOrder` - registerable elements are sorted on the basis of this property.\n */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 390
| 169
|
f096600fdbabc8b4cafbffccfcb117927945ce4f
|
hemanthkodandarama/myleetcode
|
codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_659.java
|
[
"MIT"
] |
Java
|
_659
|
/**
* 659. Split Array into Consecutive Subsequences
* <p>
* Given an array nums sorted in ascending order, return true if and only if you can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and has length at least 3.
* <p>
* Example 1:
* <p>
* Input: [1,2,3,3,4,5]
* Output: True
* Explanation:
* You can split them into two consecutive subsequences :
* 1, 2, 3
* 3, 4, 5
* <p>
* Example 2:
* <p>
* Input: [1,2,3,3,4,4,5,5]
* Output: True
* Explanation:
* You can split them into two consecutive subsequences :
* 1, 2, 3, 4, 5
* 3, 4, 5
* <p>
* Example 3:
* <p>
* Input: [1,2,3,4,4,5]
* Output: False
* <p>
* Constraints:
* <p>
* 1 <= nums.length <= 10000
*/
|
659. Split Array into Consecutive Subsequences
Given an array nums sorted in ascending order, return true if and only if you can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and has length at least 3.
|
[
"659",
".",
"Split",
"Array",
"into",
"Consecutive",
"Subsequences",
"Given",
"an",
"array",
"nums",
"sorted",
"in",
"ascending",
"order",
"return",
"true",
"if",
"and",
"only",
"if",
"you",
"can",
"split",
"it",
"into",
"1",
"or",
"more",
"subsequences",
"such",
"that",
"each",
"subsequence",
"consists",
"of",
"consecutive",
"integers",
"and",
"has",
"length",
"at",
"least",
"3",
"."
] |
public class _659 {
public boolean isPossible(int[] nums) {
int pre = Integer.MIN_VALUE, p1 = 0, p2 = 0, p3 = 0;
int cur = 0, cnt = 0, c1 = 0, c2 = 0, c3 = 0;
for (int i = 0; i < nums.length; pre = cur, p1 = c1, p2 = c2, p3 = c3) {
for (cur = nums[i], cnt = 0; i < nums.length && cur == nums[i]; cnt++, i++) ;
if (cur != pre + 1) {
if (p1 != 0 || p2 != 0) return false;
c1 = cnt;
c2 = 0;
c3 = 0;
} else {
if (cnt < p1 + p2) return false;
c1 = Math.max(0, cnt - (p1 + p2 + p3));
c2 = p1;
c3 = p2 + Math.min(p3, cnt - (p1 + p2));
}
}
return (p1 == 0 && p2 == 0);
}
}
|
[
"public",
"class",
"_659",
"{",
"public",
"boolean",
"isPossible",
"(",
"int",
"[",
"]",
"nums",
")",
"{",
"int",
"pre",
"=",
"Integer",
".",
"MIN_VALUE",
",",
"p1",
"=",
"0",
",",
"p2",
"=",
"0",
",",
"p3",
"=",
"0",
";",
"int",
"cur",
"=",
"0",
",",
"cnt",
"=",
"0",
",",
"c1",
"=",
"0",
",",
"c2",
"=",
"0",
",",
"c3",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nums",
".",
"length",
";",
"pre",
"=",
"cur",
",",
"p1",
"=",
"c1",
",",
"p2",
"=",
"c2",
",",
"p3",
"=",
"c3",
")",
"{",
"for",
"(",
"cur",
"=",
"nums",
"[",
"i",
"]",
",",
"cnt",
"=",
"0",
";",
"i",
"<",
"nums",
".",
"length",
"&&",
"cur",
"==",
"nums",
"[",
"i",
"]",
";",
"cnt",
"++",
",",
"i",
"++",
")",
";",
"if",
"(",
"cur",
"!=",
"pre",
"+",
"1",
")",
"{",
"if",
"(",
"p1",
"!=",
"0",
"||",
"p2",
"!=",
"0",
")",
"return",
"false",
";",
"c1",
"=",
"cnt",
";",
"c2",
"=",
"0",
";",
"c3",
"=",
"0",
";",
"}",
"else",
"{",
"if",
"(",
"cnt",
"<",
"p1",
"+",
"p2",
")",
"return",
"false",
";",
"c1",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"cnt",
"-",
"(",
"p1",
"+",
"p2",
"+",
"p3",
")",
")",
";",
"c2",
"=",
"p1",
";",
"c3",
"=",
"p2",
"+",
"Math",
".",
"min",
"(",
"p3",
",",
"cnt",
"-",
"(",
"p1",
"+",
"p2",
")",
")",
";",
"}",
"}",
"return",
"(",
"p1",
"==",
"0",
"&&",
"p2",
"==",
"0",
")",
";",
"}",
"}"
] |
659.
|
[
"659",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 276
| 269
|
d62b5954be65082f267efa70774524debab6b04f
|
reseachalps/Search-Engine
|
backend/common-http/src/main/java/com/datapublica/common/http/impl/DPHttpClientImpl.java
|
[
"MIT"
] |
Java
|
DPHttpClientImpl
|
/**
* Core implementation of DPHTTPClient This is based on Apache HttpClient, supports http and https with any
* BasicAuthHttpProxy.
* <p>
* This service supports two optional parameters
* <ul>
* <li>proxy: BasicAuthHttpProxy. Corresponds to the proxy provider which will be used</li>
* <li>userAgent: String. Default User-Agent that will be used if it is not set in the request.</li>
* </ul>
*/
|
Core implementation of DPHTTPClient This is based on Apache HttpClient, supports http and https with any
BasicAuthHttpProxy.
This service supports two optional parameters
proxy: BasicAuthHttpProxy. Corresponds to the proxy provider which will be used
userAgent: String. Default User-Agent that will be used if it is not set in the request.
|
[
"Core",
"implementation",
"of",
"DPHTTPClient",
"This",
"is",
"based",
"on",
"Apache",
"HttpClient",
"supports",
"http",
"and",
"https",
"with",
"any",
"BasicAuthHttpProxy",
".",
"This",
"service",
"supports",
"two",
"optional",
"parameters",
"proxy",
":",
"BasicAuthHttpProxy",
".",
"Corresponds",
"to",
"the",
"proxy",
"provider",
"which",
"will",
"be",
"used",
"userAgent",
":",
"String",
".",
"Default",
"User",
"-",
"Agent",
"that",
"will",
"be",
"used",
"if",
"it",
"is",
"not",
"set",
"in",
"the",
"request",
"."
] |
public class DPHttpClientImpl extends AbstractHttpClientImpl {
private static final Logger log = LoggerFactory.getLogger(DPHttpClientImpl.class);
private DefaultHttpClient client;
private BasicHttpContext localcontext;
public DPHttpClientImpl(String cookiePolicy, boolean followRedirect) {
TrustManager[] tm = new TrustManager[]{new TrustManagerManipulator()};
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tm, new SecureRandom());
} catch (KeyManagementException | NoSuchAlgorithmException e) {
// init fail for JVM reasons
throw new RuntimeException(e);
}
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext,
SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
// Declare registry
final SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
registry.register(new Scheme("https", 443, sslSocketFactory));
// Get pooled client, and set route planner
this.client = new DefaultHttpClient(new PoolingClientConnectionManager(registry));
if (followRedirect) {
// redirect and send headers again
this.client.setRedirectStrategy(new LaxRedirectStrategy() {
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
HttpUriRequest redirect = super.getRedirect(request, response, context);
redirect.setHeaders(request.getAllHeaders());
return redirect;
}
});
}
this.localcontext = new BasicHttpContext();
// Set cookie policy
this.client.getParams().setParameter(ClientPNames.COOKIE_POLICY, cookiePolicy);
}
public DPHttpClientImpl(String cookiePolicy) {
this(cookiePolicy, true);
}
public DPHttpClientImpl() {
this(CookiePolicy.IGNORE_COOKIES, true);
}
public DPHttpClientImpl(boolean followRedirect) {
this(CookiePolicy.IGNORE_COOKIES, followRedirect);
}
@Override
public void setProxy(BasicAuthHttpProxy proxy) {
super.setProxy(proxy);
this.localcontext = (this.proxy != null) ? this.proxy.initClient(this.client) : new BasicHttpContext();
}
@Override
protected DPHttpResponse process(HttpUriRequest request, int... expectedStatues) throws IOException {
return internalProcess(request, null);
}
@Override
protected DPHttpResponse processAndStore(HttpUriRequest request, File targetFile, int... expectedStatuses) throws IOException {
return internalProcess(request, targetFile);
}
protected DPHttpResponse internalProcess(HttpUriRequest request, File targetFile) throws IOException {
HttpResponse response = null;
log.debug("Executing HTTP request: " + request.getURI());
try {
// Execute query
final HttpContext context = new BasicHttpContext(this.localcontext);
final Date date = new Date();
response = this.client.execute(request, context);
// Track redirections
URI target = request.getURI();
RedirectLocations locations = (RedirectLocations) context.getAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS);
if (locations != null) {
List<URI> all = locations.getAll();
target = all.get(all.size() - 1);
log.debug("Request [{}] has been redirected to [{}]", request.getURI().toString(), target.toString());
}
HttpEntity entity = response.getEntity();
// Build response
final DPHttpResponse result = new DPHttpResponse(date, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), target.toString());
parseHeader(response, result, request);
try {
// May not use get(HttpEntity) anymore : fucking Microsoft IIS server is sending an invalid content type (between double quotes)
ContentType contentType = null;
try {
contentType = ContentType.get(entity);
} catch (IllegalArgumentException e) {
final Header[] headers = response.getHeaders("Content-Type");
if (headers != null && headers.length > 0) {
final String value = headers[0].getValue();
if (value.matches("^\".+\"$")) {
final String parsed = value.substring(1, value.length() - 1);
log.info("Parsing content type [" + parsed + "] from origin [" + value + "]");
contentType = ContentType.parse(parsed);
}
}
if (contentType == null) {
throw e;
}
}
//
if (contentType != null) {
result.setContentType(contentType.getMimeType());
Charset charset = contentType.getCharset();
if (charset != null)
result.setCharset(charset.name());
}
} catch (UnsupportedCharsetException ex) {
log.warn("Unknown charset: " + ex.getMessage());
}
// Null entity exception: we adopt the "empty body" strategy to make things easier for everyone
if (targetFile != null) {
IOUtils.copy(entity.getContent(), new FileOutputStream(targetFile));
} else {
result.setContent(entity == null ? new byte[]{} : EntityUtils.toByteArray(entity));
}
return result;
} finally {
// Consume response
if (response != null) {
EntityUtils.consume(response.getEntity());
}
}
}
}
|
[
"public",
"class",
"DPHttpClientImpl",
"extends",
"AbstractHttpClientImpl",
"{",
"private",
"static",
"final",
"Logger",
"log",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"DPHttpClientImpl",
".",
"class",
")",
";",
"private",
"DefaultHttpClient",
"client",
";",
"private",
"BasicHttpContext",
"localcontext",
";",
"public",
"DPHttpClientImpl",
"(",
"String",
"cookiePolicy",
",",
"boolean",
"followRedirect",
")",
"{",
"TrustManager",
"[",
"]",
"tm",
"=",
"new",
"TrustManager",
"[",
"]",
"{",
"new",
"TrustManagerManipulator",
"(",
")",
"}",
";",
"SSLContext",
"sslContext",
"=",
"null",
";",
"try",
"{",
"sslContext",
"=",
"SSLContext",
".",
"getInstance",
"(",
"\"",
"TLS",
"\"",
")",
";",
"sslContext",
".",
"init",
"(",
"null",
",",
"tm",
",",
"new",
"SecureRandom",
"(",
")",
")",
";",
"}",
"catch",
"(",
"KeyManagementException",
"|",
"NoSuchAlgorithmException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"SSLSocketFactory",
"sslSocketFactory",
"=",
"new",
"SSLSocketFactory",
"(",
"sslContext",
",",
"SSLSocketFactory",
".",
"ALLOW_ALL_HOSTNAME_VERIFIER",
")",
";",
"final",
"SchemeRegistry",
"registry",
"=",
"new",
"SchemeRegistry",
"(",
")",
";",
"registry",
".",
"register",
"(",
"new",
"Scheme",
"(",
"\"",
"http",
"\"",
",",
"80",
",",
"PlainSocketFactory",
".",
"getSocketFactory",
"(",
")",
")",
")",
";",
"registry",
".",
"register",
"(",
"new",
"Scheme",
"(",
"\"",
"https",
"\"",
",",
"443",
",",
"sslSocketFactory",
")",
")",
";",
"this",
".",
"client",
"=",
"new",
"DefaultHttpClient",
"(",
"new",
"PoolingClientConnectionManager",
"(",
"registry",
")",
")",
";",
"if",
"(",
"followRedirect",
")",
"{",
"this",
".",
"client",
".",
"setRedirectStrategy",
"(",
"new",
"LaxRedirectStrategy",
"(",
")",
"{",
"@",
"Override",
"public",
"HttpUriRequest",
"getRedirect",
"(",
"HttpRequest",
"request",
",",
"HttpResponse",
"response",
",",
"HttpContext",
"context",
")",
"throws",
"ProtocolException",
"{",
"HttpUriRequest",
"redirect",
"=",
"super",
".",
"getRedirect",
"(",
"request",
",",
"response",
",",
"context",
")",
";",
"redirect",
".",
"setHeaders",
"(",
"request",
".",
"getAllHeaders",
"(",
")",
")",
";",
"return",
"redirect",
";",
"}",
"}",
")",
";",
"}",
"this",
".",
"localcontext",
"=",
"new",
"BasicHttpContext",
"(",
")",
";",
"this",
".",
"client",
".",
"getParams",
"(",
")",
".",
"setParameter",
"(",
"ClientPNames",
".",
"COOKIE_POLICY",
",",
"cookiePolicy",
")",
";",
"}",
"public",
"DPHttpClientImpl",
"(",
"String",
"cookiePolicy",
")",
"{",
"this",
"(",
"cookiePolicy",
",",
"true",
")",
";",
"}",
"public",
"DPHttpClientImpl",
"(",
")",
"{",
"this",
"(",
"CookiePolicy",
".",
"IGNORE_COOKIES",
",",
"true",
")",
";",
"}",
"public",
"DPHttpClientImpl",
"(",
"boolean",
"followRedirect",
")",
"{",
"this",
"(",
"CookiePolicy",
".",
"IGNORE_COOKIES",
",",
"followRedirect",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"setProxy",
"(",
"BasicAuthHttpProxy",
"proxy",
")",
"{",
"super",
".",
"setProxy",
"(",
"proxy",
")",
";",
"this",
".",
"localcontext",
"=",
"(",
"this",
".",
"proxy",
"!=",
"null",
")",
"?",
"this",
".",
"proxy",
".",
"initClient",
"(",
"this",
".",
"client",
")",
":",
"new",
"BasicHttpContext",
"(",
")",
";",
"}",
"@",
"Override",
"protected",
"DPHttpResponse",
"process",
"(",
"HttpUriRequest",
"request",
",",
"int",
"...",
"expectedStatues",
")",
"throws",
"IOException",
"{",
"return",
"internalProcess",
"(",
"request",
",",
"null",
")",
";",
"}",
"@",
"Override",
"protected",
"DPHttpResponse",
"processAndStore",
"(",
"HttpUriRequest",
"request",
",",
"File",
"targetFile",
",",
"int",
"...",
"expectedStatuses",
")",
"throws",
"IOException",
"{",
"return",
"internalProcess",
"(",
"request",
",",
"targetFile",
")",
";",
"}",
"protected",
"DPHttpResponse",
"internalProcess",
"(",
"HttpUriRequest",
"request",
",",
"File",
"targetFile",
")",
"throws",
"IOException",
"{",
"HttpResponse",
"response",
"=",
"null",
";",
"log",
".",
"debug",
"(",
"\"",
"Executing HTTP request: ",
"\"",
"+",
"request",
".",
"getURI",
"(",
")",
")",
";",
"try",
"{",
"final",
"HttpContext",
"context",
"=",
"new",
"BasicHttpContext",
"(",
"this",
".",
"localcontext",
")",
";",
"final",
"Date",
"date",
"=",
"new",
"Date",
"(",
")",
";",
"response",
"=",
"this",
".",
"client",
".",
"execute",
"(",
"request",
",",
"context",
")",
";",
"URI",
"target",
"=",
"request",
".",
"getURI",
"(",
")",
";",
"RedirectLocations",
"locations",
"=",
"(",
"RedirectLocations",
")",
"context",
".",
"getAttribute",
"(",
"DefaultRedirectStrategy",
".",
"REDIRECT_LOCATIONS",
")",
";",
"if",
"(",
"locations",
"!=",
"null",
")",
"{",
"List",
"<",
"URI",
">",
"all",
"=",
"locations",
".",
"getAll",
"(",
")",
";",
"target",
"=",
"all",
".",
"get",
"(",
"all",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"log",
".",
"debug",
"(",
"\"",
"Request [{}] has been redirected to [{}]",
"\"",
",",
"request",
".",
"getURI",
"(",
")",
".",
"toString",
"(",
")",
",",
"target",
".",
"toString",
"(",
")",
")",
";",
"}",
"HttpEntity",
"entity",
"=",
"response",
".",
"getEntity",
"(",
")",
";",
"final",
"DPHttpResponse",
"result",
"=",
"new",
"DPHttpResponse",
"(",
"date",
",",
"response",
".",
"getStatusLine",
"(",
")",
".",
"getStatusCode",
"(",
")",
",",
"response",
".",
"getStatusLine",
"(",
")",
".",
"getReasonPhrase",
"(",
")",
",",
"target",
".",
"toString",
"(",
")",
")",
";",
"parseHeader",
"(",
"response",
",",
"result",
",",
"request",
")",
";",
"try",
"{",
"ContentType",
"contentType",
"=",
"null",
";",
"try",
"{",
"contentType",
"=",
"ContentType",
".",
"get",
"(",
"entity",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"e",
")",
"{",
"final",
"Header",
"[",
"]",
"headers",
"=",
"response",
".",
"getHeaders",
"(",
"\"",
"Content-Type",
"\"",
")",
";",
"if",
"(",
"headers",
"!=",
"null",
"&&",
"headers",
".",
"length",
">",
"0",
")",
"{",
"final",
"String",
"value",
"=",
"headers",
"[",
"0",
"]",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"value",
".",
"matches",
"(",
"\"",
"^",
"\\\"",
".+",
"\\\"",
"$",
"\"",
")",
")",
"{",
"final",
"String",
"parsed",
"=",
"value",
".",
"substring",
"(",
"1",
",",
"value",
".",
"length",
"(",
")",
"-",
"1",
")",
";",
"log",
".",
"info",
"(",
"\"",
"Parsing content type [",
"\"",
"+",
"parsed",
"+",
"\"",
"] from origin [",
"\"",
"+",
"value",
"+",
"\"",
"]",
"\"",
")",
";",
"contentType",
"=",
"ContentType",
".",
"parse",
"(",
"parsed",
")",
";",
"}",
"}",
"if",
"(",
"contentType",
"==",
"null",
")",
"{",
"throw",
"e",
";",
"}",
"}",
"if",
"(",
"contentType",
"!=",
"null",
")",
"{",
"result",
".",
"setContentType",
"(",
"contentType",
".",
"getMimeType",
"(",
")",
")",
";",
"Charset",
"charset",
"=",
"contentType",
".",
"getCharset",
"(",
")",
";",
"if",
"(",
"charset",
"!=",
"null",
")",
"result",
".",
"setCharset",
"(",
"charset",
".",
"name",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"UnsupportedCharsetException",
"ex",
")",
"{",
"log",
".",
"warn",
"(",
"\"",
"Unknown charset: ",
"\"",
"+",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"if",
"(",
"targetFile",
"!=",
"null",
")",
"{",
"IOUtils",
".",
"copy",
"(",
"entity",
".",
"getContent",
"(",
")",
",",
"new",
"FileOutputStream",
"(",
"targetFile",
")",
")",
";",
"}",
"else",
"{",
"result",
".",
"setContent",
"(",
"entity",
"==",
"null",
"?",
"new",
"byte",
"[",
"]",
"{",
"}",
":",
"EntityUtils",
".",
"toByteArray",
"(",
"entity",
")",
")",
";",
"}",
"return",
"result",
";",
"}",
"finally",
"{",
"if",
"(",
"response",
"!=",
"null",
")",
"{",
"EntityUtils",
".",
"consume",
"(",
"response",
".",
"getEntity",
"(",
")",
")",
";",
"}",
"}",
"}",
"}"
] |
Core implementation of DPHTTPClient This is based on Apache HttpClient, supports http and https with any
BasicAuthHttpProxy.
|
[
"Core",
"implementation",
"of",
"DPHTTPClient",
"This",
"is",
"based",
"on",
"Apache",
"HttpClient",
"supports",
"http",
"and",
"https",
"with",
"any",
"BasicAuthHttpProxy",
"."
] |
[
"// init fail for JVM reasons",
"// Declare registry",
"// Get pooled client, and set route planner",
"// redirect and send headers again",
"// Set cookie policy",
"// Execute query",
"// Track redirections",
"// Build response",
"// May not use get(HttpEntity) anymore : fucking Microsoft IIS server is sending an invalid content type (between double quotes)",
"//",
"// Null entity exception: we adopt the \"empty body\" strategy to make things easier for everyone",
"// Consume response"
] |
[
{
"param": "AbstractHttpClientImpl",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "AbstractHttpClientImpl",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 24
| 1,095
| 100
|
8d560ccd0150c8298a8a676a8b2f91f637819795
|
shaunmahony/seqcode
|
src/edu/psu/compbio/seqcode/gse/tools/microarray/FastaOfProbeSequences.java
|
[
"MIT"
] |
Java
|
FastaOfProbeSequences
|
/**
* Generates FASTA output on stdout of probe sequences. The sequence
* names are the probe DBIDs, suitable for later import when mapped to
* a new genome. Specify either a designname or a species name or you'll
* get *all* the probes in the DB.
*
* FastaOfProbeSequences [--design 'Hox Array'] [--species 'Mus Musculus']
*/
|
Generates FASTA output on stdout of probe sequences. The sequence
names are the probe DBIDs, suitable for later import when mapped to
a new genome. Specify either a designname or a species name or you'll
get *all* the probes in the DB.
FastaOfProbeSequences [--design 'Hox Array'] [--species 'Mus Musculus']
|
[
"Generates",
"FASTA",
"output",
"on",
"stdout",
"of",
"probe",
"sequences",
".",
"The",
"sequence",
"names",
"are",
"the",
"probe",
"DBIDs",
"suitable",
"for",
"later",
"import",
"when",
"mapped",
"to",
"a",
"new",
"genome",
".",
"Specify",
"either",
"a",
"designname",
"or",
"a",
"species",
"name",
"or",
"you",
"'",
"ll",
"get",
"*",
"all",
"*",
"the",
"probes",
"in",
"the",
"DB",
".",
"FastaOfProbeSequences",
"[",
"--",
"design",
"'",
"Hox",
"Array",
"'",
"]",
"[",
"--",
"species",
"'",
"Mus",
"Musculus",
"'",
"]"
] |
public class FastaOfProbeSequences {
public static void main(String args[]) throws Exception {
String designName = Args.parseString(args,"design",null);
String speciesName = Args.parseString(args,"species",null);
StringBuffer query = new StringBuffer("select id, sequence from probedesign");
if (speciesName != null) {
ChipChipMetadataLoader loader = new ChipChipMetadataLoader();
ArrayList<Integer> dbids = new ArrayList<Integer>();
for (ArrayDesign d : loader.loadAllArrayDesigns()) {
if (d.getGenome().getSpecies().equals(speciesName)) {
dbids.add(d.getDBID());
}
}
query.append(" where arraydesign in (");
for (int i = 0; i < dbids.size(); i++) {
if (i == 0) {
query.append(dbids.get(i));
} else {
query.append("," + dbids.get(i));
}
}
query.append(")");
}
if (designName != null) {
ChipChipMetadataLoader loader = new ChipChipMetadataLoader();
ArrayDesign design = null;
for (ArrayDesign d : loader.loadAllArrayDesigns()) {
if (d.getName().equals(designName)) {
design = d;
break;
}
}
if (design == null) {
System.err.println("Couldn't find array design with name " + designName);
} else {
query.append(" where arraydesign = " + design.getDBID());
}
}
java.sql.Connection c =
DatabaseFactory.getConnection("chipchip");
Statement stmt = c.createStatement();
System.err.println(query);
ResultSet rs = stmt.executeQuery(query.toString());
while (rs.next()) {
System.out.println(String.format(">%d\n%s",
rs.getInt(1),
rs.getString(2)));
}
rs.close();
stmt.close();
}
}
|
[
"public",
"class",
"FastaOfProbeSequences",
"{",
"public",
"static",
"void",
"main",
"(",
"String",
"args",
"[",
"]",
")",
"throws",
"Exception",
"{",
"String",
"designName",
"=",
"Args",
".",
"parseString",
"(",
"args",
",",
"\"",
"design",
"\"",
",",
"null",
")",
";",
"String",
"speciesName",
"=",
"Args",
".",
"parseString",
"(",
"args",
",",
"\"",
"species",
"\"",
",",
"null",
")",
";",
"StringBuffer",
"query",
"=",
"new",
"StringBuffer",
"(",
"\"",
"select id, sequence from probedesign",
"\"",
")",
";",
"if",
"(",
"speciesName",
"!=",
"null",
")",
"{",
"ChipChipMetadataLoader",
"loader",
"=",
"new",
"ChipChipMetadataLoader",
"(",
")",
";",
"ArrayList",
"<",
"Integer",
">",
"dbids",
"=",
"new",
"ArrayList",
"<",
"Integer",
">",
"(",
")",
";",
"for",
"(",
"ArrayDesign",
"d",
":",
"loader",
".",
"loadAllArrayDesigns",
"(",
")",
")",
"{",
"if",
"(",
"d",
".",
"getGenome",
"(",
")",
".",
"getSpecies",
"(",
")",
".",
"equals",
"(",
"speciesName",
")",
")",
"{",
"dbids",
".",
"add",
"(",
"d",
".",
"getDBID",
"(",
")",
")",
";",
"}",
"}",
"query",
".",
"append",
"(",
"\"",
" where arraydesign in (",
"\"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"dbids",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
"==",
"0",
")",
"{",
"query",
".",
"append",
"(",
"dbids",
".",
"get",
"(",
"i",
")",
")",
";",
"}",
"else",
"{",
"query",
".",
"append",
"(",
"\"",
",",
"\"",
"+",
"dbids",
".",
"get",
"(",
"i",
")",
")",
";",
"}",
"}",
"query",
".",
"append",
"(",
"\"",
")",
"\"",
")",
";",
"}",
"if",
"(",
"designName",
"!=",
"null",
")",
"{",
"ChipChipMetadataLoader",
"loader",
"=",
"new",
"ChipChipMetadataLoader",
"(",
")",
";",
"ArrayDesign",
"design",
"=",
"null",
";",
"for",
"(",
"ArrayDesign",
"d",
":",
"loader",
".",
"loadAllArrayDesigns",
"(",
")",
")",
"{",
"if",
"(",
"d",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"designName",
")",
")",
"{",
"design",
"=",
"d",
";",
"break",
";",
"}",
"}",
"if",
"(",
"design",
"==",
"null",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"",
"Couldn't find array design with name ",
"\"",
"+",
"designName",
")",
";",
"}",
"else",
"{",
"query",
".",
"append",
"(",
"\"",
" where arraydesign = ",
"\"",
"+",
"design",
".",
"getDBID",
"(",
")",
")",
";",
"}",
"}",
"java",
".",
"sql",
".",
"Connection",
"c",
"=",
"DatabaseFactory",
".",
"getConnection",
"(",
"\"",
"chipchip",
"\"",
")",
";",
"Statement",
"stmt",
"=",
"c",
".",
"createStatement",
"(",
")",
";",
"System",
".",
"err",
".",
"println",
"(",
"query",
")",
";",
"ResultSet",
"rs",
"=",
"stmt",
".",
"executeQuery",
"(",
"query",
".",
"toString",
"(",
")",
")",
";",
"while",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"String",
".",
"format",
"(",
"\"",
">%d",
"\\n",
"%s",
"\"",
",",
"rs",
".",
"getInt",
"(",
"1",
")",
",",
"rs",
".",
"getString",
"(",
"2",
")",
")",
")",
";",
"}",
"rs",
".",
"close",
"(",
")",
";",
"stmt",
".",
"close",
"(",
")",
";",
"}",
"}"
] |
Generates FASTA output on stdout of probe sequences.
|
[
"Generates",
"FASTA",
"output",
"on",
"stdout",
"of",
"probe",
"sequences",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 410
| 85
|
655f5ccb855a97c8f8154b46457ce51354f8471f
|
Chaanks/speechbrain
|
speechbrain/dataio/preprocess.py
|
[
"Apache-2.0"
] |
Python
|
AudioNormalizer
|
Normalizes audio into a standard format
Arguments
---------
sample_rate : int
The sampling rate to which the incoming signals should be converted.
mix : {"avg-to-mono", "keep"}
"avg-to-mono" - add all channels together and normalize by number of
channels. This also removes the channel dimension, resulting in [time]
format tensor.
"keep" - don't normalize channel information
Example
-------
>>> import torchaudio
>>> example_file = 'tests/samples/multi-mic/speech_-0.82918_0.55279_-0.082918.flac'
>>> signal, sr = torchaudio.load(example_file, channels_first = False)
>>> normalizer = AudioNormalizer(sample_rate=8000)
>>> normalized = normalizer(signal, sr)
>>> signal.shape
torch.Size([160000, 4])
>>> normalized.shape
torch.Size([80000])
NOTE
----
This will also upsample audio. However, upsampling cannot produce meaningful
information in the bandwidth which it adds. Generally models will not work
well for upsampled data if they have not specifically been trained to do so.
|
Normalizes audio into a standard format
Arguments
sample_rate : int
The sampling rate to which the incoming signals should be converted.
Example
NOTE
This will also upsample audio. However, upsampling cannot produce meaningful
information in the bandwidth which it adds. Generally models will not work
well for upsampled data if they have not specifically been trained to do so.
|
[
"Normalizes",
"audio",
"into",
"a",
"standard",
"format",
"Arguments",
"sample_rate",
":",
"int",
"The",
"sampling",
"rate",
"to",
"which",
"the",
"incoming",
"signals",
"should",
"be",
"converted",
".",
"Example",
"NOTE",
"This",
"will",
"also",
"upsample",
"audio",
".",
"However",
"upsampling",
"cannot",
"produce",
"meaningful",
"information",
"in",
"the",
"bandwidth",
"which",
"it",
"adds",
".",
"Generally",
"models",
"will",
"not",
"work",
"well",
"for",
"upsampled",
"data",
"if",
"they",
"have",
"not",
"specifically",
"been",
"trained",
"to",
"do",
"so",
"."
] |
class AudioNormalizer:
"""Normalizes audio into a standard format
Arguments
---------
sample_rate : int
The sampling rate to which the incoming signals should be converted.
mix : {"avg-to-mono", "keep"}
"avg-to-mono" - add all channels together and normalize by number of
channels. This also removes the channel dimension, resulting in [time]
format tensor.
"keep" - don't normalize channel information
Example
-------
>>> import torchaudio
>>> example_file = 'tests/samples/multi-mic/speech_-0.82918_0.55279_-0.082918.flac'
>>> signal, sr = torchaudio.load(example_file, channels_first = False)
>>> normalizer = AudioNormalizer(sample_rate=8000)
>>> normalized = normalizer(signal, sr)
>>> signal.shape
torch.Size([160000, 4])
>>> normalized.shape
torch.Size([80000])
NOTE
----
This will also upsample audio. However, upsampling cannot produce meaningful
information in the bandwidth which it adds. Generally models will not work
well for upsampled data if they have not specifically been trained to do so.
"""
def __init__(self, sample_rate=16000, mix="avg-to-mono"):
self.sample_rate = sample_rate
if mix not in ["avg-to-mono", "keep"]:
raise ValueError(f"Unexpected mixing configuration {mix}")
self.mix = mix
self._cached_resample = functools.lru_cache(maxsize=12)(Resample)
def __call__(self, audio, sample_rate):
"""Perform normalization
Arguments
---------
audio : tensor
The input waveform torch tensor. Assuming [time, channels],
or [time].
"""
resampler = self._cached_resample(sample_rate, self.sample_rate)
resampled = resampler(audio.unsqueeze(0)).squeeze(0)
return self._mix(resampled)
def _mix(self, audio):
"""Handle channel mixing"""
flat_input = audio.dim() == 1
if self.mix == "avg-to-mono":
if flat_input:
return audio
return torch.mean(audio, 1)
if self.mix == "keep":
return audio
|
[
"class",
"AudioNormalizer",
":",
"def",
"__init__",
"(",
"self",
",",
"sample_rate",
"=",
"16000",
",",
"mix",
"=",
"\"avg-to-mono\"",
")",
":",
"self",
".",
"sample_rate",
"=",
"sample_rate",
"if",
"mix",
"not",
"in",
"[",
"\"avg-to-mono\"",
",",
"\"keep\"",
"]",
":",
"raise",
"ValueError",
"(",
"f\"Unexpected mixing configuration {mix}\"",
")",
"self",
".",
"mix",
"=",
"mix",
"self",
".",
"_cached_resample",
"=",
"functools",
".",
"lru_cache",
"(",
"maxsize",
"=",
"12",
")",
"(",
"Resample",
")",
"def",
"__call__",
"(",
"self",
",",
"audio",
",",
"sample_rate",
")",
":",
"\"\"\"Perform normalization\n\n Arguments\n ---------\n audio : tensor\n The input waveform torch tensor. Assuming [time, channels],\n or [time].\n \"\"\"",
"resampler",
"=",
"self",
".",
"_cached_resample",
"(",
"sample_rate",
",",
"self",
".",
"sample_rate",
")",
"resampled",
"=",
"resampler",
"(",
"audio",
".",
"unsqueeze",
"(",
"0",
")",
")",
".",
"squeeze",
"(",
"0",
")",
"return",
"self",
".",
"_mix",
"(",
"resampled",
")",
"def",
"_mix",
"(",
"self",
",",
"audio",
")",
":",
"\"\"\"Handle channel mixing\"\"\"",
"flat_input",
"=",
"audio",
".",
"dim",
"(",
")",
"==",
"1",
"if",
"self",
".",
"mix",
"==",
"\"avg-to-mono\"",
":",
"if",
"flat_input",
":",
"return",
"audio",
"return",
"torch",
".",
"mean",
"(",
"audio",
",",
"1",
")",
"if",
"self",
".",
"mix",
"==",
"\"keep\"",
":",
"return",
"audio"
] |
Normalizes audio into a standard format
Arguments
|
[
"Normalizes",
"audio",
"into",
"a",
"standard",
"format",
"Arguments"
] |
[
"\"\"\"Normalizes audio into a standard format\n\n Arguments\n ---------\n sample_rate : int\n The sampling rate to which the incoming signals should be converted.\n mix : {\"avg-to-mono\", \"keep\"}\n \"avg-to-mono\" - add all channels together and normalize by number of\n channels. This also removes the channel dimension, resulting in [time]\n format tensor.\n \"keep\" - don't normalize channel information\n\n Example\n -------\n >>> import torchaudio\n >>> example_file = 'tests/samples/multi-mic/speech_-0.82918_0.55279_-0.082918.flac'\n >>> signal, sr = torchaudio.load(example_file, channels_first = False)\n >>> normalizer = AudioNormalizer(sample_rate=8000)\n >>> normalized = normalizer(signal, sr)\n >>> signal.shape\n torch.Size([160000, 4])\n >>> normalized.shape\n torch.Size([80000])\n\n NOTE\n ----\n This will also upsample audio. However, upsampling cannot produce meaningful\n information in the bandwidth which it adds. Generally models will not work\n well for upsampled data if they have not specifically been trained to do so.\n \"\"\"",
"\"\"\"Perform normalization\n\n Arguments\n ---------\n audio : tensor\n The input waveform torch tensor. Assuming [time, channels],\n or [time].\n \"\"\"",
"\"\"\"Handle channel mixing\"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 524
| 282
|
b578e89c72ee88c97c663d4d8a6f9dcefb5226bb
|
mfrigerio17/robot-model-tools
|
src/robmodel/geometry.py
|
[
"BSD-3-Clause"
] |
Python
|
Geometry
|
A model of the geometry of a multi-rigid-body mechanism.
The geometry model consists of a set of constant relative poses between
reference frames attached to the mechanism. The `reference` of any pose must
always be a link frame; the `target` is a joint frame or an arbitrary user
frame.
This class relies on `kgprim.motions.PosesSpec`, and purely performs various
consistency checks between the given models.
A succesfully constructed instance always includes the connectivity model
with ordering, the frames model, and the poses which are the actual
geometric data.
|
A model of the geometry of a multi-rigid-body mechanism.
The geometry model consists of a set of constant relative poses between
reference frames attached to the mechanism. The `reference` of any pose must
always be a link frame; the `target` is a joint frame or an arbitrary user
frame.
This class relies on `kgprim.motions.PosesSpec`, and purely performs various
consistency checks between the given models.
A succesfully constructed instance always includes the connectivity model
with ordering, the frames model, and the poses which are the actual
geometric data.
|
[
"A",
"model",
"of",
"the",
"geometry",
"of",
"a",
"multi",
"-",
"rigid",
"-",
"body",
"mechanism",
".",
"The",
"geometry",
"model",
"consists",
"of",
"a",
"set",
"of",
"constant",
"relative",
"poses",
"between",
"reference",
"frames",
"attached",
"to",
"the",
"mechanism",
".",
"The",
"`",
"reference",
"`",
"of",
"any",
"pose",
"must",
"always",
"be",
"a",
"link",
"frame",
";",
"the",
"`",
"target",
"`",
"is",
"a",
"joint",
"frame",
"or",
"an",
"arbitrary",
"user",
"frame",
".",
"This",
"class",
"relies",
"on",
"`",
"kgprim",
".",
"motions",
".",
"PosesSpec",
"`",
"and",
"purely",
"performs",
"various",
"consistency",
"checks",
"between",
"the",
"given",
"models",
".",
"A",
"succesfully",
"constructed",
"instance",
"always",
"includes",
"the",
"connectivity",
"model",
"with",
"ordering",
"the",
"frames",
"model",
"and",
"the",
"poses",
"which",
"are",
"the",
"actual",
"geometric",
"data",
"."
] |
class Geometry:
'''
A model of the geometry of a multi-rigid-body mechanism.
The geometry model consists of a set of constant relative poses between
reference frames attached to the mechanism. The `reference` of any pose must
always be a link frame; the `target` is a joint frame or an arbitrary user
frame.
This class relies on `kgprim.motions.PosesSpec`, and purely performs various
consistency checks between the given models.
A succesfully constructed instance always includes the connectivity model
with ordering, the frames model, and the poses which are the actual
geometric data.
'''
def __init__(self, connectModel, framesModel, posesModel, jointAxes=None):
'''
Construct the geometry model of a mechanism by composing the arguments.
Parameters:
- `connectModel` the connectivity model of the mechanism, with ordering
- `framesModel` the set of the Cartesian frames attached to the mechanism
- `posesModel` the constant, relative poses between the frames
- `jointAxes` the versors of the joint axes, in joint frame coordinates
The third argument is the actual geometric data; this constructor makes
sure that the three arguments are consistent and therefore can be
composed as a whole.
In fact, the poses model stored in this instance is not the given
`posesModel`. The input poses are always replaced by poses pointing to
objects of `framesModel`. This is because the frames in the given
`posesModel` might be simple placeholders. The name of the frame is used
to establish the correspondence between a placeholder frame and a
robot-attached frame.
The `jointAxes` argument defaults to `None`. In that case it is assumed
that the axis of any joint is the Z axis of its frame. Otherwise, the
argument should be a dictionary indexed by joint name, with values being
3-value tuples. Any tuple must represent the 3D joint axis versor, using
coordinates in the joint frame.
'''
if not isinstance(connectModel, ordering.Robot) :
raise RuntimeError("An ordered robot model is required")
rname = connectModel.name
if framesModel.robot.name != rname :
raise RuntimeError("Robot name mismatch in the connectivity and frames model ('{0}' vs '{1})".format(rname, framesModel.robot.name))
self.byPose = {}
for poseSpec in posesModel.poses :
ignore = False
pose = poseSpec.pose
warnmsg = '''Frame '{0}' not found on the given frames-model '{1}', ignoring'''
if pose.target.name not in framesModel.framesByName :
logger.warning(warnmsg.format(pose.target.name, rname))
ignore = True
if pose.reference.name not in framesModel.framesByName :
logger.warning(warnmsg.format(pose.reference.name, rname))
ignore = True
if not ignore:
tgtF = framesModel.framesByName[ pose.target.name ]
refF = framesModel.framesByName[ pose.reference.name ]
path = framesModel.path(tgtF, refF)
for i in range(len(path)-1) :
kind = framesModel.kind( path[i], path[i+1])
if kind == frames.FrameRelationKind.acrossJoint :
warnmsg = '''Found non-constant pose in the geometry model
('{0}' with respect to '{1}')'''.format(tgtF.name, refF.name)
logger.warning( warnmsg )
# Rebuild the Pose instance with the frames from the frames
# model, which are attached to links. The pose instance from the
# motions model (posesModel) might only refer to named frames
realpose = Pose(target=tgtF, reference=refF)
realposespec = motions.PoseSpec(pose=realpose, motion=poseSpec.motion)
self.byPose[ realpose ] = realposespec
#print( realpose )
#print( poseSpec.motion.steps, "\n\n")
# We iterate over joints and fetch the predecessor, as the joint_wrt_predecessor
# is a constant pose also for loop joints.
self.byJoint = {}
for joint in connectModel.joints.values() :
predFrame = framesModel.linkFrames [ connectModel.predecessor(joint) ]
jointFrame= framesModel.jointFrames[ joint ]
pose = Pose(target=jointFrame, reference=predFrame)
if pose not in self.byPose :
logger.warning("The geometry model does not seem to have information about the pose of '{0}' wrt '{1}'".format(
jointFrame.name, predFrame.name))
else :
self.byJoint[joint] = self.byPose[pose]
self.ordering = connectModel
self.frames = framesModel
self.poses = motions.PosesSpec(posesModel.name, list(self.byPose.values()))
# The last line creates a new PosesSpec model, to make sure we store the
# model whose poses reference robot attached frames. As said before, the
# PosesSpec model given to the constructor might have poses that refer
# to the un-attached frames.
if jointAxes == None :
jointAxes = {}
for joint in connectModel.joints.values() :
jointAxes[joint.name] = (0.0,0.0,1.0) # default is Z axis
else :
if jointAxes.keys() != connectModel.joints.keys():
logger.warning("The names in the joint-axes dictionary do not " +
"match the names in the connectivity model")
self.axes = jointAxes
@property
def robotName(self):
return self.ordering.name
@property
def connectivityModel(self):
return self.ordering
@property
def framesModel(self):
return self.frames
@property
def posesModel(self):
return self.poses
@property
def jointAxes(self):
return self.axes
|
[
"class",
"Geometry",
":",
"def",
"__init__",
"(",
"self",
",",
"connectModel",
",",
"framesModel",
",",
"posesModel",
",",
"jointAxes",
"=",
"None",
")",
":",
"'''\n Construct the geometry model of a mechanism by composing the arguments.\n\n Parameters:\n\n - `connectModel` the connectivity model of the mechanism, with ordering\n - `framesModel` the set of the Cartesian frames attached to the mechanism\n - `posesModel` the constant, relative poses between the frames\n - `jointAxes` the versors of the joint axes, in joint frame coordinates\n\n The third argument is the actual geometric data; this constructor makes\n sure that the three arguments are consistent and therefore can be\n composed as a whole.\n\n In fact, the poses model stored in this instance is not the given\n `posesModel`. The input poses are always replaced by poses pointing to\n objects of `framesModel`. This is because the frames in the given\n `posesModel` might be simple placeholders. The name of the frame is used\n to establish the correspondence between a placeholder frame and a\n robot-attached frame.\n\n The `jointAxes` argument defaults to `None`. In that case it is assumed\n that the axis of any joint is the Z axis of its frame. Otherwise, the\n argument should be a dictionary indexed by joint name, with values being\n 3-value tuples. Any tuple must represent the 3D joint axis versor, using\n coordinates in the joint frame.\n '''",
"if",
"not",
"isinstance",
"(",
"connectModel",
",",
"ordering",
".",
"Robot",
")",
":",
"raise",
"RuntimeError",
"(",
"\"An ordered robot model is required\"",
")",
"rname",
"=",
"connectModel",
".",
"name",
"if",
"framesModel",
".",
"robot",
".",
"name",
"!=",
"rname",
":",
"raise",
"RuntimeError",
"(",
"\"Robot name mismatch in the connectivity and frames model ('{0}' vs '{1})\"",
".",
"format",
"(",
"rname",
",",
"framesModel",
".",
"robot",
".",
"name",
")",
")",
"self",
".",
"byPose",
"=",
"{",
"}",
"for",
"poseSpec",
"in",
"posesModel",
".",
"poses",
":",
"ignore",
"=",
"False",
"pose",
"=",
"poseSpec",
".",
"pose",
"warnmsg",
"=",
"'''Frame '{0}' not found on the given frames-model '{1}', ignoring'''",
"if",
"pose",
".",
"target",
".",
"name",
"not",
"in",
"framesModel",
".",
"framesByName",
":",
"logger",
".",
"warning",
"(",
"warnmsg",
".",
"format",
"(",
"pose",
".",
"target",
".",
"name",
",",
"rname",
")",
")",
"ignore",
"=",
"True",
"if",
"pose",
".",
"reference",
".",
"name",
"not",
"in",
"framesModel",
".",
"framesByName",
":",
"logger",
".",
"warning",
"(",
"warnmsg",
".",
"format",
"(",
"pose",
".",
"reference",
".",
"name",
",",
"rname",
")",
")",
"ignore",
"=",
"True",
"if",
"not",
"ignore",
":",
"tgtF",
"=",
"framesModel",
".",
"framesByName",
"[",
"pose",
".",
"target",
".",
"name",
"]",
"refF",
"=",
"framesModel",
".",
"framesByName",
"[",
"pose",
".",
"reference",
".",
"name",
"]",
"path",
"=",
"framesModel",
".",
"path",
"(",
"tgtF",
",",
"refF",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"path",
")",
"-",
"1",
")",
":",
"kind",
"=",
"framesModel",
".",
"kind",
"(",
"path",
"[",
"i",
"]",
",",
"path",
"[",
"i",
"+",
"1",
"]",
")",
"if",
"kind",
"==",
"frames",
".",
"FrameRelationKind",
".",
"acrossJoint",
":",
"warnmsg",
"=",
"'''Found non-constant pose in the geometry model\n ('{0}' with respect to '{1}')'''",
".",
"format",
"(",
"tgtF",
".",
"name",
",",
"refF",
".",
"name",
")",
"logger",
".",
"warning",
"(",
"warnmsg",
")",
"realpose",
"=",
"Pose",
"(",
"target",
"=",
"tgtF",
",",
"reference",
"=",
"refF",
")",
"realposespec",
"=",
"motions",
".",
"PoseSpec",
"(",
"pose",
"=",
"realpose",
",",
"motion",
"=",
"poseSpec",
".",
"motion",
")",
"self",
".",
"byPose",
"[",
"realpose",
"]",
"=",
"realposespec",
"self",
".",
"byJoint",
"=",
"{",
"}",
"for",
"joint",
"in",
"connectModel",
".",
"joints",
".",
"values",
"(",
")",
":",
"predFrame",
"=",
"framesModel",
".",
"linkFrames",
"[",
"connectModel",
".",
"predecessor",
"(",
"joint",
")",
"]",
"jointFrame",
"=",
"framesModel",
".",
"jointFrames",
"[",
"joint",
"]",
"pose",
"=",
"Pose",
"(",
"target",
"=",
"jointFrame",
",",
"reference",
"=",
"predFrame",
")",
"if",
"pose",
"not",
"in",
"self",
".",
"byPose",
":",
"logger",
".",
"warning",
"(",
"\"The geometry model does not seem to have information about the pose of '{0}' wrt '{1}'\"",
".",
"format",
"(",
"jointFrame",
".",
"name",
",",
"predFrame",
".",
"name",
")",
")",
"else",
":",
"self",
".",
"byJoint",
"[",
"joint",
"]",
"=",
"self",
".",
"byPose",
"[",
"pose",
"]",
"self",
".",
"ordering",
"=",
"connectModel",
"self",
".",
"frames",
"=",
"framesModel",
"self",
".",
"poses",
"=",
"motions",
".",
"PosesSpec",
"(",
"posesModel",
".",
"name",
",",
"list",
"(",
"self",
".",
"byPose",
".",
"values",
"(",
")",
")",
")",
"if",
"jointAxes",
"==",
"None",
":",
"jointAxes",
"=",
"{",
"}",
"for",
"joint",
"in",
"connectModel",
".",
"joints",
".",
"values",
"(",
")",
":",
"jointAxes",
"[",
"joint",
".",
"name",
"]",
"=",
"(",
"0.0",
",",
"0.0",
",",
"1.0",
")",
"else",
":",
"if",
"jointAxes",
".",
"keys",
"(",
")",
"!=",
"connectModel",
".",
"joints",
".",
"keys",
"(",
")",
":",
"logger",
".",
"warning",
"(",
"\"The names in the joint-axes dictionary do not \"",
"+",
"\"match the names in the connectivity model\"",
")",
"self",
".",
"axes",
"=",
"jointAxes",
"@",
"property",
"def",
"robotName",
"(",
"self",
")",
":",
"return",
"self",
".",
"ordering",
".",
"name",
"@",
"property",
"def",
"connectivityModel",
"(",
"self",
")",
":",
"return",
"self",
".",
"ordering",
"@",
"property",
"def",
"framesModel",
"(",
"self",
")",
":",
"return",
"self",
".",
"frames",
"@",
"property",
"def",
"posesModel",
"(",
"self",
")",
":",
"return",
"self",
".",
"poses",
"@",
"property",
"def",
"jointAxes",
"(",
"self",
")",
":",
"return",
"self",
".",
"axes"
] |
A model of the geometry of a multi-rigid-body mechanism.
|
[
"A",
"model",
"of",
"the",
"geometry",
"of",
"a",
"multi",
"-",
"rigid",
"-",
"body",
"mechanism",
"."
] |
[
"'''\n A model of the geometry of a multi-rigid-body mechanism.\n\n The geometry model consists of a set of constant relative poses between\n reference frames attached to the mechanism. The `reference` of any pose must\n always be a link frame; the `target` is a joint frame or an arbitrary user\n frame.\n\n This class relies on `kgprim.motions.PosesSpec`, and purely performs various\n consistency checks between the given models.\n\n A succesfully constructed instance always includes the connectivity model\n with ordering, the frames model, and the poses which are the actual\n geometric data.\n '''",
"'''\n Construct the geometry model of a mechanism by composing the arguments.\n\n Parameters:\n\n - `connectModel` the connectivity model of the mechanism, with ordering\n - `framesModel` the set of the Cartesian frames attached to the mechanism\n - `posesModel` the constant, relative poses between the frames\n - `jointAxes` the versors of the joint axes, in joint frame coordinates\n\n The third argument is the actual geometric data; this constructor makes\n sure that the three arguments are consistent and therefore can be\n composed as a whole.\n\n In fact, the poses model stored in this instance is not the given\n `posesModel`. The input poses are always replaced by poses pointing to\n objects of `framesModel`. This is because the frames in the given\n `posesModel` might be simple placeholders. The name of the frame is used\n to establish the correspondence between a placeholder frame and a\n robot-attached frame.\n\n The `jointAxes` argument defaults to `None`. In that case it is assumed\n that the axis of any joint is the Z axis of its frame. Otherwise, the\n argument should be a dictionary indexed by joint name, with values being\n 3-value tuples. Any tuple must represent the 3D joint axis versor, using\n coordinates in the joint frame.\n '''",
"# Rebuild the Pose instance with the frames from the frames",
"# model, which are attached to links. The pose instance from the",
"# motions model (posesModel) might only refer to named frames",
"#print( realpose )",
"#print( poseSpec.motion.steps, \"\\n\\n\")",
"# We iterate over joints and fetch the predecessor, as the joint_wrt_predecessor",
"# is a constant pose also for loop joints.",
"# The last line creates a new PosesSpec model, to make sure we store the",
"# model whose poses reference robot attached frames. As said before, the",
"# PosesSpec model given to the constructor might have poses that refer",
"# to the un-attached frames.",
"# default is Z axis"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 18
| 1,294
| 128
|
c881b04565306e38903a3d39d256fa7c93ecf00b
|
Xpitfire/cryptoknight
|
src/CryptoKnight.Client.UI/ViewModel/MainViewModel.cs
|
[
"MIT"
] |
C#
|
MainViewModel
|
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
|
This class contains properties that the main View can data bind to.
Use the mvvminpc
You can also use Blend to data bind with the tool's support.
|
[
"This",
"class",
"contains",
"properties",
"that",
"the",
"main",
"View",
"can",
"data",
"bind",
"to",
".",
"Use",
"the",
"mvvminpc",
"You",
"can",
"also",
"use",
"Blend",
"to",
"data",
"bind",
"with",
"the",
"tool",
"'",
"s",
"support",
"."
] |
public class MainViewModel : ViewModelBase
{
private const string DefaultKey = "";
private const string DefaultPassword = "";
private static readonly User DefaultUser = new User
{
Email = "",
PasswordHash = DefaultPassword.ComputeMd5Hash()
};
private const string Localhost = "127.0.0.1";
private const int Port = 1991;
private static readonly IPEndPoint DefaultEndpoint = new IPEndPoint(IPAddress.Parse(Localhost), Port);
private readonly Encoding _encoding = Encoding.Unicode;
public UserViewModel User { get; }
public KeyViewModel Key { get; }
public IPEndPointViewModel EndPoint { get; }
private string _connectionStatus;
public string ConnectionStatus
{
get { return _connectionStatus; }
set { Set(ref _connectionStatus, value); }
}
private string _password;
public string Password
{
get { return _password; }
set { Set(ref _password, value); }
}
private string _originalText;
public string OriginalText
{
get { return _originalText; }
set { Set(ref _originalText, value); }
}
private string _convertedText;
public string ConvertedText
{
get { return _convertedText; }
set { Set(ref _convertedText, value); }
}
private bool _connected;
public bool Connected
{
get { return _connected; }
set { Set(ref _connected, value); }
}
public PluginViewModel SelectedPlugin { get; set; }
private ObservableCollection<PluginViewModel> _plugins;
public ObservableCollection<PluginViewModel> Plugins
{
get { return _plugins; }
set { Set(ref _plugins, value); }
}
public RelayCommand ConnectCommand { get; }
public RelayCommand DisconnectCommand { get; }
public RelayCommand EncryptCommand { get; }
public RelayCommand DecryptCommand { get; }
private readonly LicenseClient _licenseClient;
private FileKey _fileKey;
public MainViewModel()
{
User = new UserViewModel(DefaultUser);
Key = new KeyViewModel();
EndPoint = new IPEndPointViewModel(DefaultEndpoint);
Connected = false;
ConnectCommand = new RelayCommand(async () => await Task.Run(() => Connect()));
DisconnectCommand = new RelayCommand(async () => await Task.Run(() => Disconnect()));
EncryptCommand = new RelayCommand(async () => await Task.Run(() => EncryptText()));
DecryptCommand = new RelayCommand(async () => await Task.Run(() => DecryptText()));
_licenseClient = new LicenseClient(EndPoint.EndPoint);
_licenseClient.Connected += LicenseClientOnConnected;
_licenseClient.Disconnected += LicenseClientOnDisconnected;
_licenseClient.LoginResponse += OnLoginResponse;
_licenseClient.PluginResponse += OnPluginResponse;
Plugins = new ObservableCollection<PluginViewModel>();
}
private void Connect()
{
ConnectionStatus = Properties.Resources.Connecting;
_licenseClient.Start();
}
private void Disconnect()
{
Connected = false;
ConnectionStatus = Properties.Resources.Disconnected;
_licenseClient.Stop();
}
private void EncryptText()
{
if (SelectedPlugin?.Plugin == null || OriginalText == null) return;
var plugin = SelectedPlugin.Plugin;
var data = plugin.Encrypt(OriginalText, Password);
if (data == null) return;
ConvertedText = Convert.ToBase64String(data);
}
private void DecryptText()
{
if (SelectedPlugin?.Plugin == null || OriginalText == null) return;
var plugin = SelectedPlugin.Plugin;
try
{
var data = plugin.Decrypt(Convert.FromBase64String(OriginalText), Password);
ConvertedText = data;
}
catch (Exception)
{
}
}
private void LicenseClientOnDisconnected(TcpSocket server)
{
Disconnect();
Plugins = new ObservableCollection<PluginViewModel>();
PluginSandbox.DeleteAppDomain();
}
private void LicenseClientOnConnected(TcpSocket server)
{
Connected = true;
ConnectionStatus = Properties.Resources.Connected;
PluginSandbox.CreateAppDomain();
_licenseClient.Login(User.User, Key.Key);
}
private void OnLoginResponse(LoginResponseMessage message)
{
if (message.Key != null)
{
_fileKey = DataProtection.Decrypt(message.Key, Key.Code).ToType<FileKey>();
}
ConnectionStatus = message.Key != null
? Properties.Resources.LicenseVerified
: Properties.Resources.LicenseDenied;
}
private void OnPluginResponse(PluginResponseMessage message)
{
if (_fileKey == null) return;
if (DateTime.Now > _fileKey.Expire) return;
Application.Current.Dispatcher.Invoke(() => {
Plugins.Add(new PluginViewModel(PluginSandbox.LoadAddIn(message.Plugin, _fileKey.Password)));
});
}
}
|
[
"public",
"class",
"MainViewModel",
":",
"ViewModelBase",
"{",
"private",
"const",
"string",
"DefaultKey",
"=",
"\"",
"\"",
";",
"private",
"const",
"string",
"DefaultPassword",
"=",
"\"",
"\"",
";",
"private",
"static",
"readonly",
"User",
"DefaultUser",
"=",
"new",
"User",
"{",
"Email",
"=",
"\"",
"\"",
",",
"PasswordHash",
"=",
"DefaultPassword",
".",
"ComputeMd5Hash",
"(",
")",
"}",
";",
"private",
"const",
"string",
"Localhost",
"=",
"\"",
"127.0.0.1",
"\"",
";",
"private",
"const",
"int",
"Port",
"=",
"1991",
";",
"private",
"static",
"readonly",
"IPEndPoint",
"DefaultEndpoint",
"=",
"new",
"IPEndPoint",
"(",
"IPAddress",
".",
"Parse",
"(",
"Localhost",
")",
",",
"Port",
")",
";",
"private",
"readonly",
"Encoding",
"_encoding",
"=",
"Encoding",
".",
"Unicode",
";",
"public",
"UserViewModel",
"User",
"{",
"get",
";",
"}",
"public",
"KeyViewModel",
"Key",
"{",
"get",
";",
"}",
"public",
"IPEndPointViewModel",
"EndPoint",
"{",
"get",
";",
"}",
"private",
"string",
"_connectionStatus",
";",
"public",
"string",
"ConnectionStatus",
"{",
"get",
"{",
"return",
"_connectionStatus",
";",
"}",
"set",
"{",
"Set",
"(",
"ref",
"_connectionStatus",
",",
"value",
")",
";",
"}",
"}",
"private",
"string",
"_password",
";",
"public",
"string",
"Password",
"{",
"get",
"{",
"return",
"_password",
";",
"}",
"set",
"{",
"Set",
"(",
"ref",
"_password",
",",
"value",
")",
";",
"}",
"}",
"private",
"string",
"_originalText",
";",
"public",
"string",
"OriginalText",
"{",
"get",
"{",
"return",
"_originalText",
";",
"}",
"set",
"{",
"Set",
"(",
"ref",
"_originalText",
",",
"value",
")",
";",
"}",
"}",
"private",
"string",
"_convertedText",
";",
"public",
"string",
"ConvertedText",
"{",
"get",
"{",
"return",
"_convertedText",
";",
"}",
"set",
"{",
"Set",
"(",
"ref",
"_convertedText",
",",
"value",
")",
";",
"}",
"}",
"private",
"bool",
"_connected",
";",
"public",
"bool",
"Connected",
"{",
"get",
"{",
"return",
"_connected",
";",
"}",
"set",
"{",
"Set",
"(",
"ref",
"_connected",
",",
"value",
")",
";",
"}",
"}",
"public",
"PluginViewModel",
"SelectedPlugin",
"{",
"get",
";",
"set",
";",
"}",
"private",
"ObservableCollection",
"<",
"PluginViewModel",
">",
"_plugins",
";",
"public",
"ObservableCollection",
"<",
"PluginViewModel",
">",
"Plugins",
"{",
"get",
"{",
"return",
"_plugins",
";",
"}",
"set",
"{",
"Set",
"(",
"ref",
"_plugins",
",",
"value",
")",
";",
"}",
"}",
"public",
"RelayCommand",
"ConnectCommand",
"{",
"get",
";",
"}",
"public",
"RelayCommand",
"DisconnectCommand",
"{",
"get",
";",
"}",
"public",
"RelayCommand",
"EncryptCommand",
"{",
"get",
";",
"}",
"public",
"RelayCommand",
"DecryptCommand",
"{",
"get",
";",
"}",
"private",
"readonly",
"LicenseClient",
"_licenseClient",
";",
"private",
"FileKey",
"_fileKey",
";",
"public",
"MainViewModel",
"(",
")",
"{",
"User",
"=",
"new",
"UserViewModel",
"(",
"DefaultUser",
")",
";",
"Key",
"=",
"new",
"KeyViewModel",
"(",
")",
";",
"EndPoint",
"=",
"new",
"IPEndPointViewModel",
"(",
"DefaultEndpoint",
")",
";",
"Connected",
"=",
"false",
";",
"ConnectCommand",
"=",
"new",
"RelayCommand",
"(",
"async",
"(",
")",
"=>",
"await",
"Task",
".",
"Run",
"(",
"(",
")",
"=>",
"Connect",
"(",
")",
")",
")",
";",
"DisconnectCommand",
"=",
"new",
"RelayCommand",
"(",
"async",
"(",
")",
"=>",
"await",
"Task",
".",
"Run",
"(",
"(",
")",
"=>",
"Disconnect",
"(",
")",
")",
")",
";",
"EncryptCommand",
"=",
"new",
"RelayCommand",
"(",
"async",
"(",
")",
"=>",
"await",
"Task",
".",
"Run",
"(",
"(",
")",
"=>",
"EncryptText",
"(",
")",
")",
")",
";",
"DecryptCommand",
"=",
"new",
"RelayCommand",
"(",
"async",
"(",
")",
"=>",
"await",
"Task",
".",
"Run",
"(",
"(",
")",
"=>",
"DecryptText",
"(",
")",
")",
")",
";",
"_licenseClient",
"=",
"new",
"LicenseClient",
"(",
"EndPoint",
".",
"EndPoint",
")",
";",
"_licenseClient",
".",
"Connected",
"+=",
"LicenseClientOnConnected",
";",
"_licenseClient",
".",
"Disconnected",
"+=",
"LicenseClientOnDisconnected",
";",
"_licenseClient",
".",
"LoginResponse",
"+=",
"OnLoginResponse",
";",
"_licenseClient",
".",
"PluginResponse",
"+=",
"OnPluginResponse",
";",
"Plugins",
"=",
"new",
"ObservableCollection",
"<",
"PluginViewModel",
">",
"(",
")",
";",
"}",
"private",
"void",
"Connect",
"(",
")",
"{",
"ConnectionStatus",
"=",
"Properties",
".",
"Resources",
".",
"Connecting",
";",
"_licenseClient",
".",
"Start",
"(",
")",
";",
"}",
"private",
"void",
"Disconnect",
"(",
")",
"{",
"Connected",
"=",
"false",
";",
"ConnectionStatus",
"=",
"Properties",
".",
"Resources",
".",
"Disconnected",
";",
"_licenseClient",
".",
"Stop",
"(",
")",
";",
"}",
"private",
"void",
"EncryptText",
"(",
")",
"{",
"if",
"(",
"SelectedPlugin",
"?",
".",
"Plugin",
"==",
"null",
"||",
"OriginalText",
"==",
"null",
")",
"return",
";",
"var",
"plugin",
"=",
"SelectedPlugin",
".",
"Plugin",
";",
"var",
"data",
"=",
"plugin",
".",
"Encrypt",
"(",
"OriginalText",
",",
"Password",
")",
";",
"if",
"(",
"data",
"==",
"null",
")",
"return",
";",
"ConvertedText",
"=",
"Convert",
".",
"ToBase64String",
"(",
"data",
")",
";",
"}",
"private",
"void",
"DecryptText",
"(",
")",
"{",
"if",
"(",
"SelectedPlugin",
"?",
".",
"Plugin",
"==",
"null",
"||",
"OriginalText",
"==",
"null",
")",
"return",
";",
"var",
"plugin",
"=",
"SelectedPlugin",
".",
"Plugin",
";",
"try",
"{",
"var",
"data",
"=",
"plugin",
".",
"Decrypt",
"(",
"Convert",
".",
"FromBase64String",
"(",
"OriginalText",
")",
",",
"Password",
")",
";",
"ConvertedText",
"=",
"data",
";",
"}",
"catch",
"(",
"Exception",
")",
"{",
"}",
"}",
"private",
"void",
"LicenseClientOnDisconnected",
"(",
"TcpSocket",
"server",
")",
"{",
"Disconnect",
"(",
")",
";",
"Plugins",
"=",
"new",
"ObservableCollection",
"<",
"PluginViewModel",
">",
"(",
")",
";",
"PluginSandbox",
".",
"DeleteAppDomain",
"(",
")",
";",
"}",
"private",
"void",
"LicenseClientOnConnected",
"(",
"TcpSocket",
"server",
")",
"{",
"Connected",
"=",
"true",
";",
"ConnectionStatus",
"=",
"Properties",
".",
"Resources",
".",
"Connected",
";",
"PluginSandbox",
".",
"CreateAppDomain",
"(",
")",
";",
"_licenseClient",
".",
"Login",
"(",
"User",
".",
"User",
",",
"Key",
".",
"Key",
")",
";",
"}",
"private",
"void",
"OnLoginResponse",
"(",
"LoginResponseMessage",
"message",
")",
"{",
"if",
"(",
"message",
".",
"Key",
"!=",
"null",
")",
"{",
"_fileKey",
"=",
"DataProtection",
".",
"Decrypt",
"(",
"message",
".",
"Key",
",",
"Key",
".",
"Code",
")",
".",
"ToType",
"<",
"FileKey",
">",
"(",
")",
";",
"}",
"ConnectionStatus",
"=",
"message",
".",
"Key",
"!=",
"null",
"?",
"Properties",
".",
"Resources",
".",
"LicenseVerified",
":",
"Properties",
".",
"Resources",
".",
"LicenseDenied",
";",
"}",
"private",
"void",
"OnPluginResponse",
"(",
"PluginResponseMessage",
"message",
")",
"{",
"if",
"(",
"_fileKey",
"==",
"null",
")",
"return",
";",
"if",
"(",
"DateTime",
".",
"Now",
">",
"_fileKey",
".",
"Expire",
")",
"return",
";",
"Application",
".",
"Current",
".",
"Dispatcher",
".",
"Invoke",
"(",
"(",
")",
"=>",
"{",
"Plugins",
".",
"Add",
"(",
"new",
"PluginViewModel",
"(",
"PluginSandbox",
".",
"LoadAddIn",
"(",
"message",
".",
"Plugin",
",",
"_fileKey",
".",
"Password",
")",
")",
")",
";",
"}",
")",
";",
"}",
"}"
] |
This class contains properties that the main View can data bind to.
|
[
"This",
"class",
"contains",
"properties",
"that",
"the",
"main",
"View",
"can",
"data",
"bind",
"to",
"."
] |
[
"// TODO: remove default user ",
"// default user is used to not have to type the mail / password",
"// every time ",
"// default endpoint (can also be removed later on)",
"// invalid string size",
"// \"Convert.FromBase64String\" throws exception if",
"// the string does not have a valid base64 length",
"// go defense!"
] |
[
{
"param": "ViewModelBase",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ViewModelBase",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 22
| 1,038
| 97
|
602475f01170ef1e546837245e864a447354e2f7
|
dachshund-wcms/core
|
apps/node_modules/local-resource/lib/localResource.js
|
[
"Apache-2.0"
] |
JavaScript
|
LocalResource
|
/**
* The local resource represents a resource which is held in the local file systen. The physical element of a resource
* is a folder in the file system. The files '.properties.json' and 'auth.json' contain the properties and authorization
* information of the resource. It provides access to the child resources through the held sub-folders. The parent
* resource is the parent folder. The files in this folders can be access and modified as well.
* @class
* @extends Resource
*/
|
The local resource represents a resource which is held in the local file systen. The physical element of a resource
is a folder in the file system. The files '.properties.json' and 'auth.json' contain the properties and authorization
information of the resource. It provides access to the child resources through the held sub-folders. The parent
resource is the parent folder. The files in this folders can be access and modified as well.
@class
@extends Resource
|
[
"The",
"local",
"resource",
"represents",
"a",
"resource",
"which",
"is",
"held",
"in",
"the",
"local",
"file",
"systen",
".",
"The",
"physical",
"element",
"of",
"a",
"resource",
"is",
"a",
"folder",
"in",
"the",
"file",
"system",
".",
"The",
"files",
"'",
".",
"properties",
".",
"json",
"'",
"and",
"'",
"auth",
".",
"json",
"'",
"contain",
"the",
"properties",
"and",
"authorization",
"information",
"of",
"the",
"resource",
".",
"It",
"provides",
"access",
"to",
"the",
"child",
"resources",
"through",
"the",
"held",
"sub",
"-",
"folders",
".",
"The",
"parent",
"resource",
"is",
"the",
"parent",
"folder",
".",
"The",
"files",
"in",
"this",
"folders",
"can",
"be",
"access",
"and",
"modified",
"as",
"well",
".",
"@class",
"@extends",
"Resource"
] |
class LocalResource extends Resource {
/**
* @inheritDoc
*/
async getFiles(includeHiddenFiles) {
if (includeHiddenFiles === undefined)
{
includeHiddenFiles = false;
}
let resourceFiles = this._resourceFiles;
if (resourceFiles === null && this.type === ResourceTypes.RESOURCE)
{
resourceFiles = [];
let path = this.path;
let files = await fs.readdir("." + path);
await asyncUtils.forEachSequential(files, async file => {
let fileStat = await fs.stat("." + path + "/" + file);
if (fileStat.isFile() && (includeHiddenFiles || !file.startsWith(".")))
{
resourceFiles.push(file);
}
});
this._resourceFiles = resourceFiles;
}
return resourceFiles;
}
/**
* @inheritDoc
*/
async fileExists(filename) {
const includeHiddenFiles = true;
return (await this.getFiles(includeHiddenFiles)).indexOf(filename) !== -1;
}
/**
* @inheritDoc
*/
async deleteFile(filename) {
let fileExists = await this.fileExists(filename);
if (fileExists)
{
let filePath = "." + self.path + "/" + filename;
await fs.unlink(filePath);
self._resourceFiles = null;
}
else
{
throw new Error(`File [${filename}] doesn't exist.`);
}
}
/**
* @inheritDoc
*/
async deleteAllFiles(includeHiddenFiles) {
let self = this;
let includeHidden = includeHiddenFiles || false;
let fileList = await this.getFiles(includeHidden);
await asyncUtils.forEachParallel(fileList, file => {
return self.deleteFile(file);
});
}
/**
* @inheritDoc
*/
addFile(sourceReadStream, filename) {
return new Promise((resolve, reject) => {
let destinationPath = "." + this.path + "/" + filename;
let destinationFile = fs.createWriteStream(destinationPath);
destinationFile.on('finish', resolve).on('error', reject);
sourceReadStream.pipe(destinationFile);
});
}
/**
* @inheritDoc
*/
async loadScript(scriptName) {
let fileExists = await this.fileExists(scriptName);
if (!fileExists)
{
throw new Error(`Script [${this.path}/${scriptName}] doesn't exist.`);
}
return require(process.cwd() + this.path + "/" + scriptName);
}
/**
* @inheritDoc
*/
async getChilds(includeHidden) {
let resourceChilds = this._resourceChilds || [];
includeHidden = includeHidden || false;
if (this.type === ResourceTypes.RESOURCE && this._resourceChilds === undefined)
{
resourceChilds = [];
let path = this.path;
let files = await fs.readdir("." + path);
await asyncUtils.forEachParallel(files, async file => {
let fileStat = await fs.stat('.' + path + '/' + file);
if (fileStat.isDirectory() && (includeHidden || !file.startsWith(".")))
{
resourceChilds.push(file);
}
});
this._resourceChilds = resourceChilds;
}
return resourceChilds;
}
/**
* @inheritDoc
*/
async getChildResources(includeHidden) {
let self = this;
let childNames = await this.getChilds(includeHidden);
if (childNames.length === 0)
{
return [];
}
return await asyncUtils.forEachParallel(childNames, childName => {
let childResourcePath = self.path + "/" + childName;
return repositoryManager.resolve(childResourcePath);
});
}
/**
* @inheritDoc
*/
async getParentResource() {
let parentPath = this.path.lastSubstringBefore("/");
if (parentPath.length > 0)
{
return await repositoryManager.resolve(parentPath);
}
return null;
}
/**
* @inheritDoc
*/
async getAbsoluteParentResource(depth) {
assert(!isNaN(depth), "It is expected that the paramater [depth] is a number.");
assert(depth >= 0, "It is expected that the parameter [depth] is greater or equal than zero.");
depth += 1;
if (this.depth < depth)
{
throw new Error("The request depth [" + depth + "] can't be resolved from [" + this.path + "]");
}
else if (this.depth === depth)
{
return this;
}
else
{
let sourcePathFragments = this.path.split("/");
let destinationPathFragments = sourcePathFragments.slice(0, depth);
let destinationPath = destinationPathFragments.join("/");
return await repositoryManager.resolve(destinationPath);
}
}
/**
* @inheritDoc
*/
async getHiddenResourceChilds() {
let resourceChilds = this._resourceChilds;
if (resourceChilds === null && this.type === resourceTypes.RESOURCE)
{
resourceChilds = [];
let path = this.path;
let files = await fs.readdir("." + path);
files.forEach(async function(file) {
let filePath = "." + path + "/" + file;
let fileStat = await fs.stat(filePath);
if (fileStat.isDirectory() && file.startsWith("."))
{
resourceChilds.push(file);
}
});
this._resourceChilds = resourceChilds;
}
return resourceChilds;
}
/**
* @inheritDoc
*/
async loadProperties() {
this.properties = await nodeProperties.load(this.path);
return this.properties;
}
/**
* @inheritDoc
*/
async saveProperties() {
this.properties.id = this.properties.id || this.id;
await nodeProperties.save(this.path, this.properties);
this.properties.id = undefined;
return this;
}
/**
* @inheritDoc
*/
async loadAuthorization() {
this.auth = await nodeAuthorization.load(this.path);
return this;
}
/**
* @inheritDoc
*/
async saveAuthorization() {
await nodeAuthorization.save(this.path, this.auth);
return this;
}
}
|
[
"class",
"LocalResource",
"extends",
"Resource",
"{",
"async",
"getFiles",
"(",
"includeHiddenFiles",
")",
"{",
"if",
"(",
"includeHiddenFiles",
"===",
"undefined",
")",
"{",
"includeHiddenFiles",
"=",
"false",
";",
"}",
"let",
"resourceFiles",
"=",
"this",
".",
"_resourceFiles",
";",
"if",
"(",
"resourceFiles",
"===",
"null",
"&&",
"this",
".",
"type",
"===",
"ResourceTypes",
".",
"RESOURCE",
")",
"{",
"resourceFiles",
"=",
"[",
"]",
";",
"let",
"path",
"=",
"this",
".",
"path",
";",
"let",
"files",
"=",
"await",
"fs",
".",
"readdir",
"(",
"\".\"",
"+",
"path",
")",
";",
"await",
"asyncUtils",
".",
"forEachSequential",
"(",
"files",
",",
"async",
"file",
"=>",
"{",
"let",
"fileStat",
"=",
"await",
"fs",
".",
"stat",
"(",
"\".\"",
"+",
"path",
"+",
"\"/\"",
"+",
"file",
")",
";",
"if",
"(",
"fileStat",
".",
"isFile",
"(",
")",
"&&",
"(",
"includeHiddenFiles",
"||",
"!",
"file",
".",
"startsWith",
"(",
"\".\"",
")",
")",
")",
"{",
"resourceFiles",
".",
"push",
"(",
"file",
")",
";",
"}",
"}",
")",
";",
"this",
".",
"_resourceFiles",
"=",
"resourceFiles",
";",
"}",
"return",
"resourceFiles",
";",
"}",
"async",
"fileExists",
"(",
"filename",
")",
"{",
"const",
"includeHiddenFiles",
"=",
"true",
";",
"return",
"(",
"await",
"this",
".",
"getFiles",
"(",
"includeHiddenFiles",
")",
")",
".",
"indexOf",
"(",
"filename",
")",
"!==",
"-",
"1",
";",
"}",
"async",
"deleteFile",
"(",
"filename",
")",
"{",
"let",
"fileExists",
"=",
"await",
"this",
".",
"fileExists",
"(",
"filename",
")",
";",
"if",
"(",
"fileExists",
")",
"{",
"let",
"filePath",
"=",
"\".\"",
"+",
"self",
".",
"path",
"+",
"\"/\"",
"+",
"filename",
";",
"await",
"fs",
".",
"unlink",
"(",
"filePath",
")",
";",
"self",
".",
"_resourceFiles",
"=",
"null",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"filename",
"}",
"`",
")",
";",
"}",
"}",
"async",
"deleteAllFiles",
"(",
"includeHiddenFiles",
")",
"{",
"let",
"self",
"=",
"this",
";",
"let",
"includeHidden",
"=",
"includeHiddenFiles",
"||",
"false",
";",
"let",
"fileList",
"=",
"await",
"this",
".",
"getFiles",
"(",
"includeHidden",
")",
";",
"await",
"asyncUtils",
".",
"forEachParallel",
"(",
"fileList",
",",
"file",
"=>",
"{",
"return",
"self",
".",
"deleteFile",
"(",
"file",
")",
";",
"}",
")",
";",
"}",
"addFile",
"(",
"sourceReadStream",
",",
"filename",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"let",
"destinationPath",
"=",
"\".\"",
"+",
"this",
".",
"path",
"+",
"\"/\"",
"+",
"filename",
";",
"let",
"destinationFile",
"=",
"fs",
".",
"createWriteStream",
"(",
"destinationPath",
")",
";",
"destinationFile",
".",
"on",
"(",
"'finish'",
",",
"resolve",
")",
".",
"on",
"(",
"'error'",
",",
"reject",
")",
";",
"sourceReadStream",
".",
"pipe",
"(",
"destinationFile",
")",
";",
"}",
")",
";",
"}",
"async",
"loadScript",
"(",
"scriptName",
")",
"{",
"let",
"fileExists",
"=",
"await",
"this",
".",
"fileExists",
"(",
"scriptName",
")",
";",
"if",
"(",
"!",
"fileExists",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"this",
".",
"path",
"}",
"${",
"scriptName",
"}",
"`",
")",
";",
"}",
"return",
"require",
"(",
"process",
".",
"cwd",
"(",
")",
"+",
"this",
".",
"path",
"+",
"\"/\"",
"+",
"scriptName",
")",
";",
"}",
"async",
"getChilds",
"(",
"includeHidden",
")",
"{",
"let",
"resourceChilds",
"=",
"this",
".",
"_resourceChilds",
"||",
"[",
"]",
";",
"includeHidden",
"=",
"includeHidden",
"||",
"false",
";",
"if",
"(",
"this",
".",
"type",
"===",
"ResourceTypes",
".",
"RESOURCE",
"&&",
"this",
".",
"_resourceChilds",
"===",
"undefined",
")",
"{",
"resourceChilds",
"=",
"[",
"]",
";",
"let",
"path",
"=",
"this",
".",
"path",
";",
"let",
"files",
"=",
"await",
"fs",
".",
"readdir",
"(",
"\".\"",
"+",
"path",
")",
";",
"await",
"asyncUtils",
".",
"forEachParallel",
"(",
"files",
",",
"async",
"file",
"=>",
"{",
"let",
"fileStat",
"=",
"await",
"fs",
".",
"stat",
"(",
"'.'",
"+",
"path",
"+",
"'/'",
"+",
"file",
")",
";",
"if",
"(",
"fileStat",
".",
"isDirectory",
"(",
")",
"&&",
"(",
"includeHidden",
"||",
"!",
"file",
".",
"startsWith",
"(",
"\".\"",
")",
")",
")",
"{",
"resourceChilds",
".",
"push",
"(",
"file",
")",
";",
"}",
"}",
")",
";",
"this",
".",
"_resourceChilds",
"=",
"resourceChilds",
";",
"}",
"return",
"resourceChilds",
";",
"}",
"async",
"getChildResources",
"(",
"includeHidden",
")",
"{",
"let",
"self",
"=",
"this",
";",
"let",
"childNames",
"=",
"await",
"this",
".",
"getChilds",
"(",
"includeHidden",
")",
";",
"if",
"(",
"childNames",
".",
"length",
"===",
"0",
")",
"{",
"return",
"[",
"]",
";",
"}",
"return",
"await",
"asyncUtils",
".",
"forEachParallel",
"(",
"childNames",
",",
"childName",
"=>",
"{",
"let",
"childResourcePath",
"=",
"self",
".",
"path",
"+",
"\"/\"",
"+",
"childName",
";",
"return",
"repositoryManager",
".",
"resolve",
"(",
"childResourcePath",
")",
";",
"}",
")",
";",
"}",
"async",
"getParentResource",
"(",
")",
"{",
"let",
"parentPath",
"=",
"this",
".",
"path",
".",
"lastSubstringBefore",
"(",
"\"/\"",
")",
";",
"if",
"(",
"parentPath",
".",
"length",
">",
"0",
")",
"{",
"return",
"await",
"repositoryManager",
".",
"resolve",
"(",
"parentPath",
")",
";",
"}",
"return",
"null",
";",
"}",
"async",
"getAbsoluteParentResource",
"(",
"depth",
")",
"{",
"assert",
"(",
"!",
"isNaN",
"(",
"depth",
")",
",",
"\"It is expected that the paramater [depth] is a number.\"",
")",
";",
"assert",
"(",
"depth",
">=",
"0",
",",
"\"It is expected that the parameter [depth] is greater or equal than zero.\"",
")",
";",
"depth",
"+=",
"1",
";",
"if",
"(",
"this",
".",
"depth",
"<",
"depth",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"The request depth [\"",
"+",
"depth",
"+",
"\"] can't be resolved from [\"",
"+",
"this",
".",
"path",
"+",
"\"]\"",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"depth",
"===",
"depth",
")",
"{",
"return",
"this",
";",
"}",
"else",
"{",
"let",
"sourcePathFragments",
"=",
"this",
".",
"path",
".",
"split",
"(",
"\"/\"",
")",
";",
"let",
"destinationPathFragments",
"=",
"sourcePathFragments",
".",
"slice",
"(",
"0",
",",
"depth",
")",
";",
"let",
"destinationPath",
"=",
"destinationPathFragments",
".",
"join",
"(",
"\"/\"",
")",
";",
"return",
"await",
"repositoryManager",
".",
"resolve",
"(",
"destinationPath",
")",
";",
"}",
"}",
"async",
"getHiddenResourceChilds",
"(",
")",
"{",
"let",
"resourceChilds",
"=",
"this",
".",
"_resourceChilds",
";",
"if",
"(",
"resourceChilds",
"===",
"null",
"&&",
"this",
".",
"type",
"===",
"resourceTypes",
".",
"RESOURCE",
")",
"{",
"resourceChilds",
"=",
"[",
"]",
";",
"let",
"path",
"=",
"this",
".",
"path",
";",
"let",
"files",
"=",
"await",
"fs",
".",
"readdir",
"(",
"\".\"",
"+",
"path",
")",
";",
"files",
".",
"forEach",
"(",
"async",
"function",
"(",
"file",
")",
"{",
"let",
"filePath",
"=",
"\".\"",
"+",
"path",
"+",
"\"/\"",
"+",
"file",
";",
"let",
"fileStat",
"=",
"await",
"fs",
".",
"stat",
"(",
"filePath",
")",
";",
"if",
"(",
"fileStat",
".",
"isDirectory",
"(",
")",
"&&",
"file",
".",
"startsWith",
"(",
"\".\"",
")",
")",
"{",
"resourceChilds",
".",
"push",
"(",
"file",
")",
";",
"}",
"}",
")",
";",
"this",
".",
"_resourceChilds",
"=",
"resourceChilds",
";",
"}",
"return",
"resourceChilds",
";",
"}",
"async",
"loadProperties",
"(",
")",
"{",
"this",
".",
"properties",
"=",
"await",
"nodeProperties",
".",
"load",
"(",
"this",
".",
"path",
")",
";",
"return",
"this",
".",
"properties",
";",
"}",
"async",
"saveProperties",
"(",
")",
"{",
"this",
".",
"properties",
".",
"id",
"=",
"this",
".",
"properties",
".",
"id",
"||",
"this",
".",
"id",
";",
"await",
"nodeProperties",
".",
"save",
"(",
"this",
".",
"path",
",",
"this",
".",
"properties",
")",
";",
"this",
".",
"properties",
".",
"id",
"=",
"undefined",
";",
"return",
"this",
";",
"}",
"async",
"loadAuthorization",
"(",
")",
"{",
"this",
".",
"auth",
"=",
"await",
"nodeAuthorization",
".",
"load",
"(",
"this",
".",
"path",
")",
";",
"return",
"this",
";",
"}",
"async",
"saveAuthorization",
"(",
")",
"{",
"await",
"nodeAuthorization",
".",
"save",
"(",
"this",
".",
"path",
",",
"this",
".",
"auth",
")",
";",
"return",
"this",
";",
"}",
"}"
] |
The local resource represents a resource which is held in the local file systen.
|
[
"The",
"local",
"resource",
"represents",
"a",
"resource",
"which",
"is",
"held",
"in",
"the",
"local",
"file",
"systen",
"."
] |
[
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */",
"/**\n\t * @inheritDoc\n\t */"
] |
[
{
"param": "Resource",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Resource",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 22
| 1,339
| 104
|
6cd9149df56effded82f9c6f381cb28f9967df38
|
drbrain/uuid
|
lib/uuid.rb
|
[
"MIT"
] |
Ruby
|
Server
|
# With UUID server you don't have to worry about multiple processes
# synchronizing over the state file, calling next_sequence when forking a
# process and other things you're probably not worried about (because
# statistically they're very unlikely to break your code).
#
# But if you are worried about and thought to yourself, "what would a simple
# UUID server look like?", here's the answer. The protocol is dead simple:
# client sends a byte, server responds with a UUID. Can use TCP or domain
# sockets.
|
With UUID server you don't have to worry about multiple processes
synchronizing over the state file, calling next_sequence when forking a
process and other things you're probably not worried about (because
statistically they're very unlikely to break your code).
But if you are worried about and thought to yourself, "what would a simple
UUID server look like?", here's the answer. The protocol is dead simple:
client sends a byte, server responds with a UUID. Can use TCP or domain
sockets.
|
[
"With",
"UUID",
"server",
"you",
"don",
"'",
"t",
"have",
"to",
"worry",
"about",
"multiple",
"processes",
"synchronizing",
"over",
"the",
"state",
"file",
"calling",
"next_sequence",
"when",
"forking",
"a",
"process",
"and",
"other",
"things",
"you",
"'",
"re",
"probably",
"not",
"worried",
"about",
"(",
"because",
"statistically",
"they",
"'",
"re",
"very",
"unlikely",
"to",
"break",
"your",
"code",
")",
".",
"But",
"if",
"you",
"are",
"worried",
"about",
"and",
"thought",
"to",
"yourself",
"\"",
"what",
"would",
"a",
"simple",
"UUID",
"server",
"look",
"like?",
"\"",
"here",
"'",
"s",
"the",
"answer",
".",
"The",
"protocol",
"is",
"dead",
"simple",
":",
"client",
"sends",
"a",
"byte",
"server",
"responds",
"with",
"a",
"UUID",
".",
"Can",
"use",
"TCP",
"or",
"domain",
"sockets",
"."
] |
class Server
# Create new server. Nothing interesting happens until you call listen.
def initialize()
@generator = UUID.new
end
# Start the server listening on the specific address. Blocks and never
# returns. Address can be:
# - A Socket object
# - UNIX domain socket name (e.g. /var/run/uuid.sock, must start with /)
# - IP address, colon, port (e.g. localhost:1337)
def listen(address)
sock = bind(address)
while client = sock.accept
Thread.start(client) do |socket|
while socket.read 1
socket.write @generator.generate
end
end
end
end
# Returns UNIXServer or TCPServer from address. Returns argument if not a
# string, so can pass through (see #listen).
def bind(address)
return address unless String === address
if address[0] == ?/
if File.exist?(address)
raise ArgumentError, "#{address} is not a socket" unless File.socket?(address)
File.unlink(address)
end
sock = UNIXServer.new(address)
File.chmod 0666, address
elsif address =~ /^(\d+\.\d+\.\d+\.\d+):(\d+)$/
sock = TCPServer.new($1, $2.to_i)
else
raise ArgumentError, "Don't know how to bind #{address}"
end
sock.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1) if defined?(TCP_NODELAY)
sock
end
end
|
[
"class",
"Server",
"def",
"initialize",
"(",
")",
"@generator",
"=",
"UUID",
".",
"new",
"end",
"def",
"listen",
"(",
"address",
")",
"sock",
"=",
"bind",
"(",
"address",
")",
"while",
"client",
"=",
"sock",
".",
"accept",
"Thread",
".",
"start",
"(",
"client",
")",
"do",
"|",
"socket",
"|",
"while",
"socket",
".",
"read",
"1",
"socket",
".",
"write",
"@generator",
".",
"generate",
"end",
"end",
"end",
"end",
"def",
"bind",
"(",
"address",
")",
"return",
"address",
"unless",
"String",
"===",
"address",
"if",
"address",
"[",
"0",
"]",
"==",
"?/",
"if",
"File",
".",
"exist?",
"(",
"address",
")",
"raise",
"ArgumentError",
",",
"\"#{address} is not a socket\"",
"unless",
"File",
".",
"socket?",
"(",
"address",
")",
"File",
".",
"unlink",
"(",
"address",
")",
"end",
"sock",
"=",
"UNIXServer",
".",
"new",
"(",
"address",
")",
"File",
".",
"chmod",
"0666",
",",
"address",
"elsif",
"address",
"=~",
"/",
"^(",
"\\d",
"+",
"\\.",
"\\d",
"+",
"\\.",
"\\d",
"+",
"\\.",
"\\d",
"+):(",
"\\d",
"+)$",
"/",
"sock",
"=",
"TCPServer",
".",
"new",
"(",
"$1",
",",
"$2",
".",
"to_i",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Don't know how to bind #{address}\"",
"end",
"sock",
".",
"setsockopt",
"(",
"IPPROTO_TCP",
",",
"TCP_NODELAY",
",",
"1",
")",
"if",
"defined?",
"(",
"TCP_NODELAY",
")",
"sock",
"end",
"end"
] |
With UUID server you don't have to worry about multiple processes
synchronizing over the state file, calling next_sequence when forking a
process and other things you're probably not worried about (because
statistically they're very unlikely to break your code).
|
[
"With",
"UUID",
"server",
"you",
"don",
"'",
"t",
"have",
"to",
"worry",
"about",
"multiple",
"processes",
"synchronizing",
"over",
"the",
"state",
"file",
"calling",
"next_sequence",
"when",
"forking",
"a",
"process",
"and",
"other",
"things",
"you",
"'",
"re",
"probably",
"not",
"worried",
"about",
"(",
"because",
"statistically",
"they",
"'",
"re",
"very",
"unlikely",
"to",
"break",
"your",
"code",
")",
"."
] |
[
"# Create new server. Nothing interesting happens until you call listen.",
"# Start the server listening on the specific address. Blocks and never",
"# returns. Address can be:",
"# - A Socket object",
"# - UNIX domain socket name (e.g. /var/run/uuid.sock, must start with /)",
"# - IP address, colon, port (e.g. localhost:1337)",
"# Returns UNIXServer or TCPServer from address. Returns argument if not a",
"# string, so can pass through (see #listen)."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 355
| 114
|
d0df954499c95aeb304f1eb2a0fa0c9338ae50f6
|
DeonHeyns/ServiceStack
|
src/ServiceStack/ApiHandlers.cs
|
[
"MIT",
"Apache-2.0",
"MS-PL"
] |
C#
|
ApiHandlers
|
/// <summary>
/// Add a new API Handler at a custom route.
///
/// RawHttpHandlers.Add(ApiHandlers.Json("/api/{Request}")) => delegates /api/* requests to JSON Request Handler, e.g:
/// - /api/Hello => {"result":"Hello"}
/// - /api/Hello?name=World => {"result":"Hello, World"}
/// </summary>
|
Add a new API Handler at a custom route.
|
[
"Add",
"a",
"new",
"API",
"Handler",
"at",
"a",
"custom",
"route",
"."
] |
public static class ApiHandlers
{
public static Func<IHttpRequest, HttpAsyncTaskHandler> Json(string apiPath) =>
Generic(apiPath, MimeTypes.Json, RequestAttributes.Reply | RequestAttributes.Json, Feature.Json);
public static Func<IHttpRequest, HttpAsyncTaskHandler> Jsv(string apiPath) =>
Generic(apiPath, MimeTypes.Jsv, RequestAttributes.Reply | RequestAttributes.Jsv, Feature.Jsv);
public static Func<IHttpRequest, HttpAsyncTaskHandler> Csv(string apiPath) =>
Generic(apiPath, MimeTypes.Csv, RequestAttributes.Reply | RequestAttributes.Csv, Feature.Csv);
public static Func<IHttpRequest, HttpAsyncTaskHandler> Xml(string apiPath) =>
Generic(apiPath, MimeTypes.Xml, RequestAttributes.Reply | RequestAttributes.Xml, Feature.Xml);
public static Func<IHttpRequest, HttpAsyncTaskHandler> Generic(string apiPath,
string contentType, RequestAttributes requestAttributes, Feature feature)
{
if (string.IsNullOrEmpty(apiPath))
throw new ArgumentNullException(nameof(apiPath));
if (apiPath[0] != '/')
throw new ArgumentException(apiPath + " must start with '/'");
if (!apiPath.EndsWith("/{Request}"))
throw new ArgumentException(apiPath + " must end with '/{Request}'");
var useApiPath = apiPath.LastLeftPart('/');
return req => {
if (req.HttpMethod == HttpMethods.Options) return null;
var pathInfo = req.PathInfo;
if (pathInfo.StartsWith(useApiPath) && pathInfo.IndexOf('/',1) >= 0)
{
var apiName = pathInfo.LastRightPart('/');
return new GenericHandler(contentType, requestAttributes, feature) {
RequestName = apiName
};
}
return null;
};
}
}
|
[
"public",
"static",
"class",
"ApiHandlers",
"{",
"public",
"static",
"Func",
"<",
"IHttpRequest",
",",
"HttpAsyncTaskHandler",
">",
"Json",
"(",
"string",
"apiPath",
")",
"=>",
"Generic",
"(",
"apiPath",
",",
"MimeTypes",
".",
"Json",
",",
"RequestAttributes",
".",
"Reply",
"|",
"RequestAttributes",
".",
"Json",
",",
"Feature",
".",
"Json",
")",
";",
"public",
"static",
"Func",
"<",
"IHttpRequest",
",",
"HttpAsyncTaskHandler",
">",
"Jsv",
"(",
"string",
"apiPath",
")",
"=>",
"Generic",
"(",
"apiPath",
",",
"MimeTypes",
".",
"Jsv",
",",
"RequestAttributes",
".",
"Reply",
"|",
"RequestAttributes",
".",
"Jsv",
",",
"Feature",
".",
"Jsv",
")",
";",
"public",
"static",
"Func",
"<",
"IHttpRequest",
",",
"HttpAsyncTaskHandler",
">",
"Csv",
"(",
"string",
"apiPath",
")",
"=>",
"Generic",
"(",
"apiPath",
",",
"MimeTypes",
".",
"Csv",
",",
"RequestAttributes",
".",
"Reply",
"|",
"RequestAttributes",
".",
"Csv",
",",
"Feature",
".",
"Csv",
")",
";",
"public",
"static",
"Func",
"<",
"IHttpRequest",
",",
"HttpAsyncTaskHandler",
">",
"Xml",
"(",
"string",
"apiPath",
")",
"=>",
"Generic",
"(",
"apiPath",
",",
"MimeTypes",
".",
"Xml",
",",
"RequestAttributes",
".",
"Reply",
"|",
"RequestAttributes",
".",
"Xml",
",",
"Feature",
".",
"Xml",
")",
";",
"public",
"static",
"Func",
"<",
"IHttpRequest",
",",
"HttpAsyncTaskHandler",
">",
"Generic",
"(",
"string",
"apiPath",
",",
"string",
"contentType",
",",
"RequestAttributes",
"requestAttributes",
",",
"Feature",
"feature",
")",
"{",
"if",
"(",
"string",
".",
"IsNullOrEmpty",
"(",
"apiPath",
")",
")",
"throw",
"new",
"ArgumentNullException",
"(",
"nameof",
"(",
"apiPath",
")",
")",
";",
"if",
"(",
"apiPath",
"[",
"0",
"]",
"!=",
"'",
"/",
"'",
")",
"throw",
"new",
"ArgumentException",
"(",
"apiPath",
"+",
"\"",
" must start with '/'",
"\"",
")",
";",
"if",
"(",
"!",
"apiPath",
".",
"EndsWith",
"(",
"\"",
"/{Request}",
"\"",
")",
")",
"throw",
"new",
"ArgumentException",
"(",
"apiPath",
"+",
"\"",
" must end with '/{Request}'",
"\"",
")",
";",
"var",
"useApiPath",
"=",
"apiPath",
".",
"LastLeftPart",
"(",
"'",
"/",
"'",
")",
";",
"return",
"req",
"=>",
"{",
"if",
"(",
"req",
".",
"HttpMethod",
"==",
"HttpMethods",
".",
"Options",
")",
"return",
"null",
";",
"var",
"pathInfo",
"=",
"req",
".",
"PathInfo",
";",
"if",
"(",
"pathInfo",
".",
"StartsWith",
"(",
"useApiPath",
")",
"&&",
"pathInfo",
".",
"IndexOf",
"(",
"'",
"/",
"'",
",",
"1",
")",
">=",
"0",
")",
"{",
"var",
"apiName",
"=",
"pathInfo",
".",
"LastRightPart",
"(",
"'",
"/",
"'",
")",
";",
"return",
"new",
"GenericHandler",
"(",
"contentType",
",",
"requestAttributes",
",",
"feature",
")",
"{",
"RequestName",
"=",
"apiName",
"}",
";",
"}",
"return",
"null",
";",
"}",
";",
"}",
"}"
] |
Add a new API Handler at a custom route.
|
[
"Add",
"a",
"new",
"API",
"Handler",
"at",
"a",
"custom",
"route",
"."
] |
[
"// Don't handle OPTIONS CORS requests"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 379
| 82
|
8daa37365b7e8c3583b0b2edde69645f33e36ace
|
maxburke/arrow
|
ruby/red-arrow/lib/arrow/table-saver.rb
|
[
"Apache-2.0"
] |
Ruby
|
Arrow
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
|
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
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.
|
[
"Licensed",
"to",
"the",
"Apache",
"Software",
"Foundation",
"(",
"ASF",
")",
"under",
"one",
"or",
"more",
"contributor",
"license",
"agreements",
".",
"See",
"the",
"NOTICE",
"file",
"distributed",
"with",
"this",
"work",
"for",
"additional",
"information",
"regarding",
"copyright",
"ownership",
".",
"The",
"ASF",
"licenses",
"this",
"file",
"to",
"you",
"under",
"the",
"Apache",
"License",
"Version",
"2",
".",
"0",
"(",
"the",
"\"",
"License",
"\"",
")",
";",
"you",
"may",
"not",
"use",
"this",
"file",
"except",
"in",
"compliance",
"with",
"the",
"License",
".",
"You",
"may",
"obtain",
"a",
"copy",
"of",
"the",
"License",
"at",
"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",
"."
] |
module Arrow
class TableSaver
class << self
def save(table, output, options={})
new(table, output, options).save
end
end
def initialize(table, output, options={})
@table = table
output = output.to_path if output.respond_to?(:to_path)
@output = output
@options = options
fill_options
end
def save
format = @options[:format]
custom_save_method = "save_as_#{format}"
unless respond_to?(custom_save_method, true)
available_formats = []
(methods(true) | private_methods(true)).each do |name|
match_data = /\Asave_as_/.match(name.to_s)
if match_data
available_formats << match_data.post_match
end
end
deprecated_formats = ["batch", "stream"]
available_formats -= deprecated_formats
message = "Arrow::Table save format must be one of ["
message << available_formats.join(", ")
message << "]: #{format.inspect}"
raise ArgumentError, message
end
if method(custom_save_method).arity.zero?
__send__(custom_save_method)
else
# For backward compatibility.
__send__(custom_save_method, @output)
end
end
private
def fill_options
if @options[:format] and @options.key?(:compression)
return
end
if @output.is_a?(Buffer)
info = {}
else
extension = PathExtension.new(@output)
info = extension.extract
end
format = info[:format]
@options = @options.dup
if format and respond_to?("save_as_#{format}", true)
@options[:format] ||= format.to_sym
else
@options[:format] ||= :arrow
end
unless @options.key?(:compression)
@options[:compression] = info[:compression]
end
end
def open_raw_output_stream(&block)
if @output.is_a?(Buffer)
BufferOutputStream.open(@output, &block)
else
FileOutputStream.open(@output, false, &block)
end
end
def open_output_stream(&block)
compression = @options[:compression]
if compression
codec = Codec.new(compression)
open_raw_output_stream do |raw_output|
CompressedOutputStream.open(codec, raw_output) do |output|
yield(output)
end
end
else
open_raw_output_stream(&block)
end
end
def save_raw(writer_class)
open_output_stream do |output|
writer_class.open(output, @table.schema) do |writer|
writer.write_table(@table)
end
end
end
def save_as_arrow
save_as_arrow_file
end
# @since 1.0.0
def save_as_arrow_file
save_raw(RecordBatchFileWriter)
end
# @deprecated Use `format: :arrow_batch` instead.
def save_as_batch
save_as_arrow_file
end
# @since 1.0.0
def save_as_arrow_streaming
save_raw(RecordBatchStreamWriter)
end
# @deprecated Use `format: :arrow_streaming` instead.
def save_as_stream
save_as_arrow_streaming
end
def save_as_csv
open_output_stream do |output|
csv = CSV.new(output)
names = @table.schema.fields.collect(&:name)
csv << names
@table.each_record(reuse_record: true) do |record|
csv << names.collect do |name|
record[name]
end
end
end
end
def save_as_feather
open_output_stream do |output|
FeatherFileWriter.open(output) do |writer|
writer.write(@table)
end
end
end
end
end
|
[
"module",
"Arrow",
"class",
"TableSaver",
"class",
"<<",
"self",
"def",
"save",
"(",
"table",
",",
"output",
",",
"options",
"=",
"{",
"}",
")",
"new",
"(",
"table",
",",
"output",
",",
"options",
")",
".",
"save",
"end",
"end",
"def",
"initialize",
"(",
"table",
",",
"output",
",",
"options",
"=",
"{",
"}",
")",
"@table",
"=",
"table",
"output",
"=",
"output",
".",
"to_path",
"if",
"output",
".",
"respond_to?",
"(",
":to_path",
")",
"@output",
"=",
"output",
"@options",
"=",
"options",
"fill_options",
"end",
"def",
"save",
"format",
"=",
"@options",
"[",
":format",
"]",
"custom_save_method",
"=",
"\"save_as_#{format}\"",
"unless",
"respond_to?",
"(",
"custom_save_method",
",",
"true",
")",
"available_formats",
"=",
"[",
"]",
"(",
"methods",
"(",
"true",
")",
"|",
"private_methods",
"(",
"true",
")",
")",
".",
"each",
"do",
"|",
"name",
"|",
"match_data",
"=",
"/",
"\\A",
"save_as_",
"/",
".",
"match",
"(",
"name",
".",
"to_s",
")",
"if",
"match_data",
"available_formats",
"<<",
"match_data",
".",
"post_match",
"end",
"end",
"deprecated_formats",
"=",
"[",
"\"batch\"",
",",
"\"stream\"",
"]",
"available_formats",
"-=",
"deprecated_formats",
"message",
"=",
"\"Arrow::Table save format must be one of [\"",
"message",
"<<",
"available_formats",
".",
"join",
"(",
"\", \"",
")",
"message",
"<<",
"\"]: #{format.inspect}\"",
"raise",
"ArgumentError",
",",
"message",
"end",
"if",
"method",
"(",
"custom_save_method",
")",
".",
"arity",
".",
"zero?",
"__send__",
"(",
"custom_save_method",
")",
"else",
"__send__",
"(",
"custom_save_method",
",",
"@output",
")",
"end",
"end",
"private",
"def",
"fill_options",
"if",
"@options",
"[",
":format",
"]",
"and",
"@options",
".",
"key?",
"(",
":compression",
")",
"return",
"end",
"if",
"@output",
".",
"is_a?",
"(",
"Buffer",
")",
"info",
"=",
"{",
"}",
"else",
"extension",
"=",
"PathExtension",
".",
"new",
"(",
"@output",
")",
"info",
"=",
"extension",
".",
"extract",
"end",
"format",
"=",
"info",
"[",
":format",
"]",
"@options",
"=",
"@options",
".",
"dup",
"if",
"format",
"and",
"respond_to?",
"(",
"\"save_as_#{format}\"",
",",
"true",
")",
"@options",
"[",
":format",
"]",
"||=",
"format",
".",
"to_sym",
"else",
"@options",
"[",
":format",
"]",
"||=",
":arrow",
"end",
"unless",
"@options",
".",
"key?",
"(",
":compression",
")",
"@options",
"[",
":compression",
"]",
"=",
"info",
"[",
":compression",
"]",
"end",
"end",
"def",
"open_raw_output_stream",
"(",
"&",
"block",
")",
"if",
"@output",
".",
"is_a?",
"(",
"Buffer",
")",
"BufferOutputStream",
".",
"open",
"(",
"@output",
",",
"&",
"block",
")",
"else",
"FileOutputStream",
".",
"open",
"(",
"@output",
",",
"false",
",",
"&",
"block",
")",
"end",
"end",
"def",
"open_output_stream",
"(",
"&",
"block",
")",
"compression",
"=",
"@options",
"[",
":compression",
"]",
"if",
"compression",
"codec",
"=",
"Codec",
".",
"new",
"(",
"compression",
")",
"open_raw_output_stream",
"do",
"|",
"raw_output",
"|",
"CompressedOutputStream",
".",
"open",
"(",
"codec",
",",
"raw_output",
")",
"do",
"|",
"output",
"|",
"yield",
"(",
"output",
")",
"end",
"end",
"else",
"open_raw_output_stream",
"(",
"&",
"block",
")",
"end",
"end",
"def",
"save_raw",
"(",
"writer_class",
")",
"open_output_stream",
"do",
"|",
"output",
"|",
"writer_class",
".",
"open",
"(",
"output",
",",
"@table",
".",
"schema",
")",
"do",
"|",
"writer",
"|",
"writer",
".",
"write_table",
"(",
"@table",
")",
"end",
"end",
"end",
"def",
"save_as_arrow",
"save_as_arrow_file",
"end",
"def",
"save_as_arrow_file",
"save_raw",
"(",
"RecordBatchFileWriter",
")",
"end",
"def",
"save_as_batch",
"save_as_arrow_file",
"end",
"def",
"save_as_arrow_streaming",
"save_raw",
"(",
"RecordBatchStreamWriter",
")",
"end",
"def",
"save_as_stream",
"save_as_arrow_streaming",
"end",
"def",
"save_as_csv",
"open_output_stream",
"do",
"|",
"output",
"|",
"csv",
"=",
"CSV",
".",
"new",
"(",
"output",
")",
"names",
"=",
"@table",
".",
"schema",
".",
"fields",
".",
"collect",
"(",
"&",
":name",
")",
"csv",
"<<",
"names",
"@table",
".",
"each_record",
"(",
"reuse_record",
":",
"true",
")",
"do",
"|",
"record",
"|",
"csv",
"<<",
"names",
".",
"collect",
"do",
"|",
"name",
"|",
"record",
"[",
"name",
"]",
"end",
"end",
"end",
"end",
"def",
"save_as_feather",
"open_output_stream",
"do",
"|",
"output",
"|",
"FeatherFileWriter",
".",
"open",
"(",
"output",
")",
"do",
"|",
"writer",
"|",
"writer",
".",
"write",
"(",
"@table",
")",
"end",
"end",
"end",
"end",
"end"
] |
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.
|
[
"Licensed",
"to",
"the",
"Apache",
"Software",
"Foundation",
"(",
"ASF",
")",
"under",
"one",
"or",
"more",
"contributor",
"license",
"agreements",
"."
] |
[
"# For backward compatibility.",
"# @since 1.0.0",
"# @deprecated Use `format: :arrow_batch` instead.",
"# @since 1.0.0",
"# @deprecated Use `format: :arrow_streaming` instead."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 18
| 852
| 174
|
ad4bf6fa6cf6684d096d069d41adeb20af38d2cc
|
RossBrunton/DuskWolf
|
engine/rooms/RoomManager.js
|
[
"MIT"
] |
JavaScript
|
RoomManager
|
/** Manages rooms, which contain tilemap data and the entities in the room.
*
* This is intended to be used with an instance of `{@link dusk.rooms.sgui.LayeredRoom}` and essentially serves as a
* storage for its rooms. Both `{@link dusk.rooms.plat}` and `{@link dusk.rooms.quest}` have their own room
* managers for their own types of rooms.
*
* @memberof dusk.rooms
* @since 0.0.16-alpha
*/
|
Manages rooms, which contain tilemap data and the entities in the room.
This is intended to be used with an instance of ` dusk.rooms.sgui.LayeredRoom` and essentially serves as a
storage for its rooms. Both ` dusk.rooms.plat` and ` dusk.rooms.quest` have their own room
managers for their own types of rooms.
|
[
"Manages",
"rooms",
"which",
"contain",
"tilemap",
"data",
"and",
"the",
"entities",
"in",
"the",
"room",
".",
"This",
"is",
"intended",
"to",
"be",
"used",
"with",
"an",
"instance",
"of",
"`",
"dusk",
".",
"rooms",
".",
"sgui",
".",
"LayeredRoom",
"`",
"and",
"essentially",
"serves",
"as",
"a",
"storage",
"for",
"its",
"rooms",
".",
"Both",
"`",
"dusk",
".",
"rooms",
".",
"plat",
"`",
"and",
"`",
"dusk",
".",
"rooms",
".",
"quest",
"`",
"have",
"their",
"own",
"room",
"managers",
"for",
"their",
"own",
"types",
"of",
"rooms",
"."
] |
class RoomManager {
/** Creates a new RoomManager
*
* @param {?string} packageName The package that this room manager depends on; for generating rooms in the
* editor.
* @param {?string} managerPath The path to this object from it's package.
*/
constructor(packageName, managerPath) {
/** All the rooms that have been added.
*
* The key is the name of the room, and the value is the room data.
* @type object
* @private
* @memberof! dusk.rooms.RoomManager#
*/
this._rooms = new Map();
/** An event dispatcher which fires when a room is loaded.
*
* This has the properties `"room"`; the name of the room, and `"spawn"` the mark number of the spawn point.
* @type dusk.utils.EventDispatcher
* @memberof! dusk.rooms.RoomManager#
*/
this.roomLoaded = new EventDispatcher("dusk.rooms.RoomManager.roomLoaded");
/** The LayeredRoom instance this manager is for.
*
* You should use `{@link dusk.rooms.RoomManager#setLayeredRoom}` to set this, instead of setting it directly.
* @type dusk.rooms.sgui.LayeredRoom
* @memberof! dusk.rooms.RoomManager#
*/
this.basicMain = null;
/** The name of the package that this room manager is from.
* @type ?string
* @memberof! dusk.rooms.RoomManager#
*/
this.packageName = packageName;
/** Path to this object, from window. For example `"rooms"` or so.
* @type ?string
* @memberof! dusk.rooms.RoomManager#
*/
this.managerPath = managerPath;
/** The transitions for the current room.
* @type dusk.rooms.RoomTransitions
* @since 0.0.21-alpha
* @memberof! dusk.rooms.RoomManager#
*/
this.currentTransitions = null;
}
/** Stores a room.
*
* @param {string} name The name of the room.
* @param {object} data The room data to store.
*/
createRoom(name, data) {
this._rooms.set(name, data);
}
/** Returns a room stored under the specified name.
*
* @param {string} name The name to look up.
* @return {promise(object)} A promise that resolves to the given room.
*/
getRoomData(name) {
if(this._rooms.has(name)) {
return Promise.resolve(this._rooms.get(name));
}else{
return load.importAndEvaluate(name).then((function(p) {
this._rooms.set(name, p);
return p;
}).bind(this));
}
}
/** Asks the basic main to set a room, with the "seek" entitiy at the mark specified.
*
* @param {string} room The name of the room to load.
* @param {?integer} spawn The mark ID for the seek entity to appear at.
* @param {boolean=} callNewRoom Whether to call the "newRoom" method of the room transitions, which may be
* required to do effects.
* @return {promise(object)} A promise that fulfills when the room has finished loading. The value is an object
* containing `room` and `spawn`.
*/
setRoom(room, spawn, callNewRoom) {
if(!room) {
console.error("No room specified to set!");
return;
}
if(!this.basicMain) {
console.error("No LayeredRoom to set the room!");
return;
}
console.log("Setting room "+room);
return this.getRoomData(room).then((function(roomData) {
if(this.currentTransitions) this.currentTransitions.destroy();
this.currentTransitions = new RoomTransitions(roomData.transitions, room, this);
var prom = this.basicMain.createRoom(room, spawn);
if(callNewRoom) {
prom = prom.then(this.currentTransitions.newRoom.bind(this.currentTransitions));
}
return prom.then((function(e) {
this.roomLoaded.fire({"room":room, "spawn":spawn}, room);
return {"room":room, "spawn":spawn};
}).bind(this));
}).bind(this));
}
/** Sets the Basic Main instance this is for; this should be called instead of setting it directly.
* @param {dusk.rooms.sgui.LayeredRoom} bm The Basic Main instance.
*/
setLayeredRoom(bm) {
this.basicMain = bm;
bm.roomManager = this;
}
/** Sets the Basic Main instance this is for; this should be called instead of setting it directly.
* @param {dusk.rooms.sgui.LayeredRoom} bm The Basic Main instance.
*/
export(name) {
if(!editor.active) {
console.warn("Tried to export a room while the editor is disabled.");
return;
}
if(!name) name = prompt("Please enter a package name.", this.basicMain.roomName);
console.log("----- Exported Room Data "+name+" -----");
var deps = ["dusk.entities"];
var out = "";
out += "// Code generated by RoomManager from DuskWolf "+dusk.ver+" for room "+name;
out += "\n\"use strict\";\n\n";
out += "load.provide(\""+name+"\", function() {";
var addDep = function(str) {
if(!deps.includes(str)) deps.push(str);
};
var room = this.basicMain.saveRoom(addDep);
room.transitions = this.currentTransitions.export();
out += "\n\tvar manager = load.require(\""+this.packageName+"\")";
if(this.managerPath) out += "."+this.managerPath;
out += ";";
for(var i = 0; i < deps.length; i ++) {
out += "\n\tload.require(\""+deps[i]+"\");";
}
out += "\n\t";
out += "\n\tvar room = "+JSON.stringify(room, undefined, 0)+";\n\t";
out += "\n\tmanager.createRoom(\""+name+"\", room);\n\t";
out += "\n\t//Remember to add extra code!\n\t";
out += "\n\treturn room;";
out += "\n});";
console.log(out);
console.log("----- End Exported Room Data -----");
return false;
}
}
|
[
"class",
"RoomManager",
"{",
"constructor",
"(",
"packageName",
",",
"managerPath",
")",
"{",
"this",
".",
"_rooms",
"=",
"new",
"Map",
"(",
")",
";",
"this",
".",
"roomLoaded",
"=",
"new",
"EventDispatcher",
"(",
"\"dusk.rooms.RoomManager.roomLoaded\"",
")",
";",
"this",
".",
"basicMain",
"=",
"null",
";",
"this",
".",
"packageName",
"=",
"packageName",
";",
"this",
".",
"managerPath",
"=",
"managerPath",
";",
"this",
".",
"currentTransitions",
"=",
"null",
";",
"}",
"createRoom",
"(",
"name",
",",
"data",
")",
"{",
"this",
".",
"_rooms",
".",
"set",
"(",
"name",
",",
"data",
")",
";",
"}",
"getRoomData",
"(",
"name",
")",
"{",
"if",
"(",
"this",
".",
"_rooms",
".",
"has",
"(",
"name",
")",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"this",
".",
"_rooms",
".",
"get",
"(",
"name",
")",
")",
";",
"}",
"else",
"{",
"return",
"load",
".",
"importAndEvaluate",
"(",
"name",
")",
".",
"then",
"(",
"(",
"function",
"(",
"p",
")",
"{",
"this",
".",
"_rooms",
".",
"set",
"(",
"name",
",",
"p",
")",
";",
"return",
"p",
";",
"}",
")",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"}",
"setRoom",
"(",
"room",
",",
"spawn",
",",
"callNewRoom",
")",
"{",
"if",
"(",
"!",
"room",
")",
"{",
"console",
".",
"error",
"(",
"\"No room specified to set!\"",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"this",
".",
"basicMain",
")",
"{",
"console",
".",
"error",
"(",
"\"No LayeredRoom to set the room!\"",
")",
";",
"return",
";",
"}",
"console",
".",
"log",
"(",
"\"Setting room \"",
"+",
"room",
")",
";",
"return",
"this",
".",
"getRoomData",
"(",
"room",
")",
".",
"then",
"(",
"(",
"function",
"(",
"roomData",
")",
"{",
"if",
"(",
"this",
".",
"currentTransitions",
")",
"this",
".",
"currentTransitions",
".",
"destroy",
"(",
")",
";",
"this",
".",
"currentTransitions",
"=",
"new",
"RoomTransitions",
"(",
"roomData",
".",
"transitions",
",",
"room",
",",
"this",
")",
";",
"var",
"prom",
"=",
"this",
".",
"basicMain",
".",
"createRoom",
"(",
"room",
",",
"spawn",
")",
";",
"if",
"(",
"callNewRoom",
")",
"{",
"prom",
"=",
"prom",
".",
"then",
"(",
"this",
".",
"currentTransitions",
".",
"newRoom",
".",
"bind",
"(",
"this",
".",
"currentTransitions",
")",
")",
";",
"}",
"return",
"prom",
".",
"then",
"(",
"(",
"function",
"(",
"e",
")",
"{",
"this",
".",
"roomLoaded",
".",
"fire",
"(",
"{",
"\"room\"",
":",
"room",
",",
"\"spawn\"",
":",
"spawn",
"}",
",",
"room",
")",
";",
"return",
"{",
"\"room\"",
":",
"room",
",",
"\"spawn\"",
":",
"spawn",
"}",
";",
"}",
")",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
")",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"setLayeredRoom",
"(",
"bm",
")",
"{",
"this",
".",
"basicMain",
"=",
"bm",
";",
"bm",
".",
"roomManager",
"=",
"this",
";",
"}",
"export",
"(",
"name",
")",
"{",
"if",
"(",
"!",
"editor",
".",
"active",
")",
"{",
"console",
".",
"warn",
"(",
"\"Tried to export a room while the editor is disabled.\"",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"name",
")",
"name",
"=",
"prompt",
"(",
"\"Please enter a package name.\"",
",",
"this",
".",
"basicMain",
".",
"roomName",
")",
";",
"console",
".",
"log",
"(",
"\"----- Exported Room Data \"",
"+",
"name",
"+",
"\" -----\"",
")",
";",
"var",
"deps",
"=",
"[",
"\"dusk.entities\"",
"]",
";",
"var",
"out",
"=",
"\"\"",
";",
"out",
"+=",
"\"// Code generated by RoomManager from DuskWolf \"",
"+",
"dusk",
".",
"ver",
"+",
"\" for room \"",
"+",
"name",
";",
"out",
"+=",
"\"\\n\\\"use strict\\\";\\n\\n\"",
";",
"out",
"+=",
"\"load.provide(\\\"\"",
"+",
"name",
"+",
"\"\\\", function() {\"",
";",
"var",
"addDep",
"=",
"function",
"(",
"str",
")",
"{",
"if",
"(",
"!",
"deps",
".",
"includes",
"(",
"str",
")",
")",
"deps",
".",
"push",
"(",
"str",
")",
";",
"}",
";",
"var",
"room",
"=",
"this",
".",
"basicMain",
".",
"saveRoom",
"(",
"addDep",
")",
";",
"room",
".",
"transitions",
"=",
"this",
".",
"currentTransitions",
".",
"export",
"(",
")",
";",
"out",
"+=",
"\"\\n\\tvar manager = load.require(\\\"\"",
"+",
"this",
".",
"packageName",
"+",
"\"\\\")\"",
";",
"if",
"(",
"this",
".",
"managerPath",
")",
"out",
"+=",
"\".\"",
"+",
"this",
".",
"managerPath",
";",
"out",
"+=",
"\";\"",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"deps",
".",
"length",
";",
"i",
"++",
")",
"{",
"out",
"+=",
"\"\\n\\tload.require(\\\"\"",
"+",
"deps",
"[",
"i",
"]",
"+",
"\"\\\");\"",
";",
"}",
"out",
"+=",
"\"\\n\\t\"",
";",
"out",
"+=",
"\"\\n\\tvar room = \"",
"+",
"JSON",
".",
"stringify",
"(",
"room",
",",
"undefined",
",",
"0",
")",
"+",
"\";\\n\\t\"",
";",
"out",
"+=",
"\"\\n\\tmanager.createRoom(\\\"\"",
"+",
"name",
"+",
"\"\\\", room);\\n\\t\"",
";",
"out",
"+=",
"\"\\n\\t//Remember to add extra code!\\n\\t\"",
";",
"out",
"+=",
"\"\\n\\treturn room;\"",
";",
"out",
"+=",
"\"\\n});\"",
";",
"console",
".",
"log",
"(",
"out",
")",
";",
"console",
".",
"log",
"(",
"\"----- End Exported Room Data -----\"",
")",
";",
"return",
"false",
";",
"}",
"}"
] |
Manages rooms, which contain tilemap data and the entities in the room.
|
[
"Manages",
"rooms",
"which",
"contain",
"tilemap",
"data",
"and",
"the",
"entities",
"in",
"the",
"room",
"."
] |
[
"/** Creates a new RoomManager\n\t\t * \n\t\t * @param {?string} packageName The package that this room manager depends on; for generating rooms in the\n\t\t * editor.\n\t\t * @param {?string} managerPath The path to this object from it's package.\n\t\t */",
"/** All the rooms that have been added.\n\t\t\t * \n\t\t\t * The key is the name of the room, and the value is the room data.\n\t\t\t * @type object\n\t\t\t * @private\n\t\t\t * @memberof! dusk.rooms.RoomManager#\n\t\t\t */",
"/** An event dispatcher which fires when a room is loaded.\n\t\t\t * \n\t\t\t * This has the properties `\"room\"`; the name of the room, and `\"spawn\"` the mark number of the spawn point.\n\t\t\t * @type dusk.utils.EventDispatcher\n\t\t\t * @memberof! dusk.rooms.RoomManager#\n\t\t\t */",
"/** The LayeredRoom instance this manager is for.\n\t\t\t * \n\t\t\t * You should use `{@link dusk.rooms.RoomManager#setLayeredRoom}` to set this, instead of setting it directly.\n\t\t\t * @type dusk.rooms.sgui.LayeredRoom\n\t\t\t * @memberof! dusk.rooms.RoomManager#\n\t\t\t */",
"/** The name of the package that this room manager is from.\n\t\t\t * @type ?string\n\t\t\t * @memberof! dusk.rooms.RoomManager#\n\t\t\t */",
"/** Path to this object, from window. For example `\"rooms\"` or so.\n\t\t\t * @type ?string\n\t\t\t * @memberof! dusk.rooms.RoomManager#\n\t\t\t */",
"/** The transitions for the current room.\n\t\t\t * @type dusk.rooms.RoomTransitions\n\t\t\t * @since 0.0.21-alpha\n\t\t\t * @memberof! dusk.rooms.RoomManager#\n\t\t\t */",
"/** Stores a room.\n\t\t * \n\t\t * @param {string} name The name of the room.\n\t\t * @param {object} data The room data to store.\n\t\t */",
"/** Returns a room stored under the specified name.\n\t\t * \n\t\t * @param {string} name The name to look up.\n\t\t * @return {promise(object)} A promise that resolves to the given room.\n\t\t */",
"/** Asks the basic main to set a room, with the \"seek\" entitiy at the mark specified.\n\t\t * \n\t\t * @param {string} room The name of the room to load.\n\t\t * @param {?integer} spawn The mark ID for the seek entity to appear at.\n\t\t * @param {boolean=} callNewRoom Whether to call the \"newRoom\" method of the room transitions, which may be\n\t\t * required to do effects.\n\t\t * @return {promise(object)} A promise that fulfills when the room has finished loading. The value is an object\n\t\t * containing `room` and `spawn`.\n\t\t */",
"/** Sets the Basic Main instance this is for; this should be called instead of setting it directly.\n\t\t * @param {dusk.rooms.sgui.LayeredRoom} bm The Basic Main instance.\n\t\t */",
"/** Sets the Basic Main instance this is for; this should be called instead of setting it directly.\n\t\t * @param {dusk.rooms.sgui.LayeredRoom} bm The Basic Main instance.\n\t\t */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 27
| 1,467
| 115
|
012c7074ad90059acb645bc6de1711eb3b95d62c
|
kamiingithub/kafka-dig
|
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/SourceTaskOffsetCommitter.java
|
[
"Apache-2.0"
] |
Java
|
SourceTaskOffsetCommitter
|
/**
* <p>
* Manages offset commit scheduling and execution for SourceTasks.
* </p>
* <p>
* Unlike sink tasks which directly manage their offset commits in the main poll() thread since
* they drive the event loop and control (for all intents and purposes) the timeouts, source
* tasks are at the whim of the connector and cannot be guaranteed to wake up on the necessary
* schedule. Instead, this class tracks all the active tasks, their schedule for commits, and
* ensures they are invoked in a timely fashion.
* </p>
*/
|
Manages offset commit scheduling and execution for SourceTasks.
Unlike sink tasks which directly manage their offset commits in the main poll() thread since
they drive the event loop and control (for all intents and purposes) the timeouts, source
tasks are at the whim of the connector and cannot be guaranteed to wake up on the necessary
schedule. Instead, this class tracks all the active tasks, their schedule for commits, and
ensures they are invoked in a timely fashion.
|
[
"Manages",
"offset",
"commit",
"scheduling",
"and",
"execution",
"for",
"SourceTasks",
".",
"Unlike",
"sink",
"tasks",
"which",
"directly",
"manage",
"their",
"offset",
"commits",
"in",
"the",
"main",
"poll",
"()",
"thread",
"since",
"they",
"drive",
"the",
"event",
"loop",
"and",
"control",
"(",
"for",
"all",
"intents",
"and",
"purposes",
")",
"the",
"timeouts",
"source",
"tasks",
"are",
"at",
"the",
"whim",
"of",
"the",
"connector",
"and",
"cannot",
"be",
"guaranteed",
"to",
"wake",
"up",
"on",
"the",
"necessary",
"schedule",
".",
"Instead",
"this",
"class",
"tracks",
"all",
"the",
"active",
"tasks",
"their",
"schedule",
"for",
"commits",
"and",
"ensures",
"they",
"are",
"invoked",
"in",
"a",
"timely",
"fashion",
"."
] |
class SourceTaskOffsetCommitter {
private static final Logger log = LoggerFactory.getLogger(SourceTaskOffsetCommitter.class);
private final WorkerConfig config;
private final ScheduledExecutorService commitExecutorService;
private final ConcurrentMap<ConnectorTaskId, ScheduledFuture<?>> committers;
// visible for testing
SourceTaskOffsetCommitter(WorkerConfig config,
ScheduledExecutorService commitExecutorService,
ConcurrentMap<ConnectorTaskId, ScheduledFuture<?>> committers) {
this.config = config;
this.commitExecutorService = commitExecutorService;
this.committers = committers;
}
public SourceTaskOffsetCommitter(WorkerConfig config) {
this(config, Executors.newSingleThreadScheduledExecutor(ThreadUtils.createThreadFactory(
SourceTaskOffsetCommitter.class.getSimpleName() + "-%d", false)),
new ConcurrentHashMap<ConnectorTaskId, ScheduledFuture<?>>());
}
public void close(long timeoutMs) {
commitExecutorService.shutdown();
try {
if (!commitExecutorService.awaitTermination(timeoutMs, TimeUnit.MILLISECONDS)) {
log.error("Graceful shutdown of offset commitOffsets thread timed out.");
}
} catch (InterruptedException e) {
// ignore and allow to exit immediately
}
}
public void schedule(final ConnectorTaskId id, final WorkerSourceTask workerTask) {
long commitIntervalMs = config.getLong(WorkerConfig.OFFSET_COMMIT_INTERVAL_MS_CONFIG);
ScheduledFuture<?> commitFuture = commitExecutorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try (LoggingContext loggingContext = LoggingContext.forOffsets(id)) {
commit(workerTask);
}
}
}, commitIntervalMs, commitIntervalMs, TimeUnit.MILLISECONDS);
committers.put(id, commitFuture);
}
public void remove(ConnectorTaskId id) {
final ScheduledFuture<?> task = committers.remove(id);
if (task == null)
return;
try (LoggingContext loggingContext = LoggingContext.forTask(id)) {
task.cancel(false);
if (!task.isDone())
task.get();
} catch (CancellationException e) {
// ignore
log.trace("Offset commit thread was cancelled by another thread while removing connector task with id: {}", id);
} catch (ExecutionException | InterruptedException e) {
throw new ConnectException("Unexpected interruption in SourceTaskOffsetCommitter while removing task with id: " + id, e);
}
}
private void commit(WorkerSourceTask workerTask) {
log.debug("{} Committing offsets", workerTask);
try {
if (workerTask.commitOffsets()) {
return;
}
log.error("{} Failed to commit offsets", workerTask);
} catch (Throwable t) {
// We're very careful about exceptions here since any uncaught exceptions in the commit
// thread would cause the fixed interval schedule on the ExecutorService to stop running
// for that task
log.error("{} Unhandled exception when committing: ", workerTask, t);
}
}
}
|
[
"class",
"SourceTaskOffsetCommitter",
"{",
"private",
"static",
"final",
"Logger",
"log",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"SourceTaskOffsetCommitter",
".",
"class",
")",
";",
"private",
"final",
"WorkerConfig",
"config",
";",
"private",
"final",
"ScheduledExecutorService",
"commitExecutorService",
";",
"private",
"final",
"ConcurrentMap",
"<",
"ConnectorTaskId",
",",
"ScheduledFuture",
"<",
"?",
">",
">",
"committers",
";",
"SourceTaskOffsetCommitter",
"(",
"WorkerConfig",
"config",
",",
"ScheduledExecutorService",
"commitExecutorService",
",",
"ConcurrentMap",
"<",
"ConnectorTaskId",
",",
"ScheduledFuture",
"<",
"?",
">",
">",
"committers",
")",
"{",
"this",
".",
"config",
"=",
"config",
";",
"this",
".",
"commitExecutorService",
"=",
"commitExecutorService",
";",
"this",
".",
"committers",
"=",
"committers",
";",
"}",
"public",
"SourceTaskOffsetCommitter",
"(",
"WorkerConfig",
"config",
")",
"{",
"this",
"(",
"config",
",",
"Executors",
".",
"newSingleThreadScheduledExecutor",
"(",
"ThreadUtils",
".",
"createThreadFactory",
"(",
"SourceTaskOffsetCommitter",
".",
"class",
".",
"getSimpleName",
"(",
")",
"+",
"\"",
"-%d",
"\"",
",",
"false",
")",
")",
",",
"new",
"ConcurrentHashMap",
"<",
"ConnectorTaskId",
",",
"ScheduledFuture",
"<",
"?",
">",
">",
"(",
")",
")",
";",
"}",
"public",
"void",
"close",
"(",
"long",
"timeoutMs",
")",
"{",
"commitExecutorService",
".",
"shutdown",
"(",
")",
";",
"try",
"{",
"if",
"(",
"!",
"commitExecutorService",
".",
"awaitTermination",
"(",
"timeoutMs",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"Graceful shutdown of offset commitOffsets thread timed out.",
"\"",
")",
";",
"}",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"}",
"}",
"public",
"void",
"schedule",
"(",
"final",
"ConnectorTaskId",
"id",
",",
"final",
"WorkerSourceTask",
"workerTask",
")",
"{",
"long",
"commitIntervalMs",
"=",
"config",
".",
"getLong",
"(",
"WorkerConfig",
".",
"OFFSET_COMMIT_INTERVAL_MS_CONFIG",
")",
";",
"ScheduledFuture",
"<",
"?",
">",
"commitFuture",
"=",
"commitExecutorService",
".",
"scheduleWithFixedDelay",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"(",
"LoggingContext",
"loggingContext",
"=",
"LoggingContext",
".",
"forOffsets",
"(",
"id",
")",
")",
"{",
"commit",
"(",
"workerTask",
")",
";",
"}",
"}",
"}",
",",
"commitIntervalMs",
",",
"commitIntervalMs",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"committers",
".",
"put",
"(",
"id",
",",
"commitFuture",
")",
";",
"}",
"public",
"void",
"remove",
"(",
"ConnectorTaskId",
"id",
")",
"{",
"final",
"ScheduledFuture",
"<",
"?",
">",
"task",
"=",
"committers",
".",
"remove",
"(",
"id",
")",
";",
"if",
"(",
"task",
"==",
"null",
")",
"return",
";",
"try",
"(",
"LoggingContext",
"loggingContext",
"=",
"LoggingContext",
".",
"forTask",
"(",
"id",
")",
")",
"{",
"task",
".",
"cancel",
"(",
"false",
")",
";",
"if",
"(",
"!",
"task",
".",
"isDone",
"(",
")",
")",
"task",
".",
"get",
"(",
")",
";",
"}",
"catch",
"(",
"CancellationException",
"e",
")",
"{",
"log",
".",
"trace",
"(",
"\"",
"Offset commit thread was cancelled by another thread while removing connector task with id: {}",
"\"",
",",
"id",
")",
";",
"}",
"catch",
"(",
"ExecutionException",
"|",
"InterruptedException",
"e",
")",
"{",
"throw",
"new",
"ConnectException",
"(",
"\"",
"Unexpected interruption in SourceTaskOffsetCommitter while removing task with id: ",
"\"",
"+",
"id",
",",
"e",
")",
";",
"}",
"}",
"private",
"void",
"commit",
"(",
"WorkerSourceTask",
"workerTask",
")",
"{",
"log",
".",
"debug",
"(",
"\"",
"{} Committing offsets",
"\"",
",",
"workerTask",
")",
";",
"try",
"{",
"if",
"(",
"workerTask",
".",
"commitOffsets",
"(",
")",
")",
"{",
"return",
";",
"}",
"log",
".",
"error",
"(",
"\"",
"{} Failed to commit offsets",
"\"",
",",
"workerTask",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"log",
".",
"error",
"(",
"\"",
"{} Unhandled exception when committing: ",
"\"",
",",
"workerTask",
",",
"t",
")",
";",
"}",
"}",
"}"
] |
<p>
Manages offset commit scheduling and execution for SourceTasks.
|
[
"<p",
">",
"Manages",
"offset",
"commit",
"scheduling",
"and",
"execution",
"for",
"SourceTasks",
"."
] |
[
"// visible for testing",
"// ignore and allow to exit immediately",
"// ignore",
"// We're very careful about exceptions here since any uncaught exceptions in the commit",
"// thread would cause the fixed interval schedule on the ExecutorService to stop running",
"// for that task"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 18
| 628
| 118
|
6c2af2f666b3d1ca6cfde1e8c443cfbf92f855d8
|
EuroServizi/spider
|
apps/core/components/widgets/admin/admin.rb
|
[
"MIT"
] |
Ruby
|
Admin
|
# This widget creates an administration page for models.
#
# Attributes:
# *:models* Comma-separated list of model names
# *:title*
# *:logout_url*
#
# Content:
# Takes the tags
# *admin:model* A model to administer
# *admin:app* Administer all models belonging to the app. Can have an 'except' attribute.
|
This widget creates an administration page for models.
Attributes:
:models* Comma-separated list of model names
:title
:logout_url
Takes the tags
admin:model* A model to administer
admin:app* Administer all models belonging to the app. Can have an 'except' attribute.
|
[
"This",
"widget",
"creates",
"an",
"administration",
"page",
"for",
"models",
".",
"Attributes",
":",
":",
"models",
"*",
"Comma",
"-",
"separated",
"list",
"of",
"model",
"names",
":",
"title",
":",
"logout_url",
"Takes",
"the",
"tags",
"admin",
":",
"model",
"*",
"A",
"model",
"to",
"administer",
"admin",
":",
"app",
"*",
"Administer",
"all",
"models",
"belonging",
"to",
"the",
"app",
".",
"Can",
"have",
"an",
"'",
"except",
"'",
"attribute",
"."
] |
class Admin < Spider::Widget
tag 'admin'
i_attribute :models, :process => Proc.new{ |models| models.split(/,[\s\n]*/).map{|m| const_get_full(m) } }
is_attr_accessor :title, :default => Proc.new{ _("Administration") }
is_attr_accessor :logout_url, :default => Spider::Auth.request_url+'/login/logout'
is_attr_accessor :"full-page", :type => Spider::Bool, :default => false
attr_accessor :custom_widgets
def init
@items = []
end
def route_widget
[:switcher, @_action]
end
def prepare_widgets
#widget di base della parte admin, faccio sanitize dei parametri
@request.params = @request.params.sanitize_object
@models.each do |model|
if @user_checks && user_check = @user_checks[model]
next unless @request.user
next unless @request.user.respond_to?(user_check)
next unless @request.user.send(user_check)
end
crud = Crud.new(@request, @response)
crud.id = model.name.to_s.gsub('::', '_').downcase
crud.model = model
if @custom_widgets && @custom_widgets[model]
crud.table_widget = @custom_widgets[model][:table] if @custom_widgets[model][:table]
crud.form_widget = @custom_widgets[model][:form] if @custom_widgets[model][:form]
end
@widgets[:switcher].add(model.label_plural, crud, _('Manage Data'))
end
if (@request.respond_to?(:user) && @request.user)
@scene.username = @request.user.to_s
else
@scene.username = _("guest")
@scene.guest = true
end
super
end
def run
@scene.current = @widgets[:switcher].current_label
if @scene._parent.admin_breadcrumb
@scene.breadcrumb = @scene._parent.admin_breadcrumb
bc = []
bc << {:label => @scene.current, :url => @widgets[:switcher].link(@scene.current)}
if @widgets[:switcher].current.action == :form
bc += @widgets[:switcher].current.form.breadcrumb
end
@scene.breadcrumb.concat(bc)
end
super
end
def self.parse_content(doc)
assets_widgets = []
doc.search('admin:model').each do |mod|
if table = mod.get_attribute('table')
assets_widgets << table
end
if form = mod.get_attribute('form')
assets_widgets << form
end
end
assets_widgets.uniq!
rc, ov = super
unless assets_widgets.empty?
ov << Hpricot("<tpl:prepend><tpl:assets widgets=\"#{assets_widgets.uniq.join(',')}\"></tpl:prepend>").root
end
[rc, ov]
end
def parse_runtime_content(doc, src_path)
@custom_widgets ||= {}
@user_checks ||= {}
doc = super
mods = []
doc.search('admin:model').each do |mod|
model = const_get_full(mod.innerText)
mods << model
if table = mod.get_attribute('table')
@custom_widgets[model] ||= {}
@custom_widgets[model][:table] = table
end
if form = mod.get_attribute('form')
@custom_widgets[model] ||= {}
@custom_widgets[model][:form] = form
end
if user_check = mod.get_attribute('if-user')
@user_checks[model] = user_check.to_sym
end
end
doc.search('admin:app').each do |app_tag|
except = []
if (app_tag.attributes['except'])
except = app_tag.attributes['except'].split(',').map{ |e| e.strip }
end
app = const_get_full(app_tag.innerText.strip)
mods += app.models.select{ |m|
!m.attributes[:sub_model] && m.mapper.class.write? && !except.include?(m.name.split('::')[-1])
}.sort{ |a, b| a.name <=> b.name }
end
@models ||= []
@models += mods
return doc
end
end
|
[
"class",
"Admin",
"<",
"Spider",
"::",
"Widget",
"tag",
"'admin'",
"i_attribute",
":models",
",",
":process",
"=>",
"Proc",
".",
"new",
"{",
"|",
"models",
"|",
"models",
".",
"split",
"(",
"/",
",[",
"\\s",
"\\n",
"]*",
"/",
")",
".",
"map",
"{",
"|",
"m",
"|",
"const_get_full",
"(",
"m",
")",
"}",
"}",
"is_attr_accessor",
":title",
",",
":default",
"=>",
"Proc",
".",
"new",
"{",
"_",
"(",
"\"Administration\"",
")",
"}",
"is_attr_accessor",
":logout_url",
",",
":default",
"=>",
"Spider",
"::",
"Auth",
".",
"request_url",
"+",
"'/login/logout'",
"is_attr_accessor",
":\"",
"full-page",
"\"",
",",
":type",
"=>",
"Spider",
"::",
"Bool",
",",
":default",
"=>",
"false",
"attr_accessor",
":custom_widgets",
"def",
"init",
"@items",
"=",
"[",
"]",
"end",
"def",
"route_widget",
"[",
":switcher",
",",
"@_action",
"]",
"end",
"def",
"prepare_widgets",
"@request",
".",
"params",
"=",
"@request",
".",
"params",
".",
"sanitize_object",
"@models",
".",
"each",
"do",
"|",
"model",
"|",
"if",
"@user_checks",
"&&",
"user_check",
"=",
"@user_checks",
"[",
"model",
"]",
"next",
"unless",
"@request",
".",
"user",
"next",
"unless",
"@request",
".",
"user",
".",
"respond_to?",
"(",
"user_check",
")",
"next",
"unless",
"@request",
".",
"user",
".",
"send",
"(",
"user_check",
")",
"end",
"crud",
"=",
"Crud",
".",
"new",
"(",
"@request",
",",
"@response",
")",
"crud",
".",
"id",
"=",
"model",
".",
"name",
".",
"to_s",
".",
"gsub",
"(",
"'::'",
",",
"'_'",
")",
".",
"downcase",
"crud",
".",
"model",
"=",
"model",
"if",
"@custom_widgets",
"&&",
"@custom_widgets",
"[",
"model",
"]",
"crud",
".",
"table_widget",
"=",
"@custom_widgets",
"[",
"model",
"]",
"[",
":table",
"]",
"if",
"@custom_widgets",
"[",
"model",
"]",
"[",
":table",
"]",
"crud",
".",
"form_widget",
"=",
"@custom_widgets",
"[",
"model",
"]",
"[",
":form",
"]",
"if",
"@custom_widgets",
"[",
"model",
"]",
"[",
":form",
"]",
"end",
"@widgets",
"[",
":switcher",
"]",
".",
"add",
"(",
"model",
".",
"label_plural",
",",
"crud",
",",
"_",
"(",
"'Manage Data'",
")",
")",
"end",
"if",
"(",
"@request",
".",
"respond_to?",
"(",
":user",
")",
"&&",
"@request",
".",
"user",
")",
"@scene",
".",
"username",
"=",
"@request",
".",
"user",
".",
"to_s",
"else",
"@scene",
".",
"username",
"=",
"_",
"(",
"\"guest\"",
")",
"@scene",
".",
"guest",
"=",
"true",
"end",
"super",
"end",
"def",
"run",
"@scene",
".",
"current",
"=",
"@widgets",
"[",
":switcher",
"]",
".",
"current_label",
"if",
"@scene",
".",
"_parent",
".",
"admin_breadcrumb",
"@scene",
".",
"breadcrumb",
"=",
"@scene",
".",
"_parent",
".",
"admin_breadcrumb",
"bc",
"=",
"[",
"]",
"bc",
"<<",
"{",
":label",
"=>",
"@scene",
".",
"current",
",",
":url",
"=>",
"@widgets",
"[",
":switcher",
"]",
".",
"link",
"(",
"@scene",
".",
"current",
")",
"}",
"if",
"@widgets",
"[",
":switcher",
"]",
".",
"current",
".",
"action",
"==",
":form",
"bc",
"+=",
"@widgets",
"[",
":switcher",
"]",
".",
"current",
".",
"form",
".",
"breadcrumb",
"end",
"@scene",
".",
"breadcrumb",
".",
"concat",
"(",
"bc",
")",
"end",
"super",
"end",
"def",
"self",
".",
"parse_content",
"(",
"doc",
")",
"assets_widgets",
"=",
"[",
"]",
"doc",
".",
"search",
"(",
"'admin:model'",
")",
".",
"each",
"do",
"|",
"mod",
"|",
"if",
"table",
"=",
"mod",
".",
"get_attribute",
"(",
"'table'",
")",
"assets_widgets",
"<<",
"table",
"end",
"if",
"form",
"=",
"mod",
".",
"get_attribute",
"(",
"'form'",
")",
"assets_widgets",
"<<",
"form",
"end",
"end",
"assets_widgets",
".",
"uniq!",
"rc",
",",
"ov",
"=",
"super",
"unless",
"assets_widgets",
".",
"empty?",
"ov",
"<<",
"Hpricot",
"(",
"\"<tpl:prepend><tpl:assets widgets=\\\"#{assets_widgets.uniq.join(',')}\\\"></tpl:prepend>\"",
")",
".",
"root",
"end",
"[",
"rc",
",",
"ov",
"]",
"end",
"def",
"parse_runtime_content",
"(",
"doc",
",",
"src_path",
")",
"@custom_widgets",
"||=",
"{",
"}",
"@user_checks",
"||=",
"{",
"}",
"doc",
"=",
"super",
"mods",
"=",
"[",
"]",
"doc",
".",
"search",
"(",
"'admin:model'",
")",
".",
"each",
"do",
"|",
"mod",
"|",
"model",
"=",
"const_get_full",
"(",
"mod",
".",
"innerText",
")",
"mods",
"<<",
"model",
"if",
"table",
"=",
"mod",
".",
"get_attribute",
"(",
"'table'",
")",
"@custom_widgets",
"[",
"model",
"]",
"||=",
"{",
"}",
"@custom_widgets",
"[",
"model",
"]",
"[",
":table",
"]",
"=",
"table",
"end",
"if",
"form",
"=",
"mod",
".",
"get_attribute",
"(",
"'form'",
")",
"@custom_widgets",
"[",
"model",
"]",
"||=",
"{",
"}",
"@custom_widgets",
"[",
"model",
"]",
"[",
":form",
"]",
"=",
"form",
"end",
"if",
"user_check",
"=",
"mod",
".",
"get_attribute",
"(",
"'if-user'",
")",
"@user_checks",
"[",
"model",
"]",
"=",
"user_check",
".",
"to_sym",
"end",
"end",
"doc",
".",
"search",
"(",
"'admin:app'",
")",
".",
"each",
"do",
"|",
"app_tag",
"|",
"except",
"=",
"[",
"]",
"if",
"(",
"app_tag",
".",
"attributes",
"[",
"'except'",
"]",
")",
"except",
"=",
"app_tag",
".",
"attributes",
"[",
"'except'",
"]",
".",
"split",
"(",
"','",
")",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"strip",
"}",
"end",
"app",
"=",
"const_get_full",
"(",
"app_tag",
".",
"innerText",
".",
"strip",
")",
"mods",
"+=",
"app",
".",
"models",
".",
"select",
"{",
"|",
"m",
"|",
"!",
"m",
".",
"attributes",
"[",
":sub_model",
"]",
"&&",
"m",
".",
"mapper",
".",
"class",
".",
"write?",
"&&",
"!",
"except",
".",
"include?",
"(",
"m",
".",
"name",
".",
"split",
"(",
"'::'",
")",
"[",
"-",
"1",
"]",
")",
"}",
".",
"sort",
"{",
"|",
"a",
",",
"b",
"|",
"a",
".",
"name",
"<=>",
"b",
".",
"name",
"}",
"end",
"@models",
"||=",
"[",
"]",
"@models",
"+=",
"mods",
"return",
"doc",
"end",
"end"
] |
This widget creates an administration page for models.
|
[
"This",
"widget",
"creates",
"an",
"administration",
"page",
"for",
"models",
"."
] |
[
"#widget di base della parte admin, faccio sanitize dei parametri"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 21
| 924
| 84
|
4e1d4b1ea27a3c69ab883e42b3348b34d6e2d1e7
|
uk-gov-mirror/ministryofjustice.Claim-for-Crown-Court-Defence
|
app/controllers/messages_controller.rb
|
[
"MIT"
] |
Ruby
|
MessagesController
|
# == Schema Information
#
# Table name: messages
#
# id :integer not null, primary key
# body :text
# claim_id :integer
# sender_id :integer
# created_at :datetime
# updated_at :datetime
# attachment_file_name :string
# attachment_content_type :string
# attachment_file_size :integer
# attachment_updated_at :datetime
#
|
Schema Information
Table name: messages
|
[
"Schema",
"Information",
"Table",
"name",
":",
"messages"
] |
class MessagesController < ApplicationController
include ActiveStorage::SetCurrent
respond_to :html
def create
@message = Message.new(message_params.merge(sender_id: current_user.id))
@notification = if @message.save
{ notice: 'Message successfully sent' }
else
{ alert: 'Message not sent: ' + @message.errors.full_messages.join(', ') }
end
respond_to do |format|
format.js
format.html { redirect_to redirect_to_url, @notification }
end
end
def download_attachment
raise 'No attachment present on this message' unless message.attachment.attached?
redirect_to message.attachment.blob.service_url(disposition: 'attachment')
end
private
def message
@message ||= Message.find(params[:id])
end
def redirect_to_url
method = "#{current_user.persona.class.to_s.pluralize.underscore}_claim_path"
__send__(method, @message.claim, messages: true) + '#claim-accordion'
end
def refresh_required?
Settings.claim_actions.include?(message_params[:claim_action])
end
def message_params
params.require(:message).permit(
:sender_id,
:claim_id,
:attachment,
:body,
:claim_action,
:written_reasons_submitted
)
end
end
|
[
"class",
"MessagesController",
"<",
"ApplicationController",
"include",
"ActiveStorage",
"::",
"SetCurrent",
"respond_to",
":html",
"def",
"create",
"@message",
"=",
"Message",
".",
"new",
"(",
"message_params",
".",
"merge",
"(",
"sender_id",
":",
"current_user",
".",
"id",
")",
")",
"@notification",
"=",
"if",
"@message",
".",
"save",
"{",
"notice",
":",
"'Message successfully sent'",
"}",
"else",
"{",
"alert",
":",
"'Message not sent: '",
"+",
"@message",
".",
"errors",
".",
"full_messages",
".",
"join",
"(",
"', '",
")",
"}",
"end",
"respond_to",
"do",
"|",
"format",
"|",
"format",
".",
"js",
"format",
".",
"html",
"{",
"redirect_to",
"redirect_to_url",
",",
"@notification",
"}",
"end",
"end",
"def",
"download_attachment",
"raise",
"'No attachment present on this message'",
"unless",
"message",
".",
"attachment",
".",
"attached?",
"redirect_to",
"message",
".",
"attachment",
".",
"blob",
".",
"service_url",
"(",
"disposition",
":",
"'attachment'",
")",
"end",
"private",
"def",
"message",
"@message",
"||=",
"Message",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"end",
"def",
"redirect_to_url",
"method",
"=",
"\"#{current_user.persona.class.to_s.pluralize.underscore}_claim_path\"",
"__send__",
"(",
"method",
",",
"@message",
".",
"claim",
",",
"messages",
":",
"true",
")",
"+",
"'#claim-accordion'",
"end",
"def",
"refresh_required?",
"Settings",
".",
"claim_actions",
".",
"include?",
"(",
"message_params",
"[",
":claim_action",
"]",
")",
"end",
"def",
"message_params",
"params",
".",
"require",
"(",
":message",
")",
".",
"permit",
"(",
":sender_id",
",",
":claim_id",
",",
":attachment",
",",
":body",
",",
":claim_action",
",",
":written_reasons_submitted",
")",
"end",
"end"
] |
Schema Information
Table name: messages
|
[
"Schema",
"Information",
"Table",
"name",
":",
"messages"
] |
[] |
[
{
"param": "ApplicationController",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ApplicationController",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 294
| 101
|
842299872220402e94ab4829ec232cc41d4f5419
|
rightscale/right_link
|
lib/clouds/metadata_formatters/flat_metadata_formatter.rb
|
[
"MIT"
] |
Ruby
|
RightScale
|
#
# Copyright (c) 2010-2011 RightScale Inc
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
|
[
"The",
"above",
"copyright",
"notice",
"and",
"this",
"permission",
"notice",
"shall",
"be",
"included",
"in",
"all",
"copies",
"or",
"substantial",
"portions",
"of",
"the",
"Software",
"."
] |
module RightScale
# Abstracts a formatter which maps one kind of metadata output to another.
class FlatMetadataFormatter
# RS_ is reserved for use by RightScale and should be avoided by users
# passing non-RightScale metadata to instances.
RS_METADATA_PREFIX = 'RS_'
attr_accessor :formatted_path_prefix
# Initializer.
#
# === Parameters
# options[:formatted_path_prefix](String):: default prefix for formatted metadata keys
def initialize(options = {})
# options
@formatted_path_prefix = options[:formatted_path_prefix] || RS_METADATA_PREFIX
end
# Formats a structured json blob such that sublevels in the structured json
# get translated to underscores, as in a hierarhical file system. i.e.
# Also prepend stuff with abbreviation
# { :a => { :b => "X", :c => "Y"}} would now be {"EC2_A_B" => "X", "EC2_A_C" => "Y"}
#
#
# === Parameters
# tree_metadata(Hash):: tree of raw metadata
#
# === Returns
# flat_metadata(Hash):: flattened metadata (one level hash)
def format(metadata)
return recursive_flatten_metadata(metadata)
end
def can_format?(metadata)
metadata.respond_to?(:has_key?)
end
protected
# Recursively flattens metadata.
#
# === Parameters
# tree_metadata(Hash):: metadata to flatten
# flat_metadata(Hash):: flattened metadata or {}
# metadata_path(Array):: array of metadata path elements or []
# path_index(int):: path array index to update or 0
#
# === Returns
# flat_metadata(Hash):: flattened metadata
def recursive_flatten_metadata(tree_metadata, flat_metadata = {}, metadata_path = [], path_index = 0)
unless tree_metadata.empty?
tree_metadata.each do |key, value|
metadata_path[path_index] = key
if value.respond_to?(:has_key?)
recursive_flatten_metadata(value, flat_metadata, metadata_path, path_index + 1)
else
flat_path = flatten_metadata_path(metadata_path)
flat_metadata[flat_path] = value
end
end
metadata_path.pop
raise "Unexpected path" unless metadata_path.size == path_index
end
return flat_metadata
end
# Flattens a sequence of metadata keys into a simple key string
# distinguishing the path to a value stored at some depth in a tree of
# metadata.
#
# === Parameters
# metadata_path(Array):: array of metadata path elements
#
# === Returns
# flat_path(String):: flattened path
def flatten_metadata_path(metadata_path)
flat_path = transform_path(metadata_path)
if @formatted_path_prefix && !(flat_path.start_with?(RS_METADATA_PREFIX) || flat_path.start_with?(@formatted_path_prefix))
return @formatted_path_prefix + flat_path
end
return flat_path
end
def transform_path(path)
path.join('_').gsub(/[\W,\/]/, '_').upcase
end
end # FlatMetadataFormatter
end
|
[
"module",
"RightScale",
"class",
"FlatMetadataFormatter",
"RS_METADATA_PREFIX",
"=",
"'RS_'",
"attr_accessor",
":formatted_path_prefix",
"def",
"initialize",
"(",
"options",
"=",
"{",
"}",
")",
"@formatted_path_prefix",
"=",
"options",
"[",
":formatted_path_prefix",
"]",
"||",
"RS_METADATA_PREFIX",
"end",
"def",
"format",
"(",
"metadata",
")",
"return",
"recursive_flatten_metadata",
"(",
"metadata",
")",
"end",
"def",
"can_format?",
"(",
"metadata",
")",
"metadata",
".",
"respond_to?",
"(",
":has_key?",
")",
"end",
"protected",
"def",
"recursive_flatten_metadata",
"(",
"tree_metadata",
",",
"flat_metadata",
"=",
"{",
"}",
",",
"metadata_path",
"=",
"[",
"]",
",",
"path_index",
"=",
"0",
")",
"unless",
"tree_metadata",
".",
"empty?",
"tree_metadata",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"metadata_path",
"[",
"path_index",
"]",
"=",
"key",
"if",
"value",
".",
"respond_to?",
"(",
":has_key?",
")",
"recursive_flatten_metadata",
"(",
"value",
",",
"flat_metadata",
",",
"metadata_path",
",",
"path_index",
"+",
"1",
")",
"else",
"flat_path",
"=",
"flatten_metadata_path",
"(",
"metadata_path",
")",
"flat_metadata",
"[",
"flat_path",
"]",
"=",
"value",
"end",
"end",
"metadata_path",
".",
"pop",
"raise",
"\"Unexpected path\"",
"unless",
"metadata_path",
".",
"size",
"==",
"path_index",
"end",
"return",
"flat_metadata",
"end",
"def",
"flatten_metadata_path",
"(",
"metadata_path",
")",
"flat_path",
"=",
"transform_path",
"(",
"metadata_path",
")",
"if",
"@formatted_path_prefix",
"&&",
"!",
"(",
"flat_path",
".",
"start_with?",
"(",
"RS_METADATA_PREFIX",
")",
"||",
"flat_path",
".",
"start_with?",
"(",
"@formatted_path_prefix",
")",
")",
"return",
"@formatted_path_prefix",
"+",
"flat_path",
"end",
"return",
"flat_path",
"end",
"def",
"transform_path",
"(",
"path",
")",
"path",
".",
"join",
"(",
"'_'",
")",
".",
"gsub",
"(",
"/",
"[",
"\\W",
",",
"\\/",
"]",
"/",
",",
"'_'",
")",
".",
"upcase",
"end",
"end",
"end"
] |
Copyright (c) 2010-2011 RightScale Inc
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
|
[
"Copyright",
"(",
"c",
")",
"2010",
"-",
"2011",
"RightScale",
"Inc",
"Permission",
"is",
"hereby",
"granted",
"free",
"of",
"charge",
"to",
"any",
"person",
"obtaining",
"a",
"copy",
"of",
"this",
"software",
"and",
"associated",
"documentation",
"files",
"(",
"the",
"\"",
"Software",
"\"",
")",
"to",
"deal",
"in",
"the",
"Software",
"without",
"restriction",
"including",
"without",
"limitation",
"the",
"rights",
"to",
"use",
"copy",
"modify",
"merge",
"publish",
"distribute",
"sublicense",
"and",
"/",
"or",
"sell",
"copies",
"of",
"the",
"Software",
"and",
"to",
"permit",
"persons",
"to",
"whom",
"the",
"Software",
"is",
"furnished",
"to",
"do",
"so",
"subject",
"to",
"the",
"following",
"conditions",
":"
] |
[
"# Abstracts a formatter which maps one kind of metadata output to another.",
"# RS_ is reserved for use by RightScale and should be avoided by users",
"# passing non-RightScale metadata to instances.",
"# Initializer.",
"#",
"# === Parameters",
"# options[:formatted_path_prefix](String):: default prefix for formatted metadata keys",
"# options",
"# Formats a structured json blob such that sublevels in the structured json",
"# get translated to underscores, as in a hierarhical file system. i.e.",
"# Also prepend stuff with abbreviation",
"# { :a => { :b => \"X\", :c => \"Y\"}} would now be {\"EC2_A_B\" => \"X\", \"EC2_A_C\" => \"Y\"}",
"#",
"#",
"# === Parameters",
"# tree_metadata(Hash):: tree of raw metadata",
"#",
"# === Returns",
"# flat_metadata(Hash):: flattened metadata (one level hash)",
"# Recursively flattens metadata.",
"#",
"# === Parameters",
"# tree_metadata(Hash):: metadata to flatten",
"# flat_metadata(Hash):: flattened metadata or {}",
"# metadata_path(Array):: array of metadata path elements or []",
"# path_index(int):: path array index to update or 0",
"#",
"# === Returns",
"# flat_metadata(Hash):: flattened metadata",
"# Flattens a sequence of metadata keys into a simple key string",
"# distinguishing the path to a value stored at some depth in a tree of",
"# metadata.",
"#",
"# === Parameters",
"# metadata_path(Array):: array of metadata path elements",
"#",
"# === Returns",
"# flat_path(String):: flattened path",
"# FlatMetadataFormatter"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 687
| 242
|
ca71d3ecc2152460beaba0913174759242cc03d4
|
Steven9Smith/Mixamo-For-Unity-DOTS
|
Assets/Scenes/Advanced/InertialMotionBlending/TransitionNode.cs
|
[
"MIT"
] |
C#
|
WeightAccumulatorNode
|
/// <summary>
/// Returns a weight to ensure a smooth transition with a duration
/// We need a specific node to make the weight move like the inertial motion blending node,
/// Essentially the weight moves towards 1 (with a speed depending on duration) and when ChangeClip
/// is set, the weight starts moving towards 0. If ChangeClip is set again the weight starts moving
/// towards 1 again.
/// </summary>
|
Returns a weight to ensure a smooth transition with a duration
We need a specific node to make the weight move like the inertial motion blending node,
Essentially the weight moves towards 1 (with a speed depending on duration) and when ChangeClip
is set, the weight starts moving towards 0. If ChangeClip is set again the weight starts moving
towards 1 again.
|
[
"Returns",
"a",
"weight",
"to",
"ensure",
"a",
"smooth",
"transition",
"with",
"a",
"duration",
"We",
"need",
"a",
"specific",
"node",
"to",
"make",
"the",
"weight",
"move",
"like",
"the",
"inertial",
"motion",
"blending",
"node",
"Essentially",
"the",
"weight",
"moves",
"towards",
"1",
"(",
"with",
"a",
"speed",
"depending",
"on",
"duration",
")",
"and",
"when",
"ChangeClip",
"is",
"set",
"the",
"weight",
"starts",
"moving",
"towards",
"0",
".",
"If",
"ChangeClip",
"is",
"set",
"again",
"the",
"weight",
"starts",
"moving",
"towards",
"1",
"again",
"."
] |
public class WeightAccumulatorNode
: SimulationKernelNodeDefinition<WeightAccumulatorNode.SimPorts, WeightAccumulatorNode.KernelDefs>
{
public struct SimPorts : ISimulationPortDefinition
{
public MessageInput<WeightAccumulatorNode, float> Duration;
public MessageInput<WeightAccumulatorNode, bool> ClipSource;
}
public struct KernelDefs : IKernelPortDefinition
{
public DataInput<WeightAccumulatorNode, float> DeltaTime;
public DataOutput<WeightAccumulatorNode, float> BlendWeight;
}
struct Data
: INodeData
, IInit
, IMsgHandler<float>
, IMsgHandler<bool>
{
float m_Duration;
bool m_Target;
public void Init(InitContext ctx)
{
m_Duration = 1;
ctx.UpdateKernelData(RecalculateSpeed());
}
public void HandleMessage(MessageContext ctx, in float msg)
{
m_Duration = msg;
ctx.UpdateKernelData(RecalculateSpeed());
}
public void HandleMessage(MessageContext ctx, in bool msg)
{
m_Target = msg;
ctx.UpdateKernelData(RecalculateSpeed());
}
KernelData RecalculateSpeed() =>
new KernelData { Speed = math.select(-1, 1, m_Target) / m_Duration };
}
struct KernelData : IKernelData
{
public float Speed;
}
struct Kernel : IGraphKernel<KernelData, KernelDefs>
{
public void Execute(RenderContext ctx, in KernelData data, ref KernelDefs ports)
{
var deltaWeight = data.Speed * ctx.Resolve(ports.DeltaTime);
ref var blendWeight = ref ctx.Resolve(ref ports.BlendWeight);
blendWeight = math.clamp(blendWeight + deltaWeight, 0, 1);
}
}
}
|
[
"public",
"class",
"WeightAccumulatorNode",
":",
"SimulationKernelNodeDefinition",
"<",
"WeightAccumulatorNode",
".",
"SimPorts",
",",
"WeightAccumulatorNode",
".",
"KernelDefs",
">",
"{",
"public",
"struct",
"SimPorts",
":",
"ISimulationPortDefinition",
"{",
"public",
"MessageInput",
"<",
"WeightAccumulatorNode",
",",
"float",
">",
"Duration",
";",
"public",
"MessageInput",
"<",
"WeightAccumulatorNode",
",",
"bool",
">",
"ClipSource",
";",
"}",
"public",
"struct",
"KernelDefs",
":",
"IKernelPortDefinition",
"{",
"public",
"DataInput",
"<",
"WeightAccumulatorNode",
",",
"float",
">",
"DeltaTime",
";",
"public",
"DataOutput",
"<",
"WeightAccumulatorNode",
",",
"float",
">",
"BlendWeight",
";",
"}",
"struct",
"Data",
":",
"INodeData",
",",
"IInit",
",",
"IMsgHandler",
"<",
"float",
">",
",",
"IMsgHandler",
"<",
"bool",
">",
"{",
"float",
"m_Duration",
";",
"bool",
"m_Target",
";",
"public",
"void",
"Init",
"(",
"InitContext",
"ctx",
")",
"{",
"m_Duration",
"=",
"1",
";",
"ctx",
".",
"UpdateKernelData",
"(",
"RecalculateSpeed",
"(",
")",
")",
";",
"}",
"public",
"void",
"HandleMessage",
"(",
"MessageContext",
"ctx",
",",
"in",
"float",
"msg",
")",
"{",
"m_Duration",
"=",
"msg",
";",
"ctx",
".",
"UpdateKernelData",
"(",
"RecalculateSpeed",
"(",
")",
")",
";",
"}",
"public",
"void",
"HandleMessage",
"(",
"MessageContext",
"ctx",
",",
"in",
"bool",
"msg",
")",
"{",
"m_Target",
"=",
"msg",
";",
"ctx",
".",
"UpdateKernelData",
"(",
"RecalculateSpeed",
"(",
")",
")",
";",
"}",
"KernelData",
"RecalculateSpeed",
"(",
")",
"=>",
"new",
"KernelData",
"{",
"Speed",
"=",
"math",
".",
"select",
"(",
"-",
"1",
",",
"1",
",",
"m_Target",
")",
"/",
"m_Duration",
"}",
";",
"}",
"struct",
"KernelData",
":",
"IKernelData",
"{",
"public",
"float",
"Speed",
";",
"}",
"struct",
"Kernel",
":",
"IGraphKernel",
"<",
"KernelData",
",",
"KernelDefs",
">",
"{",
"public",
"void",
"Execute",
"(",
"RenderContext",
"ctx",
",",
"in",
"KernelData",
"data",
",",
"ref",
"KernelDefs",
"ports",
")",
"{",
"var",
"deltaWeight",
"=",
"data",
".",
"Speed",
"*",
"ctx",
".",
"Resolve",
"(",
"ports",
".",
"DeltaTime",
")",
";",
"ref",
"var",
"blendWeight",
"=",
"ref",
"ctx",
".",
"Resolve",
"(",
"ref",
"ports",
".",
"BlendWeight",
")",
";",
"blendWeight",
"=",
"math",
".",
"clamp",
"(",
"blendWeight",
"+",
"deltaWeight",
",",
"0",
",",
"1",
")",
";",
"}",
"}",
"}"
] |
Returns a weight to ensure a smooth transition with a duration
We need a specific node to make the weight move like the inertial motion blending node,
Essentially the weight moves towards 1 (with a speed depending on duration) and when ChangeClip
is set, the weight starts moving towards 0.
|
[
"Returns",
"a",
"weight",
"to",
"ensure",
"a",
"smooth",
"transition",
"with",
"a",
"duration",
"We",
"need",
"a",
"specific",
"node",
"to",
"make",
"the",
"weight",
"move",
"like",
"the",
"inertial",
"motion",
"blending",
"node",
"Essentially",
"the",
"weight",
"moves",
"towards",
"1",
"(",
"with",
"a",
"speed",
"depending",
"on",
"duration",
")",
"and",
"when",
"ChangeClip",
"is",
"set",
"the",
"weight",
"starts",
"moving",
"towards",
"0",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 410
| 90
|
0b522b72f590b261d8fe0cb959df2a3dbec974c8
|
absolunet/node-ioc
|
src/http/HttpServiceProvider.js
|
[
"MIT"
] |
JavaScript
|
HttpServiceProvider
|
/**
* The HTTP service provider.
* It bind these following services:
* <ul>
* <li><a href="http.services.Client.html">http</a></li>
* <li><a href="http.services.Server.html">server</a></li>
* <li><a href="http.services.Router.html">router</a></li>
* <li><a href="http.services.Handler.html">router.handler</a></li>
* <li><a href="http.services.HttpErrorMapper.html">http.error.mapper</a></li>
* <li><a href="http.repositories.RouteRepository.html">router.route</a></li>
* <li><a href="http.repositories.ControllerRepository.html">route.controller</a></li>
* </ul>
* It also offers these commands:
* <ul>
* <li><a href="http.commands.MakeControllerCommand.html">make:controller</a></li>
* <li><a href="http.commands.ServeCommand.html">serve</a></li>
* </ul>
* It also uses configuration under "http" namespace.
*
* @memberof http
* @augments foundation.ServiceProvider
* @hideconstructor
*/
|
The HTTP service provider.
It bind these following services:
http
server
router
router.handler
http.error.mapper
router.route
route.controller
It also offers these commands:
make:controller
serve
It also uses configuration under "http" namespace.
@memberof http
@augments foundation.ServiceProvider
@hideconstructor
|
[
"The",
"HTTP",
"service",
"provider",
".",
"It",
"bind",
"these",
"following",
"services",
":",
"http",
"server",
"router",
"router",
".",
"handler",
"http",
".",
"error",
".",
"mapper",
"router",
".",
"route",
"route",
".",
"controller",
"It",
"also",
"offers",
"these",
"commands",
":",
"make",
":",
"controller",
"serve",
"It",
"also",
"uses",
"configuration",
"under",
"\"",
"http",
"\"",
"namespace",
".",
"@memberof",
"http",
"@augments",
"foundation",
".",
"ServiceProvider",
"@hideconstructor"
] |
class HttpServiceProvider extends ServiceProvider {
/**
* @inheritdoc
*/
get name() {
return 'Node IoC - HTTP';
}
/**
* Register the service provider.
*/
register() {
this.loadAndPublishConfig(this.app.formatPath(__dirname, 'config'));
this.bindHttpClient();
this.bindHttpServer();
this.bindRouter();
this.bindRouteHandler();
this.bindHttpErrorMapper();
this.bindRouteRepository();
this.bindControllerRepository();
}
/**
* Boot the service provider.
*/
boot() {
this.createPolicies();
this.bootDefaultControllers();
this.loadCommands([
MakeControllerCommand,
ServeCommand
]);
}
/**
* Bind HTTP client service.
*/
bindHttpClient() {
this.app.singleton('http', HttpClient);
}
/**
* Bind HTTP server service.
*/
bindHttpServer() {
this.app.singleton('server', HttpServer);
}
/**
* Bind HTTP router.
*/
bindRouter() {
this.app.singleton('router', Router);
}
/**
* Bind router handler service.
*/
bindRouteHandler() {
this.app.singleton('router.handler', Handler);
}
/**
* Bind HTTP error mapper.
*/
bindHttpErrorMapper() {
this.app.singleton('http.error.mapper', HttpErrorMapper);
}
/**
* Bind route repository.
*/
bindRouteRepository() {
this.app.singleton('router.route', RouteRepository);
}
/**
* Bind controller repository.
*/
bindControllerRepository() {
this.app.singleton('router.controller', ControllerRepository);
}
/**
* Create database related policies.
*/
createPolicies() {
if (this.app.isBound('gate')) {
this.app.make('gate')
.policy('http', () => {
return this.app.make('config').get('http.enabled', false);
});
}
}
/**
* Boot the default controllers.
*/
bootDefaultControllers() {
const controllerRepository = this.app.make('router.controller');
controllerRepository.group(controllerRepository.coreNamespace, () => {
controllerRepository.add('StaticController', StaticController);
controllerRepository.add('RedirectController', RedirectController);
});
}
}
|
[
"class",
"HttpServiceProvider",
"extends",
"ServiceProvider",
"{",
"get",
"name",
"(",
")",
"{",
"return",
"'Node IoC - HTTP'",
";",
"}",
"register",
"(",
")",
"{",
"this",
".",
"loadAndPublishConfig",
"(",
"this",
".",
"app",
".",
"formatPath",
"(",
"__dirname",
",",
"'config'",
")",
")",
";",
"this",
".",
"bindHttpClient",
"(",
")",
";",
"this",
".",
"bindHttpServer",
"(",
")",
";",
"this",
".",
"bindRouter",
"(",
")",
";",
"this",
".",
"bindRouteHandler",
"(",
")",
";",
"this",
".",
"bindHttpErrorMapper",
"(",
")",
";",
"this",
".",
"bindRouteRepository",
"(",
")",
";",
"this",
".",
"bindControllerRepository",
"(",
")",
";",
"}",
"boot",
"(",
")",
"{",
"this",
".",
"createPolicies",
"(",
")",
";",
"this",
".",
"bootDefaultControllers",
"(",
")",
";",
"this",
".",
"loadCommands",
"(",
"[",
"MakeControllerCommand",
",",
"ServeCommand",
"]",
")",
";",
"}",
"bindHttpClient",
"(",
")",
"{",
"this",
".",
"app",
".",
"singleton",
"(",
"'http'",
",",
"HttpClient",
")",
";",
"}",
"bindHttpServer",
"(",
")",
"{",
"this",
".",
"app",
".",
"singleton",
"(",
"'server'",
",",
"HttpServer",
")",
";",
"}",
"bindRouter",
"(",
")",
"{",
"this",
".",
"app",
".",
"singleton",
"(",
"'router'",
",",
"Router",
")",
";",
"}",
"bindRouteHandler",
"(",
")",
"{",
"this",
".",
"app",
".",
"singleton",
"(",
"'router.handler'",
",",
"Handler",
")",
";",
"}",
"bindHttpErrorMapper",
"(",
")",
"{",
"this",
".",
"app",
".",
"singleton",
"(",
"'http.error.mapper'",
",",
"HttpErrorMapper",
")",
";",
"}",
"bindRouteRepository",
"(",
")",
"{",
"this",
".",
"app",
".",
"singleton",
"(",
"'router.route'",
",",
"RouteRepository",
")",
";",
"}",
"bindControllerRepository",
"(",
")",
"{",
"this",
".",
"app",
".",
"singleton",
"(",
"'router.controller'",
",",
"ControllerRepository",
")",
";",
"}",
"createPolicies",
"(",
")",
"{",
"if",
"(",
"this",
".",
"app",
".",
"isBound",
"(",
"'gate'",
")",
")",
"{",
"this",
".",
"app",
".",
"make",
"(",
"'gate'",
")",
".",
"policy",
"(",
"'http'",
",",
"(",
")",
"=>",
"{",
"return",
"this",
".",
"app",
".",
"make",
"(",
"'config'",
")",
".",
"get",
"(",
"'http.enabled'",
",",
"false",
")",
";",
"}",
")",
";",
"}",
"}",
"bootDefaultControllers",
"(",
")",
"{",
"const",
"controllerRepository",
"=",
"this",
".",
"app",
".",
"make",
"(",
"'router.controller'",
")",
";",
"controllerRepository",
".",
"group",
"(",
"controllerRepository",
".",
"coreNamespace",
",",
"(",
")",
"=>",
"{",
"controllerRepository",
".",
"add",
"(",
"'StaticController'",
",",
"StaticController",
")",
";",
"controllerRepository",
".",
"add",
"(",
"'RedirectController'",
",",
"RedirectController",
")",
";",
"}",
")",
";",
"}",
"}"
] |
The HTTP service provider.
|
[
"The",
"HTTP",
"service",
"provider",
"."
] |
[
"/**\n\t * @inheritdoc\n\t */",
"/**\n\t * Register the service provider.\n\t */",
"/**\n\t * Boot the service provider.\n\t */",
"/**\n\t * Bind HTTP client service.\n\t */",
"/**\n\t * Bind HTTP server service.\n\t */",
"/**\n\t * Bind HTTP router.\n\t */",
"/**\n\t * Bind router handler service.\n\t */",
"/**\n\t * Bind HTTP error mapper.\n\t */",
"/**\n\t * Bind route repository.\n\t */",
"/**\n\t * Bind controller repository.\n\t */",
"/**\n\t * Create database related policies.\n\t */",
"/**\n\t * Boot the default controllers.\n\t */"
] |
[
{
"param": "ServiceProvider",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ServiceProvider",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 18
| 488
| 253
|
aa358cc54984a60edd16b49c491b8e98c3ba6086
|
Laura7089/GOF2BountyBot
|
BB/scheduling/TimedTask.py
|
[
"MIT"
] |
Python
|
TimedTask
|
A fairly generic class that, at its core, tracks when a requested amount of time has passed.
Using an expiryFunction, a function call may be delayed by a given amount of time.
Using autoRescheduling, this class can also be used to easily schedule reoccurring tasks.
At least one of expiryTime or expiryDelta must be given.
If the task is set to autoReschedule, issueTime is updated to show the task's current rescheduling time.
:var issueTime: The datetime when this task was created.
:vartype issueTime: datetime.datetime
:var expiryTime: The datetime when this task should expire.
:vartype expiryTime: datetime.datetime
:var expiryDelta: The timedelta to add to issueTime, to find the expiryTime.
:vartype expiryDelta: datetime.timedelta
:var expiryFunction: The function to call once expiryTime has been reached/surpassed.
:vartype expiryFunction: function
:var hasExpiryFunction: Whether or not the task has an expiry function to call
:vartype hasExpiryFunction: bool
:var expiryFunctionArgs: The data to pass to the expiryFunction. There is no type requirement, but a dictionary is recommended as a close representation of KWArgs.
:var hasExpiryFunctionArgs: Whether or not expiryFunction contains anything and should be passed to expiryFunction
:vartype hasExpiryFunctionArgs: bool
:var autoReschedule: Whether or not this task should automatically reschedule itself by the same timedelta.
:vartype autoReschedule: bool
:var gravestone: marked as True when the TimedTask will no longer execute and can be removed from any TimedTask heap. I.e, it is expired (whether manually or through timeout) and does not auto-reschedule
:vartype gravestone: bool
:var asyncExpiryFunction: whether or not the expiryFunction is a coroutine and needs to be awaited
:vartype asyncExpiryFunction: bool
|
A fairly generic class that, at its core, tracks when a requested amount of time has passed.
Using an expiryFunction, a function call may be delayed by a given amount of time.
Using autoRescheduling, this class can also be used to easily schedule reoccurring tasks.
At least one of expiryTime or expiryDelta must be given.
If the task is set to autoReschedule, issueTime is updated to show the task's current rescheduling time.
|
[
"A",
"fairly",
"generic",
"class",
"that",
"at",
"its",
"core",
"tracks",
"when",
"a",
"requested",
"amount",
"of",
"time",
"has",
"passed",
".",
"Using",
"an",
"expiryFunction",
"a",
"function",
"call",
"may",
"be",
"delayed",
"by",
"a",
"given",
"amount",
"of",
"time",
".",
"Using",
"autoRescheduling",
"this",
"class",
"can",
"also",
"be",
"used",
"to",
"easily",
"schedule",
"reoccurring",
"tasks",
".",
"At",
"least",
"one",
"of",
"expiryTime",
"or",
"expiryDelta",
"must",
"be",
"given",
".",
"If",
"the",
"task",
"is",
"set",
"to",
"autoReschedule",
"issueTime",
"is",
"updated",
"to",
"show",
"the",
"task",
"'",
"s",
"current",
"rescheduling",
"time",
"."
] |
class TimedTask:
"""A fairly generic class that, at its core, tracks when a requested amount of time has passed.
Using an expiryFunction, a function call may be delayed by a given amount of time.
Using autoRescheduling, this class can also be used to easily schedule reoccurring tasks.
At least one of expiryTime or expiryDelta must be given.
If the task is set to autoReschedule, issueTime is updated to show the task's current rescheduling time.
:var issueTime: The datetime when this task was created.
:vartype issueTime: datetime.datetime
:var expiryTime: The datetime when this task should expire.
:vartype expiryTime: datetime.datetime
:var expiryDelta: The timedelta to add to issueTime, to find the expiryTime.
:vartype expiryDelta: datetime.timedelta
:var expiryFunction: The function to call once expiryTime has been reached/surpassed.
:vartype expiryFunction: function
:var hasExpiryFunction: Whether or not the task has an expiry function to call
:vartype hasExpiryFunction: bool
:var expiryFunctionArgs: The data to pass to the expiryFunction. There is no type requirement, but a dictionary is recommended as a close representation of KWArgs.
:var hasExpiryFunctionArgs: Whether or not expiryFunction contains anything and should be passed to expiryFunction
:vartype hasExpiryFunctionArgs: bool
:var autoReschedule: Whether or not this task should automatically reschedule itself by the same timedelta.
:vartype autoReschedule: bool
:var gravestone: marked as True when the TimedTask will no longer execute and can be removed from any TimedTask heap. I.e, it is expired (whether manually or through timeout) and does not auto-reschedule
:vartype gravestone: bool
:var asyncExpiryFunction: whether or not the expiryFunction is a coroutine and needs to be awaited
:vartype asyncExpiryFunction: bool
"""
def __init__(self, issueTime=None, expiryTime=None, expiryDelta=None, expiryFunction=None, expiryFunctionArgs={}, autoReschedule=False):
"""
:param datetime.datetime issueTime: The datetime when this task was created. (Default now)
:param datetime.datetime expiryTime: The datetime when this task should expire. (Default None)
:param datetime.timedelta expiryDelta: The timedelta to add to issueTime, to find the expiryTime. (Default None)
:param function expiryFunction: The function to call once expiryTime has been reached/surpassed. (Default None)
:param expiryFunctionArgs: The data to pass to the expiryFunction. There is no type requirement, but a dictionary is recommended as a close representation of KWArgs. (Default {})
:param bool autoReschedule: Whether or not this task should automatically reschedule itself by the same timedelta. (Default False)
"""
# Ensure that at least one of expiryTime or expiryDelta is specified
if expiryTime is None and expiryDelta is None:
raise ValueError("No expiry time given, both expiryTime and expiryDelta are None")
# Calculate issueTime as now if none is given
self.issueTime = datetime.utcnow() if issueTime is None else issueTime
# Calculate expiryTime as issueTime + expiryDelta if none is given
self.expiryTime = self.issueTime + expiryDelta if expiryTime is None else expiryTime
# Calculate expiryDelta as expiryTime - issueTime if none is given. This is needed for rescheduling.
self.expiryDelta = self.expiryTime - self.issueTime if expiryDelta is None else expiryDelta
self.expiryFunction = expiryFunction
self.hasExpiryFunction = expiryFunction is not None
self.expiryFunctionArgs = expiryFunctionArgs
self.hasExpiryFunctionArgs = expiryFunctionArgs != {}
self.autoReschedule = autoReschedule
# A task's 'gravestone' is marked as True when the TimedTask will no longer execute and can be removed from any TimedTask heap.
# I.e, it is expired (whether manually or through timeout) and does not auto-reschedule.
self.gravestone = False
# Track whether or not the expiryFunction is a coroutine and needs to be awaited
self.asyncExpiryFunction = inspect.iscoroutinefunction(expiryFunction)
def __lt__(self, other : TimedTask) -> bool:
"""< Overload, to be used in TimedTask heaps.
The other object must be a TimedTask. Compares only the expiryTimes of the two tasks.
:param TimedTask other: other TimedTask to compare against.
:return: True if this TimedTask's expiryTime is < other's expiryTime, False otherwise.
:rtype: bool
"""
if not isinstance(other, TimedTask):
raise TypeError("< error: TimedTask can only be compared to other TimedTasks")
return self.expiryTime < other.expiryTime
def __gt__(self, other : TimedTask) -> bool:
"""> Overload, to be used in TimedTask heaps.
The other object must be a TimedTask. Compares only the expiryTimes of the two tasks.
:param TimedTask other: other TimedTask to compare against.
:return: True if this TimedTask's expiryTime is > other's expiryTime, False otherwise.
:rtype: bool
"""
if not isinstance(other, TimedTask):
raise TypeError("> error: TimedTask can only be compared to other TimedTasks")
return self.expiryTime > other.expiryTime
def __lte__(self, other : TimedTask) -> bool:
"""<= Overload, to be used in TimedTask heaps.
The other object must be a TimedTask. Compares only the expiryTimes of the two tasks.
:param TimedTask other: other TimedTask to compare against.
:return: True if this TimedTask's expiryTime is <= other's expiryTime, False otherwise.
:rtype: bool
"""
if not isinstance(other, TimedTask):
raise TypeError("<= error: TimedTask can only be compared to other TimedTasks")
return self.expiryTime <= other.expiryTime
def __gte__(self, other : TimedTask) -> bool:
""">= Overload, to be used in TimedTask heaps.
The other object must be a TimedTask. Compares only the expiryTimes of the two tasks.
:param TimedTask other: other TimedTask to compare against.
:return: True if this TimedTask's expiryTime is >= other's expiryTime, False otherwise.
:rtype: bool
"""
if not isinstance(other, TimedTask):
raise TypeError(">= error: TimedTask can only be compared to other TimedTasks")
return self.expiryTime >= other.expiryTime
def isExpired(self) -> bool:
"""Decide whether or not this task has expired.
This can be due to reaching the task's expiryTime, or due to manual expiry.
:return: True if this timedTask has been manually expired, or has reached its expiryTime. False otherwise
:rtype: bool
"""
self.gravestone = self.gravestone or self.expiryTime <= datetime.utcnow()
return self.gravestone
async def callExpiryFunction(self):
"""Call the task's expiryFunction, if one is specified.
Handles passing of arguments to the expiryFunction, if specified.
:return: the results of the expiryFunction
"""
if self.asyncExpiryFunction:
if self.hasExpiryFunctionArgs:
return await self.expiryFunction(self.expiryFunctionArgs)
else:
return await self.expiryFunction()
else:
if self.hasExpiryFunctionArgs:
return self.expiryFunction(self.expiryFunctionArgs)
else:
return self.expiryFunction()
async def doExpiryCheck(self, callExpiryFunc=True) -> bool:
"""Function to be called regularly, that handles the expiry of this task.
Handles calling of the task's expiry function if specified, and rescheduling of the task if specified.
:param bool callExpiryFunc: Whether or not to call this task's expiryFunction if it is expired. Default: True
:return: True if this task is expired in this check, False otherwise. Regardless of autorescheduling.
:rtype: bool
"""
expired = self.isExpired()
# If the task has expired, call expiry function and reschedule if specified
if expired:
if callExpiryFunc and self.hasExpiryFunction:
await self.callExpiryFunction()
if self.autoReschedule:
await self.reschedule()
return expired
async def reschedule(self, expiryTime=None, expiryDelta=None):
"""Reschedule this task, with the timedelta given/calculated on the task's creation, or to a given expiryTime/Delta.
Rescheduling will update the task's issueTime to now. TODO: A firstIssueTime may be useful in the future to represent creation time.
Giving an expiryTime or expiryDelta will not update the task's stored expiryDelta. I.e, if the task is rescheduled again without giving an expiryDelta,
The expiryDelta given/calculated on the task's creation will be used.
If both an expiryTime and an expiryDelta is given, the expiryTime takes precedence.
:param datetime.datetime expiryTime: The new expiry time for the task. Default: now + expiryTime if expiryTime is specified, now + self.expiryTime otherwise
:param datetime.timedelta expiryDelta: The amount of time to wait until the task's next expiry. Default: now + self.expiryTime
"""
# Update the task's issueTime to now
self.issueTime = datetime.utcnow()
# Create the new expiryTime from now + expirydelta
self.expiryTime = self.issueTime + (self.expiryDelta if expiryDelta is None else expiryDelta) if expiryTime is None else expiryTime
# reset the gravestone to False, in case the task had been expired and marked for removal
self.gravestone = False
async def forceExpire(self, callExpiryFunc=True):
"""Force the expiry of this task.
Handles calling of this task's expiryFunction, and rescheduling if specified. Set's the task's expiryTime to now.
:param bool callExpiryFunction: Whether or not to call the task's expiryFunction if the task expires. Default: True
:return: The result of the expiry function, if it is called
"""
# Update expiryTime
self.expiryTime = datetime.utcnow()
# Call expiryFunction and reschedule if specified
if callExpiryFunc and self.hasExpiryFunction:
expiryFuncResults = await self.callExpiryFunction()
if self.autoReschedule:
await self.reschedule()
# Mark for removal if not rescheduled
else:
self.gravestone = True
# Return expiry function results
if callExpiryFunc and self.hasExpiryFunction:
return expiryFuncResults
|
[
"class",
"TimedTask",
":",
"def",
"__init__",
"(",
"self",
",",
"issueTime",
"=",
"None",
",",
"expiryTime",
"=",
"None",
",",
"expiryDelta",
"=",
"None",
",",
"expiryFunction",
"=",
"None",
",",
"expiryFunctionArgs",
"=",
"{",
"}",
",",
"autoReschedule",
"=",
"False",
")",
":",
"\"\"\"\n :param datetime.datetime issueTime: The datetime when this task was created. (Default now)\n :param datetime.datetime expiryTime: The datetime when this task should expire. (Default None)\n :param datetime.timedelta expiryDelta: The timedelta to add to issueTime, to find the expiryTime. (Default None)\n :param function expiryFunction: The function to call once expiryTime has been reached/surpassed. (Default None)\n :param expiryFunctionArgs: The data to pass to the expiryFunction. There is no type requirement, but a dictionary is recommended as a close representation of KWArgs. (Default {})\n :param bool autoReschedule: Whether or not this task should automatically reschedule itself by the same timedelta. (Default False)\n \"\"\"",
"if",
"expiryTime",
"is",
"None",
"and",
"expiryDelta",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"No expiry time given, both expiryTime and expiryDelta are None\"",
")",
"self",
".",
"issueTime",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"issueTime",
"is",
"None",
"else",
"issueTime",
"self",
".",
"expiryTime",
"=",
"self",
".",
"issueTime",
"+",
"expiryDelta",
"if",
"expiryTime",
"is",
"None",
"else",
"expiryTime",
"self",
".",
"expiryDelta",
"=",
"self",
".",
"expiryTime",
"-",
"self",
".",
"issueTime",
"if",
"expiryDelta",
"is",
"None",
"else",
"expiryDelta",
"self",
".",
"expiryFunction",
"=",
"expiryFunction",
"self",
".",
"hasExpiryFunction",
"=",
"expiryFunction",
"is",
"not",
"None",
"self",
".",
"expiryFunctionArgs",
"=",
"expiryFunctionArgs",
"self",
".",
"hasExpiryFunctionArgs",
"=",
"expiryFunctionArgs",
"!=",
"{",
"}",
"self",
".",
"autoReschedule",
"=",
"autoReschedule",
"self",
".",
"gravestone",
"=",
"False",
"self",
".",
"asyncExpiryFunction",
"=",
"inspect",
".",
"iscoroutinefunction",
"(",
"expiryFunction",
")",
"def",
"__lt__",
"(",
"self",
",",
"other",
":",
"TimedTask",
")",
"->",
"bool",
":",
"\"\"\"< Overload, to be used in TimedTask heaps.\n The other object must be a TimedTask. Compares only the expiryTimes of the two tasks.\n\n :param TimedTask other: other TimedTask to compare against.\n :return: True if this TimedTask's expiryTime is < other's expiryTime, False otherwise. \n :rtype: bool\n \"\"\"",
"if",
"not",
"isinstance",
"(",
"other",
",",
"TimedTask",
")",
":",
"raise",
"TypeError",
"(",
"\"< error: TimedTask can only be compared to other TimedTasks\"",
")",
"return",
"self",
".",
"expiryTime",
"<",
"other",
".",
"expiryTime",
"def",
"__gt__",
"(",
"self",
",",
"other",
":",
"TimedTask",
")",
"->",
"bool",
":",
"\"\"\"> Overload, to be used in TimedTask heaps.\n The other object must be a TimedTask. Compares only the expiryTimes of the two tasks.\n\n :param TimedTask other: other TimedTask to compare against.\n :return: True if this TimedTask's expiryTime is > other's expiryTime, False otherwise. \n :rtype: bool\n \"\"\"",
"if",
"not",
"isinstance",
"(",
"other",
",",
"TimedTask",
")",
":",
"raise",
"TypeError",
"(",
"\"> error: TimedTask can only be compared to other TimedTasks\"",
")",
"return",
"self",
".",
"expiryTime",
">",
"other",
".",
"expiryTime",
"def",
"__lte__",
"(",
"self",
",",
"other",
":",
"TimedTask",
")",
"->",
"bool",
":",
"\"\"\"<= Overload, to be used in TimedTask heaps.\n The other object must be a TimedTask. Compares only the expiryTimes of the two tasks.\n\n :param TimedTask other: other TimedTask to compare against.\n :return: True if this TimedTask's expiryTime is <= other's expiryTime, False otherwise. \n :rtype: bool\n \"\"\"",
"if",
"not",
"isinstance",
"(",
"other",
",",
"TimedTask",
")",
":",
"raise",
"TypeError",
"(",
"\"<= error: TimedTask can only be compared to other TimedTasks\"",
")",
"return",
"self",
".",
"expiryTime",
"<=",
"other",
".",
"expiryTime",
"def",
"__gte__",
"(",
"self",
",",
"other",
":",
"TimedTask",
")",
"->",
"bool",
":",
"\"\"\">= Overload, to be used in TimedTask heaps.\n The other object must be a TimedTask. Compares only the expiryTimes of the two tasks.\n\n :param TimedTask other: other TimedTask to compare against.\n :return: True if this TimedTask's expiryTime is >= other's expiryTime, False otherwise. \n :rtype: bool\n \"\"\"",
"if",
"not",
"isinstance",
"(",
"other",
",",
"TimedTask",
")",
":",
"raise",
"TypeError",
"(",
"\">= error: TimedTask can only be compared to other TimedTasks\"",
")",
"return",
"self",
".",
"expiryTime",
">=",
"other",
".",
"expiryTime",
"def",
"isExpired",
"(",
"self",
")",
"->",
"bool",
":",
"\"\"\"Decide whether or not this task has expired.\n This can be due to reaching the task's expiryTime, or due to manual expiry.\n\n :return: True if this timedTask has been manually expired, or has reached its expiryTime. False otherwise\n :rtype: bool\n \"\"\"",
"self",
".",
"gravestone",
"=",
"self",
".",
"gravestone",
"or",
"self",
".",
"expiryTime",
"<=",
"datetime",
".",
"utcnow",
"(",
")",
"return",
"self",
".",
"gravestone",
"async",
"def",
"callExpiryFunction",
"(",
"self",
")",
":",
"\"\"\"Call the task's expiryFunction, if one is specified.\n Handles passing of arguments to the expiryFunction, if specified.\n\n :return: the results of the expiryFunction\n \"\"\"",
"if",
"self",
".",
"asyncExpiryFunction",
":",
"if",
"self",
".",
"hasExpiryFunctionArgs",
":",
"return",
"await",
"self",
".",
"expiryFunction",
"(",
"self",
".",
"expiryFunctionArgs",
")",
"else",
":",
"return",
"await",
"self",
".",
"expiryFunction",
"(",
")",
"else",
":",
"if",
"self",
".",
"hasExpiryFunctionArgs",
":",
"return",
"self",
".",
"expiryFunction",
"(",
"self",
".",
"expiryFunctionArgs",
")",
"else",
":",
"return",
"self",
".",
"expiryFunction",
"(",
")",
"async",
"def",
"doExpiryCheck",
"(",
"self",
",",
"callExpiryFunc",
"=",
"True",
")",
"->",
"bool",
":",
"\"\"\"Function to be called regularly, that handles the expiry of this task.\n Handles calling of the task's expiry function if specified, and rescheduling of the task if specified.\n\n :param bool callExpiryFunc: Whether or not to call this task's expiryFunction if it is expired. Default: True\n :return: True if this task is expired in this check, False otherwise. Regardless of autorescheduling.\n :rtype: bool\n \"\"\"",
"expired",
"=",
"self",
".",
"isExpired",
"(",
")",
"if",
"expired",
":",
"if",
"callExpiryFunc",
"and",
"self",
".",
"hasExpiryFunction",
":",
"await",
"self",
".",
"callExpiryFunction",
"(",
")",
"if",
"self",
".",
"autoReschedule",
":",
"await",
"self",
".",
"reschedule",
"(",
")",
"return",
"expired",
"async",
"def",
"reschedule",
"(",
"self",
",",
"expiryTime",
"=",
"None",
",",
"expiryDelta",
"=",
"None",
")",
":",
"\"\"\"Reschedule this task, with the timedelta given/calculated on the task's creation, or to a given expiryTime/Delta.\n Rescheduling will update the task's issueTime to now. TODO: A firstIssueTime may be useful in the future to represent creation time.\n Giving an expiryTime or expiryDelta will not update the task's stored expiryDelta. I.e, if the task is rescheduled again without giving an expiryDelta,\n The expiryDelta given/calculated on the task's creation will be used.\n If both an expiryTime and an expiryDelta is given, the expiryTime takes precedence.\n\n :param datetime.datetime expiryTime: The new expiry time for the task. Default: now + expiryTime if expiryTime is specified, now + self.expiryTime otherwise\n :param datetime.timedelta expiryDelta: The amount of time to wait until the task's next expiry. Default: now + self.expiryTime\n \"\"\"",
"self",
".",
"issueTime",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"self",
".",
"expiryTime",
"=",
"self",
".",
"issueTime",
"+",
"(",
"self",
".",
"expiryDelta",
"if",
"expiryDelta",
"is",
"None",
"else",
"expiryDelta",
")",
"if",
"expiryTime",
"is",
"None",
"else",
"expiryTime",
"self",
".",
"gravestone",
"=",
"False",
"async",
"def",
"forceExpire",
"(",
"self",
",",
"callExpiryFunc",
"=",
"True",
")",
":",
"\"\"\"Force the expiry of this task.\n Handles calling of this task's expiryFunction, and rescheduling if specified. Set's the task's expiryTime to now.\n\n :param bool callExpiryFunction: Whether or not to call the task's expiryFunction if the task expires. Default: True\n :return: The result of the expiry function, if it is called\n \"\"\"",
"self",
".",
"expiryTime",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"callExpiryFunc",
"and",
"self",
".",
"hasExpiryFunction",
":",
"expiryFuncResults",
"=",
"await",
"self",
".",
"callExpiryFunction",
"(",
")",
"if",
"self",
".",
"autoReschedule",
":",
"await",
"self",
".",
"reschedule",
"(",
")",
"else",
":",
"self",
".",
"gravestone",
"=",
"True",
"if",
"callExpiryFunc",
"and",
"self",
".",
"hasExpiryFunction",
":",
"return",
"expiryFuncResults"
] |
A fairly generic class that, at its core, tracks when a requested amount of time has passed.
|
[
"A",
"fairly",
"generic",
"class",
"that",
"at",
"its",
"core",
"tracks",
"when",
"a",
"requested",
"amount",
"of",
"time",
"has",
"passed",
"."
] |
[
"\"\"\"A fairly generic class that, at its core, tracks when a requested amount of time has passed.\n Using an expiryFunction, a function call may be delayed by a given amount of time.\n Using autoRescheduling, this class can also be used to easily schedule reoccurring tasks.\n At least one of expiryTime or expiryDelta must be given.\n If the task is set to autoReschedule, issueTime is updated to show the task's current rescheduling time.\n\n :var issueTime: The datetime when this task was created.\n :vartype issueTime: datetime.datetime\n :var expiryTime: The datetime when this task should expire.\n :vartype expiryTime: datetime.datetime\n :var expiryDelta: The timedelta to add to issueTime, to find the expiryTime.\n :vartype expiryDelta: datetime.timedelta\n :var expiryFunction: The function to call once expiryTime has been reached/surpassed.\n :vartype expiryFunction: function\n :var hasExpiryFunction: Whether or not the task has an expiry function to call\n :vartype hasExpiryFunction: bool\n :var expiryFunctionArgs: The data to pass to the expiryFunction. There is no type requirement, but a dictionary is recommended as a close representation of KWArgs.\n :var hasExpiryFunctionArgs: Whether or not expiryFunction contains anything and should be passed to expiryFunction\n :vartype hasExpiryFunctionArgs: bool\n :var autoReschedule: Whether or not this task should automatically reschedule itself by the same timedelta.\n :vartype autoReschedule: bool\n :var gravestone: marked as True when the TimedTask will no longer execute and can be removed from any TimedTask heap. I.e, it is expired (whether manually or through timeout) and does not auto-reschedule\n :vartype gravestone: bool\n :var asyncExpiryFunction: whether or not the expiryFunction is a coroutine and needs to be awaited\n :vartype asyncExpiryFunction: bool\n \"\"\"",
"\"\"\"\n :param datetime.datetime issueTime: The datetime when this task was created. (Default now)\n :param datetime.datetime expiryTime: The datetime when this task should expire. (Default None)\n :param datetime.timedelta expiryDelta: The timedelta to add to issueTime, to find the expiryTime. (Default None)\n :param function expiryFunction: The function to call once expiryTime has been reached/surpassed. (Default None)\n :param expiryFunctionArgs: The data to pass to the expiryFunction. There is no type requirement, but a dictionary is recommended as a close representation of KWArgs. (Default {})\n :param bool autoReschedule: Whether or not this task should automatically reschedule itself by the same timedelta. (Default False)\n \"\"\"",
"# Ensure that at least one of expiryTime or expiryDelta is specified",
"# Calculate issueTime as now if none is given",
"# Calculate expiryTime as issueTime + expiryDelta if none is given",
"# Calculate expiryDelta as expiryTime - issueTime if none is given. This is needed for rescheduling.",
"# A task's 'gravestone' is marked as True when the TimedTask will no longer execute and can be removed from any TimedTask heap.",
"# I.e, it is expired (whether manually or through timeout) and does not auto-reschedule.",
"# Track whether or not the expiryFunction is a coroutine and needs to be awaited",
"\"\"\"< Overload, to be used in TimedTask heaps.\n The other object must be a TimedTask. Compares only the expiryTimes of the two tasks.\n\n :param TimedTask other: other TimedTask to compare against.\n :return: True if this TimedTask's expiryTime is < other's expiryTime, False otherwise. \n :rtype: bool\n \"\"\"",
"\"\"\"> Overload, to be used in TimedTask heaps.\n The other object must be a TimedTask. Compares only the expiryTimes of the two tasks.\n\n :param TimedTask other: other TimedTask to compare against.\n :return: True if this TimedTask's expiryTime is > other's expiryTime, False otherwise. \n :rtype: bool\n \"\"\"",
"\"\"\"<= Overload, to be used in TimedTask heaps.\n The other object must be a TimedTask. Compares only the expiryTimes of the two tasks.\n\n :param TimedTask other: other TimedTask to compare against.\n :return: True if this TimedTask's expiryTime is <= other's expiryTime, False otherwise. \n :rtype: bool\n \"\"\"",
"\"\"\">= Overload, to be used in TimedTask heaps.\n The other object must be a TimedTask. Compares only the expiryTimes of the two tasks.\n\n :param TimedTask other: other TimedTask to compare against.\n :return: True if this TimedTask's expiryTime is >= other's expiryTime, False otherwise. \n :rtype: bool\n \"\"\"",
"\"\"\"Decide whether or not this task has expired.\n This can be due to reaching the task's expiryTime, or due to manual expiry.\n\n :return: True if this timedTask has been manually expired, or has reached its expiryTime. False otherwise\n :rtype: bool\n \"\"\"",
"\"\"\"Call the task's expiryFunction, if one is specified.\n Handles passing of arguments to the expiryFunction, if specified.\n\n :return: the results of the expiryFunction\n \"\"\"",
"\"\"\"Function to be called regularly, that handles the expiry of this task.\n Handles calling of the task's expiry function if specified, and rescheduling of the task if specified.\n\n :param bool callExpiryFunc: Whether or not to call this task's expiryFunction if it is expired. Default: True\n :return: True if this task is expired in this check, False otherwise. Regardless of autorescheduling.\n :rtype: bool\n \"\"\"",
"# If the task has expired, call expiry function and reschedule if specified",
"\"\"\"Reschedule this task, with the timedelta given/calculated on the task's creation, or to a given expiryTime/Delta.\n Rescheduling will update the task's issueTime to now. TODO: A firstIssueTime may be useful in the future to represent creation time.\n Giving an expiryTime or expiryDelta will not update the task's stored expiryDelta. I.e, if the task is rescheduled again without giving an expiryDelta,\n The expiryDelta given/calculated on the task's creation will be used.\n If both an expiryTime and an expiryDelta is given, the expiryTime takes precedence.\n\n :param datetime.datetime expiryTime: The new expiry time for the task. Default: now + expiryTime if expiryTime is specified, now + self.expiryTime otherwise\n :param datetime.timedelta expiryDelta: The amount of time to wait until the task's next expiry. Default: now + self.expiryTime\n \"\"\"",
"# Update the task's issueTime to now",
"# Create the new expiryTime from now + expirydelta",
"# reset the gravestone to False, in case the task had been expired and marked for removal",
"\"\"\"Force the expiry of this task.\n Handles calling of this task's expiryFunction, and rescheduling if specified. Set's the task's expiryTime to now.\n\n :param bool callExpiryFunction: Whether or not to call the task's expiryFunction if the task expires. Default: True\n :return: The result of the expiry function, if it is called\n \"\"\"",
"# Update expiryTime",
"# Call expiryFunction and reschedule if specified",
"# Mark for removal if not rescheduled",
"# Return expiry function results"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "issueTime",
"type": null,
"docstring": "The datetime when this task was created.",
"docstring_tokens": [
"The",
"datetime",
"when",
"this",
"task",
"was",
"created",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "expiryTime",
"type": null,
"docstring": "The datetime when this task should expire.",
"docstring_tokens": [
"The",
"datetime",
"when",
"this",
"task",
"should",
"expire",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "expiryDelta",
"type": null,
"docstring": "The timedelta to add to issueTime, to find the expiryTime.",
"docstring_tokens": [
"The",
"timedelta",
"to",
"add",
"to",
"issueTime",
"to",
"find",
"the",
"expiryTime",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "expiryFunction",
"type": null,
"docstring": "The function to call once expiryTime has been reached/surpassed.",
"docstring_tokens": [
"The",
"function",
"to",
"call",
"once",
"expiryTime",
"has",
"been",
"reached",
"/",
"surpassed",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "hasExpiryFunction",
"type": null,
"docstring": "Whether or not the task has an expiry function to call",
"docstring_tokens": [
"Whether",
"or",
"not",
"the",
"task",
"has",
"an",
"expiry",
"function",
"to",
"call"
],
"default": null,
"is_optional": null
},
{
"identifier": "expiryFunctionArgs",
"type": null,
"docstring": "The data to pass to the expiryFunction. There is no type requirement, but a dictionary is recommended as a close representation of KWArgs.",
"docstring_tokens": [
"The",
"data",
"to",
"pass",
"to",
"the",
"expiryFunction",
".",
"There",
"is",
"no",
"type",
"requirement",
"but",
"a",
"dictionary",
"is",
"recommended",
"as",
"a",
"close",
"representation",
"of",
"KWArgs",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "hasExpiryFunctionArgs",
"type": null,
"docstring": "Whether or not expiryFunction contains anything and should be passed to expiryFunction",
"docstring_tokens": [
"Whether",
"or",
"not",
"expiryFunction",
"contains",
"anything",
"and",
"should",
"be",
"passed",
"to",
"expiryFunction"
],
"default": null,
"is_optional": null
},
{
"identifier": "autoReschedule",
"type": null,
"docstring": "Whether or not this task should automatically reschedule itself by the same timedelta.",
"docstring_tokens": [
"Whether",
"or",
"not",
"this",
"task",
"should",
"automatically",
"reschedule",
"itself",
"by",
"the",
"same",
"timedelta",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "gravestone",
"type": null,
"docstring": "marked as True when the TimedTask will no longer execute and can be removed from any TimedTask heap. I.e, it is expired (whether manually or through timeout) and does not auto-reschedule",
"docstring_tokens": [
"marked",
"as",
"True",
"when",
"the",
"TimedTask",
"will",
"no",
"longer",
"execute",
"and",
"can",
"be",
"removed",
"from",
"any",
"TimedTask",
"heap",
".",
"I",
".",
"e",
"it",
"is",
"expired",
"(",
"whether",
"manually",
"or",
"through",
"timeout",
")",
"and",
"does",
"not",
"auto",
"-",
"reschedule"
],
"default": null,
"is_optional": null
},
{
"identifier": "asyncExpiryFunction",
"type": null,
"docstring": "whether or not the expiryFunction is a coroutine and needs to be awaited",
"docstring_tokens": [
"whether",
"or",
"not",
"the",
"expiryFunction",
"is",
"a",
"coroutine",
"and",
"needs",
"to",
"be",
"awaited"
],
"default": null,
"is_optional": null
}
],
"others": [
{
"identifier": "vartype",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "vartype",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "vartype",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "vartype",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "vartype",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "vartype",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "vartype",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "vartype",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "vartype",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 14
| 2,444
| 441
|
c9eb9598f2f24bb16cb2be64d786c0ee0cefc274
|
Herdo/AdaptiveTriggerLibrary
|
AdaptiveTriggerLibrary/Triggers/AdaptiveTriggerBase.cs
|
[
"MIT"
] |
C#
|
AdaptiveTriggerBase
|
/// <summary>
/// Generic base class for all adaptive triggers in the project.
/// </summary>
/// <typeparam name="TCondition">The type of the <see cref="Condition"/>.</typeparam>
/// <typeparam name="TConditionModifier">The type of the <see cref="ConditionModifier"/>, that can influence the way that the <see cref="Condition"/> is treated.</typeparam>
|
Generic base class for all adaptive triggers in the project.
|
[
"Generic",
"base",
"class",
"for",
"all",
"adaptive",
"triggers",
"in",
"the",
"project",
"."
] |
public abstract class AdaptiveTriggerBase<TCondition, TConditionModifier> : AdaptiveTriggerBase,
IAdaptiveTrigger<TCondition, TConditionModifier>
where TConditionModifier : IConditionModifier
{
#region Fields
private readonly bool _initialConditionProvided;
private bool _isConditionSet;
private bool _isConditionModifierSet;
private bool _isCurrentValueSet;
private TCondition _currentValue;
private TCondition _condition;
private TConditionModifier _conditionModifier;
#endregion
#region Properties
protected TCondition CurrentValue
{
private get { return _currentValue; }
set
{
_currentValue = value;
_isCurrentValueSet = true;
ValidateIfActive();
}
}
#endregion
#region Constructors
protected AdaptiveTriggerBase(TConditionModifier defaultModifier)
{
_initialConditionProvided = false;
_condition = default(TCondition);
_conditionModifier = defaultModifier;
_isConditionSet =
_isConditionModifierSet =
_isCurrentValueSet = false;
}
protected AdaptiveTriggerBase(TCondition defaultCondition, TConditionModifier defaultModifier)
: this(defaultModifier)
{
_condition = defaultCondition;
_initialConditionProvided = true;
}
#endregion
#region Private Methods
private void ValidateIfActive()
{
if ((!_initialConditionProvided && !_isConditionSet)
|| !_isCurrentValueSet)
return;
IsActive = ConditionModifier.IsConditionMet(Condition, CurrentValue);
}
#endregion
#region IAdaptiveTrigger<TCondition, TConditionModifier> Members
public TCondition Condition
{
get => _condition;
set
{
if (_isConditionSet)
throw new InvalidOperationException("Condition has already been set.");
_condition = value;
_isConditionSet = true;
ValidateIfActive();
}
}
public TConditionModifier ConditionModifier
{
get => _conditionModifier;
set
{
if (_isConditionModifierSet)
throw new InvalidOperationException("ConditionModifier has already been set.");
_conditionModifier = value;
_isConditionModifierSet = true;
ValidateIfActive();
}
}
#endregion
}
|
[
"public",
"abstract",
"class",
"AdaptiveTriggerBase",
"<",
"TCondition",
",",
"TConditionModifier",
">",
":",
"AdaptiveTriggerBase",
",",
"IAdaptiveTrigger",
"<",
"TCondition",
",",
"TConditionModifier",
">",
"where",
"TConditionModifier",
":",
"IConditionModifier",
"{",
"region",
" Fields",
"private",
"readonly",
"bool",
"_initialConditionProvided",
";",
"private",
"bool",
"_isConditionSet",
";",
"private",
"bool",
"_isConditionModifierSet",
";",
"private",
"bool",
"_isCurrentValueSet",
";",
"private",
"TCondition",
"_currentValue",
";",
"private",
"TCondition",
"_condition",
";",
"private",
"TConditionModifier",
"_conditionModifier",
";",
"endregion",
"region",
" Properties",
"protected",
"TCondition",
"CurrentValue",
"{",
"private",
"get",
"{",
"return",
"_currentValue",
";",
"}",
"set",
"{",
"_currentValue",
"=",
"value",
";",
"_isCurrentValueSet",
"=",
"true",
";",
"ValidateIfActive",
"(",
")",
";",
"}",
"}",
"endregion",
"region",
" Constructors",
"protected",
"AdaptiveTriggerBase",
"(",
"TConditionModifier",
"defaultModifier",
")",
"{",
"_initialConditionProvided",
"=",
"false",
";",
"_condition",
"=",
"default",
"(",
"TCondition",
")",
";",
"_conditionModifier",
"=",
"defaultModifier",
";",
"_isConditionSet",
"=",
"_isConditionModifierSet",
"=",
"_isCurrentValueSet",
"=",
"false",
";",
"}",
"protected",
"AdaptiveTriggerBase",
"(",
"TCondition",
"defaultCondition",
",",
"TConditionModifier",
"defaultModifier",
")",
":",
"this",
"(",
"defaultModifier",
")",
"{",
"_condition",
"=",
"defaultCondition",
";",
"_initialConditionProvided",
"=",
"true",
";",
"}",
"endregion",
"region",
" Private Methods",
"private",
"void",
"ValidateIfActive",
"(",
")",
"{",
"if",
"(",
"(",
"!",
"_initialConditionProvided",
"&&",
"!",
"_isConditionSet",
")",
"||",
"!",
"_isCurrentValueSet",
")",
"return",
";",
"IsActive",
"=",
"ConditionModifier",
".",
"IsConditionMet",
"(",
"Condition",
",",
"CurrentValue",
")",
";",
"}",
"endregion",
"region",
" IAdaptiveTrigger<TCondition, TConditionModifier> Members",
"public",
"TCondition",
"Condition",
"{",
"get",
"=>",
"_condition",
";",
"set",
"{",
"if",
"(",
"_isConditionSet",
")",
"throw",
"new",
"InvalidOperationException",
"(",
"\"",
"Condition has already been set.",
"\"",
")",
";",
"_condition",
"=",
"value",
";",
"_isConditionSet",
"=",
"true",
";",
"ValidateIfActive",
"(",
")",
";",
"}",
"}",
"public",
"TConditionModifier",
"ConditionModifier",
"{",
"get",
"=>",
"_conditionModifier",
";",
"set",
"{",
"if",
"(",
"_isConditionModifierSet",
")",
"throw",
"new",
"InvalidOperationException",
"(",
"\"",
"ConditionModifier has already been set.",
"\"",
")",
";",
"_conditionModifier",
"=",
"value",
";",
"_isConditionModifierSet",
"=",
"true",
";",
"ValidateIfActive",
"(",
")",
";",
"}",
"}",
"endregion",
"}"
] |
Generic base class for all adaptive triggers in the project.
|
[
"Generic",
"base",
"class",
"for",
"all",
"adaptive",
"triggers",
"in",
"the",
"project",
"."
] |
[
"///////////////////////////////////////////////////////////////////",
"///////////////////////////////////////////////////////////////////",
"/// <summary>",
"/// Sets the current value.",
"/// </summary>",
"/// <exception cref=\"InvalidOperationException\"><see cref=\"Condition\"/> is not set and no static value is provided.</exception>",
"///////////////////////////////////////////////////////////////////",
"/// <summary>",
"/// Initializes a new instance of the <see cref=\"AdaptiveTriggerBase{TCondition, TConditionModifier}\"/> class with a given default modifier.",
"/// </summary>",
"/// <param name=\"defaultModifier\">The default modifier.</param>",
"/// <summary>",
"/// Initializes a new instance of the <see cref=\"AdaptiveTriggerBase{TCondition, TConditionModifier}\"/> class with a given default condition and default modifier.",
"/// </summary>",
"/// <param name=\"defaultCondition\">The default condition.</param>",
"/// <param name=\"defaultModifier\">The default modifier.</param>",
"///////////////////////////////////////////////////////////////////",
"///////////////////////////////////////////////////////////////////",
"/// <summary>",
"/// Gets or sets the condition that must be met, in order to set <see cref=\"IAdaptiveTrigger.IsActive\"/> to true.",
"/// </summary>",
"/// <remarks>This property can only be set once.</remarks>",
"/// <exception cref=\"InvalidOperationException\"><see cref=\"IAdaptiveTrigger{TCondition,TConditionModifier}.Condition\"/> is set more than once.</exception>",
"/// <summary>",
"/// Gets or sets the modifier that will be applied to the validation of the <see cref=\"IAdaptiveTrigger{TCondition,TConditionModifier}.Condition\"/>.",
"/// </summary>",
"/// <remarks>This property can only be set once.",
"/// If no condition modifier is specified, the default modifier for the <typeparamref name=\"TConditionModifier\"/> will be used.</remarks>",
"/// <exception cref=\"InvalidOperationException\"><see cref=\"IAdaptiveTrigger{TCondition,TConditionModifier}.ConditionModifier\"/> is set more than once.</exception>"
] |
[
{
"param": "AdaptiveTriggerBase",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "AdaptiveTriggerBase",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "typeparam",
"docstring": "The type of the .",
"docstring_tokens": [
"The",
"type",
"of",
"the",
"."
]
},
{
"identifier": "typeparam",
"docstring": "The type of the , that can influence the way that the is treated.",
"docstring_tokens": [
"The",
"type",
"of",
"the",
"that",
"can",
"influence",
"the",
"way",
"that",
"the",
"is",
"treated",
"."
]
}
]
}
| false
| 13
| 487
| 79
|
c5bb02bd94bbc4aa5ead10b25fb5cc1c710f4238
|
monde/impostor
|
lib/impostor/phpbb3.rb
|
[
"MIT",
"Unlicense"
] |
Ruby
|
Post
|
##
# Additional configuration parameters for a Phpbb3 compatible agent:
#
# :posting_page
#
# Typical configuration parameters
# { :type => :phpbb3,
# :app_root => 'http://example.com/forum/',
# :login_page => 'ucp.php?mode=login',
# :posting_page => 'posting.php',
# :user_agent => 'Windows IE 7',
# :username => 'myuser',
# :password => 'mypasswd' }
|
Additional configuration parameters for a Phpbb3 compatible agent:
:posting_page
|
[
"Additional",
"configuration",
"parameters",
"for",
"a",
"Phpbb3",
"compatible",
"agent",
":",
":",
"posting_page"
] |
module Post
##
# return a uri used to fetch the reply page based on the forum, topic, and
# message
def get_reply_uri(forum, topic)
uri = URI.join(self.config.app_root, self.config.config(:posting_page))
uri.query = "mode=reply&f=#{forum}&t=#{topic}"
uri
end
##
# return the form used for posting a message from the reply page
def get_post_form(page)
form = page.forms.detect { |form| form.action =~ /#{Regexp.escape(self.config.config(:posting_page))}/ }
raise Impostor::PostError.new("unknown reply page format") unless form
form
end
##
# set the message to reply with on the reply form
def set_message(form, message)
form.message = message
form["post"] = "Submit"
form
end
##
# get post id from the result of posting the message form
def get_post_from_result(page)
error_message = page_error_message(page)
if error_message =~ /You cannot make another post so soon after your last/
raise Impostor::ThrottledError.new("too many posts in too short amount of time, #{error_message}")
elsif !error_message.empty?
raise Impostor::PostError.new(error_message)
end
begin
kv = page.links.collect{ |l| l.uri }.compact.
collect{ |l| l.query }.compact.
collect{ |q| q.split('&')}.flatten.
detect { |p| p =~ /^p=/ }
raise StandardError.new("Message did not post.") if kv.nil?
postid = URI.unescape(kv).split('#').first.split('=').last.to_i
raise StandardError.new("Message did not post.") if postid.zero?
postid
rescue StandardError => err
raise Impostor::PostError.new(err)
end
end
##
# Extract the error from a page
def page_error_message(page, prepend='')
message = page.search(".//p[@class='error']").last || ''
message = message.text if message.respond_to?(:text)
prepend = '' if message.empty?
"#{prepend}#{message}"
end
end
|
[
"module",
"Post",
"def",
"get_reply_uri",
"(",
"forum",
",",
"topic",
")",
"uri",
"=",
"URI",
".",
"join",
"(",
"self",
".",
"config",
".",
"app_root",
",",
"self",
".",
"config",
".",
"config",
"(",
":posting_page",
")",
")",
"uri",
".",
"query",
"=",
"\"mode=reply&f=#{forum}&t=#{topic}\"",
"uri",
"end",
"def",
"get_post_form",
"(",
"page",
")",
"form",
"=",
"page",
".",
"forms",
".",
"detect",
"{",
"|",
"form",
"|",
"form",
".",
"action",
"=~",
"/",
"#{",
"Regexp",
".",
"escape",
"(",
"self",
".",
"config",
".",
"config",
"(",
":posting_page",
")",
")",
"}",
"/",
"}",
"raise",
"Impostor",
"::",
"PostError",
".",
"new",
"(",
"\"unknown reply page format\"",
")",
"unless",
"form",
"form",
"end",
"def",
"set_message",
"(",
"form",
",",
"message",
")",
"form",
".",
"message",
"=",
"message",
"form",
"[",
"\"post\"",
"]",
"=",
"\"Submit\"",
"form",
"end",
"def",
"get_post_from_result",
"(",
"page",
")",
"error_message",
"=",
"page_error_message",
"(",
"page",
")",
"if",
"error_message",
"=~",
"/",
"You cannot make another post so soon after your last",
"/",
"raise",
"Impostor",
"::",
"ThrottledError",
".",
"new",
"(",
"\"too many posts in too short amount of time, #{error_message}\"",
")",
"elsif",
"!",
"error_message",
".",
"empty?",
"raise",
"Impostor",
"::",
"PostError",
".",
"new",
"(",
"error_message",
")",
"end",
"begin",
"kv",
"=",
"page",
".",
"links",
".",
"collect",
"{",
"|",
"l",
"|",
"l",
".",
"uri",
"}",
".",
"compact",
".",
"collect",
"{",
"|",
"l",
"|",
"l",
".",
"query",
"}",
".",
"compact",
".",
"collect",
"{",
"|",
"q",
"|",
"q",
".",
"split",
"(",
"'&'",
")",
"}",
".",
"flatten",
".",
"detect",
"{",
"|",
"p",
"|",
"p",
"=~",
"/",
"^p=",
"/",
"}",
"raise",
"StandardError",
".",
"new",
"(",
"\"Message did not post.\"",
")",
"if",
"kv",
".",
"nil?",
"postid",
"=",
"URI",
".",
"unescape",
"(",
"kv",
")",
".",
"split",
"(",
"'#'",
")",
".",
"first",
".",
"split",
"(",
"'='",
")",
".",
"last",
".",
"to_i",
"raise",
"StandardError",
".",
"new",
"(",
"\"Message did not post.\"",
")",
"if",
"postid",
".",
"zero?",
"postid",
"rescue",
"StandardError",
"=>",
"err",
"raise",
"Impostor",
"::",
"PostError",
".",
"new",
"(",
"err",
")",
"end",
"end",
"def",
"page_error_message",
"(",
"page",
",",
"prepend",
"=",
"''",
")",
"message",
"=",
"page",
".",
"search",
"(",
"\".//p[@class='error']\"",
")",
".",
"last",
"||",
"''",
"message",
"=",
"message",
".",
"text",
"if",
"message",
".",
"respond_to?",
"(",
":text",
")",
"prepend",
"=",
"''",
"if",
"message",
".",
"empty?",
"\"#{prepend}#{message}\"",
"end",
"end"
] |
Additional configuration parameters for a Phpbb3 compatible agent:
:posting_page
|
[
"Additional",
"configuration",
"parameters",
"for",
"a",
"Phpbb3",
"compatible",
"agent",
":",
":",
"posting_page"
] |
[
"##",
"# return a uri used to fetch the reply page based on the forum, topic, and",
"# message",
"##",
"# return the form used for posting a message from the reply page",
"##",
"# set the message to reply with on the reply form",
"##",
"# get post id from the result of posting the message form",
"##",
"# Extract the error from a page"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 497
| 105
|
7bde7b1605968210107b078a4e5e1f17c8531fdc
|
jaylinhong/jdk14-learn
|
src/jdk14-source/jdk.jshell/jdk/internal/jshell/tool/Startup.java
|
[
"MIT"
] |
Java
|
Startup
|
/**
* Processing start-up "script" information. The startup may consist of several
* entries, each of which may have been read from a user file or be a built-in
* resource. The startup may also be empty ("-none"); Which is stored as the
* empty string different from unset (null). Built-in resources come from
* resource files. Startup is stored as named elements rather than concatenated
* text, for display purposes but also importantly so that when resources update
* with new releases the built-in will update.
* @author Robert Field
*/
|
Processing start-up "script" information. The startup may consist of several
entries, each of which may have been read from a user file or be a built-in
resource. The startup may also be empty ("-none"); Which is stored as the
empty string different from unset (null). Built-in resources come from
resource files. Startup is stored as named elements rather than concatenated
text, for display purposes but also importantly so that when resources update
with new releases the built-in will update.
@author Robert Field
|
[
"Processing",
"start",
"-",
"up",
"\"",
"script",
"\"",
"information",
".",
"The",
"startup",
"may",
"consist",
"of",
"several",
"entries",
"each",
"of",
"which",
"may",
"have",
"been",
"read",
"from",
"a",
"user",
"file",
"or",
"be",
"a",
"built",
"-",
"in",
"resource",
".",
"The",
"startup",
"may",
"also",
"be",
"empty",
"(",
"\"",
"-",
"none",
"\"",
")",
";",
"Which",
"is",
"stored",
"as",
"the",
"empty",
"string",
"different",
"from",
"unset",
"(",
"null",
")",
".",
"Built",
"-",
"in",
"resources",
"come",
"from",
"resource",
"files",
".",
"Startup",
"is",
"stored",
"as",
"named",
"elements",
"rather",
"than",
"concatenated",
"text",
"for",
"display",
"purposes",
"but",
"also",
"importantly",
"so",
"that",
"when",
"resources",
"update",
"with",
"new",
"releases",
"the",
"built",
"-",
"in",
"will",
"update",
".",
"@author",
"Robert",
"Field"
] |
class Startup {
// Store one entry in the start-up list
private static class StartupEntry {
// is this a JShell built-in?
private final boolean isBuiltIn;
// the file or resource name
private final String name;
// the commands/snippets as text
private final String content;
// for files, the date/time read in -- makes clear it is a snapshot
private final String timeStamp;
StartupEntry(boolean isBuiltIn, String name, String content) {
this(isBuiltIn, name, content, "");
}
StartupEntry(boolean isBuiltIn, String name, String content, String timeStamp) {
this.isBuiltIn = isBuiltIn;
this.name = name;
this.content = content;
this.timeStamp = timeStamp;
}
// string form to store in storage (e.g. Preferences)
String storedForm() {
return (isBuiltIn ? "*" : "-") + RECORD_SEPARATOR +
name + RECORD_SEPARATOR +
timeStamp + RECORD_SEPARATOR +
content + RECORD_SEPARATOR;
}
// the content
@Override
public String toString() {
return content;
}
@Override
public int hashCode() {
int hash = 7;
hash = 41 * hash + (this.isBuiltIn ? 1 : 0);
hash = 41 * hash + Objects.hashCode(this.name);
if (!isBuiltIn) {
hash = 41 * hash + Objects.hashCode(this.content);
}
return hash;
}
// built-ins match on name only. Time stamp isn't considered
@Override
public boolean equals(Object o) {
if (!(o instanceof StartupEntry)) {
return false;
}
StartupEntry sue = (StartupEntry) o;
return isBuiltIn == sue.isBuiltIn &&
name.equals(sue.name) &&
(isBuiltIn || content.equals(sue.content));
}
}
private static final String DEFAULT_STARTUP_NAME = "DEFAULT";
// cached DEFAULT start-up
private static Startup defaultStartup = null;
// the list of entries
private List<StartupEntry> entries;
// the concatenated content of the list of entries
private String content;
// created only with factory methods (below)
private Startup(List<StartupEntry> entries) {
this.entries = entries;
this.content = entries.stream()
.map(sue -> sue.toString())
.collect(joining());
}
private Startup(StartupEntry entry) {
this(Collections.singletonList(entry));
}
// retrieve the content
@Override
public String toString() {
return content;
}
@Override
public int hashCode() {
return 9 + Objects.hashCode(this.entries);
}
@Override
public boolean equals(Object o) {
return (o instanceof Startup)
&& entries.equals(((Startup) o).entries);
}
// are there no entries ("-none")?
boolean isEmpty() {
return entries.isEmpty();
}
// is this the "-default" setting -- one entry which is DEFAULT
boolean isDefault() {
if (entries.size() == 1) {
StartupEntry sue = entries.get(0);
if (sue.isBuiltIn && sue.name.equals(DEFAULT_STARTUP_NAME)) {
return true;
}
}
return false;
}
// string form to store in storage (e.g. Preferences)
String storedForm() {
return entries.stream()
.map(sue -> sue.storedForm())
.collect(joining());
}
// show commands to re-create
String show(boolean isRetained) {
String cmd = "/set start " + (isRetained ? "-retain " : "");
if (isDefault()) {
return cmd + "-default\n";
} else if (isEmpty()) {
return cmd + "-none\n";
} else {
return entries.stream()
.map(sue -> sue.name)
.collect(joining(" ", cmd, "\n"));
}
}
// show corresponding contents for show()
String showDetail() {
if (isDefault() || isEmpty()) {
return "";
} else {
return entries.stream()
.map(sue -> "---- " + sue.name
+ (sue.timeStamp.isEmpty()
? ""
: " @ " + sue.timeStamp)
+ " ----\n" + sue.content)
.collect(joining());
}
}
/**
* Factory method: Unpack from stored form.
*
* @param storedForm the Startup in the form as stored on persistent
* storage (e.g. Preferences)
* @param mh handler for error messages
* @return Startup, or default startup when error (message has been printed)
*/
static Startup unpack(String storedForm, MessageHandler mh) {
if (storedForm != null) {
if (storedForm.isEmpty()) {
return noStartup();
}
try {
String[] all = storedForm.split(RECORD_SEPARATOR);
if (all.length == 1) {
// legacy (content only)
return new Startup(new StartupEntry(false, "user.jsh", storedForm));
} else if (all.length % 4 == 0) {
List<StartupEntry> e = new ArrayList<>(all.length / 4);
for (int i = 0; i < all.length; i += 4) {
final boolean isBuiltIn;
switch (all[i]) {
case "*":
isBuiltIn = true;
break;
case "-":
isBuiltIn = false;
break;
default:
throw new IllegalArgumentException("Unexpected StartupEntry kind: " + all[i]);
}
String name = all[i + 1];
String timeStamp = all[i + 2];
String content = all[i + 3];
if (isBuiltIn) {
// update to current definition, use stored if removed/error
String resource = getResource(name);
if (resource != null) {
content = resource;
}
}
e.add(new StartupEntry(isBuiltIn, name, content, timeStamp));
}
return new Startup(e);
} else {
throw new IllegalArgumentException("Unexpected StartupEntry entry count: " + all.length);
}
} catch (Exception ex) {
mh.errormsg("jshell.err.corrupted.stored.startup", ex.getMessage());
}
}
return defaultStartup(mh);
}
/**
* Factory method: Read Startup from a list of external files or resources.
*
* @param fns list of file/resource names to access
* @param context printable non-natural language context for errors
* @param mh handler for error messages
* @return files as Startup, or null when error (message has been printed)
*/
static Startup fromFileList(List<String> fns, String context, MessageHandler mh) {
List<StartupEntry> entries = fns.stream()
.map(fn -> readFile(fn, context, mh))
.collect(toList());
if (entries.stream().anyMatch(sue -> sue == null)) {
return null;
}
return new Startup(entries);
}
/**
* Read a external file or a resource.
*
* @param filename file/resource to access
* @param context printable non-natural language context for errors
* @param mh handler for error messages
* @return file as startup entry, or null when error (message has been printed)
*/
private static StartupEntry readFile(String filename, String context, MessageHandler mh) {
if (filename != null) {
try {
byte[] encoded = Files.readAllBytes(toPathResolvingUserHome(filename));
return new StartupEntry(false, filename, new String(encoded),
LocalDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)));
} catch (AccessDeniedException e) {
mh.errormsg("jshell.err.file.not.accessible", context, filename, e.getMessage());
} catch (NoSuchFileException e) {
String resource = getResource(filename);
if (resource != null) {
// Not found as file, but found as resource
return new StartupEntry(true, filename, resource);
}
mh.errormsg("jshell.err.file.not.found", context, filename);
} catch (Exception e) {
mh.errormsg("jshell.err.file.exception", context, filename, e);
}
} else {
mh.errormsg("jshell.err.file.filename", context);
}
return null;
}
/**
* Factory method: The empty Startup ("-none").
*
* @return the empty Startup
*/
static Startup noStartup() {
return new Startup(Collections.emptyList());
}
/**
* Factory method: The default Startup ("-default.").
*
* @param mh handler for error messages
* @return The default Startup, or empty startup when error (message has been printed)
*/
static Startup defaultStartup(MessageHandler mh) {
if (defaultStartup != null) {
return defaultStartup;
}
try {
String content = readResource(DEFAULT_STARTUP_NAME);
return defaultStartup = new Startup(
new StartupEntry(true, DEFAULT_STARTUP_NAME, content));
} catch (AccessDeniedException e) {
mh.errormsg("jshell.err.file.not.accessible", "jshell", DEFAULT_STARTUP_NAME, e.getMessage());
} catch (NoSuchFileException e) {
mh.errormsg("jshell.err.file.not.found", "jshell", DEFAULT_STARTUP_NAME);
} catch (Exception e) {
mh.errormsg("jshell.err.file.exception", "jshell", DEFAULT_STARTUP_NAME, e);
}
return defaultStartup = noStartup();
}
}
|
[
"class",
"Startup",
"{",
"private",
"static",
"class",
"StartupEntry",
"{",
"private",
"final",
"boolean",
"isBuiltIn",
";",
"private",
"final",
"String",
"name",
";",
"private",
"final",
"String",
"content",
";",
"private",
"final",
"String",
"timeStamp",
";",
"StartupEntry",
"(",
"boolean",
"isBuiltIn",
",",
"String",
"name",
",",
"String",
"content",
")",
"{",
"this",
"(",
"isBuiltIn",
",",
"name",
",",
"content",
",",
"\"",
"\"",
")",
";",
"}",
"StartupEntry",
"(",
"boolean",
"isBuiltIn",
",",
"String",
"name",
",",
"String",
"content",
",",
"String",
"timeStamp",
")",
"{",
"this",
".",
"isBuiltIn",
"=",
"isBuiltIn",
";",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"content",
"=",
"content",
";",
"this",
".",
"timeStamp",
"=",
"timeStamp",
";",
"}",
"String",
"storedForm",
"(",
")",
"{",
"return",
"(",
"isBuiltIn",
"?",
"\"",
"*",
"\"",
":",
"\"",
"-",
"\"",
")",
"+",
"RECORD_SEPARATOR",
"+",
"name",
"+",
"RECORD_SEPARATOR",
"+",
"timeStamp",
"+",
"RECORD_SEPARATOR",
"+",
"content",
"+",
"RECORD_SEPARATOR",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"content",
";",
"}",
"@",
"Override",
"public",
"int",
"hashCode",
"(",
")",
"{",
"int",
"hash",
"=",
"7",
";",
"hash",
"=",
"41",
"*",
"hash",
"+",
"(",
"this",
".",
"isBuiltIn",
"?",
"1",
":",
"0",
")",
";",
"hash",
"=",
"41",
"*",
"hash",
"+",
"Objects",
".",
"hashCode",
"(",
"this",
".",
"name",
")",
";",
"if",
"(",
"!",
"isBuiltIn",
")",
"{",
"hash",
"=",
"41",
"*",
"hash",
"+",
"Objects",
".",
"hashCode",
"(",
"this",
".",
"content",
")",
";",
"}",
"return",
"hash",
";",
"}",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"Object",
"o",
")",
"{",
"if",
"(",
"!",
"(",
"o",
"instanceof",
"StartupEntry",
")",
")",
"{",
"return",
"false",
";",
"}",
"StartupEntry",
"sue",
"=",
"(",
"StartupEntry",
")",
"o",
";",
"return",
"isBuiltIn",
"==",
"sue",
".",
"isBuiltIn",
"&&",
"name",
".",
"equals",
"(",
"sue",
".",
"name",
")",
"&&",
"(",
"isBuiltIn",
"||",
"content",
".",
"equals",
"(",
"sue",
".",
"content",
")",
")",
";",
"}",
"}",
"private",
"static",
"final",
"String",
"DEFAULT_STARTUP_NAME",
"=",
"\"",
"DEFAULT",
"\"",
";",
"private",
"static",
"Startup",
"defaultStartup",
"=",
"null",
";",
"private",
"List",
"<",
"StartupEntry",
">",
"entries",
";",
"private",
"String",
"content",
";",
"private",
"Startup",
"(",
"List",
"<",
"StartupEntry",
">",
"entries",
")",
"{",
"this",
".",
"entries",
"=",
"entries",
";",
"this",
".",
"content",
"=",
"entries",
".",
"stream",
"(",
")",
".",
"map",
"(",
"sue",
"->",
"sue",
".",
"toString",
"(",
")",
")",
".",
"collect",
"(",
"joining",
"(",
")",
")",
";",
"}",
"private",
"Startup",
"(",
"StartupEntry",
"entry",
")",
"{",
"this",
"(",
"Collections",
".",
"singletonList",
"(",
"entry",
")",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"content",
";",
"}",
"@",
"Override",
"public",
"int",
"hashCode",
"(",
")",
"{",
"return",
"9",
"+",
"Objects",
".",
"hashCode",
"(",
"this",
".",
"entries",
")",
";",
"}",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"Object",
"o",
")",
"{",
"return",
"(",
"o",
"instanceof",
"Startup",
")",
"&&",
"entries",
".",
"equals",
"(",
"(",
"(",
"Startup",
")",
"o",
")",
".",
"entries",
")",
";",
"}",
"boolean",
"isEmpty",
"(",
")",
"{",
"return",
"entries",
".",
"isEmpty",
"(",
")",
";",
"}",
"boolean",
"isDefault",
"(",
")",
"{",
"if",
"(",
"entries",
".",
"size",
"(",
")",
"==",
"1",
")",
"{",
"StartupEntry",
"sue",
"=",
"entries",
".",
"get",
"(",
"0",
")",
";",
"if",
"(",
"sue",
".",
"isBuiltIn",
"&&",
"sue",
".",
"name",
".",
"equals",
"(",
"DEFAULT_STARTUP_NAME",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}",
"String",
"storedForm",
"(",
")",
"{",
"return",
"entries",
".",
"stream",
"(",
")",
".",
"map",
"(",
"sue",
"->",
"sue",
".",
"storedForm",
"(",
")",
")",
".",
"collect",
"(",
"joining",
"(",
")",
")",
";",
"}",
"String",
"show",
"(",
"boolean",
"isRetained",
")",
"{",
"String",
"cmd",
"=",
"\"",
"/set start ",
"\"",
"+",
"(",
"isRetained",
"?",
"\"",
"-retain ",
"\"",
":",
"\"",
"\"",
")",
";",
"if",
"(",
"isDefault",
"(",
")",
")",
"{",
"return",
"cmd",
"+",
"\"",
"-default",
"\\n",
"\"",
";",
"}",
"else",
"if",
"(",
"isEmpty",
"(",
")",
")",
"{",
"return",
"cmd",
"+",
"\"",
"-none",
"\\n",
"\"",
";",
"}",
"else",
"{",
"return",
"entries",
".",
"stream",
"(",
")",
".",
"map",
"(",
"sue",
"->",
"sue",
".",
"name",
")",
".",
"collect",
"(",
"joining",
"(",
"\"",
" ",
"\"",
",",
"cmd",
",",
"\"",
"\\n",
"\"",
")",
")",
";",
"}",
"}",
"String",
"showDetail",
"(",
")",
"{",
"if",
"(",
"isDefault",
"(",
")",
"||",
"isEmpty",
"(",
")",
")",
"{",
"return",
"\"",
"\"",
";",
"}",
"else",
"{",
"return",
"entries",
".",
"stream",
"(",
")",
".",
"map",
"(",
"sue",
"->",
"\"",
"---- ",
"\"",
"+",
"sue",
".",
"name",
"+",
"(",
"sue",
".",
"timeStamp",
".",
"isEmpty",
"(",
")",
"?",
"\"",
"\"",
":",
"\"",
" @ ",
"\"",
"+",
"sue",
".",
"timeStamp",
")",
"+",
"\"",
" ----",
"\\n",
"\"",
"+",
"sue",
".",
"content",
")",
".",
"collect",
"(",
"joining",
"(",
")",
")",
";",
"}",
"}",
"/**\n * Factory method: Unpack from stored form.\n *\n * @param storedForm the Startup in the form as stored on persistent\n * storage (e.g. Preferences)\n * @param mh handler for error messages\n * @return Startup, or default startup when error (message has been printed)\n */",
"static",
"Startup",
"unpack",
"(",
"String",
"storedForm",
",",
"MessageHandler",
"mh",
")",
"{",
"if",
"(",
"storedForm",
"!=",
"null",
")",
"{",
"if",
"(",
"storedForm",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"noStartup",
"(",
")",
";",
"}",
"try",
"{",
"String",
"[",
"]",
"all",
"=",
"storedForm",
".",
"split",
"(",
"RECORD_SEPARATOR",
")",
";",
"if",
"(",
"all",
".",
"length",
"==",
"1",
")",
"{",
"return",
"new",
"Startup",
"(",
"new",
"StartupEntry",
"(",
"false",
",",
"\"",
"user.jsh",
"\"",
",",
"storedForm",
")",
")",
";",
"}",
"else",
"if",
"(",
"all",
".",
"length",
"%",
"4",
"==",
"0",
")",
"{",
"List",
"<",
"StartupEntry",
">",
"e",
"=",
"new",
"ArrayList",
"<",
">",
"(",
"all",
".",
"length",
"/",
"4",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"all",
".",
"length",
";",
"i",
"+=",
"4",
")",
"{",
"final",
"boolean",
"isBuiltIn",
";",
"switch",
"(",
"all",
"[",
"i",
"]",
")",
"{",
"case",
"\"",
"*",
"\"",
":",
"isBuiltIn",
"=",
"true",
";",
"break",
";",
"case",
"\"",
"-",
"\"",
":",
"isBuiltIn",
"=",
"false",
";",
"break",
";",
"default",
":",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Unexpected StartupEntry kind: ",
"\"",
"+",
"all",
"[",
"i",
"]",
")",
";",
"}",
"String",
"name",
"=",
"all",
"[",
"i",
"+",
"1",
"]",
";",
"String",
"timeStamp",
"=",
"all",
"[",
"i",
"+",
"2",
"]",
";",
"String",
"content",
"=",
"all",
"[",
"i",
"+",
"3",
"]",
";",
"if",
"(",
"isBuiltIn",
")",
"{",
"String",
"resource",
"=",
"getResource",
"(",
"name",
")",
";",
"if",
"(",
"resource",
"!=",
"null",
")",
"{",
"content",
"=",
"resource",
";",
"}",
"}",
"e",
".",
"add",
"(",
"new",
"StartupEntry",
"(",
"isBuiltIn",
",",
"name",
",",
"content",
",",
"timeStamp",
")",
")",
";",
"}",
"return",
"new",
"Startup",
"(",
"e",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Unexpected StartupEntry entry count: ",
"\"",
"+",
"all",
".",
"length",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"mh",
".",
"errormsg",
"(",
"\"",
"jshell.err.corrupted.stored.startup",
"\"",
",",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"return",
"defaultStartup",
"(",
"mh",
")",
";",
"}",
"/**\n * Factory method: Read Startup from a list of external files or resources.\n *\n * @param fns list of file/resource names to access\n * @param context printable non-natural language context for errors\n * @param mh handler for error messages\n * @return files as Startup, or null when error (message has been printed)\n */",
"static",
"Startup",
"fromFileList",
"(",
"List",
"<",
"String",
">",
"fns",
",",
"String",
"context",
",",
"MessageHandler",
"mh",
")",
"{",
"List",
"<",
"StartupEntry",
">",
"entries",
"=",
"fns",
".",
"stream",
"(",
")",
".",
"map",
"(",
"fn",
"->",
"readFile",
"(",
"fn",
",",
"context",
",",
"mh",
")",
")",
".",
"collect",
"(",
"toList",
"(",
")",
")",
";",
"if",
"(",
"entries",
".",
"stream",
"(",
")",
".",
"anyMatch",
"(",
"sue",
"->",
"sue",
"==",
"null",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"new",
"Startup",
"(",
"entries",
")",
";",
"}",
"/**\n * Read a external file or a resource.\n *\n * @param filename file/resource to access\n * @param context printable non-natural language context for errors\n * @param mh handler for error messages\n * @return file as startup entry, or null when error (message has been printed)\n */",
"private",
"static",
"StartupEntry",
"readFile",
"(",
"String",
"filename",
",",
"String",
"context",
",",
"MessageHandler",
"mh",
")",
"{",
"if",
"(",
"filename",
"!=",
"null",
")",
"{",
"try",
"{",
"byte",
"[",
"]",
"encoded",
"=",
"Files",
".",
"readAllBytes",
"(",
"toPathResolvingUserHome",
"(",
"filename",
")",
")",
";",
"return",
"new",
"StartupEntry",
"(",
"false",
",",
"filename",
",",
"new",
"String",
"(",
"encoded",
")",
",",
"LocalDateTime",
".",
"now",
"(",
")",
".",
"format",
"(",
"DateTimeFormatter",
".",
"ofLocalizedDateTime",
"(",
"FormatStyle",
".",
"MEDIUM",
")",
")",
")",
";",
"}",
"catch",
"(",
"AccessDeniedException",
"e",
")",
"{",
"mh",
".",
"errormsg",
"(",
"\"",
"jshell.err.file.not.accessible",
"\"",
",",
"context",
",",
"filename",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"catch",
"(",
"NoSuchFileException",
"e",
")",
"{",
"String",
"resource",
"=",
"getResource",
"(",
"filename",
")",
";",
"if",
"(",
"resource",
"!=",
"null",
")",
"{",
"return",
"new",
"StartupEntry",
"(",
"true",
",",
"filename",
",",
"resource",
")",
";",
"}",
"mh",
".",
"errormsg",
"(",
"\"",
"jshell.err.file.not.found",
"\"",
",",
"context",
",",
"filename",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"mh",
".",
"errormsg",
"(",
"\"",
"jshell.err.file.exception",
"\"",
",",
"context",
",",
"filename",
",",
"e",
")",
";",
"}",
"}",
"else",
"{",
"mh",
".",
"errormsg",
"(",
"\"",
"jshell.err.file.filename",
"\"",
",",
"context",
")",
";",
"}",
"return",
"null",
";",
"}",
"/**\n * Factory method: The empty Startup (\"-none\").\n *\n * @return the empty Startup\n */",
"static",
"Startup",
"noStartup",
"(",
")",
"{",
"return",
"new",
"Startup",
"(",
"Collections",
".",
"emptyList",
"(",
")",
")",
";",
"}",
"/**\n * Factory method: The default Startup (\"-default.\").\n *\n * @param mh handler for error messages\n * @return The default Startup, or empty startup when error (message has been printed)\n */",
"static",
"Startup",
"defaultStartup",
"(",
"MessageHandler",
"mh",
")",
"{",
"if",
"(",
"defaultStartup",
"!=",
"null",
")",
"{",
"return",
"defaultStartup",
";",
"}",
"try",
"{",
"String",
"content",
"=",
"readResource",
"(",
"DEFAULT_STARTUP_NAME",
")",
";",
"return",
"defaultStartup",
"=",
"new",
"Startup",
"(",
"new",
"StartupEntry",
"(",
"true",
",",
"DEFAULT_STARTUP_NAME",
",",
"content",
")",
")",
";",
"}",
"catch",
"(",
"AccessDeniedException",
"e",
")",
"{",
"mh",
".",
"errormsg",
"(",
"\"",
"jshell.err.file.not.accessible",
"\"",
",",
"\"",
"jshell",
"\"",
",",
"DEFAULT_STARTUP_NAME",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"catch",
"(",
"NoSuchFileException",
"e",
")",
"{",
"mh",
".",
"errormsg",
"(",
"\"",
"jshell.err.file.not.found",
"\"",
",",
"\"",
"jshell",
"\"",
",",
"DEFAULT_STARTUP_NAME",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"mh",
".",
"errormsg",
"(",
"\"",
"jshell.err.file.exception",
"\"",
",",
"\"",
"jshell",
"\"",
",",
"DEFAULT_STARTUP_NAME",
",",
"e",
")",
";",
"}",
"return",
"defaultStartup",
"=",
"noStartup",
"(",
")",
";",
"}",
"}"
] |
Processing start-up "script" information.
|
[
"Processing",
"start",
"-",
"up",
"\"",
"script",
"\"",
"information",
"."
] |
[
"// Store one entry in the start-up list",
"// is this a JShell built-in?",
"// the file or resource name",
"// the commands/snippets as text",
"// for files, the date/time read in -- makes clear it is a snapshot",
"// string form to store in storage (e.g. Preferences)",
"// the content",
"// built-ins match on name only. Time stamp isn't considered",
"// cached DEFAULT start-up",
"// the list of entries",
"// the concatenated content of the list of entries",
"// created only with factory methods (below)",
"// retrieve the content",
"// are there no entries (\"-none\")?",
"// is this the \"-default\" setting -- one entry which is DEFAULT",
"// string form to store in storage (e.g. Preferences)",
"// show commands to re-create",
"// show corresponding contents for show()",
"// legacy (content only)",
"// update to current definition, use stored if removed/error",
"// Not found as file, but found as resource"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 22
| 2,094
| 120
|
17213620d9aa04c86d9b4fc275998df19dd64f98
|
yonaxTics/contalcob
|
app/com/contalcob/set/location/city/dao/CityDao.java
|
[
"MIT"
] |
Java
|
CityDao
|
/**
* company : [email protected] <br/>
* user : YQ<br/>
* update date : May 22, 2015<br/>
* update by : Yonatan Alexis Quintero Rodriguez<br/>
*
* @created : May 22, 2015<br/>
* @version : 0.1 <br/>
* @author Yonatan Alexis Quintero Rodriguez
*
*/
|
company : [email protected]
user : YQ
update date : May 22, 2015
update by : Yonatan Alexis Quintero Rodriguez
@created : May 22, 2015
@version : 0.1
@author Yonatan Alexis Quintero Rodriguez
|
[
"company",
":",
"yonax73@gmail",
".",
"com",
"user",
":",
"YQ",
"update",
"date",
":",
"May",
"22",
"2015",
"update",
"by",
":",
"Yonatan",
"Alexis",
"Quintero",
"Rodriguez",
"@created",
":",
"May",
"22",
"2015",
"@version",
":",
"0",
".",
"1",
"@author",
"Yonatan",
"Alexis",
"Quintero",
"Rodriguez"
] |
public class CityDao extends Dao {
public static boolean create(City city) {
boolean created = false;
CallableStatement cst = null;
Connection conn = null;
try {
conn = DB.getConnection();
cst = conn.prepareCall("CALL contalcob_schema.sp_set_cities_CREATE(?,?,?)");
cst.registerOutParameter(1, Types.INTEGER);
cst.setString(2, city.getCity());
cst.setString(3, city.getCountry());
created = cst.executeUpdate() > 0;
if (created) {
city.setId(cst.getInt(1));
created = city.exists();
}
} catch (Exception e) {
Logger.error("An error has been ocurred tryining created the city.\n" + e.getMessage(), e);
} finally {
close(cst, conn);
}
return created;
}
public static boolean update(City city) {
boolean updated = false;
CallableStatement cst = null;
Connection conn = null;
try {
conn = DB.getConnection();
cst = conn.prepareCall("CALL contalcob_schema.sp_set_cities_UPDATE(?,?,?)");
cst.setInt(1, city.getId());
cst.setString(2, city.getCity());
cst.setString(3, city.getCountry());
updated = cst.executeUpdate() > 0;
} catch (Exception e) {
Logger.error("An error has been ocurred tryining update the city.\n" + e.getMessage(), e);
} finally {
close(cst, conn);
}
return updated;
}
}
|
[
"public",
"class",
"CityDao",
"extends",
"Dao",
"{",
"public",
"static",
"boolean",
"create",
"(",
"City",
"city",
")",
"{",
"boolean",
"created",
"=",
"false",
";",
"CallableStatement",
"cst",
"=",
"null",
";",
"Connection",
"conn",
"=",
"null",
";",
"try",
"{",
"conn",
"=",
"DB",
".",
"getConnection",
"(",
")",
";",
"cst",
"=",
"conn",
".",
"prepareCall",
"(",
"\"",
"CALL contalcob_schema.sp_set_cities_CREATE(?,?,?)",
"\"",
")",
";",
"cst",
".",
"registerOutParameter",
"(",
"1",
",",
"Types",
".",
"INTEGER",
")",
";",
"cst",
".",
"setString",
"(",
"2",
",",
"city",
".",
"getCity",
"(",
")",
")",
";",
"cst",
".",
"setString",
"(",
"3",
",",
"city",
".",
"getCountry",
"(",
")",
")",
";",
"created",
"=",
"cst",
".",
"executeUpdate",
"(",
")",
">",
"0",
";",
"if",
"(",
"created",
")",
"{",
"city",
".",
"setId",
"(",
"cst",
".",
"getInt",
"(",
"1",
")",
")",
";",
"created",
"=",
"city",
".",
"exists",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"Logger",
".",
"error",
"(",
"\"",
"An error has been ocurred tryining created the city.",
"\\n",
"\"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"finally",
"{",
"close",
"(",
"cst",
",",
"conn",
")",
";",
"}",
"return",
"created",
";",
"}",
"public",
"static",
"boolean",
"update",
"(",
"City",
"city",
")",
"{",
"boolean",
"updated",
"=",
"false",
";",
"CallableStatement",
"cst",
"=",
"null",
";",
"Connection",
"conn",
"=",
"null",
";",
"try",
"{",
"conn",
"=",
"DB",
".",
"getConnection",
"(",
")",
";",
"cst",
"=",
"conn",
".",
"prepareCall",
"(",
"\"",
"CALL contalcob_schema.sp_set_cities_UPDATE(?,?,?)",
"\"",
")",
";",
"cst",
".",
"setInt",
"(",
"1",
",",
"city",
".",
"getId",
"(",
")",
")",
";",
"cst",
".",
"setString",
"(",
"2",
",",
"city",
".",
"getCity",
"(",
")",
")",
";",
"cst",
".",
"setString",
"(",
"3",
",",
"city",
".",
"getCountry",
"(",
")",
")",
";",
"updated",
"=",
"cst",
".",
"executeUpdate",
"(",
")",
">",
"0",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"Logger",
".",
"error",
"(",
"\"",
"An error has been ocurred tryining update the city.",
"\\n",
"\"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"finally",
"{",
"close",
"(",
"cst",
",",
"conn",
")",
";",
"}",
"return",
"updated",
";",
"}",
"}"
] |
company : [email protected] <br/>
user : YQ<br/>
update date : May 22, 2015<br/>
update by : Yonatan Alexis Quintero Rodriguez<br/>
|
[
"company",
":",
"yonax73@gmail",
".",
"com",
"<br",
"/",
">",
"user",
":",
"YQ<br",
"/",
">",
"update",
"date",
":",
"May",
"22",
"2015<br",
"/",
">",
"update",
"by",
":",
"Yonatan",
"Alexis",
"Quintero",
"Rodriguez<br",
"/",
">"
] |
[] |
[
{
"param": "Dao",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Dao",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 352
| 94
|
3f4931fde5a53e81f2b5e06c8b9acb860980874b
|
mate-code/alfred
|
src/alfred3/quota.py
|
[
"MIT"
] |
Python
|
SessionQuota
|
A quota for experiment sessions.
The quota allows you to enforce an upper limit on the number of
participants in your experiment.
Args:
nslots (int): Maximum number of slots.
exp (alfred3.ExperimentSession): Experiment session.
respect_version (bool):
inclusive (bool):
If *False* (default), the quota will only assign a
slot, if there are no pending sessions for that slot. It will
not assign a slot, if a session in that slot
is finished, or if there is an ongoing session in that slot
that has not yet timed out. You will end up with exactly
as many participants, as specified in *nslots*.
If *True*, the quota will assign a slot,
if there is no finished session in that slot. That means,
there may be two ongoing sessions for the same slot, and
both might end up to finish.
While inclusive=*False* may lead to participants being turned
away before the experiment is really complete, inclusive=True
may lead to more data being collected than necessary.
Defaults to *False*.
name (str):
An identifier for the quota. If you
give this a custom value, you can use multiple quotas
in the same experiment. Defaults to 'quota'.
abort_page (alfred3.Page): You can reference a custom
page to be displayed to new participants, if the
quota is full.
.. versionadded:: 2.2.0
Examples:
A simple example on how to use the quota::
import alfred3 as al
exp = al.Experiment()
@exp.setup
def setup(exp):
quota = al.SessionQuota(10, exp)
quota.count()
exp += al.Page(title = "Hello, World!", name="hello_world")
|
A quota for experiment sessions.
The quota allows you to enforce an upper limit on the number of
participants in your experiment.
|
[
"A",
"quota",
"for",
"experiment",
"sessions",
".",
"The",
"quota",
"allows",
"you",
"to",
"enforce",
"an",
"upper",
"limit",
"on",
"the",
"number",
"of",
"participants",
"in",
"your",
"experiment",
"."
] |
class SessionQuota:
"""
A quota for experiment sessions.
The quota allows you to enforce an upper limit on the number of
participants in your experiment.
Args:
nslots (int): Maximum number of slots.
exp (alfred3.ExperimentSession): Experiment session.
respect_version (bool):
inclusive (bool):
If *False* (default), the quota will only assign a
slot, if there are no pending sessions for that slot. It will
not assign a slot, if a session in that slot
is finished, or if there is an ongoing session in that slot
that has not yet timed out. You will end up with exactly
as many participants, as specified in *nslots*.
If *True*, the quota will assign a slot,
if there is no finished session in that slot. That means,
there may be two ongoing sessions for the same slot, and
both might end up to finish.
While inclusive=*False* may lead to participants being turned
away before the experiment is really complete, inclusive=True
may lead to more data being collected than necessary.
Defaults to *False*.
name (str):
An identifier for the quota. If you
give this a custom value, you can use multiple quotas
in the same experiment. Defaults to 'quota'.
abort_page (alfred3.Page): You can reference a custom
page to be displayed to new participants, if the
quota is full.
.. versionadded:: 2.2.0
Examples:
A simple example on how to use the quota::
import alfred3 as al
exp = al.Experiment()
@exp.setup
def setup(exp):
quota = al.SessionQuota(10, exp)
quota.count()
exp += al.Page(title = "Hello, World!", name="hello_world")
"""
DATA_TYPE = "quota_data"
def __init__(self, nslots: int, exp, respect_version: bool = True, inclusive: bool = False, name: str = "quota", abort_page=None):
self.nslots = nslots
self.slot_label = "slot"
self.exp = exp
self.respect_version = respect_version
self.exp_version = self.exp.version if respect_version else ""
self.inclusive = inclusive
self.name = name
self.session_ids = [exp.session_id]
self.io = QuotaIO(self)
self.abort_page = abort_page
self._initialize_slots()
@property
def _insert(self) -> QuotaData:
data = QuotaData(
name=self.name,
exp_id=self.exp.exp_id,
exp_version=self.exp_version,
inclusive=self.inclusive,
type=self.DATA_TYPE
)
return data
def _initialize_slots(self):
self.io.load()
with self.io as data:
if not data.slots:
data.slots = self._generate_slots()
self.io.save(data)
def _generate_slots(self) -> List[dict]:
slots = [{"label": self.slot_label}] * self.nslots
return slots
@property
def nopen(self) -> int:
"""
int: Number of open slots.
"""
with self.io as data:
return self._nopen(data)
def _nopen(self, data) -> int:
slot_manager = self._slot_manager(data)
open_slots = list(slot_manager.open_slots(self.exp))
return len(open_slots)
@property
def npending(self) -> int:
"""
int: Number of slots in which a session is still ongoing.
"""
with self.io as data:
return self._npending(data)
def _npending(self, data) -> int:
slot_manager = self._slot_manager(data)
pending_slots = list(slot_manager.pending_slots(self.exp))
return len(pending_slots)
@property
def full(self) -> bool:
"""
bool: *True*, if the randomizer has allocated all available slots.
"""
if self.inclusive:
return (self.nopen + self.npending) == 0
else:
return self.nopen == 0
@property
def nfinished(self) -> int:
"""
int: Number of finished slots.
"""
with self.io as data:
nopen = self._nopen(data)
npending = self._npending(data)
return self.nslots - (nopen + npending)
@property
def allfinished(self) -> bool:
"""
bool: Indicates, whether all slots in the quota are finished.
"""
return self.nfinished == self.nslots
def _accepts_sessions(self, data) -> bool:
"""
bool: *True*, if all slots are full. In 'strict' mode,
unfinished but pending experiment sessions ('pending' sessions)
are counted. In 'inclusive' mode, only sessions that are fully
finished are counted.
"""
if self.inclusive:
nopen = self._nopen(data)
npending = self._npending(data)
n_unfinished = nopen + npending
return not n_unfinished == 0
else:
return self._nopen(data) > 0
def count(self, raise_exception: bool = False) -> str:
"""
Counts the experiment session associated with the quota.
Args:
raise_exception (bool): If True, the function raises
the :class:`.AllSlotsFull` exception instead of
automatically aborting the experiment if all slots
are full. This allows you to catch the exception and
customize the experiment's behavior in this case.
Returns:
str: The slot label.
Raises:
AllSlotsFull: If raise_exception is True and
all slots are full.
SlotInconsistency: If slot validation fails.
Examples:
A simple example on how to use the quota::
import alfred3 as al
exp = al.Experiment()
@exp.setup
def setup(exp):
quota = al.SessionQuota(10, exp)
quota.count()
exp += al.Page(title = "Hello, World!", name="hello_world")
"""
with self.io as data:
self._validate(data)
slot_manager = self._slot_manager(data)
slot = self._own_slot(data)
if slot:
return slot.label
full = not self._accepts_sessions(data)
if full and raise_exception:
raise AllSlotsFull
elif full:
self._abort_exp()
return "__ABORTED__"
slot = next(slot_manager.open_slots(self.exp), None)
if slot is None and self.inclusive:
slot = slot_manager.next_pending(self.exp)
if slot is None:
msg = "No slot found, even though the quota does not appear to be full."
raise SlotInconsistency(msg)
self._update_slot(slot)
data.slots = asdict(slot_manager)["slots"]
self.io.save(data)
return slot.label
def _update_slot(self, slot):
group = SessionGroup(self.session_ids)
slot.session_groups.append(group)
def _slot_manager(self, data: QuotaData) -> SlotManager:
return SlotManager(data.slots)
def next(self) -> Slot:
"""
Returns the next open slot.
"""
with self.io as data:
open_slots = self._slot_manager(data).open_slots(self.exp)
return next(open_slots)
def _own_slot(self, data: QuotaData) -> Slot:
slot_manager = self._slot_manager(data)
slot = slot_manager.find_slot(self.session_ids)
return slot
def _validate(self, data: QuotaData):
if self.respect_version:
if not self.exp.version == data.exp_version:
raise SlotInconsistency(
"Experiment version and randomizer version do not match."
)
def _abort_exp(self):
full_page_title = "Experiment closed"
full_page_text = (
"Sorry, the experiment currently does not accept any further participants."
)
self.exp.abort(
reason="full",
title=full_page_title,
msg=full_page_text,
icon="user-check",
page=self.abort_page,
)
|
[
"class",
"SessionQuota",
":",
"DATA_TYPE",
"=",
"\"quota_data\"",
"def",
"__init__",
"(",
"self",
",",
"nslots",
":",
"int",
",",
"exp",
",",
"respect_version",
":",
"bool",
"=",
"True",
",",
"inclusive",
":",
"bool",
"=",
"False",
",",
"name",
":",
"str",
"=",
"\"quota\"",
",",
"abort_page",
"=",
"None",
")",
":",
"self",
".",
"nslots",
"=",
"nslots",
"self",
".",
"slot_label",
"=",
"\"slot\"",
"self",
".",
"exp",
"=",
"exp",
"self",
".",
"respect_version",
"=",
"respect_version",
"self",
".",
"exp_version",
"=",
"self",
".",
"exp",
".",
"version",
"if",
"respect_version",
"else",
"\"\"",
"self",
".",
"inclusive",
"=",
"inclusive",
"self",
".",
"name",
"=",
"name",
"self",
".",
"session_ids",
"=",
"[",
"exp",
".",
"session_id",
"]",
"self",
".",
"io",
"=",
"QuotaIO",
"(",
"self",
")",
"self",
".",
"abort_page",
"=",
"abort_page",
"self",
".",
"_initialize_slots",
"(",
")",
"@",
"property",
"def",
"_insert",
"(",
"self",
")",
"->",
"QuotaData",
":",
"data",
"=",
"QuotaData",
"(",
"name",
"=",
"self",
".",
"name",
",",
"exp_id",
"=",
"self",
".",
"exp",
".",
"exp_id",
",",
"exp_version",
"=",
"self",
".",
"exp_version",
",",
"inclusive",
"=",
"self",
".",
"inclusive",
",",
"type",
"=",
"self",
".",
"DATA_TYPE",
")",
"return",
"data",
"def",
"_initialize_slots",
"(",
"self",
")",
":",
"self",
".",
"io",
".",
"load",
"(",
")",
"with",
"self",
".",
"io",
"as",
"data",
":",
"if",
"not",
"data",
".",
"slots",
":",
"data",
".",
"slots",
"=",
"self",
".",
"_generate_slots",
"(",
")",
"self",
".",
"io",
".",
"save",
"(",
"data",
")",
"def",
"_generate_slots",
"(",
"self",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"slots",
"=",
"[",
"{",
"\"label\"",
":",
"self",
".",
"slot_label",
"}",
"]",
"*",
"self",
".",
"nslots",
"return",
"slots",
"@",
"property",
"def",
"nopen",
"(",
"self",
")",
"->",
"int",
":",
"\"\"\"\n int: Number of open slots.\n \"\"\"",
"with",
"self",
".",
"io",
"as",
"data",
":",
"return",
"self",
".",
"_nopen",
"(",
"data",
")",
"def",
"_nopen",
"(",
"self",
",",
"data",
")",
"->",
"int",
":",
"slot_manager",
"=",
"self",
".",
"_slot_manager",
"(",
"data",
")",
"open_slots",
"=",
"list",
"(",
"slot_manager",
".",
"open_slots",
"(",
"self",
".",
"exp",
")",
")",
"return",
"len",
"(",
"open_slots",
")",
"@",
"property",
"def",
"npending",
"(",
"self",
")",
"->",
"int",
":",
"\"\"\"\n int: Number of slots in which a session is still ongoing.\n \"\"\"",
"with",
"self",
".",
"io",
"as",
"data",
":",
"return",
"self",
".",
"_npending",
"(",
"data",
")",
"def",
"_npending",
"(",
"self",
",",
"data",
")",
"->",
"int",
":",
"slot_manager",
"=",
"self",
".",
"_slot_manager",
"(",
"data",
")",
"pending_slots",
"=",
"list",
"(",
"slot_manager",
".",
"pending_slots",
"(",
"self",
".",
"exp",
")",
")",
"return",
"len",
"(",
"pending_slots",
")",
"@",
"property",
"def",
"full",
"(",
"self",
")",
"->",
"bool",
":",
"\"\"\"\n bool: *True*, if the randomizer has allocated all available slots.\n \"\"\"",
"if",
"self",
".",
"inclusive",
":",
"return",
"(",
"self",
".",
"nopen",
"+",
"self",
".",
"npending",
")",
"==",
"0",
"else",
":",
"return",
"self",
".",
"nopen",
"==",
"0",
"@",
"property",
"def",
"nfinished",
"(",
"self",
")",
"->",
"int",
":",
"\"\"\"\n int: Number of finished slots.\n \"\"\"",
"with",
"self",
".",
"io",
"as",
"data",
":",
"nopen",
"=",
"self",
".",
"_nopen",
"(",
"data",
")",
"npending",
"=",
"self",
".",
"_npending",
"(",
"data",
")",
"return",
"self",
".",
"nslots",
"-",
"(",
"nopen",
"+",
"npending",
")",
"@",
"property",
"def",
"allfinished",
"(",
"self",
")",
"->",
"bool",
":",
"\"\"\"\n bool: Indicates, whether all slots in the quota are finished.\n \"\"\"",
"return",
"self",
".",
"nfinished",
"==",
"self",
".",
"nslots",
"def",
"_accepts_sessions",
"(",
"self",
",",
"data",
")",
"->",
"bool",
":",
"\"\"\"\n bool: *True*, if all slots are full. In 'strict' mode,\n unfinished but pending experiment sessions ('pending' sessions) \n are counted. In 'inclusive' mode, only sessions that are fully \n finished are counted.\n \"\"\"",
"if",
"self",
".",
"inclusive",
":",
"nopen",
"=",
"self",
".",
"_nopen",
"(",
"data",
")",
"npending",
"=",
"self",
".",
"_npending",
"(",
"data",
")",
"n_unfinished",
"=",
"nopen",
"+",
"npending",
"return",
"not",
"n_unfinished",
"==",
"0",
"else",
":",
"return",
"self",
".",
"_nopen",
"(",
"data",
")",
">",
"0",
"def",
"count",
"(",
"self",
",",
"raise_exception",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"\"\"\"\n Counts the experiment session associated with the quota.\n\n Args:\n raise_exception (bool): If True, the function raises\n the :class:`.AllSlotsFull` exception instead of\n automatically aborting the experiment if all slots\n are full. This allows you to catch the exception and\n customize the experiment's behavior in this case.\n \n Returns:\n str: The slot label.\n\n Raises:\n AllSlotsFull: If raise_exception is True and\n all slots are full.\n SlotInconsistency: If slot validation fails.\n \n Examples:\n A simple example on how to use the quota::\n\n import alfred3 as al\n exp = al.Experiment()\n\n @exp.setup\n def setup(exp):\n quota = al.SessionQuota(10, exp)\n quota.count()\n \n exp += al.Page(title = \"Hello, World!\", name=\"hello_world\")\n \"\"\"",
"with",
"self",
".",
"io",
"as",
"data",
":",
"self",
".",
"_validate",
"(",
"data",
")",
"slot_manager",
"=",
"self",
".",
"_slot_manager",
"(",
"data",
")",
"slot",
"=",
"self",
".",
"_own_slot",
"(",
"data",
")",
"if",
"slot",
":",
"return",
"slot",
".",
"label",
"full",
"=",
"not",
"self",
".",
"_accepts_sessions",
"(",
"data",
")",
"if",
"full",
"and",
"raise_exception",
":",
"raise",
"AllSlotsFull",
"elif",
"full",
":",
"self",
".",
"_abort_exp",
"(",
")",
"return",
"\"__ABORTED__\"",
"slot",
"=",
"next",
"(",
"slot_manager",
".",
"open_slots",
"(",
"self",
".",
"exp",
")",
",",
"None",
")",
"if",
"slot",
"is",
"None",
"and",
"self",
".",
"inclusive",
":",
"slot",
"=",
"slot_manager",
".",
"next_pending",
"(",
"self",
".",
"exp",
")",
"if",
"slot",
"is",
"None",
":",
"msg",
"=",
"\"No slot found, even though the quota does not appear to be full.\"",
"raise",
"SlotInconsistency",
"(",
"msg",
")",
"self",
".",
"_update_slot",
"(",
"slot",
")",
"data",
".",
"slots",
"=",
"asdict",
"(",
"slot_manager",
")",
"[",
"\"slots\"",
"]",
"self",
".",
"io",
".",
"save",
"(",
"data",
")",
"return",
"slot",
".",
"label",
"def",
"_update_slot",
"(",
"self",
",",
"slot",
")",
":",
"group",
"=",
"SessionGroup",
"(",
"self",
".",
"session_ids",
")",
"slot",
".",
"session_groups",
".",
"append",
"(",
"group",
")",
"def",
"_slot_manager",
"(",
"self",
",",
"data",
":",
"QuotaData",
")",
"->",
"SlotManager",
":",
"return",
"SlotManager",
"(",
"data",
".",
"slots",
")",
"def",
"next",
"(",
"self",
")",
"->",
"Slot",
":",
"\"\"\"\n Returns the next open slot.\n \"\"\"",
"with",
"self",
".",
"io",
"as",
"data",
":",
"open_slots",
"=",
"self",
".",
"_slot_manager",
"(",
"data",
")",
".",
"open_slots",
"(",
"self",
".",
"exp",
")",
"return",
"next",
"(",
"open_slots",
")",
"def",
"_own_slot",
"(",
"self",
",",
"data",
":",
"QuotaData",
")",
"->",
"Slot",
":",
"slot_manager",
"=",
"self",
".",
"_slot_manager",
"(",
"data",
")",
"slot",
"=",
"slot_manager",
".",
"find_slot",
"(",
"self",
".",
"session_ids",
")",
"return",
"slot",
"def",
"_validate",
"(",
"self",
",",
"data",
":",
"QuotaData",
")",
":",
"if",
"self",
".",
"respect_version",
":",
"if",
"not",
"self",
".",
"exp",
".",
"version",
"==",
"data",
".",
"exp_version",
":",
"raise",
"SlotInconsistency",
"(",
"\"Experiment version and randomizer version do not match.\"",
")",
"def",
"_abort_exp",
"(",
"self",
")",
":",
"full_page_title",
"=",
"\"Experiment closed\"",
"full_page_text",
"=",
"(",
"\"Sorry, the experiment currently does not accept any further participants.\"",
")",
"self",
".",
"exp",
".",
"abort",
"(",
"reason",
"=",
"\"full\"",
",",
"title",
"=",
"full_page_title",
",",
"msg",
"=",
"full_page_text",
",",
"icon",
"=",
"\"user-check\"",
",",
"page",
"=",
"self",
".",
"abort_page",
",",
")"
] |
A quota for experiment sessions.
|
[
"A",
"quota",
"for",
"experiment",
"sessions",
"."
] |
[
"\"\"\"\n A quota for experiment sessions.\n\n The quota allows you to enforce an upper limit on the number of \n participants in your experiment.\n\n Args:\n nslots (int): Maximum number of slots.\n exp (alfred3.ExperimentSession): Experiment session.\n respect_version (bool):\n inclusive (bool):\n If *False* (default), the quota will only assign a\n slot, if there are no pending sessions for that slot. It will\n not assign a slot, if a session in that slot\n is finished, or if there is an ongoing session in that slot\n that has not yet timed out. You will end up with exactly\n as many participants, as specified in *nslots*.\n\n If *True*, the quota will assign a slot,\n if there is no finished session in that slot. That means,\n there may be two ongoing sessions for the same slot, and\n both might end up to finish.\n\n While inclusive=*False* may lead to participants being turned\n away before the experiment is really complete, inclusive=True\n may lead to more data being collected than necessary.\n\n Defaults to *False*.\n name (str): \n An identifier for the quota. If you\n give this a custom value, you can use multiple quotas\n in the same experiment. Defaults to 'quota'.\n abort_page (alfred3.Page): You can reference a custom\n page to be displayed to new participants, if the\n quota is full.\n \n .. versionadded:: 2.2.0\n\n Examples:\n A simple example on how to use the quota::\n\n import alfred3 as al\n exp = al.Experiment()\n\n @exp.setup\n def setup(exp):\n quota = al.SessionQuota(10, exp)\n quota.count()\n \n exp += al.Page(title = \"Hello, World!\", name=\"hello_world\")\n\n \"\"\"",
"\"\"\"\n int: Number of open slots.\n \"\"\"",
"\"\"\"\n int: Number of slots in which a session is still ongoing.\n \"\"\"",
"\"\"\"\n bool: *True*, if the randomizer has allocated all available slots.\n \"\"\"",
"\"\"\"\n int: Number of finished slots.\n \"\"\"",
"\"\"\"\n bool: Indicates, whether all slots in the quota are finished.\n \"\"\"",
"\"\"\"\n bool: *True*, if all slots are full. In 'strict' mode,\n unfinished but pending experiment sessions ('pending' sessions) \n are counted. In 'inclusive' mode, only sessions that are fully \n finished are counted.\n \"\"\"",
"\"\"\"\n Counts the experiment session associated with the quota.\n\n Args:\n raise_exception (bool): If True, the function raises\n the :class:`.AllSlotsFull` exception instead of\n automatically aborting the experiment if all slots\n are full. This allows you to catch the exception and\n customize the experiment's behavior in this case.\n \n Returns:\n str: The slot label.\n\n Raises:\n AllSlotsFull: If raise_exception is True and\n all slots are full.\n SlotInconsistency: If slot validation fails.\n \n Examples:\n A simple example on how to use the quota::\n\n import alfred3 as al\n exp = al.Experiment()\n\n @exp.setup\n def setup(exp):\n quota = al.SessionQuota(10, exp)\n quota.count()\n \n exp += al.Page(title = \"Hello, World!\", name=\"hello_world\")\n \"\"\"",
"\"\"\"\n Returns the next open slot.\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "nslots",
"type": null,
"docstring": "Maximum number of slots.",
"docstring_tokens": [
"Maximum",
"number",
"of",
"slots",
"."
],
"default": null,
"is_optional": false
},
{
"identifier": "exp",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": false
},
{
"identifier": "respect_version",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": false
},
{
"identifier": "inclusive",
"type": null,
"docstring": "If *False* (default), the quota will only assign a\nslot, if there are no pending sessions for that slot. It will\nnot assign a slot, if a session in that slot\nis finished, or if there is an ongoing session in that slot\nthat has not yet timed out. You will end up with exactly\nas many participants, as specified in *nslots*.\n\nIf *True*, the quota will assign a slot,\nif there is no finished session in that slot. That means,\nthere may be two ongoing sessions for the same slot, and\nboth might end up to finish.\n\nWhile inclusive=*False* may lead to participants being turned\naway before the experiment is really complete, inclusive=True\nmay lead to more data being collected than necessary.\n\nDefaults to *False*.",
"docstring_tokens": [
"If",
"*",
"False",
"*",
"(",
"default",
")",
"the",
"quota",
"will",
"only",
"assign",
"a",
"slot",
"if",
"there",
"are",
"no",
"pending",
"sessions",
"for",
"that",
"slot",
".",
"It",
"will",
"not",
"assign",
"a",
"slot",
"if",
"a",
"session",
"in",
"that",
"slot",
"is",
"finished",
"or",
"if",
"there",
"is",
"an",
"ongoing",
"session",
"in",
"that",
"slot",
"that",
"has",
"not",
"yet",
"timed",
"out",
".",
"You",
"will",
"end",
"up",
"with",
"exactly",
"as",
"many",
"participants",
"as",
"specified",
"in",
"*",
"nslots",
"*",
".",
"If",
"*",
"True",
"*",
"the",
"quota",
"will",
"assign",
"a",
"slot",
"if",
"there",
"is",
"no",
"finished",
"session",
"in",
"that",
"slot",
".",
"That",
"means",
"there",
"may",
"be",
"two",
"ongoing",
"sessions",
"for",
"the",
"same",
"slot",
"and",
"both",
"might",
"end",
"up",
"to",
"finish",
".",
"While",
"inclusive",
"=",
"*",
"False",
"*",
"may",
"lead",
"to",
"participants",
"being",
"turned",
"away",
"before",
"the",
"experiment",
"is",
"really",
"complete",
"inclusive",
"=",
"True",
"may",
"lead",
"to",
"more",
"data",
"being",
"collected",
"than",
"necessary",
".",
"Defaults",
"to",
"*",
"False",
"*",
"."
],
"default": null,
"is_optional": false
},
{
"identifier": "name",
"type": null,
"docstring": "An identifier for the quota. If you\ngive this a custom value, you can use multiple quotas\nin the same experiment. Defaults to 'quota'.",
"docstring_tokens": [
"An",
"identifier",
"for",
"the",
"quota",
".",
"If",
"you",
"give",
"this",
"a",
"custom",
"value",
"you",
"can",
"use",
"multiple",
"quotas",
"in",
"the",
"same",
"experiment",
".",
"Defaults",
"to",
"'",
"quota",
"'",
"."
],
"default": null,
"is_optional": false
},
{
"identifier": "abort_page",
"type": null,
"docstring": "You can reference a custom\npage to be displayed to new participants, if the\nquota is full.",
"docstring_tokens": [
"You",
"can",
"reference",
"a",
"custom",
"page",
"to",
"be",
"displayed",
"to",
"new",
"participants",
"if",
"the",
"quota",
"is",
"full",
"."
],
"default": null,
"is_optional": false
}
],
"others": [
{
"identifier": "examples",
"docstring": "A simple example on how to use the quota:.\n\nimport alfred3 as al\nexp = al.Experiment()\n\[email protected]\ndef setup(exp):\nquota = al.SessionQuota(10, exp)\nquota.count()\n\nexp += al.Page(title = \"Hello, World!\", name=\"hello_world\")",
"docstring_tokens": [
"A",
"simple",
"example",
"on",
"how",
"to",
"use",
"the",
"quota",
":",
".",
"import",
"alfred3",
"as",
"al",
"exp",
"=",
"al",
".",
"Experiment",
"()",
"@exp",
".",
"setup",
"def",
"setup",
"(",
"exp",
")",
":",
"quota",
"=",
"al",
".",
"SessionQuota",
"(",
"10",
"exp",
")",
"quota",
".",
"count",
"()",
"exp",
"+",
"=",
"al",
".",
"Page",
"(",
"title",
"=",
"\"",
"Hello",
"World!",
"\"",
"name",
"=",
"\"",
"hello_world",
"\"",
")"
]
}
]
}
| false
| 14
| 1,815
| 405
|
96b63c8b7edac3da6592d76f7582cd7ca309a36c
|
591094733/google-api-dotnet-client
|
Src/Generated/Google.Apis.AndroidEnterprise.v1/Google.Apis.AndroidEnterprise.v1.cs
|
[
"Apache-2.0"
] |
C#
|
PatchRequest
|
/// <summary>Adds or updates the managed configuration settings for an app for the specified user. If you
/// support the Managed configurations iframe, you can apply managed configurations to a user by specifying an
/// mcmId and its associated configuration variables (if any) in the request. Alternatively, all EMMs can apply
/// managed configurations by passing a list of managed properties. This method supports patch
/// semantics.</summary>
|
Adds or updates the managed configuration settings for an app for the specified user. If you
support the Managed configurations iframe, you can apply managed configurations to a user by specifying an
mcmId and its associated configuration variables (if any) in the request. Alternatively, all EMMs can apply
managed configurations by passing a list of managed properties. This method supports patch
semantics.
|
[
"Adds",
"or",
"updates",
"the",
"managed",
"configuration",
"settings",
"for",
"an",
"app",
"for",
"the",
"specified",
"user",
".",
"If",
"you",
"support",
"the",
"Managed",
"configurations",
"iframe",
"you",
"can",
"apply",
"managed",
"configurations",
"to",
"a",
"user",
"by",
"specifying",
"an",
"mcmId",
"and",
"its",
"associated",
"configuration",
"variables",
"(",
"if",
"any",
")",
"in",
"the",
"request",
".",
"Alternatively",
"all",
"EMMs",
"can",
"apply",
"managed",
"configurations",
"by",
"passing",
"a",
"list",
"of",
"managed",
"properties",
".",
"This",
"method",
"supports",
"patch",
"semantics",
"."
] |
public class PatchRequest : AndroidEnterpriseBaseServiceRequest<Google.Apis.AndroidEnterprise.v1.Data.ManagedConfiguration>
{
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.AndroidEnterprise.v1.Data.ManagedConfiguration body, string enterpriseId, string userId, string managedConfigurationForUserId)
: base(service)
{
EnterpriseId = enterpriseId;
UserId = userId;
ManagedConfigurationForUserId = managedConfigurationForUserId;
Body = body;
InitParameters();
}
[Google.Apis.Util.RequestParameterAttribute("enterpriseId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string EnterpriseId { get; private set; }
[Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string UserId { get; private set; }
[Google.Apis.Util.RequestParameterAttribute("managedConfigurationForUserId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ManagedConfigurationForUserId { get; private set; }
Google.Apis.AndroidEnterprise.v1.Data.ManagedConfiguration Body { get; set; }
protected override object GetBody() { return Body; }
public override string MethodName
{
get { return "patch"; }
}
public override string HttpMethod
{
get { return "PATCH"; }
}
public override string RestPath
{
get { return "enterprises/{enterpriseId}/users/{userId}/managedConfigurationsForUser/{managedConfigurationForUserId}"; }
}
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"enterpriseId", new Google.Apis.Discovery.Parameter
{
Name = "enterpriseId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userId", new Google.Apis.Discovery.Parameter
{
Name = "userId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"managedConfigurationForUserId", new Google.Apis.Discovery.Parameter
{
Name = "managedConfigurationForUserId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
|
[
"public",
"class",
"PatchRequest",
":",
"AndroidEnterpriseBaseServiceRequest",
"<",
"Google",
".",
"Apis",
".",
"AndroidEnterprise",
".",
"v1",
".",
"Data",
".",
"ManagedConfiguration",
">",
"{",
"public",
"PatchRequest",
"(",
"Google",
".",
"Apis",
".",
"Services",
".",
"IClientService",
"service",
",",
"Google",
".",
"Apis",
".",
"AndroidEnterprise",
".",
"v1",
".",
"Data",
".",
"ManagedConfiguration",
"body",
",",
"string",
"enterpriseId",
",",
"string",
"userId",
",",
"string",
"managedConfigurationForUserId",
")",
":",
"base",
"(",
"service",
")",
"{",
"EnterpriseId",
"=",
"enterpriseId",
";",
"UserId",
"=",
"userId",
";",
"ManagedConfigurationForUserId",
"=",
"managedConfigurationForUserId",
";",
"Body",
"=",
"body",
";",
"InitParameters",
"(",
")",
";",
"}",
"[",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterAttribute",
"(",
"\"",
"enterpriseId",
"\"",
",",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterType",
".",
"Path",
")",
"]",
"public",
"virtual",
"string",
"EnterpriseId",
"{",
"get",
";",
"private",
"set",
";",
"}",
"[",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterAttribute",
"(",
"\"",
"userId",
"\"",
",",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterType",
".",
"Path",
")",
"]",
"public",
"virtual",
"string",
"UserId",
"{",
"get",
";",
"private",
"set",
";",
"}",
"[",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterAttribute",
"(",
"\"",
"managedConfigurationForUserId",
"\"",
",",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterType",
".",
"Path",
")",
"]",
"public",
"virtual",
"string",
"ManagedConfigurationForUserId",
"{",
"get",
";",
"private",
"set",
";",
"}",
"Google",
".",
"Apis",
".",
"AndroidEnterprise",
".",
"v1",
".",
"Data",
".",
"ManagedConfiguration",
"Body",
"{",
"get",
";",
"set",
";",
"}",
"protected",
"override",
"object",
"GetBody",
"(",
")",
"{",
"return",
"Body",
";",
"}",
"public",
"override",
"string",
"MethodName",
"{",
"get",
"{",
"return",
"\"",
"patch",
"\"",
";",
"}",
"}",
"public",
"override",
"string",
"HttpMethod",
"{",
"get",
"{",
"return",
"\"",
"PATCH",
"\"",
";",
"}",
"}",
"public",
"override",
"string",
"RestPath",
"{",
"get",
"{",
"return",
"\"",
"enterprises/{enterpriseId}/users/{userId}/managedConfigurationsForUser/{managedConfigurationForUserId}",
"\"",
";",
"}",
"}",
"protected",
"override",
"void",
"InitParameters",
"(",
")",
"{",
"base",
".",
"InitParameters",
"(",
")",
";",
"RequestParameters",
".",
"Add",
"(",
"\"",
"enterpriseId",
"\"",
",",
"new",
"Google",
".",
"Apis",
".",
"Discovery",
".",
"Parameter",
"{",
"Name",
"=",
"\"",
"enterpriseId",
"\"",
",",
"IsRequired",
"=",
"true",
",",
"ParameterType",
"=",
"\"",
"path",
"\"",
",",
"DefaultValue",
"=",
"null",
",",
"Pattern",
"=",
"null",
",",
"}",
")",
";",
"RequestParameters",
".",
"Add",
"(",
"\"",
"userId",
"\"",
",",
"new",
"Google",
".",
"Apis",
".",
"Discovery",
".",
"Parameter",
"{",
"Name",
"=",
"\"",
"userId",
"\"",
",",
"IsRequired",
"=",
"true",
",",
"ParameterType",
"=",
"\"",
"path",
"\"",
",",
"DefaultValue",
"=",
"null",
",",
"Pattern",
"=",
"null",
",",
"}",
")",
";",
"RequestParameters",
".",
"Add",
"(",
"\"",
"managedConfigurationForUserId",
"\"",
",",
"new",
"Google",
".",
"Apis",
".",
"Discovery",
".",
"Parameter",
"{",
"Name",
"=",
"\"",
"managedConfigurationForUserId",
"\"",
",",
"IsRequired",
"=",
"true",
",",
"ParameterType",
"=",
"\"",
"path",
"\"",
",",
"DefaultValue",
"=",
"null",
",",
"Pattern",
"=",
"null",
",",
"}",
")",
";",
"}",
"}"
] |
Adds or updates the managed configuration settings for an app for the specified user.
|
[
"Adds",
"or",
"updates",
"the",
"managed",
"configuration",
"settings",
"for",
"an",
"app",
"for",
"the",
"specified",
"user",
"."
] |
[
"/// <summary>Constructs a new Patch request.</summary>",
"/// <summary>The ID of the enterprise.</summary>",
"/// <summary>The ID of the user.</summary>",
"/// <summary>The ID of the managed configuration (a product ID), e.g. \"app:com.google.android.gm\".</summary>",
"/// <summary>Gets or sets the body of this request.</summary>",
"///<summary>Returns the body of the request.</summary>",
"///<summary>Gets the method name.</summary>",
"///<summary>Gets the HTTP method.</summary>",
"///<summary>Gets the REST path.</summary>",
"/// <summary>Initializes Patch parameter list.</summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 483
| 88
|
b6bc327810d68b4c09fa8167f92b90e62c6ff2bb
|
286studio/Sim286
|
AVG/Assets/Naninovel/Runtime/Command/Player/Gosub.cs
|
[
"MIT"
] |
C#
|
Gosub
|
/// <summary>
/// Navigates naninovel script playback to the provided path and saves that path to global state;
/// [@return] commands use this info to redirect to command after the last invoked gosub command.
/// Designed to serve as a function (subroutine) in a programming language, allowing to reuse a piece of naninovel script.
/// Useful for invoking a repeating set of commands multiple times.
/// </summary>
/// <remarks>
/// It's possible to declare a gosub outside of the currently played script and use it from any other scripts;
/// by default state reset won't happen when you're loading another script to play a gosub or returning back to
/// prevent delays and loading screens. Be aware though, that all the resources referenced in gosub script will be
/// held until the next state reset.
/// </remarks>
/// <example>
/// ; Navigate the playback to the label `VictoryScene` in the currently played script,
/// ; executes the commands and navigates back to the command after the `gosub`.
/// @gosub .VictoryScene
/// ...
/// @stop
///
/// # VictoryScene
/// @back Victory
/// @sfx Fireworks
/// @bgm Fanfares
/// You are victorious!
/// @return
///
/// ; Another example with some branching inside the subroutine.
/// @set time=10
/// ; Here we get one result
/// @gosub .Room
/// ...
/// @set time=3
/// ; And here we get another
/// @gosub .Room
/// ...
///
/// # Room
/// @print "It's too early, I should visit this place when it's dark." if:time<21&&time>6
/// @print "I can sense an ominous presence here!" if:time>21&&time<6
/// @return
/// </example>
|
Navigates naninovel script playback to the provided path and saves that path to global state;
[@return] commands use this info to redirect to command after the last invoked gosub command.
Designed to serve as a function (subroutine) in a programming language, allowing to reuse a piece of naninovel script.
Useful for invoking a repeating set of commands multiple times.
|
[
"Navigates",
"naninovel",
"script",
"playback",
"to",
"the",
"provided",
"path",
"and",
"saves",
"that",
"path",
"to",
"global",
"state",
";",
"[",
"@return",
"]",
"commands",
"use",
"this",
"info",
"to",
"redirect",
"to",
"command",
"after",
"the",
"last",
"invoked",
"gosub",
"command",
".",
"Designed",
"to",
"serve",
"as",
"a",
"function",
"(",
"subroutine",
")",
"in",
"a",
"programming",
"language",
"allowing",
"to",
"reuse",
"a",
"piece",
"of",
"naninovel",
"script",
".",
"Useful",
"for",
"invoking",
"a",
"repeating",
"set",
"of",
"commands",
"multiple",
"times",
"."
] |
public class Gosub : Command, Command.IForceWait
{
[ParameterAlias(NamelessParameterAlias), RequiredParameter]
public NamedStringParameter Path;
[ParameterAlias("reset")]
public StringListParameter ResetState;
public override async UniTask ExecuteAsync (CancellationToken cancellationToken = default)
{
var player = Engine.GetService<IScriptPlayer>();
var spot = new PlaybackSpot(player.PlayedScript.Name, player.PlayedCommand?.PlaybackSpot.LineIndex + 1 ?? 0, 0);
player.GosubReturnSpots.Push(spot);
var resetState = Assigned(ResetState) ? ResetState : (StringListParameter)new List<string> { Goto.NoResetFlag };
await new Goto { Path = Path, ResetState = resetState }.ExecuteAsync(cancellationToken);
}
}
|
[
"public",
"class",
"Gosub",
":",
"Command",
",",
"Command",
".",
"IForceWait",
"{",
"[",
"ParameterAlias",
"(",
"NamelessParameterAlias",
")",
",",
"RequiredParameter",
"]",
"public",
"NamedStringParameter",
"Path",
";",
"[",
"ParameterAlias",
"(",
"\"",
"reset",
"\"",
")",
"]",
"public",
"StringListParameter",
"ResetState",
";",
"public",
"override",
"async",
"UniTask",
"ExecuteAsync",
"(",
"CancellationToken",
"cancellationToken",
"=",
"default",
")",
"{",
"var",
"player",
"=",
"Engine",
".",
"GetService",
"<",
"IScriptPlayer",
">",
"(",
")",
";",
"var",
"spot",
"=",
"new",
"PlaybackSpot",
"(",
"player",
".",
"PlayedScript",
".",
"Name",
",",
"player",
".",
"PlayedCommand",
"?",
".",
"PlaybackSpot",
".",
"LineIndex",
"+",
"1",
"??",
"0",
",",
"0",
")",
";",
"player",
".",
"GosubReturnSpots",
".",
"Push",
"(",
"spot",
")",
";",
"var",
"resetState",
"=",
"Assigned",
"(",
"ResetState",
")",
"?",
"ResetState",
":",
"(",
"StringListParameter",
")",
"new",
"List",
"<",
"string",
">",
"{",
"Goto",
".",
"NoResetFlag",
"}",
";",
"await",
"new",
"Goto",
"{",
"Path",
"=",
"Path",
",",
"ResetState",
"=",
"resetState",
"}",
".",
"ExecuteAsync",
"(",
"cancellationToken",
")",
";",
"}",
"}"
] |
Navigates naninovel script playback to the provided path and saves that path to global state;
[@return] commands use this info to redirect to command after the last invoked gosub command.
|
[
"Navigates",
"naninovel",
"script",
"playback",
"to",
"the",
"provided",
"path",
"and",
"saves",
"that",
"path",
"to",
"global",
"state",
";",
"[",
"@return",
"]",
"commands",
"use",
"this",
"info",
"to",
"redirect",
"to",
"command",
"after",
"the",
"last",
"invoked",
"gosub",
"command",
"."
] |
[
"/// <summary>",
"/// Path to navigate into in the following format: `ScriptName.LabelName`.",
"/// When label name is ommited, will play provided script from the start.",
"/// When script name is ommited, will attempt to find a label in the currently played script.",
"/// </summary>",
"/// <summary>",
"/// When specified, will reset the engine services state before loading a script (in case the path is leading to another script).",
"/// Specify `*` to reset all the services (except variable manager), or specify service names to exclude from reset.",
"/// By default, the state does not reset.",
"/// </summary>"
] |
[
{
"param": "Command",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Command",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "It's possible to declare a gosub outside of the currently played script and use it from any other scripts;\nby default state reset won't happen when you're loading another script to play a gosub or returning back to\nprevent delays and loading screens. Be aware though, that all the resources referenced in gosub script will be\nheld until the next state reset.",
"docstring_tokens": [
"It",
"'",
"s",
"possible",
"to",
"declare",
"a",
"gosub",
"outside",
"of",
"the",
"currently",
"played",
"script",
"and",
"use",
"it",
"from",
"any",
"other",
"scripts",
";",
"by",
"default",
"state",
"reset",
"won",
"'",
"t",
"happen",
"when",
"you",
"'",
"re",
"loading",
"another",
"script",
"to",
"play",
"a",
"gosub",
"or",
"returning",
"back",
"to",
"prevent",
"delays",
"and",
"loading",
"screens",
".",
"Be",
"aware",
"though",
"that",
"all",
"the",
"resources",
"referenced",
"in",
"gosub",
"script",
"will",
"be",
"held",
"until",
"the",
"next",
"state",
"reset",
"."
]
},
{
"identifier": "example",
"docstring": "; Navigate the playback to the label `VictoryScene` in the currently played script,\n; executes the commands and navigates back to the command after the `gosub`.\n@gosub .VictoryScene\n\n@stop\n\nVictoryScene\n@back Victory\n@sfx Fireworks\n@bgm Fanfares\nYou are victorious.\n@return\n\n; Another example with some branching inside the subroutine.\n@set time=10\n; Here we get one result\n@gosub .Room\n\n@set time=3\n; And here we get another\n@gosub .Room\n\nRoom\n@print \"It's too early, I should visit this place when it's dark.\" if:time<21&&time>6\n@print \"I can sense an ominous presence here!\" if:time>21&&time<6\n@return",
"docstring_tokens": [
";",
"Navigate",
"the",
"playback",
"to",
"the",
"label",
"`",
"VictoryScene",
"`",
"in",
"the",
"currently",
"played",
"script",
";",
"executes",
"the",
"commands",
"and",
"navigates",
"back",
"to",
"the",
"command",
"after",
"the",
"`",
"gosub",
"`",
".",
"@gosub",
".",
"VictoryScene",
"@stop",
"VictoryScene",
"@back",
"Victory",
"@sfx",
"Fireworks",
"@bgm",
"Fanfares",
"You",
"are",
"victorious",
".",
"@return",
";",
"Another",
"example",
"with",
"some",
"branching",
"inside",
"the",
"subroutine",
".",
"@set",
"time",
"=",
"10",
";",
"Here",
"we",
"get",
"one",
"result",
"@gosub",
".",
"Room",
"@set",
"time",
"=",
"3",
";",
"And",
"here",
"we",
"get",
"another",
"@gosub",
".",
"Room",
"Room",
"@print",
"\"",
"It",
"'",
"s",
"too",
"early",
"I",
"should",
"visit",
"this",
"place",
"when",
"it",
"'",
"s",
"dark",
".",
"\"",
"if",
":",
"time<21&&time",
">",
"6",
"@print",
"\"",
"I",
"can",
"sense",
"an",
"ominous",
"presence",
"here!",
"\"",
"if",
":",
"time",
">",
"21&&time<6",
"@return"
]
}
]
}
| false
| 16
| 174
| 409
|
91f2ae248059a75ea181ba34f48fabbfd68bd772
|
runslash/async-mongo-ruby-driver
|
lib/mongo/protocol/update.rb
|
[
"Apache-2.0"
] |
Ruby
|
Mongo
|
# Copyright (C) 2014-2019 MongoDB, Inc.
#
# 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.
|
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.
|
[
"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",
"."
] |
module Mongo
module Protocol
# MongoDB Wire protocol Update message.
#
# This is a client request message that is sent to the server in order
# to update documents matching the provided query.
#
# The default is to update a single document. In order to update many at
# a time users should set the +:multi_update+ flag for the update.
#
# If an upsert (update or insert) is desired, users can set the +:upsert+
# flag in order to indicate they would like to insert the merged selector
# and update if no document matching the update query currently exists.
#
# @api semipublic
class Update < Message
# Creates a new Update message
#
# @example Update single document
# Update.new('xgen', 'users', {:name => 'Tyler'}, {:name => 'Bob'})
#
# @example Perform a multi update
# Update.new('xgen', 'users',
# {:age => 20}, {:age => 21}, :flags => [:multi_update])
#
# @example Perform an upsert
# Update.new('xgen', 'users', {:name => 'Tyler'}, :flags => [:upsert])
#
# @param database [String, Symbol] The database to update.
# @param collection [String, Symbol] The collection to update.
# @param selector [Hash] The update selector.
# @param update [Hash] The update to perform.
# @param options [Hash] The additional query options.
#
# @option options :flags [Array] The flags for the update message.
#
# Supported flags: +:upsert+, +:multi_update+
def initialize(database, collection, selector, update, options = {})
@database = database
@collection = collection
@namespace = "#{database}.#{collection}"
@selector = selector
@update = update
@flags = options[:flags] || []
@upconverter = Upconverter.new(collection, selector, update, flags)
super
end
# Return the event payload for monitoring.
#
# @example Return the event payload.
# message.payload
#
# @return [ BSON::Document ] The event payload.
#
# @since 2.1.0
def payload
BSON::Document.new(
command_name: 'update',
database_name: @database,
command: upconverter.command,
request_id: request_id
)
end
protected
attr_reader :upconverter
private
# The operation code required to specify an Update message.
# @return [Fixnum] the operation code.
#
# @since 2.5.0
OP_CODE = 2001
# Available flags for an Update message.
FLAGS = [:upsert, :multi_update]
# Field representing Zero encoded as an Int32.
field :zero, Zero
# @!attribute
# @return [String] The namespace for this Update message.
field :namespace, CString
# @!attribute
# @return [Array<Symbol>] The flags for this Update message.
field :flags, BitVector.new(FLAGS)
# @!attribute
# @return [Hash] The selector for this Update message.
field :selector, Document
# @!attribute
# @return [Hash] The update for this Delete message.
field :update, Document
# Converts legacy update messages to the appropriare OP_COMMAND style
# message.
#
# @since 2.1.0
class Upconverter
# The multi constant.
#
# @since 2.2.0
MULTI = 'multi'.freeze
# The u constant.
#
# @since 2.2.0
U = 'u'.freeze
# The update constant.
#
# @since 2.2.0
UPDATE = 'update'.freeze
# The updates constant.
#
# @since 2.2.0
UPDATES = 'updates'.freeze
# The upsert constant.
#
# @since 2.2.0
UPSERT = 'upsert'.freeze
# @return [ String ] collection The name of the collection.
attr_reader :collection
# @return [ Hash ] filter The filter.
attr_reader :filter
# @return [ Hash ] update The update.
attr_reader :update
# @return [ Array<Symbol> ] flags The flags.
attr_reader :flags
# Instantiate the upconverter.
#
# @example Instantiate the upconverter.
# Upconverter.new(
# 'users',
# { name: 'test' },
# { '$set' => { 'name' => 't' }},
# []
# )
#
# @param [ String ] collection The name of the collection.
# @param [ Hash ] filter The filter.
# @param [ Hash ] update The update.
# @param [ Array<Symbol> ] flags The flags.
#
# @since 2.1.0
def initialize(collection, filter, update, flags)
@collection = collection
@filter = filter
@update = update
@flags = flags
end
# Get the upconverted command.
#
# @example Get the command.
# upconverter.command
#
# @return [ BSON::Document ] The upconverted command.
#
# @since 2.1.0
def command
document = BSON::Document.new
updates = BSON::Document.new
updates.store(Message::Q, filter)
updates.store(U, update)
if flags.include?(:multi_update)
updates.store(MULTI, true)
end
if flags.include?(:upsert)
updates.store(UPSERT, true)
end
document.store(UPDATE, collection)
document.store(Message::ORDERED, true)
document.store(UPDATES, [ updates ])
document
end
end
Registry.register(OP_CODE, self)
end
end
end
|
[
"module",
"Mongo",
"module",
"Protocol",
"class",
"Update",
"<",
"Message",
"def",
"initialize",
"(",
"database",
",",
"collection",
",",
"selector",
",",
"update",
",",
"options",
"=",
"{",
"}",
")",
"@database",
"=",
"database",
"@collection",
"=",
"collection",
"@namespace",
"=",
"\"#{database}.#{collection}\"",
"@selector",
"=",
"selector",
"@update",
"=",
"update",
"@flags",
"=",
"options",
"[",
":flags",
"]",
"||",
"[",
"]",
"@upconverter",
"=",
"Upconverter",
".",
"new",
"(",
"collection",
",",
"selector",
",",
"update",
",",
"flags",
")",
"super",
"end",
"def",
"payload",
"BSON",
"::",
"Document",
".",
"new",
"(",
"command_name",
":",
"'update'",
",",
"database_name",
":",
"@database",
",",
"command",
":",
"upconverter",
".",
"command",
",",
"request_id",
":",
"request_id",
")",
"end",
"protected",
"attr_reader",
":upconverter",
"private",
"OP_CODE",
"=",
"2001",
"FLAGS",
"=",
"[",
":upsert",
",",
":multi_update",
"]",
"field",
":zero",
",",
"Zero",
"field",
":namespace",
",",
"CString",
"field",
":flags",
",",
"BitVector",
".",
"new",
"(",
"FLAGS",
")",
"field",
":selector",
",",
"Document",
"field",
":update",
",",
"Document",
"class",
"Upconverter",
"MULTI",
"=",
"'multi'",
".",
"freeze",
"U",
"=",
"'u'",
".",
"freeze",
"UPDATE",
"=",
"'update'",
".",
"freeze",
"UPDATES",
"=",
"'updates'",
".",
"freeze",
"UPSERT",
"=",
"'upsert'",
".",
"freeze",
"attr_reader",
":collection",
"attr_reader",
":filter",
"attr_reader",
":update",
"attr_reader",
":flags",
"def",
"initialize",
"(",
"collection",
",",
"filter",
",",
"update",
",",
"flags",
")",
"@collection",
"=",
"collection",
"@filter",
"=",
"filter",
"@update",
"=",
"update",
"@flags",
"=",
"flags",
"end",
"def",
"command",
"document",
"=",
"BSON",
"::",
"Document",
".",
"new",
"updates",
"=",
"BSON",
"::",
"Document",
".",
"new",
"updates",
".",
"store",
"(",
"Message",
"::",
"Q",
",",
"filter",
")",
"updates",
".",
"store",
"(",
"U",
",",
"update",
")",
"if",
"flags",
".",
"include?",
"(",
":multi_update",
")",
"updates",
".",
"store",
"(",
"MULTI",
",",
"true",
")",
"end",
"if",
"flags",
".",
"include?",
"(",
":upsert",
")",
"updates",
".",
"store",
"(",
"UPSERT",
",",
"true",
")",
"end",
"document",
".",
"store",
"(",
"UPDATE",
",",
"collection",
")",
"document",
".",
"store",
"(",
"Message",
"::",
"ORDERED",
",",
"true",
")",
"document",
".",
"store",
"(",
"UPDATES",
",",
"[",
"updates",
"]",
")",
"document",
"end",
"end",
"Registry",
".",
"register",
"(",
"OP_CODE",
",",
"self",
")",
"end",
"end",
"end"
] |
Copyright (C) 2014-2019 MongoDB, Inc.
|
[
"Copyright",
"(",
"C",
")",
"2014",
"-",
"2019",
"MongoDB",
"Inc",
"."
] |
[
"# MongoDB Wire protocol Update message.",
"#",
"# This is a client request message that is sent to the server in order",
"# to update documents matching the provided query.",
"#",
"# The default is to update a single document. In order to update many at",
"# a time users should set the +:multi_update+ flag for the update.",
"#",
"# If an upsert (update or insert) is desired, users can set the +:upsert+",
"# flag in order to indicate they would like to insert the merged selector",
"# and update if no document matching the update query currently exists.",
"#",
"# @api semipublic",
"# Creates a new Update message",
"#",
"# @example Update single document",
"# Update.new('xgen', 'users', {:name => 'Tyler'}, {:name => 'Bob'})",
"#",
"# @example Perform a multi update",
"# Update.new('xgen', 'users',",
"# {:age => 20}, {:age => 21}, :flags => [:multi_update])",
"#",
"# @example Perform an upsert",
"# Update.new('xgen', 'users', {:name => 'Tyler'}, :flags => [:upsert])",
"#",
"# @param database [String, Symbol] The database to update.",
"# @param collection [String, Symbol] The collection to update.",
"# @param selector [Hash] The update selector.",
"# @param update [Hash] The update to perform.",
"# @param options [Hash] The additional query options.",
"#",
"# @option options :flags [Array] The flags for the update message.",
"#",
"# Supported flags: +:upsert+, +:multi_update+",
"# Return the event payload for monitoring.",
"#",
"# @example Return the event payload.",
"# message.payload",
"#",
"# @return [ BSON::Document ] The event payload.",
"#",
"# @since 2.1.0",
"# The operation code required to specify an Update message.",
"# @return [Fixnum] the operation code.",
"#",
"# @since 2.5.0",
"# Available flags for an Update message.",
"# Field representing Zero encoded as an Int32.",
"# @!attribute",
"# @return [String] The namespace for this Update message.",
"# @!attribute",
"# @return [Array<Symbol>] The flags for this Update message.",
"# @!attribute",
"# @return [Hash] The selector for this Update message.",
"# @!attribute",
"# @return [Hash] The update for this Delete message.",
"# Converts legacy update messages to the appropriare OP_COMMAND style",
"# message.",
"#",
"# @since 2.1.0",
"# The multi constant.",
"#",
"# @since 2.2.0",
"# The u constant.",
"#",
"# @since 2.2.0",
"# The update constant.",
"#",
"# @since 2.2.0",
"# The updates constant.",
"#",
"# @since 2.2.0",
"# The upsert constant.",
"#",
"# @since 2.2.0",
"# @return [ String ] collection The name of the collection.",
"# @return [ Hash ] filter The filter.",
"# @return [ Hash ] update The update.",
"# @return [ Array<Symbol> ] flags The flags.",
"# Instantiate the upconverter.",
"#",
"# @example Instantiate the upconverter.",
"# Upconverter.new(",
"# 'users',",
"# { name: 'test' },",
"# { '$set' => { 'name' => 't' }},",
"# []",
"# )",
"#",
"# @param [ String ] collection The name of the collection.",
"# @param [ Hash ] filter The filter.",
"# @param [ Hash ] update The update.",
"# @param [ Array<Symbol> ] flags The flags.",
"#",
"# @since 2.1.0",
"# Get the upconverted command.",
"#",
"# @example Get the command.",
"# upconverter.command",
"#",
"# @return [ BSON::Document ] The upconverted command.",
"#",
"# @since 2.1.0"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 1,381
| 139
|
7a27d6b15a8131242d8d8fd4305267b8bdd8ee9f
|
martinwoodward/OpenLiveWriter
|
src/managed/OpenLiveWriter.PostEditor/ContentEditor/MainFrameWindowAdapter.cs
|
[
"MIT"
] |
C#
|
MainFrameWindowAdapter
|
/// <summary>
/// MainFrameWindowAdapter will take a IContentEditorSite given by a hosting application and convert it into
/// IMainFrameWindow and IBlogPostEditingSite which are used by the ContentEditor. It's general functions
/// are to act as a middle man to the window that is holding the canvas.
/// </summary>
//ToDo: OLW Spell Checker
//internal class MainFrameWindowAdapter : IMainFrameWindow, IBlogPostEditingSite, IBlogContext, OpenLiveWriter.Interop.Com.IDropTarget, IDisposable, IETWProvider, IWordRangeProvider
|
MainFrameWindowAdapter will take a IContentEditorSite given by a hosting application and convert it into
IMainFrameWindow and IBlogPostEditingSite which are used by the ContentEditor. It's general functions
are to act as a middle man to the window that is holding the canvas.
|
[
"MainFrameWindowAdapter",
"will",
"take",
"a",
"IContentEditorSite",
"given",
"by",
"a",
"hosting",
"application",
"and",
"convert",
"it",
"into",
"IMainFrameWindow",
"and",
"IBlogPostEditingSite",
"which",
"are",
"used",
"by",
"the",
"ContentEditor",
".",
"It",
"'",
"s",
"general",
"functions",
"are",
"to",
"act",
"as",
"a",
"middle",
"man",
"to",
"the",
"window",
"that",
"is",
"holding",
"the",
"canvas",
"."
] |
internal class MainFrameWindowAdapter : IMainFrameWindow, IBlogPostEditingSite, IBlogContext, OpenLiveWriter.Interop.Com.IDropTarget, IDisposable, IETWProvider
{
private readonly IntPtr _parentWindowHandle;
private readonly Control _editorHostPanel;
private IContentEditorSite _contentEditorSite;
private string _accountId;
public MainFrameWindowAdapter(IntPtr parentWindowHandle, Control editorHostPanel, IContentEditorSite contentEditorSite, string accountId)
{
_parentWindowHandle = parentWindowHandle;
_editorHostPanel = editorHostPanel;
_contentEditorSite = contentEditorSite;
editorHostPanel.LocationChanged += new EventHandler(editorHostPanel_LocationChanged);
editorHostPanel.SizeChanged += new EventHandler(editorHostPanel_SizeChanged);
editorHostPanel.Layout += new LayoutEventHandler(editorHostPanel_Layout);
_accountId = accountId;
}
void editorHostPanel_Layout(object sender, LayoutEventArgs e)
{
FireLayout(e);
}
void editorHostPanel_SizeChanged(object sender, EventArgs e)
{
FireSizeChanged(_editorHostPanel.Width, _editorHostPanel.Height);
}
void editorHostPanel_LocationChanged(object sender, EventArgs e)
{
FireLocationChanged();
}
public IUIFramework RibbonFramework
{
get
{
return (IUIFramework)_contentEditorSite;
}
}
public void OnKeyboardLanguageChanged()
{
_contentEditorSite.OnKeyboardLanguageChanged();
}
#region IWordRangeProvider Members
#endregion
#region IMainFrameWindow Members
public string Caption
{
set
{
}
}
public Point Location
{
get
{
WINDOWINFO info = new WINDOWINFO();
User32.GetWindowInfo(_parentWindowHandle, ref info);
return new Point(info.rcWindow.left, info.rcWindow.top);
}
}
public Size Size
{
get
{
WINDOWINFO info = new WINDOWINFO();
User32.GetWindowInfo(_parentWindowHandle, ref info);
return new Size(Math.Max(info.rcWindow.Width, _width), Math.Max(info.rcWindow.Height, _height));
}
}
public event EventHandler LocationChanged;
private void FireLocationChanged()
{
if (LocationChanged != null)
LocationChanged(this, EventArgs.Empty);
}
private int _width;
private int _height;
public event EventHandler SizeChanged;
public void FireSizeChanged(int x, int y)
{
_width = x;
_height = y;
if (SizeChanged != null)
SizeChanged(this, EventArgs.Empty);
}
public event EventHandler Deactivate;
private void FireDeactivate()
{
if (Deactivate != null)
Deactivate(this, EventArgs.Empty);
}
public event LayoutEventHandler Layout;
private void FireLayout(LayoutEventArgs arg)
{
if (Layout != null)
{
Layout(this, arg);
}
}
public void Activate()
{
User32.SetForegroundWindow(_parentWindowHandle);
}
public void Update()
{
User32.UpdateWindow(_parentWindowHandle);
}
public void SetStatusBarMessage(StatusMessage message)
{
_contentEditorSite.SetStatusBarMessage(message.BlogPostStatus, message.WordCountValue);
}
private Stack<StatusMessage> _statusMessageStack = new Stack<StatusMessage>();
public void PushStatusBarMessage(StatusMessage message)
{
_statusMessageStack.Push(message);
_contentEditorSite.SetStatusBarMessage(message.BlogPostStatus, message.WordCountValue);
}
public void PopStatusBarMessage()
{
if (_statusMessageStack.Count > 0)
_statusMessageStack.Pop();
if (_statusMessageStack.Count > 0)
{
StatusMessage message = _statusMessageStack.Peek();
_contentEditorSite.SetStatusBarMessage(message.BlogPostStatus, message.WordCountValue);
}
else
{
_contentEditorSite.SetStatusBarMessage(null, null);
}
}
public void PerformLayout()
{
_editorHostPanel.PerformLayout();
}
public void Invalidate()
{
User32.InvalidateWindow(_parentWindowHandle, IntPtr.Zero, false);
}
public void Close()
{
User32.SendMessage(_parentWindowHandle, WM.CLOSE, UIntPtr.Zero, IntPtr.Zero);
}
#endregion
#region IWin32Window Members
public IntPtr Handle
{
get { return _editorHostPanel.Handle; }
}
#endregion
#region ISynchronizeInvoke Members
public IAsyncResult BeginInvoke(Delegate method, object[] args)
{
return _editorHostPanel.BeginInvoke(method, args);
}
public object EndInvoke(IAsyncResult result)
{
return _editorHostPanel.EndInvoke(result);
}
public object Invoke(Delegate method, object[] args)
{
return _editorHostPanel.Invoke(method, args);
}
public bool InvokeRequired
{
get { return _editorHostPanel.InvokeRequired; }
}
#endregion
#region IMiniFormOwner Members
public void AddOwnedForm(System.Windows.Forms.Form f)
{
User32.SetParent(f.Handle, _parentWindowHandle);
}
public void RemoveOwnedForm(System.Windows.Forms.Form f)
{
User32.SetParent(f.Handle, IntPtr.Zero);
}
#endregion
#region IBlogContext Members
public string CurrentAccountId
{
get { return null; }
set { }
}
#endregion
#region IBlogPostEditingSite Members
public IMainFrameWindow FrameWindow
{
get { return this; }
}
public event WeblogHandler WeblogChanged;
public event EventHandler WeblogListChanged;
private void InvokeWeblogChanged(string blogId)
{
WeblogHandler Handler = WeblogChanged;
if (Handler != null) Handler(blogId);
}
public event WeblogSettingsChangedHandler WeblogSettingsChanged;
private void InvokeWeblogSettingsChanged(string blogId, bool templateChanged)
{
WeblogSettingsChangedHandler Handler = WeblogSettingsChanged;
if (Handler != null) Handler(blogId, templateChanged);
}
public event WeblogSettingsChangedHandler GlobalWeblogSettingsChanged;
private void InvokeGlobalWeblogSettingsChanged(string blogId, bool templateChanged)
{
WeblogSettingsChangedHandler Handler = GlobalWeblogSettingsChanged;
if (Handler != null) Handler(blogId, templateChanged);
}
public void NotifyWeblogSettingsChanged(bool templateChanged)
{
throw new NotImplementedException();
}
public void NotifyWeblogSettingsChanged(string blogId, bool templateChanged)
{
throw new NotImplementedException();
}
public void NotifyWeblogAccountListEdited()
{
throw new NotImplementedException();
}
public void ConfigureWeblog(string blogId, Type selectedPanel)
{
throw new System.NotImplementedException();
}
public void ConfigureWeblog(string blogId)
{
throw new NotImplementedException();
}
public void ConfigureWeblogFtpUpload(string blogId)
{
throw new NotImplementedException();
}
public bool UpdateWeblogTemplate(string blogId)
{
throw new NotImplementedException();
}
public void AddWeblog()
{
throw new NotImplementedException();
}
public void OpenLocalPost(PostInfo postInfo)
{
throw new NotImplementedException();
}
public void DeleteLocalPost(PostInfo postInfo)
{
throw new NotImplementedException();
}
public event EventHandler PostListChanged;
private void InvokePostListChanged(EventArgs e)
{
EventHandler postListChangedHandler = PostListChanged;
if (postListChangedHandler != null) postListChangedHandler(this, e);
}
private void InvokeWeblogListChanged(EventArgs e)
{
EventHandler weblogListChangedHandler = WeblogListChanged;
if (weblogListChangedHandler != null) weblogListChangedHandler(this, e);
}
public OpenLiveWriter.HtmlEditor.Controls.IHtmlStylePicker StyleControl
{
get { return new NullHtmlStylePicker(); }
}
public class NullHtmlStylePicker : IHtmlStylePicker
{
#region IHtmlStylePicker Members
public event EventHandler HtmlStyleChanged;
private void InvokeHtmlStyleChanged(EventArgs e)
{
EventHandler htmlStyleChangedHandler = HtmlStyleChanged;
if (htmlStyleChangedHandler != null) htmlStyleChangedHandler(this, e);
}
public class NullHtmlFormattingStyle : IHtmlFormattingStyle
{
#region IHtmlFormattingStyle Members
public string DisplayName
{
get { return ""; }
}
public string ElementName
{
get { return ""; }
}
public mshtml._ELEMENT_TAG_ID ElementTagId
{
get { return mshtml._ELEMENT_TAG_ID.TAGID_SPAN; }
}
#endregion
}
public IHtmlFormattingStyle SelectedStyle
{
get { return new NullHtmlFormattingStyle(); }
}
public bool Enabled
{
get
{
return false;
}
set
{
}
}
public void SelectStyleByElementName(string p)
{
}
#endregion
}
#endregion
#region IDropTarget Members
public void DragEnter(OpenLiveWriter.Interop.Com.IOleDataObject pDataObj, MK grfKeyState, POINT pt, ref OpenLiveWriter.Interop.Com.DROPEFFECT pdwEffect)
{
_contentEditorSite.DragEnter(pDataObj, grfKeyState, pt, ref pdwEffect);
}
public void DragOver(MK grfKeyState, POINT pt, ref OpenLiveWriter.Interop.Com.DROPEFFECT pdwEffect)
{
_contentEditorSite.DragOver( grfKeyState, pt, ref pdwEffect);
}
public void DragLeave()
{
_contentEditorSite.DragLeave();
}
public void Drop(OpenLiveWriter.Interop.Com.IOleDataObject pDataObj, MK grfKeyState, POINT pt, ref OpenLiveWriter.Interop.Com.DROPEFFECT pdwEffect)
{
_contentEditorSite.Drop(pDataObj, grfKeyState, pt, ref pdwEffect);
}
#endregion
#region IBlogPostEditingSite Members
public CommandManager CommandManager
{
get { throw new NotImplementedException(); }
}
#endregion
#region IDisposable Members
public void Dispose()
{
_contentEditorSite = null;
}
#endregion
public void WriteEvent(string eventName)
{
if (_contentEditorSite != null)
_contentEditorSite.WriteEvent(eventName);
}
}
|
[
"internal",
"class",
"MainFrameWindowAdapter",
":",
"IMainFrameWindow",
",",
"IBlogPostEditingSite",
",",
"IBlogContext",
",",
"OpenLiveWriter",
".",
"Interop",
".",
"Com",
".",
"IDropTarget",
",",
"IDisposable",
",",
"IETWProvider",
"{",
"private",
"readonly",
"IntPtr",
"_parentWindowHandle",
";",
"private",
"readonly",
"Control",
"_editorHostPanel",
";",
"private",
"IContentEditorSite",
"_contentEditorSite",
";",
"private",
"string",
"_accountId",
";",
"public",
"MainFrameWindowAdapter",
"(",
"IntPtr",
"parentWindowHandle",
",",
"Control",
"editorHostPanel",
",",
"IContentEditorSite",
"contentEditorSite",
",",
"string",
"accountId",
")",
"{",
"_parentWindowHandle",
"=",
"parentWindowHandle",
";",
"_editorHostPanel",
"=",
"editorHostPanel",
";",
"_contentEditorSite",
"=",
"contentEditorSite",
";",
"editorHostPanel",
".",
"LocationChanged",
"+=",
"new",
"EventHandler",
"(",
"editorHostPanel_LocationChanged",
")",
";",
"editorHostPanel",
".",
"SizeChanged",
"+=",
"new",
"EventHandler",
"(",
"editorHostPanel_SizeChanged",
")",
";",
"editorHostPanel",
".",
"Layout",
"+=",
"new",
"LayoutEventHandler",
"(",
"editorHostPanel_Layout",
")",
";",
"_accountId",
"=",
"accountId",
";",
"}",
"void",
"editorHostPanel_Layout",
"(",
"object",
"sender",
",",
"LayoutEventArgs",
"e",
")",
"{",
"FireLayout",
"(",
"e",
")",
";",
"}",
"void",
"editorHostPanel_SizeChanged",
"(",
"object",
"sender",
",",
"EventArgs",
"e",
")",
"{",
"FireSizeChanged",
"(",
"_editorHostPanel",
".",
"Width",
",",
"_editorHostPanel",
".",
"Height",
")",
";",
"}",
"void",
"editorHostPanel_LocationChanged",
"(",
"object",
"sender",
",",
"EventArgs",
"e",
")",
"{",
"FireLocationChanged",
"(",
")",
";",
"}",
"public",
"IUIFramework",
"RibbonFramework",
"{",
"get",
"{",
"return",
"(",
"IUIFramework",
")",
"_contentEditorSite",
";",
"}",
"}",
"public",
"void",
"OnKeyboardLanguageChanged",
"(",
")",
"{",
"_contentEditorSite",
".",
"OnKeyboardLanguageChanged",
"(",
")",
";",
"}",
"region",
" IWordRangeProvider Members",
"endregion",
"region",
" IMainFrameWindow Members",
"public",
"string",
"Caption",
"{",
"set",
"{",
"}",
"}",
"public",
"Point",
"Location",
"{",
"get",
"{",
"WINDOWINFO",
"info",
"=",
"new",
"WINDOWINFO",
"(",
")",
";",
"User32",
".",
"GetWindowInfo",
"(",
"_parentWindowHandle",
",",
"ref",
"info",
")",
";",
"return",
"new",
"Point",
"(",
"info",
".",
"rcWindow",
".",
"left",
",",
"info",
".",
"rcWindow",
".",
"top",
")",
";",
"}",
"}",
"public",
"Size",
"Size",
"{",
"get",
"{",
"WINDOWINFO",
"info",
"=",
"new",
"WINDOWINFO",
"(",
")",
";",
"User32",
".",
"GetWindowInfo",
"(",
"_parentWindowHandle",
",",
"ref",
"info",
")",
";",
"return",
"new",
"Size",
"(",
"Math",
".",
"Max",
"(",
"info",
".",
"rcWindow",
".",
"Width",
",",
"_width",
")",
",",
"Math",
".",
"Max",
"(",
"info",
".",
"rcWindow",
".",
"Height",
",",
"_height",
")",
")",
";",
"}",
"}",
"public",
"event",
"EventHandler",
"LocationChanged",
";",
"private",
"void",
"FireLocationChanged",
"(",
")",
"{",
"if",
"(",
"LocationChanged",
"!=",
"null",
")",
"LocationChanged",
"(",
"this",
",",
"EventArgs",
".",
"Empty",
")",
";",
"}",
"private",
"int",
"_width",
";",
"private",
"int",
"_height",
";",
"public",
"event",
"EventHandler",
"SizeChanged",
";",
"public",
"void",
"FireSizeChanged",
"(",
"int",
"x",
",",
"int",
"y",
")",
"{",
"_width",
"=",
"x",
";",
"_height",
"=",
"y",
";",
"if",
"(",
"SizeChanged",
"!=",
"null",
")",
"SizeChanged",
"(",
"this",
",",
"EventArgs",
".",
"Empty",
")",
";",
"}",
"public",
"event",
"EventHandler",
"Deactivate",
";",
"private",
"void",
"FireDeactivate",
"(",
")",
"{",
"if",
"(",
"Deactivate",
"!=",
"null",
")",
"Deactivate",
"(",
"this",
",",
"EventArgs",
".",
"Empty",
")",
";",
"}",
"public",
"event",
"LayoutEventHandler",
"Layout",
";",
"private",
"void",
"FireLayout",
"(",
"LayoutEventArgs",
"arg",
")",
"{",
"if",
"(",
"Layout",
"!=",
"null",
")",
"{",
"Layout",
"(",
"this",
",",
"arg",
")",
";",
"}",
"}",
"public",
"void",
"Activate",
"(",
")",
"{",
"User32",
".",
"SetForegroundWindow",
"(",
"_parentWindowHandle",
")",
";",
"}",
"public",
"void",
"Update",
"(",
")",
"{",
"User32",
".",
"UpdateWindow",
"(",
"_parentWindowHandle",
")",
";",
"}",
"public",
"void",
"SetStatusBarMessage",
"(",
"StatusMessage",
"message",
")",
"{",
"_contentEditorSite",
".",
"SetStatusBarMessage",
"(",
"message",
".",
"BlogPostStatus",
",",
"message",
".",
"WordCountValue",
")",
";",
"}",
"private",
"Stack",
"<",
"StatusMessage",
">",
"_statusMessageStack",
"=",
"new",
"Stack",
"<",
"StatusMessage",
">",
"(",
")",
";",
"public",
"void",
"PushStatusBarMessage",
"(",
"StatusMessage",
"message",
")",
"{",
"_statusMessageStack",
".",
"Push",
"(",
"message",
")",
";",
"_contentEditorSite",
".",
"SetStatusBarMessage",
"(",
"message",
".",
"BlogPostStatus",
",",
"message",
".",
"WordCountValue",
")",
";",
"}",
"public",
"void",
"PopStatusBarMessage",
"(",
")",
"{",
"if",
"(",
"_statusMessageStack",
".",
"Count",
">",
"0",
")",
"_statusMessageStack",
".",
"Pop",
"(",
")",
";",
"if",
"(",
"_statusMessageStack",
".",
"Count",
">",
"0",
")",
"{",
"StatusMessage",
"message",
"=",
"_statusMessageStack",
".",
"Peek",
"(",
")",
";",
"_contentEditorSite",
".",
"SetStatusBarMessage",
"(",
"message",
".",
"BlogPostStatus",
",",
"message",
".",
"WordCountValue",
")",
";",
"}",
"else",
"{",
"_contentEditorSite",
".",
"SetStatusBarMessage",
"(",
"null",
",",
"null",
")",
";",
"}",
"}",
"public",
"void",
"PerformLayout",
"(",
")",
"{",
"_editorHostPanel",
".",
"PerformLayout",
"(",
")",
";",
"}",
"public",
"void",
"Invalidate",
"(",
")",
"{",
"User32",
".",
"InvalidateWindow",
"(",
"_parentWindowHandle",
",",
"IntPtr",
".",
"Zero",
",",
"false",
")",
";",
"}",
"public",
"void",
"Close",
"(",
")",
"{",
"User32",
".",
"SendMessage",
"(",
"_parentWindowHandle",
",",
"WM",
".",
"CLOSE",
",",
"UIntPtr",
".",
"Zero",
",",
"IntPtr",
".",
"Zero",
")",
";",
"}",
"endregion",
"region",
" IWin32Window Members",
"public",
"IntPtr",
"Handle",
"{",
"get",
"{",
"return",
"_editorHostPanel",
".",
"Handle",
";",
"}",
"}",
"endregion",
"region",
" ISynchronizeInvoke Members",
"public",
"IAsyncResult",
"BeginInvoke",
"(",
"Delegate",
"method",
",",
"object",
"[",
"]",
"args",
")",
"{",
"return",
"_editorHostPanel",
".",
"BeginInvoke",
"(",
"method",
",",
"args",
")",
";",
"}",
"public",
"object",
"EndInvoke",
"(",
"IAsyncResult",
"result",
")",
"{",
"return",
"_editorHostPanel",
".",
"EndInvoke",
"(",
"result",
")",
";",
"}",
"public",
"object",
"Invoke",
"(",
"Delegate",
"method",
",",
"object",
"[",
"]",
"args",
")",
"{",
"return",
"_editorHostPanel",
".",
"Invoke",
"(",
"method",
",",
"args",
")",
";",
"}",
"public",
"bool",
"InvokeRequired",
"{",
"get",
"{",
"return",
"_editorHostPanel",
".",
"InvokeRequired",
";",
"}",
"}",
"endregion",
"region",
" IMiniFormOwner Members",
"public",
"void",
"AddOwnedForm",
"(",
"System",
".",
"Windows",
".",
"Forms",
".",
"Form",
"f",
")",
"{",
"User32",
".",
"SetParent",
"(",
"f",
".",
"Handle",
",",
"_parentWindowHandle",
")",
";",
"}",
"public",
"void",
"RemoveOwnedForm",
"(",
"System",
".",
"Windows",
".",
"Forms",
".",
"Form",
"f",
")",
"{",
"User32",
".",
"SetParent",
"(",
"f",
".",
"Handle",
",",
"IntPtr",
".",
"Zero",
")",
";",
"}",
"endregion",
"region",
" IBlogContext Members",
"public",
"string",
"CurrentAccountId",
"{",
"get",
"{",
"return",
"null",
";",
"}",
"set",
"{",
"}",
"}",
"endregion",
"region",
" IBlogPostEditingSite Members",
"public",
"IMainFrameWindow",
"FrameWindow",
"{",
"get",
"{",
"return",
"this",
";",
"}",
"}",
"public",
"event",
"WeblogHandler",
"WeblogChanged",
";",
"public",
"event",
"EventHandler",
"WeblogListChanged",
";",
"private",
"void",
"InvokeWeblogChanged",
"(",
"string",
"blogId",
")",
"{",
"WeblogHandler",
"Handler",
"=",
"WeblogChanged",
";",
"if",
"(",
"Handler",
"!=",
"null",
")",
"Handler",
"(",
"blogId",
")",
";",
"}",
"public",
"event",
"WeblogSettingsChangedHandler",
"WeblogSettingsChanged",
";",
"private",
"void",
"InvokeWeblogSettingsChanged",
"(",
"string",
"blogId",
",",
"bool",
"templateChanged",
")",
"{",
"WeblogSettingsChangedHandler",
"Handler",
"=",
"WeblogSettingsChanged",
";",
"if",
"(",
"Handler",
"!=",
"null",
")",
"Handler",
"(",
"blogId",
",",
"templateChanged",
")",
";",
"}",
"public",
"event",
"WeblogSettingsChangedHandler",
"GlobalWeblogSettingsChanged",
";",
"private",
"void",
"InvokeGlobalWeblogSettingsChanged",
"(",
"string",
"blogId",
",",
"bool",
"templateChanged",
")",
"{",
"WeblogSettingsChangedHandler",
"Handler",
"=",
"GlobalWeblogSettingsChanged",
";",
"if",
"(",
"Handler",
"!=",
"null",
")",
"Handler",
"(",
"blogId",
",",
"templateChanged",
")",
";",
"}",
"public",
"void",
"NotifyWeblogSettingsChanged",
"(",
"bool",
"templateChanged",
")",
"{",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"public",
"void",
"NotifyWeblogSettingsChanged",
"(",
"string",
"blogId",
",",
"bool",
"templateChanged",
")",
"{",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"public",
"void",
"NotifyWeblogAccountListEdited",
"(",
")",
"{",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"public",
"void",
"ConfigureWeblog",
"(",
"string",
"blogId",
",",
"Type",
"selectedPanel",
")",
"{",
"throw",
"new",
"System",
".",
"NotImplementedException",
"(",
")",
";",
"}",
"public",
"void",
"ConfigureWeblog",
"(",
"string",
"blogId",
")",
"{",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"public",
"void",
"ConfigureWeblogFtpUpload",
"(",
"string",
"blogId",
")",
"{",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"public",
"bool",
"UpdateWeblogTemplate",
"(",
"string",
"blogId",
")",
"{",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"public",
"void",
"AddWeblog",
"(",
")",
"{",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"public",
"void",
"OpenLocalPost",
"(",
"PostInfo",
"postInfo",
")",
"{",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"public",
"void",
"DeleteLocalPost",
"(",
"PostInfo",
"postInfo",
")",
"{",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"public",
"event",
"EventHandler",
"PostListChanged",
";",
"private",
"void",
"InvokePostListChanged",
"(",
"EventArgs",
"e",
")",
"{",
"EventHandler",
"postListChangedHandler",
"=",
"PostListChanged",
";",
"if",
"(",
"postListChangedHandler",
"!=",
"null",
")",
"postListChangedHandler",
"(",
"this",
",",
"e",
")",
";",
"}",
"private",
"void",
"InvokeWeblogListChanged",
"(",
"EventArgs",
"e",
")",
"{",
"EventHandler",
"weblogListChangedHandler",
"=",
"WeblogListChanged",
";",
"if",
"(",
"weblogListChangedHandler",
"!=",
"null",
")",
"weblogListChangedHandler",
"(",
"this",
",",
"e",
")",
";",
"}",
"public",
"OpenLiveWriter",
".",
"HtmlEditor",
".",
"Controls",
".",
"IHtmlStylePicker",
"StyleControl",
"{",
"get",
"{",
"return",
"new",
"NullHtmlStylePicker",
"(",
")",
";",
"}",
"}",
"public",
"class",
"NullHtmlStylePicker",
":",
"IHtmlStylePicker",
"{",
"region",
" IHtmlStylePicker Members",
"public",
"event",
"EventHandler",
"HtmlStyleChanged",
";",
"private",
"void",
"InvokeHtmlStyleChanged",
"(",
"EventArgs",
"e",
")",
"{",
"EventHandler",
"htmlStyleChangedHandler",
"=",
"HtmlStyleChanged",
";",
"if",
"(",
"htmlStyleChangedHandler",
"!=",
"null",
")",
"htmlStyleChangedHandler",
"(",
"this",
",",
"e",
")",
";",
"}",
"public",
"class",
"NullHtmlFormattingStyle",
":",
"IHtmlFormattingStyle",
"{",
"region",
" IHtmlFormattingStyle Members",
"public",
"string",
"DisplayName",
"{",
"get",
"{",
"return",
"\"",
"\"",
";",
"}",
"}",
"public",
"string",
"ElementName",
"{",
"get",
"{",
"return",
"\"",
"\"",
";",
"}",
"}",
"public",
"mshtml",
".",
"_ELEMENT_TAG_ID",
"ElementTagId",
"{",
"get",
"{",
"return",
"mshtml",
".",
"_ELEMENT_TAG_ID",
".",
"TAGID_SPAN",
";",
"}",
"}",
"endregion",
"}",
"public",
"IHtmlFormattingStyle",
"SelectedStyle",
"{",
"get",
"{",
"return",
"new",
"NullHtmlFormattingStyle",
"(",
")",
";",
"}",
"}",
"public",
"bool",
"Enabled",
"{",
"get",
"{",
"return",
"false",
";",
"}",
"set",
"{",
"}",
"}",
"public",
"void",
"SelectStyleByElementName",
"(",
"string",
"p",
")",
"{",
"}",
"endregion",
"}",
"endregion",
"region",
" IDropTarget Members",
"public",
"void",
"DragEnter",
"(",
"OpenLiveWriter",
".",
"Interop",
".",
"Com",
".",
"IOleDataObject",
"pDataObj",
",",
"MK",
"grfKeyState",
",",
"POINT",
"pt",
",",
"ref",
"OpenLiveWriter",
".",
"Interop",
".",
"Com",
".",
"DROPEFFECT",
"pdwEffect",
")",
"{",
"_contentEditorSite",
".",
"DragEnter",
"(",
"pDataObj",
",",
"grfKeyState",
",",
"pt",
",",
"ref",
"pdwEffect",
")",
";",
"}",
"public",
"void",
"DragOver",
"(",
"MK",
"grfKeyState",
",",
"POINT",
"pt",
",",
"ref",
"OpenLiveWriter",
".",
"Interop",
".",
"Com",
".",
"DROPEFFECT",
"pdwEffect",
")",
"{",
"_contentEditorSite",
".",
"DragOver",
"(",
"grfKeyState",
",",
"pt",
",",
"ref",
"pdwEffect",
")",
";",
"}",
"public",
"void",
"DragLeave",
"(",
")",
"{",
"_contentEditorSite",
".",
"DragLeave",
"(",
")",
";",
"}",
"public",
"void",
"Drop",
"(",
"OpenLiveWriter",
".",
"Interop",
".",
"Com",
".",
"IOleDataObject",
"pDataObj",
",",
"MK",
"grfKeyState",
",",
"POINT",
"pt",
",",
"ref",
"OpenLiveWriter",
".",
"Interop",
".",
"Com",
".",
"DROPEFFECT",
"pdwEffect",
")",
"{",
"_contentEditorSite",
".",
"Drop",
"(",
"pDataObj",
",",
"grfKeyState",
",",
"pt",
",",
"ref",
"pdwEffect",
")",
";",
"}",
"endregion",
"region",
" IBlogPostEditingSite Members",
"public",
"CommandManager",
"CommandManager",
"{",
"get",
"{",
"throw",
"new",
"NotImplementedException",
"(",
")",
";",
"}",
"}",
"endregion",
"region",
" IDisposable Members",
"public",
"void",
"Dispose",
"(",
")",
"{",
"_contentEditorSite",
"=",
"null",
";",
"}",
"endregion",
"public",
"void",
"WriteEvent",
"(",
"string",
"eventName",
")",
"{",
"if",
"(",
"_contentEditorSite",
"!=",
"null",
")",
"_contentEditorSite",
".",
"WriteEvent",
"(",
"eventName",
")",
";",
"}",
"}"
] |
MainFrameWindowAdapter will take a IContentEditorSite given by a hosting application and convert it into
IMainFrameWindow and IBlogPostEditingSite which are used by the ContentEditor.
|
[
"MainFrameWindowAdapter",
"will",
"take",
"a",
"IContentEditorSite",
"given",
"by",
"a",
"hosting",
"application",
"and",
"convert",
"it",
"into",
"IMainFrameWindow",
"and",
"IBlogPostEditingSite",
"which",
"are",
"used",
"by",
"the",
"ContentEditor",
"."
] |
[
"//ToDo: OLW Spell Checker",
"//public IWordRange GetSubjectSpellcheckWordRange()",
"//{",
"// return ((IWordRangeProvider)_contentEditorSite).GetSubjectSpellcheckWordRange();",
"//}",
"//public void CloseSubjectSpellcheckWordRange()",
"//{",
"// ((IWordRangeProvider)_contentEditorSite).CloseSubjectSpellcheckWordRange();",
"//}",
"// @SharedCanvas - this can all be removed once the default sidebar is taken out",
"// This only exists to please the compiler.",
"// @SharedCanvas - this needs to be fixed with the ribbon. The window should not be providing",
"// a combo box for the command manager to poke up"
] |
[
{
"param": "IMainFrameWindow",
"type": null
},
{
"param": "IBlogPostEditingSite",
"type": null
},
{
"param": "IBlogContext",
"type": null
},
{
"param": "IDisposable",
"type": null
},
{
"param": "IETWProvider",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IMainFrameWindow",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "IBlogPostEditingSite",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "IBlogContext",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "IDisposable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "IETWProvider",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 16
| 2,294
| 121
|
604c30ef65960002186f13f7d040fa91b1c3f563
|
MCMrARM/sandbox-attacksurface-analysis-tools
|
NtObjectManager/Cmdlets/Object/NewNtAlpcPortSectionCmdlet.cs
|
[
"Apache-2.0"
] |
C#
|
NewNtAlpcPortSectionCmdlet
|
/// <summary>
/// <para type="synopsis">Creates a new port section from a port.</para>
/// <para type="description">This cmdlet creates a new port section with a specified size and flags for a port. You can then write to buffer and pass it as a view attribute.</para>
/// </summary>
/// <example>
/// <code>$s = New-NtAlpcPortSection -Size 10000</code>
/// <para>Create a new port section of size 10000.</para>
/// </example>
/// <example>
/// <code>$s = New-NtAlpcPortSection -Size 10000 -Secure</code>
/// <para>Create a new secure port section of size 10000.</para>
/// </example>
/// <example>
/// <code>$s = New-NtAlpcPortSection -Section $sect</code>
/// <para>>Create a new port section backed by an existing section.</para>
/// </example>
/// <example>
/// <code>$s = New-NtAlpcPortSection -Section $sect -Size 10000</code>
/// <para>>Create a new port section backed by an existing section with an explicit view size.</para>
/// </example>
/// <para type="link">about_ManagingNtObjectLifetime</para>
|
Creates a new port section from a port.This cmdlet creates a new port section with a specified size and flags for a port. You can then write to buffer and pass it as a view attribute.
|
[
"Creates",
"a",
"new",
"port",
"section",
"from",
"a",
"port",
".",
"This",
"cmdlet",
"creates",
"a",
"new",
"port",
"section",
"with",
"a",
"specified",
"size",
"and",
"flags",
"for",
"a",
"port",
".",
"You",
"can",
"then",
"write",
"to",
"buffer",
"and",
"pass",
"it",
"as",
"a",
"view",
"attribute",
"."
] |
[Cmdlet(VerbsCommon.New, "NtAlpcPortSection", DefaultParameterSetName = "FromSize")]
[OutputType(typeof(AlpcPortSection))]
public class NewNtAlpcPortSectionCmdlet : PSCmdlet
{
[Parameter(Position = 0, Mandatory = true)]
public NtAlpc Port { get; set; }
[Parameter(Position = 1, Mandatory = true, ParameterSetName = "FromSize")]
[Parameter(ParameterSetName = "FromSection")]
public long Size { get; set; }
[Parameter(ParameterSetName = "FromSize")]
public SwitchParameter Secure { get; set; }
[Parameter(Position = 1, Mandatory = true, ParameterSetName = "FromSection")]
public NtSection Section { get; set; }
protected override void ProcessRecord()
{
switch (ParameterSetName)
{
case "FromSize":
WriteObject(Port.CreatePortSection(Secure ? AlpcCreatePortSectionFlags.Secure : 0, Size));
break;
case "FromSection":
WriteObject(Port.CreatePortSection(AlpcCreatePortSectionFlags.None, Section, Size == 0 ? Section.Size : Size));
break;
}
}
}
|
[
"[",
"Cmdlet",
"(",
"VerbsCommon",
".",
"New",
",",
"\"",
"NtAlpcPortSection",
"\"",
",",
"DefaultParameterSetName",
"=",
"\"",
"FromSize",
"\"",
")",
"]",
"[",
"OutputType",
"(",
"typeof",
"(",
"AlpcPortSection",
")",
")",
"]",
"public",
"class",
"NewNtAlpcPortSectionCmdlet",
":",
"PSCmdlet",
"{",
"[",
"Parameter",
"(",
"Position",
"=",
"0",
",",
"Mandatory",
"=",
"true",
")",
"]",
"public",
"NtAlpc",
"Port",
"{",
"get",
";",
"set",
";",
"}",
"[",
"Parameter",
"(",
"Position",
"=",
"1",
",",
"Mandatory",
"=",
"true",
",",
"ParameterSetName",
"=",
"\"",
"FromSize",
"\"",
")",
"]",
"[",
"Parameter",
"(",
"ParameterSetName",
"=",
"\"",
"FromSection",
"\"",
")",
"]",
"public",
"long",
"Size",
"{",
"get",
";",
"set",
";",
"}",
"[",
"Parameter",
"(",
"ParameterSetName",
"=",
"\"",
"FromSize",
"\"",
")",
"]",
"public",
"SwitchParameter",
"Secure",
"{",
"get",
";",
"set",
";",
"}",
"[",
"Parameter",
"(",
"Position",
"=",
"1",
",",
"Mandatory",
"=",
"true",
",",
"ParameterSetName",
"=",
"\"",
"FromSection",
"\"",
")",
"]",
"public",
"NtSection",
"Section",
"{",
"get",
";",
"set",
";",
"}",
"protected",
"override",
"void",
"ProcessRecord",
"(",
")",
"{",
"switch",
"(",
"ParameterSetName",
")",
"{",
"case",
"\"",
"FromSize",
"\"",
":",
"WriteObject",
"(",
"Port",
".",
"CreatePortSection",
"(",
"Secure",
"?",
"AlpcCreatePortSectionFlags",
".",
"Secure",
":",
"0",
",",
"Size",
")",
")",
";",
"break",
";",
"case",
"\"",
"FromSection",
"\"",
":",
"WriteObject",
"(",
"Port",
".",
"CreatePortSection",
"(",
"AlpcCreatePortSectionFlags",
".",
"None",
",",
"Section",
",",
"Size",
"==",
"0",
"?",
"Section",
".",
"Size",
":",
"Size",
")",
")",
";",
"break",
";",
"}",
"}",
"}"
] |
Creates a new port section from a port.This cmdlet creates a new port section with a specified size and flags for a port.
|
[
"Creates",
"a",
"new",
"port",
"section",
"from",
"a",
"port",
".",
"This",
"cmdlet",
"creates",
"a",
"new",
"port",
"section",
"with",
"a",
"specified",
"size",
"and",
"flags",
"for",
"a",
"port",
"."
] |
[
"/// <summary>",
"/// <para type=\"description\">Specify the port to create the port section from.</para>",
"/// </summary>",
"/// <summary>",
"/// <para type=\"description\">Specify the size of the port section. This will be rounded up to the nearest allocation boundary.</para>",
"/// </summary>",
"/// <summary>",
"/// <para type=\"description\">Create a secure section.</para>",
"/// </summary>",
"/// <summary>",
"/// <para type=\"description\">Specify an existing section to back the port section.</para>",
"/// </summary>",
"/// <summary>",
"/// Process record.",
"/// </summary>"
] |
[
{
"param": "PSCmdlet",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "PSCmdlet",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "example",
"docstring": "$s = New-NtAlpcPortSection -Size 10000Create a new port section of size 10000.",
"docstring_tokens": [
"$s",
"=",
"New",
"-",
"NtAlpcPortSection",
"-",
"Size",
"10000Create",
"a",
"new",
"port",
"section",
"of",
"size",
"10000",
"."
]
},
{
"identifier": "example",
"docstring": "$s = New-NtAlpcPortSection -Size 10000 -SecureCreate a new secure port section of size 10000.",
"docstring_tokens": [
"$s",
"=",
"New",
"-",
"NtAlpcPortSection",
"-",
"Size",
"10000",
"-",
"SecureCreate",
"a",
"new",
"secure",
"port",
"section",
"of",
"size",
"10000",
"."
]
},
{
"identifier": "example",
"docstring": "$s = New-NtAlpcPortSection -Section $sect>Create a new port section backed by an existing section.",
"docstring_tokens": [
"$s",
"=",
"New",
"-",
"NtAlpcPortSection",
"-",
"Section",
"$sect",
">",
"Create",
"a",
"new",
"port",
"section",
"backed",
"by",
"an",
"existing",
"section",
"."
]
},
{
"identifier": "example",
"docstring": "$s = New-NtAlpcPortSection -Section $sect -Size 10000>Create a new port section backed by an existing section with an explicit view size.",
"docstring_tokens": [
"$s",
"=",
"New",
"-",
"NtAlpcPortSection",
"-",
"Section",
"$sect",
"-",
"Size",
"10000",
">",
"Create",
"a",
"new",
"port",
"section",
"backed",
"by",
"an",
"existing",
"section",
"with",
"an",
"explicit",
"view",
"size",
"."
]
},
{
"identifier": "para",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 17
| 267
| 301
|
fb3fadd28ddb72714fe1c5410fb67dd433fdd47f
|
q-centrix/aws-ssm-parameter-store
|
node_modules/@aws-sdk/client-ssm/dist/cjs/commands/StartSessionCommand.js
|
[
"Apache-2.0"
] |
JavaScript
|
StartSessionCommand
|
/**
* <p>Initiates a connection to a target (for example, an instance) for a Session Manager session. Returns a
* URL and token that can be used to open a WebSocket connection for sending input and receiving
* outputs.</p>
* <note>
* <p>AWS CLI usage: <code>start-session</code> is an interactive command that requires the Session Manager
* plugin to be installed on the client machine making the call. For information, see <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html">Install
* the Session Manager plugin for the AWS CLI</a> in the <i>AWS Systems Manager User Guide</i>.</p>
* <p>AWS Tools for PowerShell usage: Start-SSMSession is not currently supported by AWS Tools
* for PowerShell on Windows local machines.</p>
* </note>
*/
|
Initiates a connection to a target (for example, an instance) for a Session Manager session. Returns a
URL and token that can be used to open a WebSocket connection for sending input and receiving
outputs.
AWS CLI usage: start-session is an interactive command that requires the Session Manager
plugin to be installed on the client machine making the call. For information, see Install
the Session Manager plugin for the AWS CLI in the AWS Systems Manager User Guide.
AWS Tools for PowerShell usage: Start-SSMSession is not currently supported by AWS Tools
for PowerShell on Windows local machines.
|
[
"Initiates",
"a",
"connection",
"to",
"a",
"target",
"(",
"for",
"example",
"an",
"instance",
")",
"for",
"a",
"Session",
"Manager",
"session",
".",
"Returns",
"a",
"URL",
"and",
"token",
"that",
"can",
"be",
"used",
"to",
"open",
"a",
"WebSocket",
"connection",
"for",
"sending",
"input",
"and",
"receiving",
"outputs",
".",
"AWS",
"CLI",
"usage",
":",
"start",
"-",
"session",
"is",
"an",
"interactive",
"command",
"that",
"requires",
"the",
"Session",
"Manager",
"plugin",
"to",
"be",
"installed",
"on",
"the",
"client",
"machine",
"making",
"the",
"call",
".",
"For",
"information",
"see",
"Install",
"the",
"Session",
"Manager",
"plugin",
"for",
"the",
"AWS",
"CLI",
"in",
"the",
"AWS",
"Systems",
"Manager",
"User",
"Guide",
".",
"AWS",
"Tools",
"for",
"PowerShell",
"usage",
":",
"Start",
"-",
"SSMSession",
"is",
"not",
"currently",
"supported",
"by",
"AWS",
"Tools",
"for",
"PowerShell",
"on",
"Windows",
"local",
"machines",
"."
] |
class StartSessionCommand extends smithy_client_1.Command {
// Start section: command_properties
// End section: command_properties
constructor(input) {
// Start section: command_constructor
super();
this.input = input;
// End section: command_constructor
}
/**
* @internal
*/
resolveMiddleware(clientStack, configuration, options) {
this.middlewareStack.use(middleware_serde_1.getSerdePlugin(configuration, this.serialize, this.deserialize));
const stack = clientStack.concat(this.middlewareStack);
const { logger } = configuration;
const clientName = "SSMClient";
const commandName = "StartSessionCommand";
const handlerExecutionContext = {
logger,
clientName,
commandName,
inputFilterSensitiveLog: models_1_1.StartSessionRequest.filterSensitiveLog,
outputFilterSensitiveLog: models_1_1.StartSessionResponse.filterSensitiveLog,
};
const { requestHandler } = configuration;
return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext);
}
serialize(input, context) {
return Aws_json1_1_1.serializeAws_json1_1StartSessionCommand(input, context);
}
deserialize(output, context) {
return Aws_json1_1_1.deserializeAws_json1_1StartSessionCommand(output, context);
}
}
|
[
"class",
"StartSessionCommand",
"extends",
"smithy_client_1",
".",
"Command",
"{",
"constructor",
"(",
"input",
")",
"{",
"super",
"(",
")",
";",
"this",
".",
"input",
"=",
"input",
";",
"}",
"resolveMiddleware",
"(",
"clientStack",
",",
"configuration",
",",
"options",
")",
"{",
"this",
".",
"middlewareStack",
".",
"use",
"(",
"middleware_serde_1",
".",
"getSerdePlugin",
"(",
"configuration",
",",
"this",
".",
"serialize",
",",
"this",
".",
"deserialize",
")",
")",
";",
"const",
"stack",
"=",
"clientStack",
".",
"concat",
"(",
"this",
".",
"middlewareStack",
")",
";",
"const",
"{",
"logger",
"}",
"=",
"configuration",
";",
"const",
"clientName",
"=",
"\"SSMClient\"",
";",
"const",
"commandName",
"=",
"\"StartSessionCommand\"",
";",
"const",
"handlerExecutionContext",
"=",
"{",
"logger",
",",
"clientName",
",",
"commandName",
",",
"inputFilterSensitiveLog",
":",
"models_1_1",
".",
"StartSessionRequest",
".",
"filterSensitiveLog",
",",
"outputFilterSensitiveLog",
":",
"models_1_1",
".",
"StartSessionResponse",
".",
"filterSensitiveLog",
",",
"}",
";",
"const",
"{",
"requestHandler",
"}",
"=",
"configuration",
";",
"return",
"stack",
".",
"resolve",
"(",
"(",
"request",
")",
"=>",
"requestHandler",
".",
"handle",
"(",
"request",
".",
"request",
",",
"options",
"||",
"{",
"}",
")",
",",
"handlerExecutionContext",
")",
";",
"}",
"serialize",
"(",
"input",
",",
"context",
")",
"{",
"return",
"Aws_json1_1_1",
".",
"serializeAws_json1_1StartSessionCommand",
"(",
"input",
",",
"context",
")",
";",
"}",
"deserialize",
"(",
"output",
",",
"context",
")",
"{",
"return",
"Aws_json1_1_1",
".",
"deserializeAws_json1_1StartSessionCommand",
"(",
"output",
",",
"context",
")",
";",
"}",
"}"
] |
<p>Initiates a connection to a target (for example, an instance) for a Session Manager session.
|
[
"<p",
">",
"Initiates",
"a",
"connection",
"to",
"a",
"target",
"(",
"for",
"example",
"an",
"instance",
")",
"for",
"a",
"Session",
"Manager",
"session",
"."
] |
[
"// Start section: command_properties",
"// End section: command_properties",
"// Start section: command_constructor",
"// End section: command_constructor",
"/**\n * @internal\n */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 292
| 199
|
3371a000fdf9b0a20db1d6d9997a2ca85b916016
|
LaudateCorpus1/firebase-admin-dotnet
|
FirebaseAdmin/FirebaseAdmin/FirebaseApp.cs
|
[
"Apache-2.0"
] |
C#
|
FirebaseApp
|
/// <summary>
/// This is the entry point to the Firebase Admin SDK. It holds configuration and state common
/// to all APIs exposed from the SDK.
/// <para>Use one of the provided <c>Create()</c> methods to obtain a new instance.
/// See <a href="https://firebase.google.com/docs/admin/setup#initialize_the_sdk">
/// Initialize the SDK</a> for code samples and detailed documentation.</para>
/// </summary>
|
This is the entry point to the Firebase Admin SDK. It holds configuration and state common
to all APIs exposed from the SDK.
Use one of the provided Create()
Initialize the SDK
|
[
"This",
"is",
"the",
"entry",
"point",
"to",
"the",
"Firebase",
"Admin",
"SDK",
".",
"It",
"holds",
"configuration",
"and",
"state",
"common",
"to",
"all",
"APIs",
"exposed",
"from",
"the",
"SDK",
".",
"Use",
"one",
"of",
"the",
"provided",
"Create",
"()",
"Initialize",
"the",
"SDK"
] |
public sealed class FirebaseApp
{
internal static readonly IReadOnlyList<string> DefaultScopes = ImmutableList.Create(
"https://www.googleapis.com/auth/firebase",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/identitytoolkit",
"https://www.googleapis.com/auth/devstorage.full_control",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/datastore");
private const string DefaultAppName = "[DEFAULT]";
private static readonly Dictionary<string, FirebaseApp> Apps = new Dictionary<string, FirebaseApp>();
private static readonly ILogger Logger = ApplicationContext.Logger.ForType<FirebaseApp>();
private readonly object appLock = new object();
private readonly AppOptions options;
private readonly Dictionary<string, IFirebaseService> services = new Dictionary<string, IFirebaseService>();
private bool deleted = false;
private FirebaseApp(AppOptions options, string name)
{
this.options = new AppOptions(options);
if (this.options.Credential == null)
{
throw new ArgumentNullException("Credential must be set");
}
if (this.options.Credential.IsCreateScopedRequired)
{
this.options.Credential = this.options.Credential.CreateScoped(DefaultScopes);
}
if (this.options.HttpClientFactory == null)
{
throw new ArgumentNullException("HttpClientFactory must be set");
}
this.Name = name;
}
public static FirebaseApp DefaultInstance
{
get
{
return GetInstance(DefaultAppName);
}
}
public AppOptions Options
{
get
{
return new AppOptions(this.options);
}
}
public string Name { get; }
public static FirebaseApp GetInstance(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("App name to lookup must not be null or empty");
}
lock (Apps)
{
FirebaseApp app;
if (Apps.TryGetValue(name, out app))
{
return app;
}
}
return null;
}
public static FirebaseApp Create()
{
return Create(DefaultAppName);
}
public static FirebaseApp Create(string name)
{
return Create(null, name);
}
public static FirebaseApp Create(AppOptions options)
{
return Create(options, DefaultAppName);
}
public static FirebaseApp Create(AppOptions options, string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("App name must not be null or empty");
}
options = options ?? GetOptionsFromEnvironment();
lock (Apps)
{
if (Apps.ContainsKey(name))
{
if (name == DefaultAppName)
{
throw new ArgumentException("The default FirebaseApp already exists.");
}
else
{
throw new ArgumentException($"FirebaseApp named {name} already exists.");
}
}
var app = new FirebaseApp(options, name);
Apps.Add(name, app);
return app;
}
}
public void Delete()
{
lock (this.appLock)
{
this.deleted = true;
foreach (var entry in this.services)
{
try
{
entry.Value.Delete();
}
catch (Exception e)
{
Logger.Error(e, "Error while cleaning up service {0}", entry.Key);
}
}
this.services.Clear();
}
lock (Apps)
{
Apps.Remove(this.Name);
}
}
internal static void DeleteAll()
{
lock (Apps)
{
var copy = new Dictionary<string, FirebaseApp>(Apps);
foreach (var entry in copy)
{
entry.Value.Delete();
}
if (Apps.Count > 0)
{
throw new InvalidOperationException("Failed to delete all apps");
}
}
}
internal static string GetSdkVersion()
{
const int majorMinorPatch = 3;
return typeof(FirebaseApp).GetTypeInfo().Assembly.GetName().Version.ToString(majorMinorPatch);
}
internal T GetOrInit<T>(string id, ServiceFactory<T> initializer)
where T : class, IFirebaseService
{
lock (this.appLock)
{
if (this.deleted)
{
throw new InvalidOperationException("Cannot use an app after it has been deleted");
}
IFirebaseService service;
if (!this.services.TryGetValue(id, out service))
{
service = initializer();
this.services.Add(id, service);
}
return (T)service;
}
}
internal string GetProjectId()
{
if (!string.IsNullOrEmpty(this.Options.ProjectId))
{
return this.Options.ProjectId;
}
var projectId = this.Options.Credential.ToServiceAccountCredential()?.ProjectId;
if (!string.IsNullOrEmpty(projectId))
{
return projectId;
}
foreach (var variableName in new[] { "GOOGLE_CLOUD_PROJECT", "GCLOUD_PROJECT" })
{
projectId = Environment.GetEnvironmentVariable(variableName);
if (!string.IsNullOrEmpty(projectId))
{
return projectId;
}
}
return null;
}
private static AppOptions GetOptionsFromEnvironment()
{
return new AppOptions()
{
Credential = GoogleCredential.GetApplicationDefault(),
};
}
}
|
[
"public",
"sealed",
"class",
"FirebaseApp",
"{",
"internal",
"static",
"readonly",
"IReadOnlyList",
"<",
"string",
">",
"DefaultScopes",
"=",
"ImmutableList",
".",
"Create",
"(",
"\"",
"https://www.googleapis.com/auth/firebase",
"\"",
",",
"\"",
"https://www.googleapis.com/auth/userinfo.email",
"\"",
",",
"\"",
"https://www.googleapis.com/auth/identitytoolkit",
"\"",
",",
"\"",
"https://www.googleapis.com/auth/devstorage.full_control",
"\"",
",",
"\"",
"https://www.googleapis.com/auth/cloud-platform",
"\"",
",",
"\"",
"https://www.googleapis.com/auth/datastore",
"\"",
")",
";",
"private",
"const",
"string",
"DefaultAppName",
"=",
"\"",
"[DEFAULT]",
"\"",
";",
"private",
"static",
"readonly",
"Dictionary",
"<",
"string",
",",
"FirebaseApp",
">",
"Apps",
"=",
"new",
"Dictionary",
"<",
"string",
",",
"FirebaseApp",
">",
"(",
")",
";",
"private",
"static",
"readonly",
"ILogger",
"Logger",
"=",
"ApplicationContext",
".",
"Logger",
".",
"ForType",
"<",
"FirebaseApp",
">",
"(",
")",
";",
"private",
"readonly",
"object",
"appLock",
"=",
"new",
"object",
"(",
")",
";",
"private",
"readonly",
"AppOptions",
"options",
";",
"private",
"readonly",
"Dictionary",
"<",
"string",
",",
"IFirebaseService",
">",
"services",
"=",
"new",
"Dictionary",
"<",
"string",
",",
"IFirebaseService",
">",
"(",
")",
";",
"private",
"bool",
"deleted",
"=",
"false",
";",
"private",
"FirebaseApp",
"(",
"AppOptions",
"options",
",",
"string",
"name",
")",
"{",
"this",
".",
"options",
"=",
"new",
"AppOptions",
"(",
"options",
")",
";",
"if",
"(",
"this",
".",
"options",
".",
"Credential",
"==",
"null",
")",
"{",
"throw",
"new",
"ArgumentNullException",
"(",
"\"",
"Credential must be set",
"\"",
")",
";",
"}",
"if",
"(",
"this",
".",
"options",
".",
"Credential",
".",
"IsCreateScopedRequired",
")",
"{",
"this",
".",
"options",
".",
"Credential",
"=",
"this",
".",
"options",
".",
"Credential",
".",
"CreateScoped",
"(",
"DefaultScopes",
")",
";",
"}",
"if",
"(",
"this",
".",
"options",
".",
"HttpClientFactory",
"==",
"null",
")",
"{",
"throw",
"new",
"ArgumentNullException",
"(",
"\"",
"HttpClientFactory must be set",
"\"",
")",
";",
"}",
"this",
".",
"Name",
"=",
"name",
";",
"}",
"public",
"static",
"FirebaseApp",
"DefaultInstance",
"{",
"get",
"{",
"return",
"GetInstance",
"(",
"DefaultAppName",
")",
";",
"}",
"}",
"public",
"AppOptions",
"Options",
"{",
"get",
"{",
"return",
"new",
"AppOptions",
"(",
"this",
".",
"options",
")",
";",
"}",
"}",
"public",
"string",
"Name",
"{",
"get",
";",
"}",
"public",
"static",
"FirebaseApp",
"GetInstance",
"(",
"string",
"name",
")",
"{",
"if",
"(",
"string",
".",
"IsNullOrEmpty",
"(",
"name",
")",
")",
"{",
"throw",
"new",
"ArgumentException",
"(",
"\"",
"App name to lookup must not be null or empty",
"\"",
")",
";",
"}",
"lock",
"(",
"Apps",
")",
"{",
"FirebaseApp",
"app",
";",
"if",
"(",
"Apps",
".",
"TryGetValue",
"(",
"name",
",",
"out",
"app",
")",
")",
"{",
"return",
"app",
";",
"}",
"}",
"return",
"null",
";",
"}",
"public",
"static",
"FirebaseApp",
"Create",
"(",
")",
"{",
"return",
"Create",
"(",
"DefaultAppName",
")",
";",
"}",
"public",
"static",
"FirebaseApp",
"Create",
"(",
"string",
"name",
")",
"{",
"return",
"Create",
"(",
"null",
",",
"name",
")",
";",
"}",
"public",
"static",
"FirebaseApp",
"Create",
"(",
"AppOptions",
"options",
")",
"{",
"return",
"Create",
"(",
"options",
",",
"DefaultAppName",
")",
";",
"}",
"public",
"static",
"FirebaseApp",
"Create",
"(",
"AppOptions",
"options",
",",
"string",
"name",
")",
"{",
"if",
"(",
"string",
".",
"IsNullOrEmpty",
"(",
"name",
")",
")",
"{",
"throw",
"new",
"ArgumentException",
"(",
"\"",
"App name must not be null or empty",
"\"",
")",
";",
"}",
"options",
"=",
"options",
"??",
"GetOptionsFromEnvironment",
"(",
")",
";",
"lock",
"(",
"Apps",
")",
"{",
"if",
"(",
"Apps",
".",
"ContainsKey",
"(",
"name",
")",
")",
"{",
"if",
"(",
"name",
"==",
"DefaultAppName",
")",
"{",
"throw",
"new",
"ArgumentException",
"(",
"\"",
"The default FirebaseApp already exists.",
"\"",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"ArgumentException",
"(",
"$\"",
"FirebaseApp named ",
"{",
"name",
"}",
" already exists.",
"\"",
")",
";",
"}",
"}",
"var",
"app",
"=",
"new",
"FirebaseApp",
"(",
"options",
",",
"name",
")",
";",
"Apps",
".",
"Add",
"(",
"name",
",",
"app",
")",
";",
"return",
"app",
";",
"}",
"}",
"public",
"void",
"Delete",
"(",
")",
"{",
"lock",
"(",
"this",
".",
"appLock",
")",
"{",
"this",
".",
"deleted",
"=",
"true",
";",
"foreach",
"(",
"var",
"entry",
"in",
"this",
".",
"services",
")",
"{",
"try",
"{",
"entry",
".",
"Value",
".",
"Delete",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"Logger",
".",
"Error",
"(",
"e",
",",
"\"",
"Error while cleaning up service {0}",
"\"",
",",
"entry",
".",
"Key",
")",
";",
"}",
"}",
"this",
".",
"services",
".",
"Clear",
"(",
")",
";",
"}",
"lock",
"(",
"Apps",
")",
"{",
"Apps",
".",
"Remove",
"(",
"this",
".",
"Name",
")",
";",
"}",
"}",
"internal",
"static",
"void",
"DeleteAll",
"(",
")",
"{",
"lock",
"(",
"Apps",
")",
"{",
"var",
"copy",
"=",
"new",
"Dictionary",
"<",
"string",
",",
"FirebaseApp",
">",
"(",
"Apps",
")",
";",
"foreach",
"(",
"var",
"entry",
"in",
"copy",
")",
"{",
"entry",
".",
"Value",
".",
"Delete",
"(",
")",
";",
"}",
"if",
"(",
"Apps",
".",
"Count",
">",
"0",
")",
"{",
"throw",
"new",
"InvalidOperationException",
"(",
"\"",
"Failed to delete all apps",
"\"",
")",
";",
"}",
"}",
"}",
"internal",
"static",
"string",
"GetSdkVersion",
"(",
")",
"{",
"const",
"int",
"majorMinorPatch",
"=",
"3",
";",
"return",
"typeof",
"(",
"FirebaseApp",
")",
".",
"GetTypeInfo",
"(",
")",
".",
"Assembly",
".",
"GetName",
"(",
")",
".",
"Version",
".",
"ToString",
"(",
"majorMinorPatch",
")",
";",
"}",
"internal",
"T",
"GetOrInit",
"<",
"T",
">",
"(",
"string",
"id",
",",
"ServiceFactory",
"<",
"T",
">",
"initializer",
")",
"where",
"T",
":",
"class",
",",
"IFirebaseService",
"{",
"lock",
"(",
"this",
".",
"appLock",
")",
"{",
"if",
"(",
"this",
".",
"deleted",
")",
"{",
"throw",
"new",
"InvalidOperationException",
"(",
"\"",
"Cannot use an app after it has been deleted",
"\"",
")",
";",
"}",
"IFirebaseService",
"service",
";",
"if",
"(",
"!",
"this",
".",
"services",
".",
"TryGetValue",
"(",
"id",
",",
"out",
"service",
")",
")",
"{",
"service",
"=",
"initializer",
"(",
")",
";",
"this",
".",
"services",
".",
"Add",
"(",
"id",
",",
"service",
")",
";",
"}",
"return",
"(",
"T",
")",
"service",
";",
"}",
"}",
"internal",
"string",
"GetProjectId",
"(",
")",
"{",
"if",
"(",
"!",
"string",
".",
"IsNullOrEmpty",
"(",
"this",
".",
"Options",
".",
"ProjectId",
")",
")",
"{",
"return",
"this",
".",
"Options",
".",
"ProjectId",
";",
"}",
"var",
"projectId",
"=",
"this",
".",
"Options",
".",
"Credential",
".",
"ToServiceAccountCredential",
"(",
")",
"?",
".",
"ProjectId",
";",
"if",
"(",
"!",
"string",
".",
"IsNullOrEmpty",
"(",
"projectId",
")",
")",
"{",
"return",
"projectId",
";",
"}",
"foreach",
"(",
"var",
"variableName",
"in",
"new",
"[",
"]",
"{",
"\"",
"GOOGLE_CLOUD_PROJECT",
"\"",
",",
"\"",
"GCLOUD_PROJECT",
"\"",
"}",
")",
"{",
"projectId",
"=",
"Environment",
".",
"GetEnvironmentVariable",
"(",
"variableName",
")",
";",
"if",
"(",
"!",
"string",
".",
"IsNullOrEmpty",
"(",
"projectId",
")",
")",
"{",
"return",
"projectId",
";",
"}",
"}",
"return",
"null",
";",
"}",
"private",
"static",
"AppOptions",
"GetOptionsFromEnvironment",
"(",
")",
"{",
"return",
"new",
"AppOptions",
"(",
")",
"{",
"Credential",
"=",
"GoogleCredential",
".",
"GetApplicationDefault",
"(",
")",
",",
"}",
";",
"}",
"}"
] |
This is the entry point to the Firebase Admin SDK.
|
[
"This",
"is",
"the",
"entry",
"point",
"to",
"the",
"Firebase",
"Admin",
"SDK",
"."
] |
[
"// RTDB.",
"// RTDB",
"// User management",
"// Cloud Storage",
"// Cloud Firestore",
"// Guards the mutable state local to an app instance.",
"// A collection of stateful services initialized using this app instance (e.g.",
"// FirebaseAuth). Services are tracked here so they can be cleaned up when the app is",
"// deleted.",
"/// <summary>",
"/// Gets the default app instance. This property is <c>null</c> if the default app instance",
"/// doesn't yet exist.",
"/// </summary>",
"/// <summary>",
"/// Gets a copy of the <see cref=\"AppOptions\"/> this app was created with.",
"/// </summary>",
"/// <summary>",
"/// Gets the name of this app.",
"/// </summary>",
"/// <summary>",
"/// Returns the app instance identified by the given name.",
"/// </summary>",
"/// <returns>The <see cref=\"FirebaseApp\"/> instance with the specified name or null if it",
"/// doesn't exist.</returns>",
"/// <exception cref=\"System.ArgumentException\">If the name argument is null or empty.</exception>",
"/// <param name=\"name\">Name of the app to retrieve.</param>",
"/// <summary>",
"/// Creates the default app instance with Google Application Default Credentials.",
"/// </summary>",
"/// <returns>The newly created <see cref=\"FirebaseApp\"/> instance.</returns>",
"/// <exception cref=\"System.ArgumentException\">If the default app instance already",
"/// exists.</exception>",
"/// <summary>",
"/// Creates an app with the specified name, and Google Application Default Credentials.",
"/// </summary>",
"/// <returns>The newly created <see cref=\"FirebaseApp\"/> instance.</returns>",
"/// <exception cref=\"System.ArgumentException\">If the default app instance already",
"/// exists.</exception>",
"/// <param name=\"name\">Name of the app.</param>",
"/// <summary>",
"/// Creates the default app instance with the specified options.",
"/// </summary>",
"/// <returns>The newly created <see cref=\"FirebaseApp\"/> instance.</returns>",
"/// <exception cref=\"System.ArgumentException\">If the default app instance already",
"/// exists.</exception>",
"/// <param name=\"options\">Options to create the app with. Must at least contain the",
"/// <c>Credential</c>.</param>",
"/// <summary>",
"/// Creates an app with the specified name and options.",
"/// </summary>",
"/// <returns>The newly created <see cref=\"FirebaseApp\"/> instance.</returns>",
"/// <exception cref=\"System.ArgumentException\">If the default app instance already",
"/// exists.</exception>",
"/// <param name=\"options\">Options to create the app with. Must at least contain the",
"/// <c>Credential</c>.</param>",
"/// <param name=\"name\">Name of the app.</param>",
"/// <summary>",
"/// Deletes this app instance and cleans up any state associated with it. Once an app has",
"/// been deleted, accessing any services related to it will result in an exception.",
"/// If the app is already deleted, this method is a no-op.",
"/// </summary>",
"// Clean up local state",
"// Clean up global state",
"/// <summary>",
"/// Deleted all the apps created so far. Used for unit testing.",
"/// </summary>",
"/// <summary>",
"/// Returns the current version of the .NET assembly.",
"/// </summary>",
"/// <returns>A version string in major.minor.patch format.</returns>",
"/// <summary>",
"/// Returns the Google Cloud Platform project ID associated with this Firebase app. If a",
"/// project ID is specified in <see cref=\"AppOptions\"/>, that value is returned. If not",
"/// attempts to determine a project ID from the <see cref=\"GoogleCredential\"/> used to",
"/// initialize the app. Looks up the GOOGLE_CLOUD_PROJECT environment variable when all",
"/// else fails.",
"/// </summary>",
"/// <returns>A project ID string or null.</returns>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 1,110
| 93
|
334e5b9708e3c563d1df1a8d45fac3a712d2e74d
|
dlazerka/gae-jersey-oauth2
|
src/main/java/me/lazerka/gae/jersey/oauth2/facebook/DebugTokenResponse.java
|
[
"Apache-2.0"
] |
Java
|
DebugTokenResponse
|
/**
* See https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#checktoken
*
* Like:
* <pre>
* {
* "data": {
* "app_id": 138483919580948,
* "application": "Social Cafe",
* "expires_at": 1352419328,
* "is_valid": true,
* "issued_at": 1347235328,
* "metadata": {
* "sso": "iphone-safari"
* },
* "scopes": [
* "email",
* "publish_actions"
* ],
* "user_id": 1207059
* }
* }
* </pre>
*
*
* @author Dzmitry Lazerka
*/
|
@author Dzmitry Lazerka
|
[
"@author",
"Dzmitry",
"Lazerka"
] |
public class DebugTokenResponse {
@JsonProperty("data")
Data data;
static class Data {
@JsonProperty("is_valid")
boolean isValid;
@JsonProperty("error")
Error error;
@JsonProperty("app_id")
String appId;
@JsonProperty("application")
String application;
@JsonProperty("expires_at")
long expiresAt;
@JsonProperty("issued_at")
long issuedAt;
@JsonProperty("metadata")
Metadata metadata;
@JsonProperty("scopes")
List<String> scopes;
@JsonProperty("user_id")
String userId;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Data)) return false;
Data data = (Data) o;
return expiresAt == data.expiresAt &&
isValid == data.isValid &&
issuedAt == data.issuedAt &&
Objects.equals(appId, data.appId) &&
Objects.equals(application, data.application) &&
Objects.equals(metadata, data.metadata) &&
Objects.equals(scopes, data.scopes) &&
Objects.equals(userId, data.userId);
}
@Override
public int hashCode() {
return Objects.hash(appId, application, expiresAt, isValid, issuedAt, metadata, scopes, userId);
}
}
static class Metadata {
@JsonProperty("sso")
String sso;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Metadata)) return false;
Metadata metadata = (Metadata) o;
return Objects.equals(sso, metadata.sso);
}
@Override
public int hashCode() {
return Objects.hash(sso);
}
}
static class Error {
@JsonProperty("code")
int code;
@JsonProperty("message")
String message;
}
public boolean isValid() {
return data.isValid;
}
public String getAppId() {
return data.appId;
}
public String getApplication() {
return data.application;
}
public long getExpiresAt() {
return data.expiresAt;
}
public long getIssuedAt() {
return data.issuedAt;
}
public Metadata getMetadata() {
return data.metadata;
}
public List<String> getScopes() {
return data.scopes;
}
public String getUserId() {
return data.userId;
}
public String getSso() {
return data.metadata == null ? null : data.metadata.sso;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DebugTokenResponse)) return false;
DebugTokenResponse that = (DebugTokenResponse) o;
return Objects.equals(data, that.data);
}
@Override
public int hashCode() {
return Objects.hash(data);
}
}
|
[
"public",
"class",
"DebugTokenResponse",
"{",
"@",
"JsonProperty",
"(",
"\"",
"data",
"\"",
")",
"Data",
"data",
";",
"static",
"class",
"Data",
"{",
"@",
"JsonProperty",
"(",
"\"",
"is_valid",
"\"",
")",
"boolean",
"isValid",
";",
"@",
"JsonProperty",
"(",
"\"",
"error",
"\"",
")",
"Error",
"error",
";",
"@",
"JsonProperty",
"(",
"\"",
"app_id",
"\"",
")",
"String",
"appId",
";",
"@",
"JsonProperty",
"(",
"\"",
"application",
"\"",
")",
"String",
"application",
";",
"@",
"JsonProperty",
"(",
"\"",
"expires_at",
"\"",
")",
"long",
"expiresAt",
";",
"@",
"JsonProperty",
"(",
"\"",
"issued_at",
"\"",
")",
"long",
"issuedAt",
";",
"@",
"JsonProperty",
"(",
"\"",
"metadata",
"\"",
")",
"Metadata",
"metadata",
";",
"@",
"JsonProperty",
"(",
"\"",
"scopes",
"\"",
")",
"List",
"<",
"String",
">",
"scopes",
";",
"@",
"JsonProperty",
"(",
"\"",
"user_id",
"\"",
")",
"String",
"userId",
";",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"Object",
"o",
")",
"{",
"if",
"(",
"this",
"==",
"o",
")",
"return",
"true",
";",
"if",
"(",
"!",
"(",
"o",
"instanceof",
"Data",
")",
")",
"return",
"false",
";",
"Data",
"data",
"=",
"(",
"Data",
")",
"o",
";",
"return",
"expiresAt",
"==",
"data",
".",
"expiresAt",
"&&",
"isValid",
"==",
"data",
".",
"isValid",
"&&",
"issuedAt",
"==",
"data",
".",
"issuedAt",
"&&",
"Objects",
".",
"equals",
"(",
"appId",
",",
"data",
".",
"appId",
")",
"&&",
"Objects",
".",
"equals",
"(",
"application",
",",
"data",
".",
"application",
")",
"&&",
"Objects",
".",
"equals",
"(",
"metadata",
",",
"data",
".",
"metadata",
")",
"&&",
"Objects",
".",
"equals",
"(",
"scopes",
",",
"data",
".",
"scopes",
")",
"&&",
"Objects",
".",
"equals",
"(",
"userId",
",",
"data",
".",
"userId",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"hashCode",
"(",
")",
"{",
"return",
"Objects",
".",
"hash",
"(",
"appId",
",",
"application",
",",
"expiresAt",
",",
"isValid",
",",
"issuedAt",
",",
"metadata",
",",
"scopes",
",",
"userId",
")",
";",
"}",
"}",
"static",
"class",
"Metadata",
"{",
"@",
"JsonProperty",
"(",
"\"",
"sso",
"\"",
")",
"String",
"sso",
";",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"Object",
"o",
")",
"{",
"if",
"(",
"this",
"==",
"o",
")",
"return",
"true",
";",
"if",
"(",
"!",
"(",
"o",
"instanceof",
"Metadata",
")",
")",
"return",
"false",
";",
"Metadata",
"metadata",
"=",
"(",
"Metadata",
")",
"o",
";",
"return",
"Objects",
".",
"equals",
"(",
"sso",
",",
"metadata",
".",
"sso",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"hashCode",
"(",
")",
"{",
"return",
"Objects",
".",
"hash",
"(",
"sso",
")",
";",
"}",
"}",
"static",
"class",
"Error",
"{",
"@",
"JsonProperty",
"(",
"\"",
"code",
"\"",
")",
"int",
"code",
";",
"@",
"JsonProperty",
"(",
"\"",
"message",
"\"",
")",
"String",
"message",
";",
"}",
"public",
"boolean",
"isValid",
"(",
")",
"{",
"return",
"data",
".",
"isValid",
";",
"}",
"public",
"String",
"getAppId",
"(",
")",
"{",
"return",
"data",
".",
"appId",
";",
"}",
"public",
"String",
"getApplication",
"(",
")",
"{",
"return",
"data",
".",
"application",
";",
"}",
"public",
"long",
"getExpiresAt",
"(",
")",
"{",
"return",
"data",
".",
"expiresAt",
";",
"}",
"public",
"long",
"getIssuedAt",
"(",
")",
"{",
"return",
"data",
".",
"issuedAt",
";",
"}",
"public",
"Metadata",
"getMetadata",
"(",
")",
"{",
"return",
"data",
".",
"metadata",
";",
"}",
"public",
"List",
"<",
"String",
">",
"getScopes",
"(",
")",
"{",
"return",
"data",
".",
"scopes",
";",
"}",
"public",
"String",
"getUserId",
"(",
")",
"{",
"return",
"data",
".",
"userId",
";",
"}",
"public",
"String",
"getSso",
"(",
")",
"{",
"return",
"data",
".",
"metadata",
"==",
"null",
"?",
"null",
":",
"data",
".",
"metadata",
".",
"sso",
";",
"}",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"Object",
"o",
")",
"{",
"if",
"(",
"this",
"==",
"o",
")",
"return",
"true",
";",
"if",
"(",
"!",
"(",
"o",
"instanceof",
"DebugTokenResponse",
")",
")",
"return",
"false",
";",
"DebugTokenResponse",
"that",
"=",
"(",
"DebugTokenResponse",
")",
"o",
";",
"return",
"Objects",
".",
"equals",
"(",
"data",
",",
"that",
".",
"data",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"hashCode",
"(",
")",
"{",
"return",
"Objects",
".",
"hash",
"(",
"data",
")",
";",
"}",
"}"
] |
See https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#checktoken
Like:
<pre>
{
"data": {
"app_id": 138483919580948,
"application": "Social Cafe",
"expires_at": 1352419328,
"is_valid": true,
"issued_at": 1347235328,
"metadata": {
"sso": "iphone-safari"
},
"scopes": [
"email",
"publish_actions"
],
"user_id": 1207059
}
}
</pre>
|
[
"See",
"https",
":",
"//",
"developers",
".",
"facebook",
".",
"com",
"/",
"docs",
"/",
"facebook",
"-",
"login",
"/",
"manually",
"-",
"build",
"-",
"a",
"-",
"login",
"-",
"flow#checktoken",
"Like",
":",
"<pre",
">",
"{",
"\"",
"data",
"\"",
":",
"{",
"\"",
"app_id",
"\"",
":",
"138483919580948",
"\"",
"application",
"\"",
":",
"\"",
"Social",
"Cafe",
"\"",
"\"",
"expires_at",
"\"",
":",
"1352419328",
"\"",
"is_valid",
"\"",
":",
"true",
"\"",
"issued_at",
"\"",
":",
"1347235328",
"\"",
"metadata",
"\"",
":",
"{",
"\"",
"sso",
"\"",
":",
"\"",
"iphone",
"-",
"safari",
"\"",
"}",
"\"",
"scopes",
"\"",
":",
"[",
"\"",
"email",
"\"",
"\"",
"publish_actions",
"\"",
"]",
"\"",
"user_id",
"\"",
":",
"1207059",
"}",
"}",
"<",
"/",
"pre",
">"
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 607
| 193
|
a4d671724c07ca31892ecbcaa593ecb345ec7b1c
|
mcleo-d/App-Integrations-Core
|
integration-provisioning/src/main/java/org/symphonyoss/integration/provisioning/IntegrationProvisioningApp.java
|
[
"Apache-2.0"
] |
Java
|
IntegrationProvisioningApp
|
/**
* A command line application used by the Integration Bridge installation script to provision data
* at Symphony backend. This application is responsible for provisioning Symphony Apps, Bot Users,
* Bot Users's authentication certificates, and Webhook Configurations.
*
* The application will provision data based on an input YAML file and can be run multiple times to
* recover from temporary errors, i.e. the provisioning process is idempotent.
*
* Created by rsanchez on 28/06/16.
*/
|
A command line application used by the Integration Bridge installation script to provision data
at Symphony backend. This application is responsible for provisioning Symphony Apps, Bot Users,
Bot Users's authentication certificates, and Webhook Configurations.
The application will provision data based on an input YAML file and can be run multiple times to
recover from temporary errors, i.e. the provisioning process is idempotent.
Created by rsanchez on 28/06/16.
|
[
"A",
"command",
"line",
"application",
"used",
"by",
"the",
"Integration",
"Bridge",
"installation",
"script",
"to",
"provision",
"data",
"at",
"Symphony",
"backend",
".",
"This",
"application",
"is",
"responsible",
"for",
"provisioning",
"Symphony",
"Apps",
"Bot",
"Users",
"Bot",
"Users",
"'",
"s",
"authentication",
"certificates",
"and",
"Webhook",
"Configurations",
".",
"The",
"application",
"will",
"provision",
"data",
"based",
"on",
"an",
"input",
"YAML",
"file",
"and",
"can",
"be",
"run",
"multiple",
"times",
"to",
"recover",
"from",
"temporary",
"errors",
"i",
".",
"e",
".",
"the",
"provisioning",
"process",
"is",
"idempotent",
".",
"Created",
"by",
"rsanchez",
"on",
"28",
"/",
"06",
"/",
"16",
"."
] |
@Component
@SpringBootApplication(scanBasePackages = {"org.symphonyoss.integration"})
public class IntegrationProvisioningApp {
private static final Logger LOGGER = LoggerFactory.getLogger(IntegrationProvisioningApp.class);
private static final String FAIL_AUTH_ADMIN_USER = "provisioning.auth.unknown.exception";
/**
* Default keystore type.
*/
private static final String DEFAULT_KEYSTORE_TYPE = "pkcs12";
@Autowired
private AuthenticationService authService;
@Autowired
private IntegrationProvisioningService service;
@Autowired
private IntegrationProperties properties;
@Autowired
private LogMessageSource logMessage;
/**
* Entry point for the Provisioning App.
*/
public static void main(String[] args) {
boolean success = false;
try {
SpringApplication application = new SpringApplication(IntegrationProvisioningApp.class);
ConfigurableApplicationContext context = application.run(args);
IntegrationProvisioningApp app = context.getBean(IntegrationProvisioningApp.class);
success = app.execute();
} catch (Exception e) {
LOGGER.error("Failed to bootstrap the provisioning tool.", e);
}
int status = success ? 0 : 1;
System.exit(status);
}
/**
* Application constructor.
*
* Application arguments:
* --spring.config.location: YAML config file path. If not specified the application will try
* to lookup the file 'application.yml'
*/
public IntegrationProvisioningApp() {}
/**
* Executes the Provisioning process.
* @return Success indication (boolean).
*/
public boolean execute() {
boolean success = authenticate();
if (success) {
success = service.configure();
}
return success;
}
/**
* Authenticates the provisioning user.
* @return Success indication (boolean).
*/
private boolean authenticate() {
try {
AdminUser adminUser = properties.getAdminUser();
String keyStore = adminUser.getKeystoreFile();
String keyStorePassword = adminUser.getKeystorePassword();
IntegrationBridge integrationBridge = properties.getIntegrationBridge();
String trustStore = integrationBridge.getTruststoreFile();
String trustStoreType = null;
String trustStorePassword = null;
if (!StringUtils.isEmpty(trustStore)) {
trustStoreType = integrationBridge.getTruststoreType();
trustStorePassword = integrationBridge.getTruststorePassword();
}
authService.authenticate(DEFAULT_USER_ID, trustStore, trustStorePassword, trustStoreType,
keyStore, keyStorePassword, DEFAULT_KEYSTORE_TYPE);
return true;
} catch (IntegrationRuntimeException e) {
LOGGER.error(e.getMessage());
return false;
} catch (Exception e) {
String message = logMessage.getMessage(FAIL_AUTH_ADMIN_USER);
LOGGER.error(message, e);
return false;
}
}
}
|
[
"@",
"Component",
"@",
"SpringBootApplication",
"(",
"scanBasePackages",
"=",
"{",
"\"",
"org.symphonyoss.integration",
"\"",
"}",
")",
"public",
"class",
"IntegrationProvisioningApp",
"{",
"private",
"static",
"final",
"Logger",
"LOGGER",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"IntegrationProvisioningApp",
".",
"class",
")",
";",
"private",
"static",
"final",
"String",
"FAIL_AUTH_ADMIN_USER",
"=",
"\"",
"provisioning.auth.unknown.exception",
"\"",
";",
"/**\n * Default keystore type.\n */",
"private",
"static",
"final",
"String",
"DEFAULT_KEYSTORE_TYPE",
"=",
"\"",
"pkcs12",
"\"",
";",
"@",
"Autowired",
"private",
"AuthenticationService",
"authService",
";",
"@",
"Autowired",
"private",
"IntegrationProvisioningService",
"service",
";",
"@",
"Autowired",
"private",
"IntegrationProperties",
"properties",
";",
"@",
"Autowired",
"private",
"LogMessageSource",
"logMessage",
";",
"/**\n * Entry point for the Provisioning App.\n */",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"boolean",
"success",
"=",
"false",
";",
"try",
"{",
"SpringApplication",
"application",
"=",
"new",
"SpringApplication",
"(",
"IntegrationProvisioningApp",
".",
"class",
")",
";",
"ConfigurableApplicationContext",
"context",
"=",
"application",
".",
"run",
"(",
"args",
")",
";",
"IntegrationProvisioningApp",
"app",
"=",
"context",
".",
"getBean",
"(",
"IntegrationProvisioningApp",
".",
"class",
")",
";",
"success",
"=",
"app",
".",
"execute",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"",
"Failed to bootstrap the provisioning tool.",
"\"",
",",
"e",
")",
";",
"}",
"int",
"status",
"=",
"success",
"?",
"0",
":",
"1",
";",
"System",
".",
"exit",
"(",
"status",
")",
";",
"}",
"/**\n * Application constructor.\n *\n * Application arguments:\n * --spring.config.location: YAML config file path. If not specified the application will try\n * to lookup the file 'application.yml'\n */",
"public",
"IntegrationProvisioningApp",
"(",
")",
"{",
"}",
"/**\n * Executes the Provisioning process.\n * @return Success indication (boolean).\n */",
"public",
"boolean",
"execute",
"(",
")",
"{",
"boolean",
"success",
"=",
"authenticate",
"(",
")",
";",
"if",
"(",
"success",
")",
"{",
"success",
"=",
"service",
".",
"configure",
"(",
")",
";",
"}",
"return",
"success",
";",
"}",
"/**\n * Authenticates the provisioning user.\n * @return Success indication (boolean).\n */",
"private",
"boolean",
"authenticate",
"(",
")",
"{",
"try",
"{",
"AdminUser",
"adminUser",
"=",
"properties",
".",
"getAdminUser",
"(",
")",
";",
"String",
"keyStore",
"=",
"adminUser",
".",
"getKeystoreFile",
"(",
")",
";",
"String",
"keyStorePassword",
"=",
"adminUser",
".",
"getKeystorePassword",
"(",
")",
";",
"IntegrationBridge",
"integrationBridge",
"=",
"properties",
".",
"getIntegrationBridge",
"(",
")",
";",
"String",
"trustStore",
"=",
"integrationBridge",
".",
"getTruststoreFile",
"(",
")",
";",
"String",
"trustStoreType",
"=",
"null",
";",
"String",
"trustStorePassword",
"=",
"null",
";",
"if",
"(",
"!",
"StringUtils",
".",
"isEmpty",
"(",
"trustStore",
")",
")",
"{",
"trustStoreType",
"=",
"integrationBridge",
".",
"getTruststoreType",
"(",
")",
";",
"trustStorePassword",
"=",
"integrationBridge",
".",
"getTruststorePassword",
"(",
")",
";",
"}",
"authService",
".",
"authenticate",
"(",
"DEFAULT_USER_ID",
",",
"trustStore",
",",
"trustStorePassword",
",",
"trustStoreType",
",",
"keyStore",
",",
"keyStorePassword",
",",
"DEFAULT_KEYSTORE_TYPE",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"IntegrationRuntimeException",
"e",
")",
"{",
"LOGGER",
".",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"return",
"false",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"String",
"message",
"=",
"logMessage",
".",
"getMessage",
"(",
"FAIL_AUTH_ADMIN_USER",
")",
";",
"LOGGER",
".",
"error",
"(",
"message",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"}",
"}"
] |
A command line application used by the Integration Bridge installation script to provision data
at Symphony backend.
|
[
"A",
"command",
"line",
"application",
"used",
"by",
"the",
"Integration",
"Bridge",
"installation",
"script",
"to",
"provision",
"data",
"at",
"Symphony",
"backend",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 592
| 104
|
efc9c47d2e06d1d1dfd216d3c74f510bc04719f9
|
sushilks/nlpUnitConverter
|
src/nodes_gr/verb_base.js
|
[
"0BSD"
] |
JavaScript
|
VerbBase
|
/*
NN----(subj)---->VB(is/defined)---xcomp/nmod--->NN
NN1---(subj)--->NN2 with NN2--cop->VBZ(is)
ADD
-- Add TO VerbBase (Wh-Clauses)
- Who
- What
- when
- where
- which
- whose
- why / how
Subject : part of the sentence that commonly indicates
- What it is about
- Who or what performs the action (that is the agent)
Object : A noun.. that is affected by the action of a verb
or that completes the meaning of a preposition
Marie wrote a poem
Object(direct) = Poem
Subj = Marie
Verb = Wrote
Marie sent me an email.
object(dobj) = email
object(iobj) = me
subj = Marie
Verb = sent
Complement : A word that completes the predicate in a sentence.
My glass is empty (subject complemt)
We find them very pleasant. (Object complement)
http://grammar.about.com/od/c/g/complterm.htm
How much is 10 Foot in Meters?
"How much" - verbDep...
"10 Foot" - Subject
"Meters" - SubjectWhat
// by default water is in liquid state.
// subj/Who - Water
// Object/what - State->Liquid
// when - default (nmod:by->obj)
// default state of water is liquid.
// subj/what : state -> default
// Object : Liquid
// who : Water (nmod:of -> subj)
Time is defined to be a type of Measure.
The default unit for foo is Zque.
By default time is expressed in minutes.
*/
|
ADD
Add TO VerbBase (Wh-Clauses)
Who
What
when
where
which
whose
why / how
Subject : part of the sentence that commonly indicates
What it is about
Who or what performs the action (that is the agent)
Object : A noun.. that is affected by the action of a verb
or that completes the meaning of a preposition
Marie wrote a poem
Object(direct) = Poem
Subj = Marie
Verb = Wrote
Marie sent me an email.
object(dobj) = email
object(iobj) = me
subj = Marie
Verb = sent
Complement : A word that completes the predicate in a sentence.
My glass is empty (subject complemt)
We find them very pleasant.
by default water is in liquid state.
default state of water is liquid.
subj/what : state -> default
Object : Liquid
who : Water (nmod:of -> subj)
Time is defined to be a type of Measure.
The default unit for foo is Zque.
By default time is expressed in minutes.
|
[
"ADD",
"Add",
"TO",
"VerbBase",
"(",
"Wh",
"-",
"Clauses",
")",
"Who",
"What",
"when",
"where",
"which",
"whose",
"why",
"/",
"how",
"Subject",
":",
"part",
"of",
"the",
"sentence",
"that",
"commonly",
"indicates",
"What",
"it",
"is",
"about",
"Who",
"or",
"what",
"performs",
"the",
"action",
"(",
"that",
"is",
"the",
"agent",
")",
"Object",
":",
"A",
"noun",
"..",
"that",
"is",
"affected",
"by",
"the",
"action",
"of",
"a",
"verb",
"or",
"that",
"completes",
"the",
"meaning",
"of",
"a",
"preposition",
"Marie",
"wrote",
"a",
"poem",
"Object",
"(",
"direct",
")",
"=",
"Poem",
"Subj",
"=",
"Marie",
"Verb",
"=",
"Wrote",
"Marie",
"sent",
"me",
"an",
"email",
".",
"object",
"(",
"dobj",
")",
"=",
"email",
"object",
"(",
"iobj",
")",
"=",
"me",
"subj",
"=",
"Marie",
"Verb",
"=",
"sent",
"Complement",
":",
"A",
"word",
"that",
"completes",
"the",
"predicate",
"in",
"a",
"sentence",
".",
"My",
"glass",
"is",
"empty",
"(",
"subject",
"complemt",
")",
"We",
"find",
"them",
"very",
"pleasant",
".",
"by",
"default",
"water",
"is",
"in",
"liquid",
"state",
".",
"default",
"state",
"of",
"water",
"is",
"liquid",
".",
"subj",
"/",
"what",
":",
"state",
"-",
">",
"default",
"Object",
":",
"Liquid",
"who",
":",
"Water",
"(",
"nmod",
":",
"of",
"-",
">",
"subj",
")",
"Time",
"is",
"defined",
"to",
"be",
"a",
"type",
"of",
"Measure",
".",
"The",
"default",
"unit",
"for",
"foo",
"is",
"Zque",
".",
"By",
"default",
"time",
"is",
"expressed",
"in",
"minutes",
"."
] |
class VerbBase extends GrBase {
constructor(nodes, fromNode, linkType, toNode, matchResult) {
super(nodes, fromNode, linkType, toNode, matchResult);
this.name = 'VerbBase';
}
static getMatchToken() {
//return ['define:VB.*', 'is:VB.*', 'defined:VB.*'];
//return ['.*:VB.*'];
//return [{name:'verb-1', toPOS:'VB.*', edge:'((?!cop).)*'} ];
return [{name:'verb-1', toPOS:'VB.*', edge:'((?!cop).)*'},
{name:'verb-2', toPOS:'VB.*', edge:'cop', applyToParent:true}];
//return [{name:'verb-1', toPOS:'VB.*'];
}
/*
getValues() {;
return this.match.verb;//this.nodes.getTokens().getToken(this.verb);
}*/
dict() {
let r = this.processNode();
return r;
return this.match.vb;
}
text() {
return this.name + ':: ' + JSON.stringify(this.match);
}
getVerb() {
return this.match.verb;//this.nodes.getNodeMap(this.verb).getValues();
}
getValues(tagged=false) {
let res = [];
if (this.linkType === 'cop'){
let children = this.fromNode.getChildren();
for(let child in children) {
let c = this.fromNode.getChild(child);
if (this.toNode.getTokenId() !== c.node.getTokenId()) {
res.push(c.node.getValues(tagged));
}
}
res.push(this.fromNode.getToken());
//console.log(' \t\t getValues::Verb called for id ' + this.toNode.getTokenId() + ' reeturning :' + res.join(' '));
res = res.join(' ');
if (tagged) {
res = 'obj::<' + res + '>';
res = this.getName() + '::' + this.toNode.getValues(tagged) + ' ' + res;
} else {
res = this.toNode.getValues(tagged) + ' ' + res;
}
return res;
} else {
return super.getValues(tagged);
}
}
processNode() {
let node = this.toNode;
let nodeList = this.nodes;
let copNode = 'cop';
if (this.linkType === copNode) {
node = this.fromNode;
}
// check all the child nodes
let children = node.getChildren();
//let dbg = nodeList.dbg;
for (let child in children) {
let ch = children[child];
}
let ret = {};
// process the verb node
if (this.linkType === copNode) {
// ret.verb = {tokenId:this.toNode.getTokenId(), obj : {tokenId: this.fromNode.getTokenId()}};
//ret.verb = {tokenId: this.fromNode.getTokenId(), cop : {tokenId:this.toNode.getTokenId()}};
ret['verb:' + this.linkType] = {tokenId: this.fromNode.getTokenId(), cop : {tokenId:this.toNode.getTokenId()}};
} else {
//ret.verb = {tokenId:this.toNode.getTokenId()};
ret['verb:' + this.linkType] = {tokenId:this.toNode.getTokenId()};
}
ret = super.processNode(ret);
if (false) console.log(' ---[' + this.linkType + ']-->> ' + JSON.stringify(ret));
return ret;
}
static checkValid(nodeList, fromNode, linkType, toNode) {
let dbg = nodeList.dbg;
return [true, {}];
}
}
|
[
"class",
"VerbBase",
"extends",
"GrBase",
"{",
"constructor",
"(",
"nodes",
",",
"fromNode",
",",
"linkType",
",",
"toNode",
",",
"matchResult",
")",
"{",
"super",
"(",
"nodes",
",",
"fromNode",
",",
"linkType",
",",
"toNode",
",",
"matchResult",
")",
";",
"this",
".",
"name",
"=",
"'VerbBase'",
";",
"}",
"static",
"getMatchToken",
"(",
")",
"{",
"return",
"[",
"{",
"name",
":",
"'verb-1'",
",",
"toPOS",
":",
"'VB.*'",
",",
"edge",
":",
"'((?!cop).)*'",
"}",
",",
"{",
"name",
":",
"'verb-2'",
",",
"toPOS",
":",
"'VB.*'",
",",
"edge",
":",
"'cop'",
",",
"applyToParent",
":",
"true",
"}",
"]",
";",
"}",
"dict",
"(",
")",
"{",
"let",
"r",
"=",
"this",
".",
"processNode",
"(",
")",
";",
"return",
"r",
";",
"return",
"this",
".",
"match",
".",
"vb",
";",
"}",
"text",
"(",
")",
"{",
"return",
"this",
".",
"name",
"+",
"':: '",
"+",
"JSON",
".",
"stringify",
"(",
"this",
".",
"match",
")",
";",
"}",
"getVerb",
"(",
")",
"{",
"return",
"this",
".",
"match",
".",
"verb",
";",
"}",
"getValues",
"(",
"tagged",
"=",
"false",
")",
"{",
"let",
"res",
"=",
"[",
"]",
";",
"if",
"(",
"this",
".",
"linkType",
"===",
"'cop'",
")",
"{",
"let",
"children",
"=",
"this",
".",
"fromNode",
".",
"getChildren",
"(",
")",
";",
"for",
"(",
"let",
"child",
"in",
"children",
")",
"{",
"let",
"c",
"=",
"this",
".",
"fromNode",
".",
"getChild",
"(",
"child",
")",
";",
"if",
"(",
"this",
".",
"toNode",
".",
"getTokenId",
"(",
")",
"!==",
"c",
".",
"node",
".",
"getTokenId",
"(",
")",
")",
"{",
"res",
".",
"push",
"(",
"c",
".",
"node",
".",
"getValues",
"(",
"tagged",
")",
")",
";",
"}",
"}",
"res",
".",
"push",
"(",
"this",
".",
"fromNode",
".",
"getToken",
"(",
")",
")",
";",
"res",
"=",
"res",
".",
"join",
"(",
"' '",
")",
";",
"if",
"(",
"tagged",
")",
"{",
"res",
"=",
"'obj::<'",
"+",
"res",
"+",
"'>'",
";",
"res",
"=",
"this",
".",
"getName",
"(",
")",
"+",
"'::'",
"+",
"this",
".",
"toNode",
".",
"getValues",
"(",
"tagged",
")",
"+",
"' '",
"+",
"res",
";",
"}",
"else",
"{",
"res",
"=",
"this",
".",
"toNode",
".",
"getValues",
"(",
"tagged",
")",
"+",
"' '",
"+",
"res",
";",
"}",
"return",
"res",
";",
"}",
"else",
"{",
"return",
"super",
".",
"getValues",
"(",
"tagged",
")",
";",
"}",
"}",
"processNode",
"(",
")",
"{",
"let",
"node",
"=",
"this",
".",
"toNode",
";",
"let",
"nodeList",
"=",
"this",
".",
"nodes",
";",
"let",
"copNode",
"=",
"'cop'",
";",
"if",
"(",
"this",
".",
"linkType",
"===",
"copNode",
")",
"{",
"node",
"=",
"this",
".",
"fromNode",
";",
"}",
"let",
"children",
"=",
"node",
".",
"getChildren",
"(",
")",
";",
"for",
"(",
"let",
"child",
"in",
"children",
")",
"{",
"let",
"ch",
"=",
"children",
"[",
"child",
"]",
";",
"}",
"let",
"ret",
"=",
"{",
"}",
";",
"if",
"(",
"this",
".",
"linkType",
"===",
"copNode",
")",
"{",
"ret",
"[",
"'verb:'",
"+",
"this",
".",
"linkType",
"]",
"=",
"{",
"tokenId",
":",
"this",
".",
"fromNode",
".",
"getTokenId",
"(",
")",
",",
"cop",
":",
"{",
"tokenId",
":",
"this",
".",
"toNode",
".",
"getTokenId",
"(",
")",
"}",
"}",
";",
"}",
"else",
"{",
"ret",
"[",
"'verb:'",
"+",
"this",
".",
"linkType",
"]",
"=",
"{",
"tokenId",
":",
"this",
".",
"toNode",
".",
"getTokenId",
"(",
")",
"}",
";",
"}",
"ret",
"=",
"super",
".",
"processNode",
"(",
"ret",
")",
";",
"if",
"(",
"false",
")",
"console",
".",
"log",
"(",
"' ---['",
"+",
"this",
".",
"linkType",
"+",
"']-->> '",
"+",
"JSON",
".",
"stringify",
"(",
"ret",
")",
")",
";",
"return",
"ret",
";",
"}",
"static",
"checkValid",
"(",
"nodeList",
",",
"fromNode",
",",
"linkType",
",",
"toNode",
")",
"{",
"let",
"dbg",
"=",
"nodeList",
".",
"dbg",
";",
"return",
"[",
"true",
",",
"{",
"}",
"]",
";",
"}",
"}"
] |
NN----(subj)---->VB(is/defined)---xcomp/nmod--->NN
NN1---(subj)--->NN2 with NN2--cop->VBZ(is)
|
[
"NN",
"----",
"(",
"subj",
")",
"----",
">",
"VB",
"(",
"is",
"/",
"defined",
")",
"---",
"xcomp",
"/",
"nmod",
"---",
">",
"NN",
"NN1",
"---",
"(",
"subj",
")",
"---",
">",
"NN2",
"with",
"NN2",
"--",
"cop",
"-",
">",
"VBZ",
"(",
"is",
")"
] |
[
"//return ['define:VB.*', 'is:VB.*', 'defined:VB.*'];",
"//return ['.*:VB.*'];",
"//return [{name:'verb-1', toPOS:'VB.*', edge:'((?!cop).)*'} ];",
"//return [{name:'verb-1', toPOS:'VB.*'];",
"/*\n getValues() {;\n return this.match.verb;//this.nodes.getTokens().getToken(this.verb);\n }*/",
"//this.nodes.getNodeMap(this.verb).getValues();",
"//console.log(' \\t\\t getValues::Verb called for id ' + this.toNode.getTokenId() + ' reeturning :' + res.join(' '));",
"// check all the child nodes",
"//let dbg = nodeList.dbg;",
"// process the verb node",
"// ret.verb = {tokenId:this.toNode.getTokenId(), obj : {tokenId: this.fromNode.getTokenId()}};",
"//ret.verb = {tokenId: this.fromNode.getTokenId(), cop : {tokenId:this.toNode.getTokenId()}};",
"//ret.verb = {tokenId:this.toNode.getTokenId()};"
] |
[
{
"param": "GrBase",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "GrBase",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 17
| 799
| 383
|
4b8c2d2b19fefd43921a76d36b0599dc77d3d42b
|
experimental-dustbin/algorithmic_puzzles
|
corner_to_corner_journey/corner_to_corner.rb
|
[
"MIT"
] |
Ruby
|
KnightMoves
|
##
# We represent the state of the game by an array of moves which are just +(x, y)+
# pairs. +(0, 0)+ represents the lower left corner and +(7, 7)+. The way we expand the state
# is pretty simple. We just take the last position and perform the arithmetic operations on
# the pair that correspond to the knight's movement pattern. We throw out everything that is
# out of bounds and any already visited positions. If we end up in the top right corner then
# we keep that position only if we have already visited all other positions otherwise we
# consider than an illegal state and throw it out.
|
We represent the state of the game by an array of moves which are just +(x, y)+
pairs. +(0, 0)+ represents the lower left corner and +(7, 7)+. The way we expand the state
is pretty simple. We just take the last position and perform the arithmetic operations on
the pair that correspond to the knight's movement pattern. We throw out everything that is
out of bounds and any already visited positions. If we end up in the top right corner then
we keep that position only if we have already visited all other positions otherwise we
consider than an illegal state and throw it out.
|
[
"We",
"represent",
"the",
"state",
"of",
"the",
"game",
"by",
"an",
"array",
"of",
"moves",
"which",
"are",
"just",
"+",
"(",
"x",
"y",
")",
"+",
"pairs",
".",
"+",
"(",
"0",
"0",
")",
"+",
"represents",
"the",
"lower",
"left",
"corner",
"and",
"+",
"(",
"7",
"7",
")",
"+",
".",
"The",
"way",
"we",
"expand",
"the",
"state",
"is",
"pretty",
"simple",
".",
"We",
"just",
"take",
"the",
"last",
"position",
"and",
"perform",
"the",
"arithmetic",
"operations",
"on",
"the",
"pair",
"that",
"correspond",
"to",
"the",
"knight",
"'",
"s",
"movement",
"pattern",
".",
"We",
"throw",
"out",
"everything",
"that",
"is",
"out",
"of",
"bounds",
"and",
"any",
"already",
"visited",
"positions",
".",
"If",
"we",
"end",
"up",
"in",
"the",
"top",
"right",
"corner",
"then",
"we",
"keep",
"that",
"position",
"only",
"if",
"we",
"have",
"already",
"visited",
"all",
"other",
"positions",
"otherwise",
"we",
"consider",
"than",
"an",
"illegal",
"state",
"and",
"throw",
"it",
"out",
"."
] |
class KnightMoves < Struct.new(:visited_positions, :current_position)
@@move_offsets = [
[2, 1], [2, -1], [-2, 1], [-2, -1], # up/(right|left), down/(right|left)
[1, 2], [-1, 2], [1, -2], [-1, -2], # right/(up|down), left/(up|down)
]
def initialize(visited_positions, current_position)
super(visited_positions, current_position)
@history_hash = visited_positions.reduce({}) {|m, pos| m[pos] = true; m}
end
##
# Are we at +(7, 7)+?
def at_top_right?
row, column = current_position
row == column && row == 7
end
##
# Have we made +64+ moves counting where we started?
def visited_all?
visited_positions.size == 64
end
##
# Find all potential future positions, filter out places we have already been,
# generate new states and filter out all the states that end up in the top right
# corner without having visited all other positions.
def expand
row, column = current_position
potential_positions = @@move_offsets.map do |r_offset, c_offset|
[row + r_offset, column + c_offset]
end
potential_positions.reject! do |row, column|
@history_hash[pos] || row < 0 || row > 7 || column < 0 || column > 7
end
new_states = potential_positions.map {|p| KnightMoves.new(visited_positions + [p], p)}
new_states.reject {|s| s.at_top_right? && !s.visited_all?}
end
end
|
[
"class",
"KnightMoves",
"<",
"Struct",
".",
"new",
"(",
":visited_positions",
",",
":current_position",
")",
"@@move_offsets",
"=",
"[",
"[",
"2",
",",
"1",
"]",
",",
"[",
"2",
",",
"-",
"1",
"]",
",",
"[",
"-",
"2",
",",
"1",
"]",
",",
"[",
"-",
"2",
",",
"-",
"1",
"]",
",",
"[",
"1",
",",
"2",
"]",
",",
"[",
"-",
"1",
",",
"2",
"]",
",",
"[",
"1",
",",
"-",
"2",
"]",
",",
"[",
"-",
"1",
",",
"-",
"2",
"]",
",",
"]",
"def",
"initialize",
"(",
"visited_positions",
",",
"current_position",
")",
"super",
"(",
"visited_positions",
",",
"current_position",
")",
"@history_hash",
"=",
"visited_positions",
".",
"reduce",
"(",
"{",
"}",
")",
"{",
"|",
"m",
",",
"pos",
"|",
"m",
"[",
"pos",
"]",
"=",
"true",
";",
"m",
"}",
"end",
"def",
"at_top_right?",
"row",
",",
"column",
"=",
"current_position",
"row",
"==",
"column",
"&&",
"row",
"==",
"7",
"end",
"def",
"visited_all?",
"visited_positions",
".",
"size",
"==",
"64",
"end",
"def",
"expand",
"row",
",",
"column",
"=",
"current_position",
"potential_positions",
"=",
"@@move_offsets",
".",
"map",
"do",
"|",
"r_offset",
",",
"c_offset",
"|",
"[",
"row",
"+",
"r_offset",
",",
"column",
"+",
"c_offset",
"]",
"end",
"potential_positions",
".",
"reject!",
"do",
"|",
"row",
",",
"column",
"|",
"@history_hash",
"[",
"pos",
"]",
"||",
"row",
"<",
"0",
"||",
"row",
">",
"7",
"||",
"column",
"<",
"0",
"||",
"column",
">",
"7",
"end",
"new_states",
"=",
"potential_positions",
".",
"map",
"{",
"|",
"p",
"|",
"KnightMoves",
".",
"new",
"(",
"visited_positions",
"+",
"[",
"p",
"]",
",",
"p",
")",
"}",
"new_states",
".",
"reject",
"{",
"|",
"s",
"|",
"s",
".",
"at_top_right?",
"&&",
"!",
"s",
".",
"visited_all?",
"}",
"end",
"end"
] |
We represent the state of the game by an array of moves which are just +(x, y)+
pairs.
|
[
"We",
"represent",
"the",
"state",
"of",
"the",
"game",
"by",
"an",
"array",
"of",
"moves",
"which",
"are",
"just",
"+",
"(",
"x",
"y",
")",
"+",
"pairs",
"."
] |
[
"# up/(right|left), down/(right|left)",
"# right/(up|down), left/(up|down)",
"##",
"# Are we at +(7, 7)+?",
"##",
"# Have we made +64+ moves counting where we started?",
"##",
"# Find all potential future positions, filter out places we have already been,",
"# generate new states and filter out all the states that end up in the top right",
"# corner without having visited all other positions."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 395
| 137
|
4912b67a4e0789c0d1207214c8e32f2dd9cb9a5a
|
iShiBin/LeetCode
|
src/main/java/com/fishercoder/solutions/_362.java
|
[
"Apache-2.0"
] |
Java
|
_362
|
/**Design a hit counter which counts the number of hits received in the past 5 minutes.
Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the timestamp is monotonically increasing). You may assume that the earliest timestamp starts at 1.
It is possible that several hits arrive roughly at the same time.
Example:
HitCounter counter = new HitCounter();
// hit at timestamp 1.
counter.hit(1);
// hit at timestamp 2.
counter.hit(2);
// hit at timestamp 3.
counter.hit(3);
// get hits at timestamp 4, should return 3.
counter.getHits(4);
// hit at timestamp 300.
counter.hit(300);
// get hits at timestamp 300, should return 4.
counter.getHits(300);
// get hits at timestamp 301, should return 3.
counter.getHits(301);
Follow up:
What if the number of hits per second could be very large? Does your design scale?*/
|
Design a hit counter which counts the number of hits received in the past 5 minutes.
Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order . You may assume that the earliest timestamp starts at 1.
It is possible that several hits arrive roughly at the same time.
hit at timestamp 1.
hit at timestamp 2.
hit at timestamp 3.
get hits at timestamp 4, should return 3.
hit at timestamp 300.
get hits at timestamp 300, should return 4.
get hits at timestamp 301, should return 3.
counter.getHits(301);
Follow up:
What if the number of hits per second could be very large.
|
[
"Design",
"a",
"hit",
"counter",
"which",
"counts",
"the",
"number",
"of",
"hits",
"received",
"in",
"the",
"past",
"5",
"minutes",
".",
"Each",
"function",
"accepts",
"a",
"timestamp",
"parameter",
"(",
"in",
"seconds",
"granularity",
")",
"and",
"you",
"may",
"assume",
"that",
"calls",
"are",
"being",
"made",
"to",
"the",
"system",
"in",
"chronological",
"order",
".",
"You",
"may",
"assume",
"that",
"the",
"earliest",
"timestamp",
"starts",
"at",
"1",
".",
"It",
"is",
"possible",
"that",
"several",
"hits",
"arrive",
"roughly",
"at",
"the",
"same",
"time",
".",
"hit",
"at",
"timestamp",
"1",
".",
"hit",
"at",
"timestamp",
"2",
".",
"hit",
"at",
"timestamp",
"3",
".",
"get",
"hits",
"at",
"timestamp",
"4",
"should",
"return",
"3",
".",
"hit",
"at",
"timestamp",
"300",
".",
"get",
"hits",
"at",
"timestamp",
"300",
"should",
"return",
"4",
".",
"get",
"hits",
"at",
"timestamp",
"301",
"should",
"return",
"3",
".",
"counter",
".",
"getHits",
"(",
"301",
")",
";",
"Follow",
"up",
":",
"What",
"if",
"the",
"number",
"of",
"hits",
"per",
"second",
"could",
"be",
"very",
"large",
"."
] |
public class _362 {
class HitCounter {
/**
* Looked at this post: https://discuss.leetcode.com/topic/48758/super-easy-design-o-1-hit-o-s-gethits-no-fancy-data-structure-is-needed,
* I added one more field k to make it more generic.
*/
private int[] times;
private int[] hits;
private int k;
/**
* Initialize your data structure here.
*/
public HitCounter() {
k = 300;
times = new int[k];
hits = new int[k];
}
/**
* Record a hit.
*
* @param timestamp - The current timestamp (in seconds granularity).
*/
public void hit(int timestamp) {
int index = timestamp % k;
if (times[index] != timestamp) {
times[index] = timestamp;
hits[index] = 1;
} else {
hits[index]++;
}
}
/**
* Return the number of hits in the past 5 minutes.
*
* @param timestamp - The current timestamp (in seconds granularity).
*/
public int getHits(int timestamp) {
int total = 0;
for (int i = 0; i < k; i++) {
if (timestamp - times[i] < k) {
total += hits[i];
}
}
return total;
}
}
}
|
[
"public",
"class",
"_362",
"{",
"class",
"HitCounter",
"{",
"/**\n * Looked at this post: https://discuss.leetcode.com/topic/48758/super-easy-design-o-1-hit-o-s-gethits-no-fancy-data-structure-is-needed,\n * I added one more field k to make it more generic.\n */",
"private",
"int",
"[",
"]",
"times",
";",
"private",
"int",
"[",
"]",
"hits",
";",
"private",
"int",
"k",
";",
"/**\n * Initialize your data structure here.\n */",
"public",
"HitCounter",
"(",
")",
"{",
"k",
"=",
"300",
";",
"times",
"=",
"new",
"int",
"[",
"k",
"]",
";",
"hits",
"=",
"new",
"int",
"[",
"k",
"]",
";",
"}",
"/**\n * Record a hit.\n *\n * @param timestamp - The current timestamp (in seconds granularity).\n */",
"public",
"void",
"hit",
"(",
"int",
"timestamp",
")",
"{",
"int",
"index",
"=",
"timestamp",
"%",
"k",
";",
"if",
"(",
"times",
"[",
"index",
"]",
"!=",
"timestamp",
")",
"{",
"times",
"[",
"index",
"]",
"=",
"timestamp",
";",
"hits",
"[",
"index",
"]",
"=",
"1",
";",
"}",
"else",
"{",
"hits",
"[",
"index",
"]",
"++",
";",
"}",
"}",
"/**\n * Return the number of hits in the past 5 minutes.\n *\n * @param timestamp - The current timestamp (in seconds granularity).\n */",
"public",
"int",
"getHits",
"(",
"int",
"timestamp",
")",
"{",
"int",
"total",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"k",
";",
"i",
"++",
")",
"{",
"if",
"(",
"timestamp",
"-",
"times",
"[",
"i",
"]",
"<",
"k",
")",
"{",
"total",
"+=",
"hits",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"total",
";",
"}",
"}",
"}"
] |
Design a hit counter which counts the number of hits received in the past 5 minutes.
|
[
"Design",
"a",
"hit",
"counter",
"which",
"counts",
"the",
"number",
"of",
"hits",
"received",
"in",
"the",
"past",
"5",
"minutes",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 309
| 230
|
01f800b6a46e0eeb812dc0c0c5705bc96bbaa504
|
jkuester/ccl-testing
|
cdoc/cdoc-parser/src/main/java/com/cerner/ccl/parser/data/record/FixedLengthRecordStructureList.java
|
[
"Apache-2.0"
] |
Java
|
FixedLengthRecordStructureList
|
/**
* This extension of {@link AbstractParentRecordStructureMember} represents a fixed length list, such as the following
* featured in this example record structure:
*
* <pre>
* record request (
* 1 fixed_length_list[1]
* 2 status = c1
* )
* </pre>
*
* @author Joshua Hyde
*
*/
|
This extension of AbstractParentRecordStructureMember represents a fixed length list, such as the following
featured in this example record structure.
record request (
1 fixed_length_list[1]
2 status = c1
)
@author Joshua Hyde
|
[
"This",
"extension",
"of",
"AbstractParentRecordStructureMember",
"represents",
"a",
"fixed",
"length",
"list",
"such",
"as",
"the",
"following",
"featured",
"in",
"this",
"example",
"record",
"structure",
".",
"record",
"request",
"(",
"1",
"fixed_length_list",
"[",
"1",
"]",
"2",
"status",
"=",
"c1",
")",
"@author",
"Joshua",
"Hyde"
] |
public class FixedLengthRecordStructureList extends RecordStructureList {
private final int listSize;
/**
* Create a list without documentation.
*
* @param name
* The name of the list.
* @param level
* The {@link #getLevel() level} of this member.
* @param children
* A {@link List} of {@link RecordStructureMember} objects representing the members of this list.
* @param listSize
* The size of the list.
* @throws IllegalArgumentException
* If the given list size is negative.
*/
public FixedLengthRecordStructureList(final String name, final int level,
final List<RecordStructureMember> children, final int listSize) {
this(name, level, null, children, listSize);
}
/**
* Create a list with documentation.
*
* @param name
* The name of the list.
* @param level
* The {@link #getLevel() level} of this member.
* @param description
* A description of the list.
* @param children
* A {@link List} of {@link RecordStructureMember} objects representing the members of this list.
* @param listSize
* The size of the list.
* @throws IllegalArgumentException
* If the given list size is negative.
*/
public FixedLengthRecordStructureList(final String name, final int level, final String description,
final List<RecordStructureMember> children, final int listSize) {
super(name, level, description, children);
if (listSize < 0) {
throw new IllegalArgumentException("List size cannot be negative: " + Integer.toString(listSize));
}
this.listSize = listSize;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof FixedLengthRecordStructureList)) {
return false;
}
final FixedLengthRecordStructureList other = (FixedLengthRecordStructureList) obj;
return new EqualsBuilder().append(listSize, other.listSize).isEquals();
}
/**
* Get the size of the list.
*
* @return The size of the list.
*/
public int getListSize() {
return listSize;
}
@Override
public int hashCode() {
return 31 * super.hashCode() + listSize;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
[
"public",
"class",
"FixedLengthRecordStructureList",
"extends",
"RecordStructureList",
"{",
"private",
"final",
"int",
"listSize",
";",
"/**\n * Create a list without documentation.\n *\n * @param name\n * The name of the list.\n * @param level\n * The {@link #getLevel() level} of this member.\n * @param children\n * A {@link List} of {@link RecordStructureMember} objects representing the members of this list.\n * @param listSize\n * The size of the list.\n * @throws IllegalArgumentException\n * If the given list size is negative.\n */",
"public",
"FixedLengthRecordStructureList",
"(",
"final",
"String",
"name",
",",
"final",
"int",
"level",
",",
"final",
"List",
"<",
"RecordStructureMember",
">",
"children",
",",
"final",
"int",
"listSize",
")",
"{",
"this",
"(",
"name",
",",
"level",
",",
"null",
",",
"children",
",",
"listSize",
")",
";",
"}",
"/**\n * Create a list with documentation.\n *\n * @param name\n * The name of the list.\n * @param level\n * The {@link #getLevel() level} of this member.\n * @param description\n * A description of the list.\n * @param children\n * A {@link List} of {@link RecordStructureMember} objects representing the members of this list.\n * @param listSize\n * The size of the list.\n * @throws IllegalArgumentException\n * If the given list size is negative.\n */",
"public",
"FixedLengthRecordStructureList",
"(",
"final",
"String",
"name",
",",
"final",
"int",
"level",
",",
"final",
"String",
"description",
",",
"final",
"List",
"<",
"RecordStructureMember",
">",
"children",
",",
"final",
"int",
"listSize",
")",
"{",
"super",
"(",
"name",
",",
"level",
",",
"description",
",",
"children",
")",
";",
"if",
"(",
"listSize",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"List size cannot be negative: ",
"\"",
"+",
"Integer",
".",
"toString",
"(",
"listSize",
")",
")",
";",
"}",
"this",
".",
"listSize",
"=",
"listSize",
";",
"}",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"final",
"Object",
"obj",
")",
"{",
"if",
"(",
"this",
"==",
"obj",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"super",
".",
"equals",
"(",
"obj",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"(",
"obj",
"instanceof",
"FixedLengthRecordStructureList",
")",
")",
"{",
"return",
"false",
";",
"}",
"final",
"FixedLengthRecordStructureList",
"other",
"=",
"(",
"FixedLengthRecordStructureList",
")",
"obj",
";",
"return",
"new",
"EqualsBuilder",
"(",
")",
".",
"append",
"(",
"listSize",
",",
"other",
".",
"listSize",
")",
".",
"isEquals",
"(",
")",
";",
"}",
"/**\n * Get the size of the list.\n *\n * @return The size of the list.\n */",
"public",
"int",
"getListSize",
"(",
")",
"{",
"return",
"listSize",
";",
"}",
"@",
"Override",
"public",
"int",
"hashCode",
"(",
")",
"{",
"return",
"31",
"*",
"super",
".",
"hashCode",
"(",
")",
"+",
"listSize",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"ToStringBuilder",
".",
"reflectionToString",
"(",
"this",
")",
";",
"}",
"}"
] |
This extension of {@link AbstractParentRecordStructureMember} represents a fixed length list, such as the following
featured in this example record structure:
|
[
"This",
"extension",
"of",
"{",
"@link",
"AbstractParentRecordStructureMember",
"}",
"represents",
"a",
"fixed",
"length",
"list",
"such",
"as",
"the",
"following",
"featured",
"in",
"this",
"example",
"record",
"structure",
":"
] |
[] |
[
{
"param": "RecordStructureList",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "RecordStructureList",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 573
| 77
|
0aa523461e392425be6c321d20f60c44a9dbfc05
|
abhishekks831998/umple
|
Umplificator/UmplifiedProjects/weka-umplified-0/src/main/java/weka/classifiers/bayes/NaiveBayesMultinomial.java
|
[
"MIT"
] |
Java
|
NaiveBayesMultinomial
|
/**
<!-- globalinfo-start -->
* Class for building and using a multinomial Naive Bayes classifier. For more information see,<br/>
* <br/>
* Andrew Mccallum, Kamal Nigam: A Comparison of Event Models for Naive Bayes Text Classification. In: AAAI-98 Workshop on 'Learning for Text Categorization', 1998.<br/>
* <br/>
* The core equation for this classifier:<br/>
* <br/>
* P[Ci|D] = (P[D|Ci] x P[Ci]) / P[D] (Bayes rule)<br/>
* <br/>
* where Ci is class i and D is a document.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @inproceedings{Mccallum1998,
* author = {Andrew Mccallum and Kamal Nigam},
* booktitle = {AAAI-98 Workshop on 'Learning for Text Categorization'},
* title = {A Comparison of Event Models for Naive Bayes Text Classification},
* year = {1998}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</pre>
*
<!-- options-end -->
*
* @author Andrew Golightly ([email protected])
* @author Bernhard Pfahringer ([email protected])
* @version $Revision: 10141 $
*/
|
Class for building and using a multinomial Naive Bayes classifier. For more information see,
Andrew Mccallum, Kamal Nigam: A Comparison of Event Models for Naive Bayes Text Classification. In: AAAI-98 Workshop on 'Learning for Text Categorization', 1998.
The core equation for this classifier:
P[Ci|D] = (P[D|Ci] x P[Ci]) / P[D] (Bayes rule)
where Ci is class i and D is a document.
BibTeX:
@inproceedings{Mccallum1998,
author = {Andrew Mccallum and Kamal Nigam},
booktitle = {AAAI-98 Workshop on 'Learning for Text Categorization'},
title = {A Comparison of Event Models for Naive Bayes Text Classification},
year = {1998}
}
Valid options are:
-D
If set, classifier is run in debug mode and
may output additional info to the console
|
[
"Class",
"for",
"building",
"and",
"using",
"a",
"multinomial",
"Naive",
"Bayes",
"classifier",
".",
"For",
"more",
"information",
"see",
"Andrew",
"Mccallum",
"Kamal",
"Nigam",
":",
"A",
"Comparison",
"of",
"Event",
"Models",
"for",
"Naive",
"Bayes",
"Text",
"Classification",
".",
"In",
":",
"AAAI",
"-",
"98",
"Workshop",
"on",
"'",
"Learning",
"for",
"Text",
"Categorization",
"'",
"1998",
".",
"The",
"core",
"equation",
"for",
"this",
"classifier",
":",
"P",
"[",
"Ci|D",
"]",
"=",
"(",
"P",
"[",
"D|Ci",
"]",
"x",
"P",
"[",
"Ci",
"]",
")",
"/",
"P",
"[",
"D",
"]",
"(",
"Bayes",
"rule",
")",
"where",
"Ci",
"is",
"class",
"i",
"and",
"D",
"is",
"a",
"document",
".",
"BibTeX",
":",
"@inproceedings",
"{",
"Mccallum1998",
"author",
"=",
"{",
"Andrew",
"Mccallum",
"and",
"Kamal",
"Nigam",
"}",
"booktitle",
"=",
"{",
"AAAI",
"-",
"98",
"Workshop",
"on",
"'",
"Learning",
"for",
"Text",
"Categorization",
"'",
"}",
"title",
"=",
"{",
"A",
"Comparison",
"of",
"Event",
"Models",
"for",
"Naive",
"Bayes",
"Text",
"Classification",
"}",
"year",
"=",
"{",
"1998",
"}",
"}",
"Valid",
"options",
"are",
":",
"-",
"D",
"If",
"set",
"classifier",
"is",
"run",
"in",
"debug",
"mode",
"and",
"may",
"output",
"additional",
"info",
"to",
"the",
"console"
] |
public class NaiveBayesMultinomial
extends AbstractClassifier
implements WeightedInstancesHandler,TechnicalInformationHandler {
/** for serialization */
static final long serialVersionUID = 5932177440181257085L;
/**
* probability that a word (w) exists in a class (H) (i.e. Pr[w|H])
* The matrix is in the this format: probOfWordGivenClass[class][wordAttribute]
* NOTE: the values are actually the log of Pr[w|H]
*/
protected double[][] m_probOfWordGivenClass;
/** the probability of a class (i.e. Pr[H]) */
protected double[] m_probOfClass;
/** number of unique words */
protected int m_numAttributes;
/** number of class values */
protected int m_numClasses;
/** cache lnFactorial computations */
protected double[] m_lnFactorialCache = new double[]{0.0,0.0};
/** copy of header information for use in toString method */
protected Instances m_headerInfo;
/**
* Returns a string describing this classifier
* @return a description of the classifier suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return
"Class for building and using a multinomial Naive Bayes classifier. "
+ "For more information see,\n\n"
+ getTechnicalInformation().toString() + "\n\n"
+ "The core equation for this classifier:\n\n"
+ "P[Ci|D] = (P[D|Ci] x P[Ci]) / P[D] (Bayes rule)\n\n"
+ "where Ci is class i and D is a document.";
}
/**
* Returns an instance of a TechnicalInformation object, containing
* detailed information about the technical background of this class,
* e.g., paper reference or book this class is based on.
*
* @return the technical information about this class
*/
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(Type.INPROCEEDINGS);
result.setValue(Field.AUTHOR, "Andrew Mccallum and Kamal Nigam");
result.setValue(Field.YEAR, "1998");
result.setValue(Field.TITLE, "A Comparison of Event Models for Naive Bayes Text Classification");
result.setValue(Field.BOOKTITLE, "AAAI-98 Workshop on 'Learning for Text Categorization'");
return result;
}
/**
* Returns default capabilities of the classifier.
*
* @return the capabilities of this classifier
*/
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enable(Capability.NUMERIC_ATTRIBUTES);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
return result;
}
/**
* Generates the classifier.
*
* @param instances set of instances serving as training data
* @throws Exception if the classifier has not been generated successfully
*/
public void buildClassifier(Instances instances) throws Exception
{
// can classifier handle the data?
getCapabilities().testWithFail(instances);
// remove instances with missing class
instances = new Instances(instances);
instances.deleteWithMissingClass();
m_headerInfo = new Instances(instances, 0);
m_numClasses = instances.numClasses();
m_numAttributes = instances.numAttributes();
m_probOfWordGivenClass = new double[m_numClasses][];
/*
initialising the matrix of word counts
NOTE: Laplace estimator introduced in case a word that does not appear for a class in the
training set does so for the test set
*/
for(int c = 0; c<m_numClasses; c++)
{
m_probOfWordGivenClass[c] = new double[m_numAttributes];
for(int att = 0; att<m_numAttributes; att++)
{
m_probOfWordGivenClass[c][att] = 1;
}
}
//enumerate through the instances
Instance instance;
int classIndex;
double numOccurences;
double[] docsPerClass = new double[m_numClasses];
double[] wordsPerClass = new double[m_numClasses];
java.util.Enumeration<Instance> enumInsts = instances.enumerateInstances();
while (enumInsts.hasMoreElements())
{
instance = (Instance) enumInsts.nextElement();
classIndex = (int)instance.value(instance.classIndex());
docsPerClass[classIndex] += instance.weight();
for(int a = 0; a<instance.numValues(); a++)
if(instance.index(a) != instance.classIndex())
{
if(!instance.isMissing(a))
{
numOccurences = instance.valueSparse(a) * instance.weight();
if(numOccurences < 0)
throw new Exception("Numeric attribute values must all be greater or equal to zero.");
wordsPerClass[classIndex] += numOccurences;
m_probOfWordGivenClass[classIndex][instance.index(a)] += numOccurences;
}
}
}
/*
normalising probOfWordGivenClass values
and saving each value as the log of each value
*/
for(int c = 0; c<m_numClasses; c++)
for(int v = 0; v<m_numAttributes; v++)
m_probOfWordGivenClass[c][v] = Math.log(m_probOfWordGivenClass[c][v] / (wordsPerClass[c] + m_numAttributes - 1));
/*
calculating Pr(H)
NOTE: Laplace estimator introduced in case a class does not get mentioned in the set of
training instances
*/
final double numDocs = instances.sumOfWeights() + m_numClasses;
m_probOfClass = new double[m_numClasses];
for(int h=0; h<m_numClasses; h++)
m_probOfClass[h] = (double)(docsPerClass[h] + 1)/numDocs;
}
/**
* Calculates the class membership probabilities for the given test
* instance.
*
* @param instance the instance to be classified
* @return predicted class probability distribution
* @throws Exception if there is a problem generating the prediction
*/
public double [] distributionForInstance(Instance instance) throws Exception
{
double[] probOfClassGivenDoc = new double[m_numClasses];
//calculate the array of log(Pr[D|C])
double[] logDocGivenClass = new double[m_numClasses];
for(int h = 0; h<m_numClasses; h++)
logDocGivenClass[h] = probOfDocGivenClass(instance, h);
double max = logDocGivenClass[Utils.maxIndex(logDocGivenClass)];
double probOfDoc = 0.0;
for(int i = 0; i<m_numClasses; i++)
{
probOfClassGivenDoc[i] = Math.exp(logDocGivenClass[i] - max) * m_probOfClass[i];
probOfDoc += probOfClassGivenDoc[i];
}
Utils.normalize(probOfClassGivenDoc,probOfDoc);
return probOfClassGivenDoc;
}
/**
* log(N!) + (for all the words)(log(Pi^ni) - log(ni!))
*
* where
* N is the total number of words
* Pi is the probability of obtaining word i
* ni is the number of times the word at index i occurs in the document
*
* @param inst The instance to be classified
* @param classIndex The index of the class we are calculating the probability with respect to
*
* @return The log of the probability of the document occuring given the class
*/
private double probOfDocGivenClass(Instance inst, int classIndex)
{
double answer = 0;
//double totalWords = 0; //no need as we are not calculating the factorial at all.
double freqOfWordInDoc; //should be double
for(int i = 0; i<inst.numValues(); i++)
if(inst.index(i) != inst.classIndex())
{
freqOfWordInDoc = inst.valueSparse(i);
//totalWords += freqOfWordInDoc;
answer += (freqOfWordInDoc * m_probOfWordGivenClass[classIndex][inst.index(i)]
); //- lnFactorial(freqOfWordInDoc));
}
//answer += lnFactorial(totalWords);//The factorial terms don't make
//any difference to the classifier's
//accuracy, so not needed.
return answer;
}
/**
* Fast computation of ln(n!) for non-negative ints
*
* negative ints are passed on to the general gamma-function
* based version in weka.core.SpecialFunctions
*
* if the current n value is higher than any previous one,
* the cache is extended and filled to cover it
*
* the common case is reduced to a simple array lookup
*
* @param n the integer
* @return ln(n!)
*/
public double lnFactorial(int n)
{
if (n < 0) return weka.core.SpecialFunctions.lnFactorial(n);
if (m_lnFactorialCache.length <= n) {
double[] tmp = new double[n+1];
System.arraycopy(m_lnFactorialCache,0,tmp,0,m_lnFactorialCache.length);
for(int i = m_lnFactorialCache.length; i < tmp.length; i++)
tmp[i] = tmp[i-1] + Math.log(i);
m_lnFactorialCache = tmp;
}
return m_lnFactorialCache[n];
}
/**
* Returns a string representation of the classifier.
*
* @return a string representation of the classifier
*/
public String toString()
{
StringBuffer result = new StringBuffer("The independent probability of a class\n--------------------------------------\n");
for(int c = 0; c<m_numClasses; c++)
result.append(m_headerInfo.classAttribute().value(c)).append("\t").append(Double.toString(m_probOfClass[c])).append("\n");
result.append("\nThe probability of a word given the class\n-----------------------------------------\n\t");
for(int c = 0; c<m_numClasses; c++)
result.append(m_headerInfo.classAttribute().value(c)).append("\t");
result.append("\n");
for(int w = 0; w<m_numAttributes; w++)
{
if (w != m_headerInfo.classIndex()) {
result.append(m_headerInfo.attribute(w).name()).append("\t");
for(int c = 0; c<m_numClasses; c++)
result.append(Double.toString(Math.exp(m_probOfWordGivenClass[c][w]))).append("\t");
result.append("\n");
}
}
return result.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision: 10141 $");
}
/**
* Main method for testing this class.
*
* @param argv the options
*/
public static void main(String [] argv) {
runClassifier(new NaiveBayesMultinomial(), argv);
}
}
|
[
"public",
"class",
"NaiveBayesMultinomial",
"extends",
"AbstractClassifier",
"implements",
"WeightedInstancesHandler",
",",
"TechnicalInformationHandler",
"{",
"/** for serialization */",
"static",
"final",
"long",
"serialVersionUID",
"=",
"5932177440181257085L",
";",
"/**\n * probability that a word (w) exists in a class (H) (i.e. Pr[w|H])\n * The matrix is in the this format: probOfWordGivenClass[class][wordAttribute]\n * NOTE: the values are actually the log of Pr[w|H]\n */",
"protected",
"double",
"[",
"]",
"[",
"]",
"m_probOfWordGivenClass",
";",
"/** the probability of a class (i.e. Pr[H]) */",
"protected",
"double",
"[",
"]",
"m_probOfClass",
";",
"/** number of unique words */",
"protected",
"int",
"m_numAttributes",
";",
"/** number of class values */",
"protected",
"int",
"m_numClasses",
";",
"/** cache lnFactorial computations */",
"protected",
"double",
"[",
"]",
"m_lnFactorialCache",
"=",
"new",
"double",
"[",
"]",
"{",
"0.0",
",",
"0.0",
"}",
";",
"/** copy of header information for use in toString method */",
"protected",
"Instances",
"m_headerInfo",
";",
"/**\n * Returns a string describing this classifier\n * @return a description of the classifier suitable for\n * displaying in the explorer/experimenter gui\n */",
"public",
"String",
"globalInfo",
"(",
")",
"{",
"return",
"\"",
"Class for building and using a multinomial Naive Bayes classifier. ",
"\"",
"+",
"\"",
"For more information see,",
"\\n",
"\\n",
"\"",
"+",
"getTechnicalInformation",
"(",
")",
".",
"toString",
"(",
")",
"+",
"\"",
"\\n",
"\\n",
"\"",
"+",
"\"",
"The core equation for this classifier:",
"\\n",
"\\n",
"\"",
"+",
"\"",
"P[Ci|D] = (P[D|Ci] x P[Ci]) / P[D] (Bayes rule)",
"\\n",
"\\n",
"\"",
"+",
"\"",
"where Ci is class i and D is a document.",
"\"",
";",
"}",
"/**\n * Returns an instance of a TechnicalInformation object, containing \n * detailed information about the technical background of this class,\n * e.g., paper reference or book this class is based on.\n * \n * @return the technical information about this class\n */",
"public",
"TechnicalInformation",
"getTechnicalInformation",
"(",
")",
"{",
"TechnicalInformation",
"result",
";",
"result",
"=",
"new",
"TechnicalInformation",
"(",
"Type",
".",
"INPROCEEDINGS",
")",
";",
"result",
".",
"setValue",
"(",
"Field",
".",
"AUTHOR",
",",
"\"",
"Andrew Mccallum and Kamal Nigam",
"\"",
")",
";",
"result",
".",
"setValue",
"(",
"Field",
".",
"YEAR",
",",
"\"",
"1998",
"\"",
")",
";",
"result",
".",
"setValue",
"(",
"Field",
".",
"TITLE",
",",
"\"",
"A Comparison of Event Models for Naive Bayes Text Classification",
"\"",
")",
";",
"result",
".",
"setValue",
"(",
"Field",
".",
"BOOKTITLE",
",",
"\"",
"AAAI-98 Workshop on 'Learning for Text Categorization'",
"\"",
")",
";",
"return",
"result",
";",
"}",
"/**\n * Returns default capabilities of the classifier.\n *\n * @return the capabilities of this classifier\n */",
"public",
"Capabilities",
"getCapabilities",
"(",
")",
"{",
"Capabilities",
"result",
"=",
"super",
".",
"getCapabilities",
"(",
")",
";",
"result",
".",
"disableAll",
"(",
")",
";",
"result",
".",
"enable",
"(",
"Capability",
".",
"NUMERIC_ATTRIBUTES",
")",
";",
"result",
".",
"enable",
"(",
"Capability",
".",
"NOMINAL_CLASS",
")",
";",
"result",
".",
"enable",
"(",
"Capability",
".",
"MISSING_CLASS_VALUES",
")",
";",
"return",
"result",
";",
"}",
"/**\n * Generates the classifier.\n *\n * @param instances set of instances serving as training data \n * @throws Exception if the classifier has not been generated successfully\n */",
"public",
"void",
"buildClassifier",
"(",
"Instances",
"instances",
")",
"throws",
"Exception",
"{",
"getCapabilities",
"(",
")",
".",
"testWithFail",
"(",
"instances",
")",
";",
"instances",
"=",
"new",
"Instances",
"(",
"instances",
")",
";",
"instances",
".",
"deleteWithMissingClass",
"(",
")",
";",
"m_headerInfo",
"=",
"new",
"Instances",
"(",
"instances",
",",
"0",
")",
";",
"m_numClasses",
"=",
"instances",
".",
"numClasses",
"(",
")",
";",
"m_numAttributes",
"=",
"instances",
".",
"numAttributes",
"(",
")",
";",
"m_probOfWordGivenClass",
"=",
"new",
"double",
"[",
"m_numClasses",
"]",
"[",
"]",
";",
"/*\n initialising the matrix of word counts\n NOTE: Laplace estimator introduced in case a word that does not appear for a class in the \n training set does so for the test set\n */",
"for",
"(",
"int",
"c",
"=",
"0",
";",
"c",
"<",
"m_numClasses",
";",
"c",
"++",
")",
"{",
"m_probOfWordGivenClass",
"[",
"c",
"]",
"=",
"new",
"double",
"[",
"m_numAttributes",
"]",
";",
"for",
"(",
"int",
"att",
"=",
"0",
";",
"att",
"<",
"m_numAttributes",
";",
"att",
"++",
")",
"{",
"m_probOfWordGivenClass",
"[",
"c",
"]",
"[",
"att",
"]",
"=",
"1",
";",
"}",
"}",
"Instance",
"instance",
";",
"int",
"classIndex",
";",
"double",
"numOccurences",
";",
"double",
"[",
"]",
"docsPerClass",
"=",
"new",
"double",
"[",
"m_numClasses",
"]",
";",
"double",
"[",
"]",
"wordsPerClass",
"=",
"new",
"double",
"[",
"m_numClasses",
"]",
";",
"java",
".",
"util",
".",
"Enumeration",
"<",
"Instance",
">",
"enumInsts",
"=",
"instances",
".",
"enumerateInstances",
"(",
")",
";",
"while",
"(",
"enumInsts",
".",
"hasMoreElements",
"(",
")",
")",
"{",
"instance",
"=",
"(",
"Instance",
")",
"enumInsts",
".",
"nextElement",
"(",
")",
";",
"classIndex",
"=",
"(",
"int",
")",
"instance",
".",
"value",
"(",
"instance",
".",
"classIndex",
"(",
")",
")",
";",
"docsPerClass",
"[",
"classIndex",
"]",
"+=",
"instance",
".",
"weight",
"(",
")",
";",
"for",
"(",
"int",
"a",
"=",
"0",
";",
"a",
"<",
"instance",
".",
"numValues",
"(",
")",
";",
"a",
"++",
")",
"if",
"(",
"instance",
".",
"index",
"(",
"a",
")",
"!=",
"instance",
".",
"classIndex",
"(",
")",
")",
"{",
"if",
"(",
"!",
"instance",
".",
"isMissing",
"(",
"a",
")",
")",
"{",
"numOccurences",
"=",
"instance",
".",
"valueSparse",
"(",
"a",
")",
"*",
"instance",
".",
"weight",
"(",
")",
";",
"if",
"(",
"numOccurences",
"<",
"0",
")",
"throw",
"new",
"Exception",
"(",
"\"",
"Numeric attribute values must all be greater or equal to zero.",
"\"",
")",
";",
"wordsPerClass",
"[",
"classIndex",
"]",
"+=",
"numOccurences",
";",
"m_probOfWordGivenClass",
"[",
"classIndex",
"]",
"[",
"instance",
".",
"index",
"(",
"a",
")",
"]",
"+=",
"numOccurences",
";",
"}",
"}",
"}",
"/*\n normalising probOfWordGivenClass values\n and saving each value as the log of each value\n */",
"for",
"(",
"int",
"c",
"=",
"0",
";",
"c",
"<",
"m_numClasses",
";",
"c",
"++",
")",
"for",
"(",
"int",
"v",
"=",
"0",
";",
"v",
"<",
"m_numAttributes",
";",
"v",
"++",
")",
"m_probOfWordGivenClass",
"[",
"c",
"]",
"[",
"v",
"]",
"=",
"Math",
".",
"log",
"(",
"m_probOfWordGivenClass",
"[",
"c",
"]",
"[",
"v",
"]",
"/",
"(",
"wordsPerClass",
"[",
"c",
"]",
"+",
"m_numAttributes",
"-",
"1",
")",
")",
";",
"/*\n calculating Pr(H)\n NOTE: Laplace estimator introduced in case a class does not get mentioned in the set of \n training instances\n */",
"final",
"double",
"numDocs",
"=",
"instances",
".",
"sumOfWeights",
"(",
")",
"+",
"m_numClasses",
";",
"m_probOfClass",
"=",
"new",
"double",
"[",
"m_numClasses",
"]",
";",
"for",
"(",
"int",
"h",
"=",
"0",
";",
"h",
"<",
"m_numClasses",
";",
"h",
"++",
")",
"m_probOfClass",
"[",
"h",
"]",
"=",
"(",
"double",
")",
"(",
"docsPerClass",
"[",
"h",
"]",
"+",
"1",
")",
"/",
"numDocs",
";",
"}",
"/**\n * Calculates the class membership probabilities for the given test \n * instance.\n *\n * @param instance the instance to be classified\n * @return predicted class probability distribution\n * @throws Exception if there is a problem generating the prediction\n */",
"public",
"double",
"[",
"]",
"distributionForInstance",
"(",
"Instance",
"instance",
")",
"throws",
"Exception",
"{",
"double",
"[",
"]",
"probOfClassGivenDoc",
"=",
"new",
"double",
"[",
"m_numClasses",
"]",
";",
"double",
"[",
"]",
"logDocGivenClass",
"=",
"new",
"double",
"[",
"m_numClasses",
"]",
";",
"for",
"(",
"int",
"h",
"=",
"0",
";",
"h",
"<",
"m_numClasses",
";",
"h",
"++",
")",
"logDocGivenClass",
"[",
"h",
"]",
"=",
"probOfDocGivenClass",
"(",
"instance",
",",
"h",
")",
";",
"double",
"max",
"=",
"logDocGivenClass",
"[",
"Utils",
".",
"maxIndex",
"(",
"logDocGivenClass",
")",
"]",
";",
"double",
"probOfDoc",
"=",
"0.0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"m_numClasses",
";",
"i",
"++",
")",
"{",
"probOfClassGivenDoc",
"[",
"i",
"]",
"=",
"Math",
".",
"exp",
"(",
"logDocGivenClass",
"[",
"i",
"]",
"-",
"max",
")",
"*",
"m_probOfClass",
"[",
"i",
"]",
";",
"probOfDoc",
"+=",
"probOfClassGivenDoc",
"[",
"i",
"]",
";",
"}",
"Utils",
".",
"normalize",
"(",
"probOfClassGivenDoc",
",",
"probOfDoc",
")",
";",
"return",
"probOfClassGivenDoc",
";",
"}",
"/**\n * log(N!) + (for all the words)(log(Pi^ni) - log(ni!))\n * \n * where \n * N is the total number of words\n * Pi is the probability of obtaining word i\n * ni is the number of times the word at index i occurs in the document\n *\n * @param inst The instance to be classified\n * @param classIndex The index of the class we are calculating the probability with respect to\n *\n * @return The log of the probability of the document occuring given the class\n */",
"private",
"double",
"probOfDocGivenClass",
"(",
"Instance",
"inst",
",",
"int",
"classIndex",
")",
"{",
"double",
"answer",
"=",
"0",
";",
"double",
"freqOfWordInDoc",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"inst",
".",
"numValues",
"(",
")",
";",
"i",
"++",
")",
"if",
"(",
"inst",
".",
"index",
"(",
"i",
")",
"!=",
"inst",
".",
"classIndex",
"(",
")",
")",
"{",
"freqOfWordInDoc",
"=",
"inst",
".",
"valueSparse",
"(",
"i",
")",
";",
"answer",
"+=",
"(",
"freqOfWordInDoc",
"*",
"m_probOfWordGivenClass",
"[",
"classIndex",
"]",
"[",
"inst",
".",
"index",
"(",
"i",
")",
"]",
")",
";",
"}",
"return",
"answer",
";",
"}",
"/**\n * Fast computation of ln(n!) for non-negative ints\n *\n * negative ints are passed on to the general gamma-function\n * based version in weka.core.SpecialFunctions\n *\n * if the current n value is higher than any previous one,\n * the cache is extended and filled to cover it\n *\n * the common case is reduced to a simple array lookup\n *\n * @param n the integer \n * @return ln(n!)\n */",
"public",
"double",
"lnFactorial",
"(",
"int",
"n",
")",
"{",
"if",
"(",
"n",
"<",
"0",
")",
"return",
"weka",
".",
"core",
".",
"SpecialFunctions",
".",
"lnFactorial",
"(",
"n",
")",
";",
"if",
"(",
"m_lnFactorialCache",
".",
"length",
"<=",
"n",
")",
"{",
"double",
"[",
"]",
"tmp",
"=",
"new",
"double",
"[",
"n",
"+",
"1",
"]",
";",
"System",
".",
"arraycopy",
"(",
"m_lnFactorialCache",
",",
"0",
",",
"tmp",
",",
"0",
",",
"m_lnFactorialCache",
".",
"length",
")",
";",
"for",
"(",
"int",
"i",
"=",
"m_lnFactorialCache",
".",
"length",
";",
"i",
"<",
"tmp",
".",
"length",
";",
"i",
"++",
")",
"tmp",
"[",
"i",
"]",
"=",
"tmp",
"[",
"i",
"-",
"1",
"]",
"+",
"Math",
".",
"log",
"(",
"i",
")",
";",
"m_lnFactorialCache",
"=",
"tmp",
";",
"}",
"return",
"m_lnFactorialCache",
"[",
"n",
"]",
";",
"}",
"/**\n * Returns a string representation of the classifier.\n * \n * @return a string representation of the classifier\n */",
"public",
"String",
"toString",
"(",
")",
"{",
"StringBuffer",
"result",
"=",
"new",
"StringBuffer",
"(",
"\"",
"The independent probability of a class",
"\\n",
"--------------------------------------",
"\\n",
"\"",
")",
";",
"for",
"(",
"int",
"c",
"=",
"0",
";",
"c",
"<",
"m_numClasses",
";",
"c",
"++",
")",
"result",
".",
"append",
"(",
"m_headerInfo",
".",
"classAttribute",
"(",
")",
".",
"value",
"(",
"c",
")",
")",
".",
"append",
"(",
"\"",
"\\t",
"\"",
")",
".",
"append",
"(",
"Double",
".",
"toString",
"(",
"m_probOfClass",
"[",
"c",
"]",
")",
")",
".",
"append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"result",
".",
"append",
"(",
"\"",
"\\n",
"The probability of a word given the class",
"\\n",
"-----------------------------------------",
"\\n",
"\\t",
"\"",
")",
";",
"for",
"(",
"int",
"c",
"=",
"0",
";",
"c",
"<",
"m_numClasses",
";",
"c",
"++",
")",
"result",
".",
"append",
"(",
"m_headerInfo",
".",
"classAttribute",
"(",
")",
".",
"value",
"(",
"c",
")",
")",
".",
"append",
"(",
"\"",
"\\t",
"\"",
")",
";",
"result",
".",
"append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"for",
"(",
"int",
"w",
"=",
"0",
";",
"w",
"<",
"m_numAttributes",
";",
"w",
"++",
")",
"{",
"if",
"(",
"w",
"!=",
"m_headerInfo",
".",
"classIndex",
"(",
")",
")",
"{",
"result",
".",
"append",
"(",
"m_headerInfo",
".",
"attribute",
"(",
"w",
")",
".",
"name",
"(",
")",
")",
".",
"append",
"(",
"\"",
"\\t",
"\"",
")",
";",
"for",
"(",
"int",
"c",
"=",
"0",
";",
"c",
"<",
"m_numClasses",
";",
"c",
"++",
")",
"result",
".",
"append",
"(",
"Double",
".",
"toString",
"(",
"Math",
".",
"exp",
"(",
"m_probOfWordGivenClass",
"[",
"c",
"]",
"[",
"w",
"]",
")",
")",
")",
".",
"append",
"(",
"\"",
"\\t",
"\"",
")",
";",
"result",
".",
"append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"}",
"}",
"return",
"result",
".",
"toString",
"(",
")",
";",
"}",
"/**\n * Returns the revision string.\n * \n * @return\t\tthe revision\n */",
"public",
"String",
"getRevision",
"(",
")",
"{",
"return",
"RevisionUtils",
".",
"extract",
"(",
"\"",
"$Revision: 10141 $",
"\"",
")",
";",
"}",
"/**\n * Main method for testing this class.\n *\n * @param argv the options\n */",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"argv",
")",
"{",
"runClassifier",
"(",
"new",
"NaiveBayesMultinomial",
"(",
")",
",",
"argv",
")",
";",
"}",
"}"
] |
<!-- globalinfo-start -->
Class for building and using a multinomial Naive Bayes classifier.
|
[
"<!",
"--",
"globalinfo",
"-",
"start",
"--",
">",
"Class",
"for",
"building",
"and",
"using",
"a",
"multinomial",
"Naive",
"Bayes",
"classifier",
"."
] |
[
"// attributes",
"// class",
"// can classifier handle the data?",
"// remove instances with missing class",
"//enumerate through the instances ",
"//calculate the array of log(Pr[D|C])",
"//double totalWords = 0; //no need as we are not calculating the factorial at all.",
"//should be double",
"//totalWords += freqOfWordInDoc;",
"//- lnFactorial(freqOfWordInDoc));",
"//answer += lnFactorial(totalWords);//The factorial terms don't make ",
"//any difference to the classifier's",
"//accuracy, so not needed."
] |
[
{
"param": "AbstractClassifier",
"type": null
},
{
"param": "WeightedInstancesHandler,TechnicalInformationHandler",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "AbstractClassifier",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "WeightedInstancesHandler,TechnicalInformationHandler",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 20
| 2,520
| 383
|
719326002bc567a3ea8ba6bc93a8a60248a718a4
|
lpxz/grail-derby104
|
java/testing/org/apache/derbyTesting/unitTests/store/T_SecondaryIndexRow.java
|
[
"Apache-2.0"
] |
Java
|
T_SecondaryIndexRow
|
/**
This class implements a row which will be stored in a secondary index on
a heap table.
<p>
This class creates a new DataValueDescriptor array which will be the row used
to insert into the secondary index. The fields of this object array are made
up of references to DataValueDescriptors provided by the caller: the
DataValueDescriptors in the template and a RowLocation.
The interface is designed to support the standard access method interface
where callers provide a single template and then read rows into that template
over and over. This class keeps a reference to the objects in the template
and the rowlocation,
so the state of this object changes whenever the caller changes the template.
The caller provides a template which will contain a heap row,
and a RowLocation which provides the location of the row within the heap table.
<p>
So for example to create an index from a base table by reading the base table
and inserting each row one at a time into the secondary index you would
do something like:
DataValueDescriptors[] template = get_template_for_base_table();
RowLocation rowloc = ScanController_var.newRowLocationTemplate();
T_SecondaryIndexRow indrow = new T_SecondaryIndexRow();
indrow.init(template, rowloc, numcols_in_index);
while (ScanController_variable.next())
{
fetch(template)
fetchLocation(rowloc)
ConglomerateController_on_btree.insert(indrow.getRow());
}
**/
|
This class implements a row which will be stored in a secondary index on
a heap table.
This class creates a new DataValueDescriptor array which will be the row used
to insert into the secondary index. The fields of this object array are made
up of references to DataValueDescriptors provided by the caller: the
DataValueDescriptors in the template and a RowLocation.
The interface is designed to support the standard access method interface
where callers provide a single template and then read rows into that template
over and over. This class keeps a reference to the objects in the template
and the rowlocation,
so the state of this object changes whenever the caller changes the template.
The caller provides a template which will contain a heap row,
and a RowLocation which provides the location of the row within the heap table.
So for example to create an index from a base table by reading the base table
and inserting each row one at a time into the secondary index you would
do something like.
|
[
"This",
"class",
"implements",
"a",
"row",
"which",
"will",
"be",
"stored",
"in",
"a",
"secondary",
"index",
"on",
"a",
"heap",
"table",
".",
"This",
"class",
"creates",
"a",
"new",
"DataValueDescriptor",
"array",
"which",
"will",
"be",
"the",
"row",
"used",
"to",
"insert",
"into",
"the",
"secondary",
"index",
".",
"The",
"fields",
"of",
"this",
"object",
"array",
"are",
"made",
"up",
"of",
"references",
"to",
"DataValueDescriptors",
"provided",
"by",
"the",
"caller",
":",
"the",
"DataValueDescriptors",
"in",
"the",
"template",
"and",
"a",
"RowLocation",
".",
"The",
"interface",
"is",
"designed",
"to",
"support",
"the",
"standard",
"access",
"method",
"interface",
"where",
"callers",
"provide",
"a",
"single",
"template",
"and",
"then",
"read",
"rows",
"into",
"that",
"template",
"over",
"and",
"over",
".",
"This",
"class",
"keeps",
"a",
"reference",
"to",
"the",
"objects",
"in",
"the",
"template",
"and",
"the",
"rowlocation",
"so",
"the",
"state",
"of",
"this",
"object",
"changes",
"whenever",
"the",
"caller",
"changes",
"the",
"template",
".",
"The",
"caller",
"provides",
"a",
"template",
"which",
"will",
"contain",
"a",
"heap",
"row",
"and",
"a",
"RowLocation",
"which",
"provides",
"the",
"location",
"of",
"the",
"row",
"within",
"the",
"heap",
"table",
".",
"So",
"for",
"example",
"to",
"create",
"an",
"index",
"from",
"a",
"base",
"table",
"by",
"reading",
"the",
"base",
"table",
"and",
"inserting",
"each",
"row",
"one",
"at",
"a",
"time",
"into",
"the",
"secondary",
"index",
"you",
"would",
"do",
"something",
"like",
"."
] |
public class T_SecondaryIndexRow
{
DataValueDescriptor[] row;
RowLocation init_rowlocation = null;
/* Constructors for This class: */
public T_SecondaryIndexRow(){}
/* Private/Protected methods of This class: */
/* Public Methods of T_SecondaryIndexRow class: */
/**
* get the rows location field.
*
* @return The base table row location field from the secondary index.
*
* @exception StandardException Standard exception policy.
**/
/*
private RowLocation getRowLocationField()
throws StandardException
{
return(init_rowlocation);
}
*/
/**
* Initialize the class.
* <p>
* Save away pointers to the base table template row, and the rowlocation
* class. Build default map of base columns to key columns, this map
* can be changed with setMap().
* <p>
*
* @param template The template for the base table row.
* @param rowlocation The template for the row location.
* @param numkeys The total number of columns in the secondary index
* including the rowlocation column.
*
* @exception StandardException Standard exception policy.
**/
public void init(
DataValueDescriptor[] template,
RowLocation rowlocation,
int numkeys)
throws StandardException
{
if (SanityManager.DEBUG)
{
if (numkeys != (template.length + 1))
SanityManager.THROWASSERT(
"numkeys = " + numkeys +
" template.length = " + template.length);
}
init_rowlocation = rowlocation;
/* create new object array for the row, and copy all object references
* from template row to new secondary index row.
*/
row = new DataValueDescriptor[numkeys];
System.arraycopy(template, 0, row, 0, template.length);
/* add the reference to the row location column as the last column */
row[row.length - 1] = rowlocation;
}
/**
* Return the secondary index row.
* <p>
* Return the DataValueDescriptor array that represents the branch row,
* for use in raw store calls to fetch, insert, and update.
* <p>
*
* @return The branch row object array.
**/
public DataValueDescriptor[] getRow()
{
return(this.row);
}
public String toString()
{
String s = "{ ";
for (int colid = 0; colid < row.length; colid++)
{
s += row[colid];
if (colid < (row.length - 1))
s += ", ";
}
s += " }";
return s;
}
}
|
[
"public",
"class",
"T_SecondaryIndexRow",
"{",
"DataValueDescriptor",
"[",
"]",
"row",
";",
"RowLocation",
"init_rowlocation",
"=",
"null",
";",
"/* Constructors for This class: */",
"public",
"T_SecondaryIndexRow",
"(",
")",
"{",
"}",
"/* Private/Protected methods of This class: */",
"/* Public Methods of T_SecondaryIndexRow class: */",
"/**\n * get the rows location field.\n *\n\t * @return The base table row location field from the secondary index.\n *\n\t * @exception StandardException Standard exception policy.\n **/",
"/*\n private RowLocation getRowLocationField()\n\t\tthrows StandardException\n {\n return(init_rowlocation);\n }\n */",
"/**\n * Initialize the class.\n * <p>\n * Save away pointers to the base table template row, and the rowlocation\n * class. Build default map of base columns to key columns, this map\n * can be changed with setMap().\n * <p>\n *\n * @param template The template for the base table row.\n * @param rowlocation The template for the row location.\n * @param numkeys The total number of columns in the secondary index\n * including the rowlocation column.\n *\n\t * @exception StandardException Standard exception policy.\n **/",
"public",
"void",
"init",
"(",
"DataValueDescriptor",
"[",
"]",
"template",
",",
"RowLocation",
"rowlocation",
",",
"int",
"numkeys",
")",
"throws",
"StandardException",
"{",
"if",
"(",
"SanityManager",
".",
"DEBUG",
")",
"{",
"if",
"(",
"numkeys",
"!=",
"(",
"template",
".",
"length",
"+",
"1",
")",
")",
"SanityManager",
".",
"THROWASSERT",
"(",
"\"",
"numkeys = ",
"\"",
"+",
"numkeys",
"+",
"\"",
" template.length = ",
"\"",
"+",
"template",
".",
"length",
")",
";",
"}",
"init_rowlocation",
"=",
"rowlocation",
";",
"/* create new object array for the row, and copy all object references \n * from template row to new secondary index row.\n */",
"row",
"=",
"new",
"DataValueDescriptor",
"[",
"numkeys",
"]",
";",
"System",
".",
"arraycopy",
"(",
"template",
",",
"0",
",",
"row",
",",
"0",
",",
"template",
".",
"length",
")",
";",
"/* add the reference to the row location column as the last column */",
"row",
"[",
"row",
".",
"length",
"-",
"1",
"]",
"=",
"rowlocation",
";",
"}",
"/**\n * Return the secondary index row.\n * <p>\n * Return the DataValueDescriptor array that represents the branch row, \n * for use in raw store calls to fetch, insert, and update.\n * <p>\n *\n\t * @return The branch row object array.\n **/",
"public",
"DataValueDescriptor",
"[",
"]",
"getRow",
"(",
")",
"{",
"return",
"(",
"this",
".",
"row",
")",
";",
"}",
"public",
"String",
"toString",
"(",
")",
"{",
"String",
"s",
"=",
"\"",
"{ ",
"\"",
";",
"for",
"(",
"int",
"colid",
"=",
"0",
";",
"colid",
"<",
"row",
".",
"length",
";",
"colid",
"++",
")",
"{",
"s",
"+=",
"row",
"[",
"colid",
"]",
";",
"if",
"(",
"colid",
"<",
"(",
"row",
".",
"length",
"-",
"1",
")",
")",
"s",
"+=",
"\"",
", ",
"\"",
";",
"}",
"s",
"+=",
"\"",
" }",
"\"",
";",
"return",
"s",
";",
"}",
"}"
] |
This class implements a row which will be stored in a secondary index on
a heap table.
|
[
"This",
"class",
"implements",
"a",
"row",
"which",
"will",
"be",
"stored",
"in",
"a",
"secondary",
"index",
"on",
"a",
"heap",
"table",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 610
| 305
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.