text
stringlengths
2
1.04M
meta
dict
 using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using JsonPath; using MatterHackers.Agg; using MatterHackers.Agg.Platform; using MatterHackers.Agg.UI; using MatterHackers.DataConverters3D; using MatterHackers.ImageProcessing; using MatterHackers.Localizations; using MatterHackers.MatterControl.CustomWidgets; using MatterHackers.MatterControl.DesignTools; using MatterHackers.MatterControl.DesignTools.Operations; using MatterHackers.MatterControl.Library; using MatterHackers.MatterControl.SlicerConfiguration; using static JsonPath.JsonPathContext.ReflectionValueSystem; namespace MatterHackers.MatterControl.PartPreviewWindow { public class SelectedObjectPanel : FlowLayoutWidget, IContentStore { private IObject3D item = new Object3D(); private readonly ThemeConfig theme; private readonly ISceneContext sceneContext; private readonly SectionWidget editorSectionWidget; private readonly GuiWidget editorPanel; private readonly string editorTitle = "Properties".Localize(); public SelectedObjectPanel(View3DWidget view3DWidget, ISceneContext sceneContext, ThemeConfig theme) : base(FlowDirection.TopToBottom) { this.HAnchor = HAnchor.Stretch; this.VAnchor = VAnchor.Top | VAnchor.Fit; this.Padding = 0; this.theme = theme; this.sceneContext = sceneContext; var toolbar = new LeftClipFlowLayoutWidget() { BackgroundColor = theme.BackgroundColor, Padding = theme.ToolbarPadding, HAnchor = HAnchor.Fit, VAnchor = VAnchor.Fit }; scene = sceneContext.Scene; // put in the container for dynamic actions primaryActionsPanel = new FlowLayoutWidget() { HAnchor = HAnchor.Fit, VAnchor = VAnchor.Center | VAnchor.Fit }; toolbar.AddChild(primaryActionsPanel); // put in a make permanent button var icon = StaticData.Instance.LoadIcon("apply.png", 16, 16).SetToColor(theme.TextColor).SetPreMultiply(); applyButton = new ThemedIconButton(icon, theme) { Margin = theme.ButtonSpacing, ToolTipText = "Apply".Localize(), Enabled = true }; applyButton.Click += (s, e) => { if (this.item.CanApply) { var item = this.item; using (new DataConverters3D.SelectionMaintainer(view3DWidget.Scene)) { item.Apply(view3DWidget.Scene.UndoBuffer); } } else { // try to ungroup it sceneContext.Scene.UngroupSelection(); } }; toolbar.AddChild(applyButton); // put in a remove button cancelButton = new ThemedIconButton(StaticData.Instance.LoadIcon("cancel.png", 16, 16).SetToColor(theme.TextColor).SetPreMultiply(), theme) { Margin = theme.ButtonSpacing, ToolTipText = "Cancel".Localize(), Enabled = scene.SelectedItem != null }; cancelButton.Click += (s, e) => { var item = this.item; using (new DataConverters3D.SelectionMaintainer(view3DWidget.Scene)) { item.Cancel(view3DWidget.Scene.UndoBuffer); } }; toolbar.AddChild(cancelButton); overflowButton = new PopupMenuButton("Action".Localize(), theme) { Enabled = scene.SelectedItem != null, DrawArrow = true, }; overflowButton.ToolTipText = "Object Actions".Localize(); overflowButton.DynamicPopupContent = () => { return ApplicationController.Instance.GetModifyMenu(view3DWidget.sceneContext); }; toolbar.AddChild(overflowButton); editorPanel = new FlowLayoutWidget(FlowDirection.TopToBottom) { HAnchor = HAnchor.Stretch, VAnchor = VAnchor.Fit, Name = "editorPanel", }; // Wrap editorPanel with scrollable container var scrollableWidget = new ScrollableWidget(true) { HAnchor = HAnchor.Stretch, VAnchor = VAnchor.Stretch }; scrollableWidget.AddChild(editorPanel); scrollableWidget.ScrollArea.HAnchor = HAnchor.Stretch; editorSectionWidget = new SectionWidget(editorTitle, scrollableWidget, theme, toolbar, expandingContent: false, defaultExpansion: true, setContentVAnchor: false) { VAnchor = VAnchor.Stretch }; this.AddChild(editorSectionWidget); this.ContentPanel = editorPanel; // Register listeners scene.SelectionChanged += Scene_SelectionChanged; } public GuiWidget ContentPanel { get; set; } private readonly JsonPathContext pathGetter = new JsonPathContext(); private readonly ThemedIconButton applyButton; private readonly ThemedIconButton cancelButton; private readonly PopupMenuButton overflowButton; private readonly InteractiveScene scene; private readonly FlowLayoutWidget primaryActionsPanel; public void SetActiveItem(ISceneContext sceneContext) { var selectedItem = sceneContext?.Scene?.SelectedItem; if (this.item == selectedItem) { return; } this.item = selectedItem; editorPanel.CloseChildren(); // Allow caller to clean up with passing null for selectedItem if (item == null) { editorSectionWidget.Text = editorTitle; return; } var selectedItemType = selectedItem.GetType(); primaryActionsPanel.RemoveChildren(); IEnumerable<SceneOperation> primaryActions; if ((primaryActions = SceneOperations.GetPrimaryOperations(selectedItemType)) == null) { primaryActions = new List<SceneOperation>(); } else { // Loop over primary actions creating a button for each foreach (var primaryAction in primaryActions) { // TODO: Run visible/enable rules on actions, conditionally add/enable as appropriate var button = new ThemedIconButton(primaryAction.Icon(theme), theme) { // Name = namedAction.Title + " Button", ToolTipText = primaryAction.Title, Margin = theme.ButtonSpacing, BackgroundColor = theme.ToolbarButtonBackground, HoverColor = theme.ToolbarButtonHover, MouseDownColor = theme.ToolbarButtonDown, }; button.Click += (s, e) => { primaryAction.Action.Invoke(sceneContext); }; primaryActionsPanel.AddChild(button); } } if (primaryActionsPanel.Children.Any()) { // add in a separator from the apply and cancel buttons primaryActionsPanel.AddChild(new ToolbarSeparator(theme.GetBorderColor(50), theme.SeparatorMargin)); } editorSectionWidget.Text = selectedItem.Name ?? selectedItemType.Name; HashSet<IObject3DEditor> mappedEditors = ApplicationController.Instance.Extensions.GetEditorsForType(selectedItemType); var undoBuffer = sceneContext.Scene.UndoBuffer; void GetNextSelectionColor(Action<Color> setColor) { var scene = sceneContext.Scene; var startingSelection = scene.SelectedItem; CancellationTokenSource cancellationToken = null; void SelectionChanged(object s, EventArgs e) { var selection = scene.SelectedItem; if (selection != null) { setColor?.Invoke(selection.WorldColor()); scene.SelectionChanged -= SelectionChanged; cancellationToken?.Cancel(); scene.SelectedItem = startingSelection; } } var durationSeconds = 20; ApplicationController.Instance.Tasks.Execute("Select an object to copy its color".Localize(), null, (progress, cancellationTokenIn) => { cancellationToken = cancellationTokenIn; var time = UiThread.CurrentTimerMs; var status = new ProgressStatus(); while (UiThread.CurrentTimerMs < time + durationSeconds * 1000 && !cancellationToken.IsCancellationRequested) { Thread.Sleep(30); status.Progress0To1 = (UiThread.CurrentTimerMs - time) / 1000.0 / durationSeconds; progress.Report(status); } scene.SelectionChanged -= SelectionChanged; return Task.CompletedTask; }); scene.SelectionChanged += SelectionChanged; } if (!(selectedItem.GetType().GetCustomAttributes(typeof(HideMeterialAndColor), true).FirstOrDefault() is HideMeterialAndColor)) { var firstDetectedColor = selectedItem.VisibleMeshes()?.FirstOrDefault()?.WorldColor(); var worldColor = Color.White; if (firstDetectedColor != null) { worldColor = firstDetectedColor.Value; } // put in a color edit field var colorField = new ColorField(theme, worldColor, GetNextSelectionColor, true); colorField.Initialize(0); colorField.ValueChanged += (s, e) => { if (selectedItem.Color != colorField.Color) { if (colorField.Color == Color.Transparent) { undoBuffer.AddAndDo(new ChangeColor(selectedItem, colorField.Color, PrintOutputTypes.Default)); } else { undoBuffer.AddAndDo(new ChangeColor(selectedItem, colorField.Color, PrintOutputTypes.Solid)); } } }; ColorButton holeButton = null; var solidButton = colorField.Content.Descendants<ColorButton>().FirstOrDefault(); GuiWidget otherContainer = null; TextWidget otherText = null; GuiWidget holeContainer = null; GuiWidget solidContainer = null; void SetOtherOutputSelection(string text) { otherText.Text = text; otherContainer.Visible = true; holeContainer.BackgroundOutlineWidth = 0; holeButton.BackgroundOutlineWidth = 1; solidContainer.BackgroundOutlineWidth = 0; solidButton.BackgroundOutlineWidth = 1; } var scaledButtonSize = 24 * GuiWidget.DeviceScale; void SetButtonStates() { switch (selectedItem.OutputType) { case PrintOutputTypes.Hole: holeContainer.BackgroundOutlineWidth = 1; holeButton.BackgroundOutlineWidth = 2; holeButton.BackgroundRadius = scaledButtonSize / 2 - 1; solidContainer.BackgroundOutlineWidth = 0; solidButton.BackgroundOutlineWidth = 1; solidButton.BackgroundRadius = scaledButtonSize / 2; otherContainer.Visible = false; break; case PrintOutputTypes.Default: case PrintOutputTypes.Solid: holeContainer.BackgroundOutlineWidth = 0; holeButton.BackgroundOutlineWidth = 1; holeButton.BackgroundRadius = scaledButtonSize / 2; solidContainer.BackgroundOutlineWidth = 1; solidButton.BackgroundOutlineWidth = 2; solidButton.BackgroundRadius = scaledButtonSize / 2 - 1; otherContainer.Visible = false; break; case PrintOutputTypes.Support: SetOtherOutputSelection("Support".Localize()); break; case PrintOutputTypes.WipeTower: SetOtherOutputSelection("Wipe Tower".Localize()); break; case PrintOutputTypes.Fuzzy: SetOtherOutputSelection("Fuzzy".Localize()); break; } } void SetToSolid() { // make sure the render mode is set to shaded or outline switch(sceneContext.ViewState.RenderType) { case RenderOpenGl.RenderTypes.Shaded: case RenderOpenGl.RenderTypes.Outlines: case RenderOpenGl.RenderTypes.Polygons: break; default: // make sure the render mode is set to outline sceneContext.ViewState.RenderType = RenderOpenGl.RenderTypes.Outlines; break; } var currentOutputType = selectedItem.OutputType; if (currentOutputType != PrintOutputTypes.Solid && currentOutputType != PrintOutputTypes.Default) { undoBuffer.AddAndDo(new ChangeColor(selectedItem, colorField.Color, PrintOutputTypes.Solid)); } SetButtonStates(); Invalidate(); } solidButton.Parent.MouseDown += (s, e) => SetToSolid(); var colorRow = new SettingsRow("Output".Localize(), null, colorField.Content, theme) { // Special top border style for first item in editor Border = new BorderDouble(0, 1) }; editorPanel.AddChild(colorRow); // put in a hole button holeButton = new ColorButton(Color.DarkGray) { Margin = new BorderDouble(5, 0, 11, 0), Width = scaledButtonSize, Height = scaledButtonSize, BackgroundRadius = scaledButtonSize / 2, BackgroundOutlineWidth = 1, VAnchor = VAnchor.Center, DisabledColor = theme.MinimalShade, BorderColor = theme.TextColor, ToolTipText = "Convert to Hole".Localize(), }; GuiWidget NewTextContainer(string text) { var textWidget = new TextWidget(text.Localize(), pointSize: theme.FontSize10, textColor: theme.TextColor) { Margin = new BorderDouble(5, 4, 5, 5), AutoExpandBoundsToText = true, }; var container = new GuiWidget() { Margin = new BorderDouble(5, 0), VAnchor = VAnchor.Fit | VAnchor.Center, HAnchor = HAnchor.Fit, BackgroundRadius = 3, BackgroundOutlineWidth = 1, BorderColor = theme.PrimaryAccentColor, Selectable = true, }; container.AddChild(textWidget); return container; } var buttonRow = solidButton.Parents<FlowLayoutWidget>().FirstOrDefault(); solidContainer = NewTextContainer("Solid"); buttonRow.AddChild(solidContainer, 0); buttonRow.AddChild(holeButton, 0); holeContainer = NewTextContainer("Hole"); buttonRow.AddChild(holeContainer, 0); otherContainer = NewTextContainer(""); buttonRow.AddChild(otherContainer, 0); otherText = otherContainer.Children.First() as TextWidget; void SetToHole() { if (selectedItem.OutputType != PrintOutputTypes.Hole) { undoBuffer.AddAndDo(new MakeHole(selectedItem)); } SetButtonStates(); Invalidate(); } holeButton.Click += (s, e) => SetToHole(); holeContainer.Click += (s, e) => SetToHole(); solidContainer.Click += (s, e) => SetToSolid(); SetButtonStates(); void SelectedItemOutputChanged(object sender, EventArgs e) { SetButtonStates(); } selectedItem.Invalidated += SelectedItemOutputChanged; Closed += (s, e) => selectedItem.Invalidated -= SelectedItemOutputChanged; // put in a material edit field var materialField = new MaterialIndexField(sceneContext.Printer, theme, selectedItem.MaterialIndex); materialField.Initialize(0); materialField.ValueChanged += (s, e) => { if (selectedItem.MaterialIndex != materialField.MaterialIndex) { undoBuffer.AddAndDo(new ChangeMaterial(selectedItem, materialField.MaterialIndex)); } }; materialField.Content.MouseDown += (s, e) => { if (sceneContext.ViewState.RenderType != RenderOpenGl.RenderTypes.Materials) { // make sure the render mode is set to material sceneContext.ViewState.RenderType = RenderOpenGl.RenderTypes.Materials; } }; // material row editorPanel.AddChild(new SettingsRow("Material".Localize(), null, materialField.Content, theme)); } var rows = new SafeList<SettingsRow>(); // put in the normal editor if (selectedItem is ComponentObject3D componentObject && componentObject.Finalized) { AddComponentEditor(selectedItem, undoBuffer, rows, componentObject); } else { if (item != null && ApplicationController.Instance.Extensions.GetEditorsForType(item.GetType())?.FirstOrDefault() is IObject3DEditor editor) { ShowObjectEditor((editor, item, item.Name), selectedItem); } } } private void AddComponentEditor(IObject3D selectedItem, UndoBuffer undoBuffer, SafeList<SettingsRow> rows, ComponentObject3D componentObject) { var context = new PPEContext(); PublicPropertyEditor.AddUnlockLinkIfRequired(selectedItem, editorPanel, theme); var editorList = componentObject.SurfacedEditors; for (var editorIndex = 0; editorIndex < editorList.Count; editorIndex++) { // if it is a reference to a sheet cell if (editorList[editorIndex].StartsWith("!")) { AddSheetCellEditor(undoBuffer, componentObject, editorList, editorIndex); } else // parse it as a path to an object { // Get the named property via reflection // Selector example: '$.Children<CylinderObject3D>' var match = pathGetter.Select(componentObject, editorList[editorIndex]).ToList(); //// - Add editor row for each foreach (var instance in match) { if (instance is IObject3D object3D) { if (ApplicationController.Instance.Extensions.GetEditorsForType(object3D.GetType())?.FirstOrDefault() is IObject3DEditor editor) { ShowObjectEditor((editor, object3D, object3D.Name), selectedItem); } } else if (JsonPathContext.ReflectionValueSystem.LastMemberValue is ReflectionTarget reflectionTarget) { if (reflectionTarget.Source is IObject3D editedChild) { context.item = editedChild; } else { context.item = item; } var editableProperty = new EditableProperty(reflectionTarget.PropertyInfo, reflectionTarget.Source); var editor = PublicPropertyEditor.CreatePropertyEditor(rows, editableProperty, undoBuffer, context, theme); if (editor != null) { editorPanel.AddChild(editor); } // Init with custom 'UpdateControls' hooks (context.item as IPropertyGridModifier)?.UpdateControls(new PublicPropertyChange(context, "Update_Button")); } } } } // Enforce panel padding foreach (var sectionWidget in editorPanel.Descendants<SectionWidget>()) { sectionWidget.Margin = 0; } } private void AddSheetCellEditor(UndoBuffer undoBuffer, ComponentObject3D componentObject, List<string> editorList, int editorIndex) { var firtSheet = componentObject.Descendants<SheetObject3D>().FirstOrDefault(); if (firtSheet != null) { var (cellId, cellData) = componentObject.DecodeContent(editorIndex); var cell = firtSheet.SheetData[cellId]; if (cell != null) { // create an expresion editor var field = new ExpressionField(theme) { Name = cellId + " Field" }; field.Initialize(0); if (cellData.Contains("=")) { field.SetValue(cellData, false); } else // make sure it is formatted { double.TryParse(cellData, out double value); var format = "0." + new string('#', 5); field.SetValue(value.ToString(format), false); } field.ClearUndoHistory(); var doOrUndoing = false; field.ValueChanged += (s, e) => { if (!doOrUndoing) { var oldValue = componentObject.DecodeContent(editorIndex).cellData; var newValue = field.Value; undoBuffer.AddAndDo(new UndoRedoActions(() => { doOrUndoing = true; editorList[editorIndex] = "!" + cellId + "," + oldValue; var expression = new DoubleOrExpression(oldValue); cell.Expression = expression.Value(componentObject).ToString(); componentObject.Invalidate(InvalidateType.SheetUpdated); doOrUndoing = false; }, () => { doOrUndoing = true; editorList[editorIndex] = "!" + cellId + "," + newValue; var expression = new DoubleOrExpression(newValue); cell.Expression = expression.Value(componentObject).ToString(); componentObject.Invalidate(InvalidateType.SheetUpdated); doOrUndoing = false; })); } }; var row = new SettingsRow(cell.Name == null ? cellId : cell.Name.Replace("_", " "), null, field.Content, theme); editorPanel.AddChild(row); } } } private class OperationButton : ThemedTextButton { private readonly SceneOperation sceneOperation; private readonly ISceneContext sceneContext; public OperationButton(SceneOperation sceneOperation, ISceneContext sceneContext, ThemeConfig theme) : base(sceneOperation.Title, theme) { this.sceneOperation = sceneOperation; this.sceneContext = sceneContext; } public void EnsureAvailablity() { this.Enabled = sceneOperation.IsEnabled?.Invoke(sceneContext) != false; } } private void ShowObjectEditor((IObject3DEditor editor, IObject3D item, string displayName) scopeItem, IObject3D rootSelection) { var selectedItem = scopeItem.item; var editorWidget = scopeItem.editor.Create(selectedItem, sceneContext.Scene.UndoBuffer, theme); editorWidget.HAnchor = HAnchor.Stretch; editorWidget.VAnchor = VAnchor.Fit; if (scopeItem.item != rootSelection && scopeItem.editor is PublicPropertyEditor) { editorWidget.Padding = new BorderDouble(10, 10, 10, 0); // EditOutline section var sectionWidget = new SectionWidget( scopeItem.displayName ?? "Unknown", editorWidget, theme); theme.ApplyBoxStyle(sectionWidget, margin: 0); editorWidget = sectionWidget; } else { editorWidget.Padding = 0; } editorPanel.AddChild(editorWidget); } public Task Save(ILibraryItem item, IObject3D content) { this.item.Parent.Children.Modify(children => { children.Remove(this.item); children.Add(content); }); return null; } public override void OnClosed(EventArgs e) { // Unregister listeners scene.SelectionChanged -= Scene_SelectionChanged; base.OnClosed(e); } private void Scene_SelectionChanged(object sender, EventArgs e) { if (editorPanel.Children.FirstOrDefault()?.DescendantsAndSelf<SectionWidget>().FirstOrDefault() is SectionWidget firstSectionWidget) { firstSectionWidget.Margin = firstSectionWidget.Margin.Clone(top: 0); } var selectedItem = scene.SelectedItem; applyButton.Enabled = selectedItem != null && (selectedItem is GroupObject3D || (selectedItem.GetType() == typeof(Object3D) && selectedItem.Children.Any()) || selectedItem.CanApply); cancelButton.Enabled = selectedItem != null; overflowButton.Enabled = selectedItem != null; if (selectedItem == null) { primaryActionsPanel.RemoveChildren(); } } public void Dispose() { } } }
{ "content_hash": "018fa2d510907fd7cee59d545a429ae0", "timestamp": "", "source": "github", "line_count": 717, "max_line_length": 164, "avg_line_length": 33.09902370990237, "alnum_prop": 0.6336591943367605, "repo_name": "larsbrubaker/MatterControl", "id": "5edd51bf93b9fd3ba1487815a1d8adcfe5850ecb", "size": "25264", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "MatterControlLib/PartPreviewWindow/SelectedObjectPanel.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "1007" }, { "name": "C#", "bytes": "10319779" }, { "name": "C++", "bytes": "8783" }, { "name": "G-code", "bytes": "1473799" }, { "name": "Shell", "bytes": "322" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jordan-curve-theorem: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.10.2 / jordan-curve-theorem - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> jordan-curve-theorem <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-06-30 02:36:08 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-06-30 02:36:08 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.10.2 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/jordan-curve-theorem&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/JordanCurveTheorem&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: combinatorial hypermaps&quot; &quot;keyword: genus&quot; &quot;keyword: planarity&quot; &quot;keyword: Euler formula&quot; &quot;keyword: Discrete Jordan Curve Theorem&quot; &quot;category: Mathematics/Geometry/General&quot; &quot;date: 2008&quot; ] authors: [ &quot;Jean-François Dufourd &lt;dufourd@lsiit.u-strasbg.fr&gt; [http://dpt-info.u-strasbg.fr/~jfd/]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/jordan-curve-theorem/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/jordan-curve-theorem.git&quot; synopsis: &quot;Hypermaps, planarity and discrete Jordan curve theorem&quot; description: &quot;&quot;&quot; http://dpt-info.u-strasbg.fr/~jfd/Downloads/JORDAN_Contrib_Coq.tar.gz Constructive formalization of the combinatorial hypermaps, characterization of the planarity, genus theorem, Euler formula, ring of faces, discrete Jordan curve theorem&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/jordan-curve-theorem/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=42157391127fc6af77f7d0dfa29f7e76&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-jordan-curve-theorem.8.6.0 coq.8.10.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.2). The following dependencies couldn&#39;t be met: - coq-jordan-curve-theorem -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-jordan-curve-theorem.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "9f403c9512e554a3d771981461dc3f30", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 272, "avg_line_length": 44.21084337349398, "alnum_prop": 0.5587954762229187, "repo_name": "coq-bench/coq-bench.github.io", "id": "32151df85e843fa18d9f873c147a82101fd71225", "size": "7365", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.10.2/jordan-curve-theorem/8.6.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "ae5942d6214f4c84b8a680ab00474c6a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "6618d889d93c90d31fa3a65436b2dde3c3b79363", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Convolvulaceae/Convolvulus/Convolvulus microcalyx/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package co.cask.cdap.data2.dataset2.lib.table.hbase; import co.cask.cdap.api.common.Bytes; import co.cask.cdap.api.dataset.DataSetException; import co.cask.cdap.api.dataset.DatasetContext; import co.cask.cdap.api.dataset.DatasetSpecification; import co.cask.cdap.api.dataset.table.Scanner; import co.cask.cdap.common.utils.ImmutablePair; import co.cask.cdap.data2.dataset2.lib.table.FuzzyRowFilter; import co.cask.cdap.data2.dataset2.lib.table.MetricsTable; import co.cask.cdap.data2.dataset2.lib.table.TableProperties; import co.cask.cdap.data2.util.TableId; import co.cask.cdap.data2.util.hbase.DeleteBuilder; import co.cask.cdap.data2.util.hbase.HBaseTableUtil; import co.cask.cdap.data2.util.hbase.PutBuilder; import co.cask.cdap.data2.util.hbase.ScanBuilder; import co.cask.cdap.proto.id.NamespaceId; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Increment; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.util.Pair; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.SortedMap; import javax.annotation.Nullable; /** * An HBase metrics table client. */ public class HBaseMetricsTable implements MetricsTable { private final HBaseTableUtil tableUtil; private final TableId tableId; private final HTable hTable; private final byte[] columnFamily; public HBaseMetricsTable(DatasetContext datasetContext, DatasetSpecification spec, Configuration hConf, HBaseTableUtil tableUtil) throws IOException { this.tableUtil = tableUtil; this.tableId = tableUtil.createHTableId(new NamespaceId(datasetContext.getNamespaceId()), spec.getName()); HTable hTable = tableUtil.createHTable(hConf, tableId); // todo: make configurable hTable.setWriteBufferSize(HBaseTableUtil.DEFAULT_WRITE_BUFFER_SIZE); hTable.setAutoFlush(false); this.hTable = hTable; this.columnFamily = TableProperties.getColumnFamily(spec.getProperties()); } @Override @Nullable public byte[] get(byte[] row, byte[] column) { try { Get get = tableUtil.buildGet(row) .addColumn(columnFamily, column) .setMaxVersions(1) .build(); Result getResult = hTable.get(get); if (!getResult.isEmpty()) { return getResult.getValue(columnFamily, column); } return null; } catch (IOException e) { throw new DataSetException("Get failed on table " + tableId, e); } } @Override public void put(SortedMap<byte[], ? extends SortedMap<byte[], Long>> updates) { List<Put> puts = Lists.newArrayList(); for (Map.Entry<byte[], ? extends SortedMap<byte[], Long>> row : updates.entrySet()) { PutBuilder put = tableUtil.buildPut(row.getKey()); for (Map.Entry<byte[], Long> column : row.getValue().entrySet()) { put.add(columnFamily, column.getKey(), Bytes.toBytes(column.getValue())); } puts.add(put.build()); } try { hTable.put(puts); hTable.flushCommits(); } catch (IOException e) { throw new DataSetException("Put failed on table " + tableId, e); } } @Override public boolean swap(byte[] row, byte[] column, byte[] oldValue, byte[] newValue) { try { if (newValue == null) { // HBase API weirdness: we must use deleteColumns() because deleteColumn() deletes only the last version. Delete delete = tableUtil.buildDelete(row) .deleteColumns(columnFamily, column) .build(); return hTable.checkAndDelete(row, columnFamily, column, oldValue, delete); } else { Put put = tableUtil.buildPut(row) .add(columnFamily, column, newValue) .build(); return hTable.checkAndPut(row, columnFamily, column, oldValue, put); } } catch (IOException e) { throw new DataSetException("Swap failed on table " + tableId, e); } } @Override public void increment(byte[] row, Map<byte[], Long> increments) { Put increment = getIncrementalPut(row, increments); try { hTable.put(increment); hTable.flushCommits(); } catch (IOException e) { // figure out whether this is an illegal increment // currently there is not other way to extract that from the HBase exception than string match if (e.getMessage() != null && e.getMessage().contains("isn't 64 bits wide")) { throw new NumberFormatException("Attempted to increment a value that is not convertible to long," + " row: " + Bytes.toStringBinary(row)); } throw new DataSetException("Increment failed on table " + tableId, e); } } private Put getIncrementalPut(byte[] row, Map<byte[], Long> increments) { Put increment = getIncrementalPut(row); for (Map.Entry<byte[], Long> column : increments.entrySet()) { // note: we use default timestamp (current), which is fine because we know we collect metrics no more // frequent than each second. We also rely on same metric value to be processed by same metric processor // instance, so no conflicts are possible. increment.add(columnFamily, column.getKey(), Bytes.toBytes(column.getValue())); } return increment; } private Put getIncrementalPut(byte[] row) { return tableUtil.buildPut(row) .setAttribute(HBaseTable.DELTA_WRITE, Bytes.toBytes(true)) .build(); } @Override public void increment(NavigableMap<byte[], NavigableMap<byte[], Long>> updates) { List<Put> puts = Lists.newArrayList(); for (Map.Entry<byte[], NavigableMap<byte[], Long>> update : updates.entrySet()) { Put increment = getIncrementalPut(update.getKey(), update.getValue()); puts.add(increment); } try { hTable.put(puts); hTable.flushCommits(); } catch (IOException e) { // figure out whether this is an illegal increment // currently there is not other way to extract that from the HBase exception than string match if (e.getMessage() != null && e.getMessage().contains("isn't 64 bits wide")) { throw new NumberFormatException("Attempted to increment a value that is not convertible to long."); } throw new DataSetException("Increment failed on table " + tableId, e); } } @Override public long incrementAndGet(byte[] row, byte[] column, long delta) { Increment increment = new Increment(row); increment.addColumn(columnFamily, column, delta); try { Result result = hTable.increment(increment); return Bytes.toLong(result.getValue(columnFamily, column)); } catch (IOException e) { // figure out whether this is an illegal increment // currently there is not other way to extract that from the HBase exception than string match if (e.getMessage() != null && e.getMessage().contains("isn't 64 bits wide")) { throw new NumberFormatException("Attempted to increment a value that is not convertible to long," + " row: " + Bytes.toStringBinary(row) + " column: " + Bytes.toStringBinary(column)); } throw new DataSetException("IncrementAndGet failed on table " + tableId, e); } } @Override public void delete(byte[] row, byte[][] columns) { DeleteBuilder delete = tableUtil.buildDelete(row); for (byte[] column : columns) { delete.deleteColumns(columnFamily, column); } try { hTable.delete(delete.build()); } catch (IOException e) { throw new DataSetException("Delete failed on table " + tableId, e); } } @Override public Scanner scan(@Nullable byte[] startRow, @Nullable byte[] stopRow, @Nullable FuzzyRowFilter filter) { ScanBuilder scanBuilder = tableUtil.buildScan(); configureRangeScan(scanBuilder, startRow, stopRow, filter); try { ResultScanner resultScanner = hTable.getScanner(scanBuilder.build()); return new HBaseScanner(resultScanner, columnFamily); } catch (IOException e) { throw new DataSetException("Scan failed on table " + tableId, e); } } private ScanBuilder configureRangeScan(ScanBuilder scan, @Nullable byte[] startRow, @Nullable byte[] stopRow, @Nullable FuzzyRowFilter filter) { // todo: should be configurable scan.setCaching(1000); if (startRow != null) { scan.setStartRow(startRow); } if (stopRow != null) { scan.setStopRow(stopRow); } scan.addFamily(columnFamily); if (filter != null) { List<Pair<byte[], byte[]>> fuzzyPairs = Lists.newArrayListWithExpectedSize(filter.getFuzzyKeysData().size()); for (ImmutablePair<byte[], byte[]> pair : filter.getFuzzyKeysData()) { fuzzyPairs.add(Pair.newPair(pair.getFirst(), pair.getSecond())); } scan.setFilter(new org.apache.hadoop.hbase.filter.FuzzyRowFilter(fuzzyPairs)); } return scan; } @Override public void close() throws IOException { hTable.close(); } }
{ "content_hash": "e6a25307022e0c540fb0efd34b53ce4e", "timestamp": "", "source": "github", "line_count": 242, "max_line_length": 116, "avg_line_length": 38.735537190082646, "alnum_prop": 0.6764454875186686, "repo_name": "caskdata/cdap", "id": "f1675792e80ea8be13ccb2b705ebadf1a1eda2f2", "size": "9976", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "cdap-data-fabric/src/main/java/co/cask/cdap/data2/dataset2/lib/table/hbase/HBaseMetricsTable.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "26055" }, { "name": "CSS", "bytes": "478678" }, { "name": "HTML", "bytes": "647505" }, { "name": "Java", "bytes": "19722699" }, { "name": "JavaScript", "bytes": "2362906" }, { "name": "Python", "bytes": "166065" }, { "name": "Ruby", "bytes": "3178" }, { "name": "Scala", "bytes": "173411" }, { "name": "Shell", "bytes": "225202" }, { "name": "Visual Basic", "bytes": "870" } ], "symlink_target": "" }
package com.limpoxe.fairy.core.proxy.systemservice; import android.view.WindowManager; import com.limpoxe.fairy.core.FairyGlobal; import com.limpoxe.fairy.core.proxy.MethodDelegate; import com.limpoxe.fairy.core.proxy.ProxyUtil; import com.limpoxe.fairy.util.LogUtil; import java.lang.reflect.Method; /** * Created by cailiming on 16/1/15. * not used */ public class AndroidViewWindowManager extends MethodDelegate { public static WindowManager installProxy(Object invokeResult) { LogUtil.d("安装AndroidViewWindowManagerProxy"); WindowManager windowManager = (WindowManager)ProxyUtil.createProxy(invokeResult, new AndroidViewWindowManager()); LogUtil.d("安装完成"); return windowManager; } @Override public Object beforeInvoke(Object target, Method method, Object[] args) { if (args != null) { fixPackageName(method.getName(), args); } return super.beforeInvoke(target, method, args); } private void fixPackageName(String methodName, Object[] args) { if (methodName.equals("addView") || methodName.equals("updateViewLayout")) { for (Object object : args) { if (object instanceof WindowManager.LayoutParams) { LogUtil.v("修正WindowManager", methodName, "方法参数中的packageName", ((WindowManager.LayoutParams)object).packageName); ((WindowManager.LayoutParams)object).packageName = FairyGlobal.getHostApplication().getPackageName(); } } } } }
{ "content_hash": "16f18efac62c4beda5bf6ac7c0c8143b", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 132, "avg_line_length": 35.15909090909091, "alnum_prop": 0.6826115061409179, "repo_name": "limpoxe/Android-Plugin-Framework", "id": "8106c5ea226601714155715f162c171342f1c644", "size": "1575", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FairyPlugin/src/main/java/com/limpoxe/fairy/core/proxy/systemservice/AndroidViewWindowManager.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "746511" }, { "name": "Shell", "bytes": "693" } ], "symlink_target": "" }
from treesorting import * import unittest class TestEmpty(unittest.TestCase): def setUp(self): self.lines = [] self.tree = lines_to_tree(self.lines) def test_tree(self): empty_tree = Tree() self.assertEqual(empty_tree, self.tree) def test_tree_text(self): expected_text = None self.assertEqual(expected_text, self.tree.text) def test_string(self): self.assertEqual('', self.tree.to_string()) class TestSingleTree(unittest.TestCase): def setUp(self): self.lines = ['foo'] self.tree = lines_to_tree(self.lines) def test_text(self): expected_text = None self.assertEqual(expected_text, self.tree.text) def test_string(self): expected_string = "foo\n" self.assertEqual(expected_string, self.tree.to_string()) class TestOneDeep(unittest.TestCase): def setUp(self): self.lines = [] self.lines.append("foo") self.lines.append(" gaz") self.lines.append(" bar") self.tree = lines_to_tree(self.lines) def test_tree_text(self): """The root tree should not have any text.""" expected_text = None self.assertEqual(expected_text, self.tree.text) def test_tree_string(self): expected_string = "foo\n bar\n gaz\n" self.assertEqual(expected_string, self.tree.to_string()) class TestTwoTreesOneDeep(unittest.TestCase): def setUp(self): self.lines = [] self.lines.append('2') self.lines.append(" 2") self.lines.append(" 1") self.lines.append('1') self.lines.append(" 2") self.lines.append(" 1") self.tree = lines_to_tree(self.lines) def test_tree_string(self): expected_string = """1 1 2 2 1 2 """ self.assertEqual(expected_string, self.tree.to_string()) class TestTwoDeep(unittest.TestCase): def setUp(self): self.lines = [] self.lines.append('A') self.lines.append(" Ab") self.lines.append(" A2") self.lines.append(" A1") self.lines.append(" Aa") self.lines.append(" A2") self.lines.append(" A1") self.lines.append('B') self.lines.append(" Bb") self.lines.append(" B2") self.lines.append(" B1") self.lines.append(" Ba") self.lines.append(" B2") self.lines.append(" B1") self.tree = lines_to_tree(self.lines) self.tree_string = self.tree.to_string() def test_two_deep_tree_string(self): expected_string = """A Aa A1 A2 Ab A1 A2 B Ba B1 B2 Bb B1 B2 """ self.assertEqual(expected_string, self.tree.to_string()) class TestSorting(unittest.TestCase): def setUp(self): self.fruits = Tree('fruits') self.apple = Tree('apple') self.banana = Tree('banana') self.coconut = Tree('coconut') def assert_that_sub_trees_are_fruits_in_order(self, sub_trees): self.assertEqual('apple', sub_trees[0].text) self.assertEqual('banana', sub_trees[1].text) self.assertEqual('coconut', sub_trees[2].text) def test_adding_in_order(self): self.fruits.add_sub_tree(self.apple) self.fruits.add_sub_tree(self.banana) self.fruits.add_sub_tree(self.coconut) sub_trees = self.fruits.get_sub_trees() self.assert_that_sub_trees_are_fruits_in_order(sub_trees) def test_adding_out_of_order(self): self.fruits.add_sub_tree(self.banana) self.fruits.add_sub_tree(self.coconut) self.fruits.add_sub_tree(self.apple) self.fruits.finalise() sub_trees = self.fruits.get_sub_trees() self.assert_that_sub_trees_are_fruits_in_order(sub_trees) class TestTreesInFiles(unittest.TestCase): def setUp(self): with open('fixtures/two-deep.txt') as target_file: self.target = target_file.read() self.two_deep_unsorted = lines_to_tree(get_lines('fixtures/two-deep-unsorted.txt')) def test_remove_gaps(self): self.assertEqual(self.two_deep_unsorted.to_string(), self.target) class TestTreesSeparatedByGaps(unittest.TestCase): def setUp(self): with open('fixtures/two-deep.txt') as target_file: self.target = target_file.read() self.two_deep_with_gaps = lines_to_tree(get_lines('fixtures/two-deep-with-gaps.txt')) def test_remove_gaps_from_files(self): self.assertEqual(self.two_deep_with_gaps.to_string(), self.target) class TestTreesWithDuplicates(unittest.TestCase): def setUp(self): with open('fixtures/two-deep-with-duplicates.txt') as target_file: self.target = target_file.read() self.two_deep_unsorted = lines_to_tree(get_lines('fixtures/two-deep-with-duplicates-unsorted.txt')) def test_sort_with_duplicates(self): self.assertEqual(self.two_deep_unsorted.to_string(), self.target) class TestTreesOutputWithGaps(unittest.TestCase): def setUp(self): with open('fixtures/two-deep-with-gaps-sorted.txt') as target_file: self.target = target_file.read() self.two_deep_unsorted = lines_to_tree(get_lines('fixtures/two-deep-with-gaps.txt')) def test_sort_and_separate(self): self.assertEqual(self.two_deep_unsorted.to_string(separate_top_level=True), self.target)
{ "content_hash": "5c364ee6c148571ea165e4ddf88c4b86", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 107, "avg_line_length": 30.19672131147541, "alnum_prop": 0.6094824466159972, "repo_name": "robert-impey/tree-sorter", "id": "a5c6431c27ca402556f42013f9bffe218d0a5205", "size": "5550", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test_treesorter.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "20818" } ], "symlink_target": "" }
package net.jadecy.cmd; import java.util.Arrays; import net.jadecy.utils.MemPrintStream; public class JdcmComp_SPATH_Test extends AbstractJdcmTezt { //-------------------------------------------------------------------------- // PUBLIC METHODS //-------------------------------------------------------------------------- /* * Basic computations. */ public void test_classes() { // One shortest path from C2 to C4. final String[] args = getArgs("-spath " + C2N + " " + C4N); final MemPrintStream defaultStream = new MemPrintStream(); runArgsWithVirtualDeps(args, defaultStream); final String[] expectedLines = new String[]{ "args: " + Arrays.toString(args), "", C2N, C5N, C4N, "", "path length: 2", }; checkEqual(expectedLines, defaultStream); } public void test_packages() { // One shortest path from p1 to p2. final String[] args = getArgs("-spath " + P1N + " " + P2N + " -packages"); final MemPrintStream defaultStream = new MemPrintStream(); runArgsWithVirtualDeps(args, defaultStream); final String[] expectedLines = new String[]{ "args: " + Arrays.toString(args), "", P1N, " " + C2N, " " + C4N, P2N, "", "path length: 1", }; checkEqual(expectedLines, defaultStream); } /* * Advanced computations (only testing with classes). */ public void test_classes_noPath() { // No path. final String[] args = getArgs("-spath " + C2N + " nomatch"); final MemPrintStream defaultStream = new MemPrintStream(); runArgsWithVirtualDeps(args, defaultStream); final String[] expectedLines = new String[]{ "args: " + Arrays.toString(args), "", "no path", }; checkEqual(expectedLines, defaultStream); } public void test_classes_toSelf() { // One shortest path from C2 to C2. final String[] args = getArgs("-spath " + C2N + " " + C2N); final MemPrintStream defaultStream = new MemPrintStream(); runArgsWithVirtualDeps(args, defaultStream); final String[] expectedLines = new String[]{ "args: " + Arrays.toString(args), "", C2N, "", "path length: 0", }; checkEqual(expectedLines, defaultStream); } /* * Output options. */ public void test_packages_nocauses() { // One shortest path from p1 to p2, without causes. final String[] args = getArgs("-spath " + P1N + " " + P2N + " -packages" + " -nocauses"); final MemPrintStream defaultStream = new MemPrintStream(); runArgsWithVirtualDeps(args, defaultStream); final String[] expectedLines = new String[]{ "args: " + Arrays.toString(args), "", P1N, P2N, "", "path length: 1", }; checkEqual(expectedLines, defaultStream); } public void test_classes_nostats() { // One shortest path from C2 to C4. final String[] args = getArgs("-spath " + C2N + " " + C4N + " -nostats"); final MemPrintStream defaultStream = new MemPrintStream(); runArgsWithVirtualDeps(args, defaultStream); final String[] expectedLines = new String[]{ "args: " + Arrays.toString(args), "", C2N, C5N, C4N, }; checkEqual(expectedLines, defaultStream); } public void test_packages_nostats() { // One shortest path from p1 to p2. final String[] args = getArgs("-spath " + P1N + " " + P2N + " -packages" + " -nostats"); final MemPrintStream defaultStream = new MemPrintStream(); runArgsWithVirtualDeps(args, defaultStream); final String[] expectedLines = new String[]{ "args: " + Arrays.toString(args), "", P1N, " " + C2N, " " + C4N, P2N, }; checkEqual(expectedLines, defaultStream); } public void test_classes_onlystats() { // One shortest path from C2 to C4, only stats. final String[] args = getArgs("-spath " + C2N + " " + C4N + " -onlystats"); final MemPrintStream defaultStream = new MemPrintStream(); runArgsWithVirtualDeps(args, defaultStream); final String[] expectedLines = new String[]{ "args: " + Arrays.toString(args), "", "path length: 2", }; checkEqual(expectedLines, defaultStream); } public void test_packages_onlystats() { // One shortest path from p1 to p2, only stats. final String[] args = getArgs("-spath " + P1N + " " + P2N + " -packages" + " -onlystats"); final MemPrintStream defaultStream = new MemPrintStream(); runArgsWithVirtualDeps(args, defaultStream); final String[] expectedLines = new String[]{ "args: " + Arrays.toString(args), "", "path length: 1", }; checkEqual(expectedLines, defaultStream); } public void test_classes_dotformat() { // One shortest path from C2 to C4, in DOT format. final String[] args = getArgs("-spath " + C2N + " " + C4N + " -dotformat"); final MemPrintStream defaultStream = new MemPrintStream(); runArgsWithVirtualDeps(args, defaultStream); final String[] expectedLines = new String[]{ "// args: " + Arrays.toString(args), "digraph " + q("allsteps") + " {", " " + q(C2N) + " -> " + q(C5N) + ";", " " + q(C4N) + ";", " " + q(C5N) + " -> " + q(C4N) + ";", "}", }; checkEqual(expectedLines, defaultStream); } public void test_packages_dotformat() { // One shortest path from p1 to p2, in DOT format. final String[] args = getArgs("-spath " + P1N + " " + P2N + " -packages" + " -dotformat"); final MemPrintStream defaultStream = new MemPrintStream(); runArgsWithVirtualDeps(args, defaultStream); final String[] expectedLines = new String[]{ "// args: " + Arrays.toString(args), "digraph " + q("allsteps") + " {", " " + q(P1N) + " -> " + q(P2N) + ";", " " + q(P2N) + ";", "}", }; checkEqual(expectedLines, defaultStream); } }
{ "content_hash": "866d72c68fed47b376ec09beb4dc89a5", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 98, "avg_line_length": 32.26635514018692, "alnum_prop": 0.498913830557567, "repo_name": "jeffhain/jadecy", "id": "ac6579518f05e42109433f7fbe85e3dbc7ab70d1", "size": "7497", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/net/jadecy/cmd/JdcmComp_SPATH_Test.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3961" }, { "name": "Java", "bytes": "1764061" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Composer\Autoload; use Composer\ClassMapGenerator\ClassMap; use Composer\ClassMapGenerator\ClassMapGenerator; use Composer\Config; use Composer\EventDispatcher\EventDispatcher; use Composer\Filter\PlatformRequirementFilter\IgnoreAllPlatformRequirementFilter; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterInterface; use Composer\Installer\InstallationManager; use Composer\IO\IOInterface; use Composer\IO\NullIO; use Composer\Package\AliasPackage; use Composer\Package\PackageInterface; use Composer\Package\RootPackageInterface; use Composer\Pcre\Preg; use Composer\Repository\InstalledRepositoryInterface; use Composer\Semver\Constraint\Bound; use Composer\Util\Filesystem; use Composer\Util\Platform; use Composer\Script\ScriptEvents; use Composer\Util\PackageSorter; use Composer\Json\JsonFile; /** * @author Igor Wiedler <igor@wiedler.ch> * @author Jordi Boggiano <j.boggiano@seld.be> */ class AutoloadGenerator { /** * @var EventDispatcher */ private $eventDispatcher; /** * @var IOInterface */ private $io; /** * @var ?bool */ private $devMode = null; /** * @var bool */ private $classMapAuthoritative = false; /** * @var bool */ private $apcu = false; /** * @var string|null */ private $apcuPrefix; /** * @var bool */ private $runScripts = false; /** * @var PlatformRequirementFilterInterface */ private $platformRequirementFilter; public function __construct(EventDispatcher $eventDispatcher, ?IOInterface $io = null) { $this->eventDispatcher = $eventDispatcher; $this->io = $io ?? new NullIO(); $this->platformRequirementFilter = PlatformRequirementFilterFactory::ignoreNothing(); } /** * @return void */ public function setDevMode(bool $devMode = true) { $this->devMode = $devMode; } /** * Whether generated autoloader considers the class map authoritative. * * @return void */ public function setClassMapAuthoritative(bool $classMapAuthoritative) { $this->classMapAuthoritative = $classMapAuthoritative; } /** * Whether generated autoloader considers APCu caching. * * @return void */ public function setApcu(bool $apcu, ?string $apcuPrefix = null) { $this->apcu = $apcu; $this->apcuPrefix = $apcuPrefix !== null ? $apcuPrefix : $apcuPrefix; } /** * Whether to run scripts or not * * @return void */ public function setRunScripts(bool $runScripts = true) { $this->runScripts = $runScripts; } /** * Whether platform requirements should be ignored. * * If this is set to true, the platform check file will not be generated * If this is set to false, the platform check file will be generated with all requirements * If this is set to string[], those packages will be ignored from the platform check file * * @param bool|string[] $ignorePlatformReqs * @return void * * @deprecated use setPlatformRequirementFilter instead */ public function setIgnorePlatformRequirements($ignorePlatformReqs) { trigger_error('AutoloadGenerator::setIgnorePlatformRequirements is deprecated since Composer 2.2, use setPlatformRequirementFilter instead.', E_USER_DEPRECATED); $this->setPlatformRequirementFilter(PlatformRequirementFilterFactory::fromBoolOrList($ignorePlatformReqs)); } /** * @return void */ public function setPlatformRequirementFilter(PlatformRequirementFilterInterface $platformRequirementFilter) { $this->platformRequirementFilter = $platformRequirementFilter; } /** * @return ClassMap * @throws \Seld\JsonLint\ParsingException * @throws \RuntimeException */ public function dump(Config $config, InstalledRepositoryInterface $localRepo, RootPackageInterface $rootPackage, InstallationManager $installationManager, string $targetDir, bool $scanPsrPackages = false, ?string $suffix = null) { if ($this->classMapAuthoritative) { // Force scanPsrPackages when classmap is authoritative $scanPsrPackages = true; } // auto-set devMode based on whether dev dependencies are installed or not if (null === $this->devMode) { // we assume no-dev mode if no vendor dir is present or it is too old to contain dev information $this->devMode = false; $installedJson = new JsonFile($config->get('vendor-dir').'/composer/installed.json'); if ($installedJson->exists()) { $installedJson = $installedJson->read(); if (isset($installedJson['dev'])) { $this->devMode = $installedJson['dev']; } } } if ($this->runScripts) { // set COMPOSER_DEV_MODE in case not set yet so it is available in the dump-autoload event listeners if (!isset($_SERVER['COMPOSER_DEV_MODE'])) { Platform::putEnv('COMPOSER_DEV_MODE', $this->devMode ? '1' : '0'); } $this->eventDispatcher->dispatchScript(ScriptEvents::PRE_AUTOLOAD_DUMP, $this->devMode, [], [ 'optimize' => $scanPsrPackages, ]); } $classMapGenerator = new ClassMapGenerator(['php', 'inc', 'hh']); $classMapGenerator->avoidDuplicateScans(); $filesystem = new Filesystem(); $filesystem->ensureDirectoryExists($config->get('vendor-dir')); // Do not remove double realpath() calls. // Fixes failing Windows realpath() implementation. // See https://bugs.php.net/bug.php?id=72738 $basePath = $filesystem->normalizePath(realpath(realpath(Platform::getCwd()))); $vendorPath = $filesystem->normalizePath(realpath(realpath($config->get('vendor-dir')))); $useGlobalIncludePath = $config->get('use-include-path'); $prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true'; $targetDir = $vendorPath.'/'.$targetDir; $filesystem->ensureDirectoryExists($targetDir); $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true); $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true); $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true); $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode); $namespacesFile = <<<EOF <?php // autoload_namespaces.php @generated by Composer \$vendorDir = $vendorPathCode; \$baseDir = $appBaseDirCode; return array( EOF; $psr4File = <<<EOF <?php // autoload_psr4.php @generated by Composer \$vendorDir = $vendorPathCode; \$baseDir = $appBaseDirCode; return array( EOF; // Collect information from all packages. $devPackageNames = $localRepo->getDevPackageNames(); $packageMap = $this->buildPackageMap($installationManager, $rootPackage, $localRepo->getCanonicalPackages()); if ($this->devMode) { // if dev mode is enabled, then we do not filter any dev packages out so disable this entirely $filteredDevPackages = false; } else { // if the list of dev package names is available we use that straight, otherwise pass true which means use legacy algo to figure them out $filteredDevPackages = $devPackageNames ?: true; } $autoloads = $this->parseAutoloads($packageMap, $rootPackage, $filteredDevPackages); // Process the 'psr-0' base directories. foreach ($autoloads['psr-0'] as $namespace => $paths) { $exportedPaths = []; foreach ($paths as $path) { $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path); } $exportedPrefix = var_export($namespace, true); $namespacesFile .= " $exportedPrefix => "; $namespacesFile .= "array(".implode(', ', $exportedPaths)."),\n"; } $namespacesFile .= ");\n"; // Process the 'psr-4' base directories. foreach ($autoloads['psr-4'] as $namespace => $paths) { $exportedPaths = []; foreach ($paths as $path) { $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path); } $exportedPrefix = var_export($namespace, true); $psr4File .= " $exportedPrefix => "; $psr4File .= "array(".implode(', ', $exportedPaths)."),\n"; } $psr4File .= ");\n"; // add custom psr-0 autoloading if the root package has a target dir $targetDirLoader = null; $mainAutoload = $rootPackage->getAutoload(); if ($rootPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) { $levels = substr_count($filesystem->normalizePath($rootPackage->getTargetDir()), '/') + 1; $prefixes = implode(', ', array_map(static function ($prefix): string { return var_export($prefix, true); }, array_keys($mainAutoload['psr-0']))); $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true); $targetDirLoader = <<<EOF public static function autoload(\$class) { \$dir = $baseDirFromTargetDirCode . '/'; \$prefixes = array($prefixes); foreach (\$prefixes as \$prefix) { if (0 !== strpos(\$class, \$prefix)) { continue; } \$path = \$dir . implode('/', array_slice(explode('\\\\', \$class), $levels)).'.php'; if (!\$path = stream_resolve_include_path(\$path)) { return false; } require \$path; return true; } } EOF; } $excluded = null; if (!empty($autoloads['exclude-from-classmap'])) { $excluded = $autoloads['exclude-from-classmap']; } foreach ($autoloads['classmap'] as $dir) { $classMapGenerator->scanPaths($dir, $this->buildExclusionRegex($dir, $excluded)); } if ($scanPsrPackages) { $namespacesToScan = []; // Scan the PSR-0/4 directories for class files, and add them to the class map foreach (['psr-4', 'psr-0'] as $psrType) { foreach ($autoloads[$psrType] as $namespace => $paths) { $namespacesToScan[$namespace][] = ['paths' => $paths, 'type' => $psrType]; } } krsort($namespacesToScan); foreach ($namespacesToScan as $namespace => $groups) { foreach ($groups as $group) { foreach ($group['paths'] as $dir) { $dir = $filesystem->normalizePath($filesystem->isAbsolutePath($dir) ? $dir : $basePath.'/'.$dir); if (!is_dir($dir)) { continue; } $classMapGenerator->scanPaths($dir, $this->buildExclusionRegex($dir, $excluded), $group['type'], $namespace); } } } } $classMap = $classMapGenerator->getClassMap(); foreach ($classMap->getAmbiguousClasses() as $className => $ambiguousPaths) { if (count($ambiguousPaths) > 1) { $this->io->writeError( '<warning>Warning: Ambiguous class resolution, "'.$className.'"'. ' was found '. (count($ambiguousPaths) + 1) .'x: in "'.$classMap->getClassPath($className).'" and "'. implode('", "', $ambiguousPaths) .'", the first will be used.</warning>' ); } else { $this->io->writeError( '<warning>Warning: Ambiguous class resolution, "'.$className.'"'. ' was found in both "'.$classMap->getClassPath($className).'" and "'. implode('", "', $ambiguousPaths) .'", the first will be used.</warning>' ); } } foreach ($classMap->getPsrViolations() as $msg) { $this->io->writeError("<warning>$msg</warning>"); } $classMap->addClass('Composer\InstalledVersions', $vendorPath . '/composer/InstalledVersions.php'); $classMap->sort(); $classmapFile = <<<EOF <?php // autoload_classmap.php @generated by Composer \$vendorDir = $vendorPathCode; \$baseDir = $appBaseDirCode; return array( EOF; foreach ($classMap->getMap() as $className => $path) { $pathCode = $this->getPathCode($filesystem, $basePath, $vendorPath, $path).",\n"; $classmapFile .= ' '.var_export($className, true).' => '.$pathCode; } $classmapFile .= ");\n"; if ('' === $suffix) { $suffix = null; } if (null === $suffix) { $suffix = $config->get('autoloader-suffix'); // carry over existing autoload.php's suffix if possible and none is configured if (null === $suffix && Filesystem::isReadable($vendorPath.'/autoload.php')) { $content = file_get_contents($vendorPath.'/autoload.php'); if (Preg::isMatch('{ComposerAutoloaderInit([^:\s]+)::}', $content, $match)) { $suffix = $match[1]; } } // generate one if we still haven't got a suffix if (null === $suffix) { $suffix = md5(uniqid('', true)); } } $filesystem->filePutContentsIfModified($targetDir.'/autoload_namespaces.php', $namespacesFile); $filesystem->filePutContentsIfModified($targetDir.'/autoload_psr4.php', $psr4File); $filesystem->filePutContentsIfModified($targetDir.'/autoload_classmap.php', $classmapFile); $includePathFilePath = $targetDir.'/include_paths.php'; if ($includePathFileContents = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)) { $filesystem->filePutContentsIfModified($includePathFilePath, $includePathFileContents); } elseif (file_exists($includePathFilePath)) { unlink($includePathFilePath); } $includeFilesFilePath = $targetDir.'/autoload_files.php'; if ($includeFilesFileContents = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)) { $filesystem->filePutContentsIfModified($includeFilesFilePath, $includeFilesFileContents); } elseif (file_exists($includeFilesFilePath)) { unlink($includeFilesFilePath); } $filesystem->filePutContentsIfModified($targetDir.'/autoload_static.php', $this->getStaticFile($suffix, $targetDir, $vendorPath, $basePath)); $checkPlatform = $config->get('platform-check') !== false && !($this->platformRequirementFilter instanceof IgnoreAllPlatformRequirementFilter); $platformCheckContent = null; if ($checkPlatform) { $platformCheckContent = $this->getPlatformCheck($packageMap, $config->get('platform-check'), $devPackageNames); if (null === $platformCheckContent) { $checkPlatform = false; } } if ($checkPlatform) { $filesystem->filePutContentsIfModified($targetDir.'/platform_check.php', $platformCheckContent); } elseif (file_exists($targetDir.'/platform_check.php')) { unlink($targetDir.'/platform_check.php'); } $filesystem->filePutContentsIfModified($vendorPath.'/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix)); $filesystem->filePutContentsIfModified($targetDir.'/autoload_real.php', $this->getAutoloadRealFile(true, (bool) $includePathFileContents, $targetDirLoader, (bool) $includeFilesFileContents, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $checkPlatform)); $filesystem->safeCopy(__DIR__.'/ClassLoader.php', $targetDir.'/ClassLoader.php'); $filesystem->safeCopy(__DIR__.'/../../../LICENSE', $targetDir.'/LICENSE'); if ($this->runScripts) { $this->eventDispatcher->dispatchScript(ScriptEvents::POST_AUTOLOAD_DUMP, $this->devMode, [], [ 'optimize' => $scanPsrPackages, ]); } return $classMap; } /** * @param array<string>|null $excluded * @return non-empty-string|null */ private function buildExclusionRegex(string $dir, ?array $excluded): ?string { if (null === $excluded) { return null; } // filter excluded patterns here to only use those matching $dir // exclude-from-classmap patterns are all realpath'd so we can only filter them if $dir exists so that realpath($dir) will work // if $dir does not exist, it should anyway not find anything there so no trouble if (file_exists($dir)) { // transform $dir in the same way that exclude-from-classmap patterns are transformed so we can match them against each other $dirMatch = preg_quote(strtr(realpath($dir), '\\', '/')); foreach ($excluded as $index => $pattern) { // extract the constant string prefix of the pattern here, until we reach a non-escaped regex special character $pattern = Preg::replace('{^(([^.+*?\[^\]$(){}=!<>|:\\\\#-]+|\\\\[.+*?\[^\]$(){}=!<>|:#-])*).*}', '$1', $pattern); // if the pattern is not a subset or superset of $dir, it is unrelated and we skip it if (0 !== strpos($pattern, $dirMatch) && 0 !== strpos($dirMatch, $pattern)) { unset($excluded[$index]); } } } return \count($excluded) > 0 ? '{(' . implode('|', $excluded) . ')}' : null; } /** * @param PackageInterface[] $packages * @return array<int, array{0: PackageInterface, 1: string}> */ public function buildPackageMap(InstallationManager $installationManager, PackageInterface $rootPackage, array $packages) { // build package => install path map $packageMap = [[$rootPackage, '']]; foreach ($packages as $package) { if ($package instanceof AliasPackage) { continue; } $this->validatePackage($package); $packageMap[] = [ $package, $installationManager->getInstallPath($package), ]; } return $packageMap; } /** * @return void * @throws \InvalidArgumentException Throws an exception, if the package has illegal settings. */ protected function validatePackage(PackageInterface $package) { $autoload = $package->getAutoload(); if (!empty($autoload['psr-4']) && null !== $package->getTargetDir()) { $name = $package->getName(); $package->getTargetDir(); throw new \InvalidArgumentException("PSR-4 autoloading is incompatible with the target-dir property, remove the target-dir in package '$name'."); } if (!empty($autoload['psr-4'])) { foreach ($autoload['psr-4'] as $namespace => $dirs) { if ($namespace !== '' && '\\' !== substr($namespace, -1)) { throw new \InvalidArgumentException("psr-4 namespaces must end with a namespace separator, '$namespace' does not, use '$namespace\\'."); } } } } /** * Compiles an ordered list of namespace => path mappings * * @param array<int, array{0: PackageInterface, 1: string}> $packageMap array of array(package, installDir-relative-to-composer.json) * @param RootPackageInterface $rootPackage root package instance * @param bool|string[] $filteredDevPackages If an array, the list of packages that must be removed. If bool, whether to filter out require-dev packages * @return array * @phpstan-return array{ * 'psr-0': array<string, array<string>>, * 'psr-4': array<string, array<string>>, * 'classmap': array<int, string>, * 'files': array<string, string>, * 'exclude-from-classmap': array<int, string>, * } */ public function parseAutoloads(array $packageMap, PackageInterface $rootPackage, $filteredDevPackages = false) { $rootPackageMap = array_shift($packageMap); if (is_array($filteredDevPackages)) { $packageMap = array_filter($packageMap, static function ($item) use ($filteredDevPackages): bool { return !in_array($item[0]->getName(), $filteredDevPackages, true); }); } elseif ($filteredDevPackages) { $packageMap = $this->filterPackageMap($packageMap, $rootPackage); } $sortedPackageMap = $this->sortPackageMap($packageMap); $sortedPackageMap[] = $rootPackageMap; array_unshift($packageMap, $rootPackageMap); $psr0 = $this->parseAutoloadsType($packageMap, 'psr-0', $rootPackage); $psr4 = $this->parseAutoloadsType($packageMap, 'psr-4', $rootPackage); $classmap = $this->parseAutoloadsType(array_reverse($sortedPackageMap), 'classmap', $rootPackage); $files = $this->parseAutoloadsType($sortedPackageMap, 'files', $rootPackage); $exclude = $this->parseAutoloadsType($sortedPackageMap, 'exclude-from-classmap', $rootPackage); krsort($psr0); krsort($psr4); return [ 'psr-0' => $psr0, 'psr-4' => $psr4, 'classmap' => $classmap, 'files' => $files, 'exclude-from-classmap' => $exclude, ]; } /** * Registers an autoloader based on an autoload-map returned by parseAutoloads * * @param array<string, mixed[]> $autoloads see parseAutoloads return value * @return ClassLoader */ public function createLoader(array $autoloads, ?string $vendorDir = null) { $loader = new ClassLoader($vendorDir); if (isset($autoloads['psr-0'])) { foreach ($autoloads['psr-0'] as $namespace => $path) { $loader->add($namespace, $path); } } if (isset($autoloads['psr-4'])) { foreach ($autoloads['psr-4'] as $namespace => $path) { $loader->addPsr4($namespace, $path); } } if (isset($autoloads['classmap'])) { $excluded = null; if (!empty($autoloads['exclude-from-classmap'])) { $excluded = $autoloads['exclude-from-classmap']; } $classMapGenerator = new ClassMapGenerator(['php', 'inc', 'hh']); $classMapGenerator->avoidDuplicateScans(); foreach ($autoloads['classmap'] as $dir) { try { $classMapGenerator->scanPaths($dir, $this->buildExclusionRegex($dir, $excluded)); } catch (\RuntimeException $e) { $this->io->writeError('<warning>'.$e->getMessage().'</warning>'); } } $loader->addClassMap($classMapGenerator->getClassMap()->getMap()); } return $loader; } /** * @param array<int, array{0: PackageInterface, 1: string}> $packageMap * @return ?string */ protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, string $basePath, string $vendorPath, string $vendorPathCode, string $appBaseDirCode) { $includePaths = []; foreach ($packageMap as $item) { [$package, $installPath] = $item; if (null !== $package->getTargetDir() && strlen($package->getTargetDir()) > 0) { $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir())); } foreach ($package->getIncludePaths() as $includePath) { $includePath = trim($includePath, '/'); $includePaths[] = empty($installPath) ? $includePath : $installPath.'/'.$includePath; } } if (!$includePaths) { return null; } $includePathsCode = ''; foreach ($includePaths as $path) { $includePathsCode .= " " . $this->getPathCode($filesystem, $basePath, $vendorPath, $path) . ",\n"; } return <<<EOF <?php // include_paths.php @generated by Composer \$vendorDir = $vendorPathCode; \$baseDir = $appBaseDirCode; return array( $includePathsCode); EOF; } /** * @param array<string, string> $files * @return ?string */ protected function getIncludeFilesFile(array $files, Filesystem $filesystem, string $basePath, string $vendorPath, string $vendorPathCode, string $appBaseDirCode) { $filesCode = ''; foreach ($files as $fileIdentifier => $functionFile) { $filesCode .= ' ' . var_export($fileIdentifier, true) . ' => ' . $this->getPathCode($filesystem, $basePath, $vendorPath, $functionFile) . ",\n"; } if (!$filesCode) { return null; } return <<<EOF <?php // autoload_files.php @generated by Composer \$vendorDir = $vendorPathCode; \$baseDir = $appBaseDirCode; return array( $filesCode); EOF; } /** * @return string */ protected function getPathCode(Filesystem $filesystem, string $basePath, string $vendorPath, string $path) { if (!$filesystem->isAbsolutePath($path)) { $path = $basePath . '/' . $path; } $path = $filesystem->normalizePath($path); $baseDir = ''; if (strpos($path.'/', $vendorPath.'/') === 0) { $path = (string) substr($path, strlen($vendorPath)); $baseDir = '$vendorDir . '; } else { $path = $filesystem->normalizePath($filesystem->findShortestPath($basePath, $path, true)); if (!$filesystem->isAbsolutePath($path)) { $baseDir = '$baseDir . '; $path = '/' . $path; } } if (strpos($path, '.phar') !== false) { $baseDir = "'phar://' . " . $baseDir; } return $baseDir . var_export($path, true); } /** * @param array<int, array{0: PackageInterface, 1: string}> $packageMap * @param bool|'php-only' $checkPlatform * @param string[] $devPackageNames * @return ?string */ protected function getPlatformCheck(array $packageMap, $checkPlatform, array $devPackageNames) { $lowestPhpVersion = Bound::zero(); $requiredExtensions = []; $extensionProviders = []; foreach ($packageMap as $item) { $package = $item[0]; foreach (array_merge($package->getReplaces(), $package->getProvides()) as $link) { if (Preg::isMatch('{^ext-(.+)$}iD', $link->getTarget(), $match)) { $extensionProviders[$match[1]][] = $link->getConstraint(); } } } foreach ($packageMap as $item) { $package = $item[0]; // skip dev dependencies platform requirements as platform-check really should only be a production safeguard if (in_array($package->getName(), $devPackageNames, true)) { continue; } foreach ($package->getRequires() as $link) { if ($this->platformRequirementFilter->isIgnored($link->getTarget())) { continue; } if ('php' === $link->getTarget()) { $constraint = $link->getConstraint(); if ($constraint->getLowerBound()->compareTo($lowestPhpVersion, '>')) { $lowestPhpVersion = $constraint->getLowerBound(); } } if ($checkPlatform === true && Preg::isMatch('{^ext-(.+)$}iD', $link->getTarget(), $match)) { // skip extension checks if they have a valid provider/replacer if (isset($extensionProviders[$match[1]])) { foreach ($extensionProviders[$match[1]] as $provided) { if ($provided->matches($link->getConstraint())) { continue 2; } } } if ($match[1] === 'zend-opcache') { $match[1] = 'zend opcache'; } $extension = var_export($match[1], true); if ($match[1] === 'pcntl' || $match[1] === 'readline') { $requiredExtensions[$extension] = "PHP_SAPI !== 'cli' || extension_loaded($extension) || \$missingExtensions[] = $extension;\n"; } else { $requiredExtensions[$extension] = "extension_loaded($extension) || \$missingExtensions[] = $extension;\n"; } } } } ksort($requiredExtensions); $formatToPhpVersionId = static function (Bound $bound): int { if ($bound->isZero()) { return 0; } if ($bound->isPositiveInfinity()) { return 99999; } $version = str_replace('-', '.', $bound->getVersion()); $chunks = array_map('intval', explode('.', $version)); return $chunks[0] * 10000 + $chunks[1] * 100 + $chunks[2]; }; $formatToHumanReadable = static function (Bound $bound) { if ($bound->isZero()) { return 0; } if ($bound->isPositiveInfinity()) { return 99999; } $version = str_replace('-', '.', $bound->getVersion()); $chunks = explode('.', $version); $chunks = array_slice($chunks, 0, 3); return implode('.', $chunks); }; $requiredPhp = ''; $requiredPhpError = ''; if (!$lowestPhpVersion->isZero()) { $operator = $lowestPhpVersion->isInclusive() ? '>=' : '>'; $requiredPhp = 'PHP_VERSION_ID '.$operator.' '.$formatToPhpVersionId($lowestPhpVersion); $requiredPhpError = '"'.$operator.' '.$formatToHumanReadable($lowestPhpVersion).'"'; } if ($requiredPhp) { $requiredPhp = <<<PHP_CHECK if (!($requiredPhp)) { \$issues[] = 'Your Composer dependencies require a PHP version $requiredPhpError. You are running ' . PHP_VERSION . '.'; } PHP_CHECK; } $requiredExtensions = implode('', $requiredExtensions); if ('' !== $requiredExtensions) { $requiredExtensions = <<<EXT_CHECKS \$missingExtensions = array(); $requiredExtensions if (\$missingExtensions) { \$issues[] = 'Your Composer dependencies require the following PHP extensions to be installed: ' . implode(', ', \$missingExtensions) . '.'; } EXT_CHECKS; } if (!$requiredPhp && !$requiredExtensions) { return null; } return <<<PLATFORM_CHECK <?php // platform_check.php @generated by Composer \$issues = array(); {$requiredPhp}{$requiredExtensions} if (\$issues) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, \$issues) . PHP_EOL.PHP_EOL); } elseif (!headers_sent()) { echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, \$issues)) . PHP_EOL.PHP_EOL; } } trigger_error( 'Composer detected issues in your platform: ' . implode(' ', \$issues), E_USER_ERROR ); } PLATFORM_CHECK; } /** * @return string */ protected function getAutoloadFile(string $vendorPathToTargetDirCode, string $suffix) { $lastChar = $vendorPathToTargetDirCode[strlen($vendorPathToTargetDirCode) - 1]; if ("'" === $lastChar || '"' === $lastChar) { $vendorPathToTargetDirCode = substr($vendorPathToTargetDirCode, 0, -1).'/autoload_real.php'.$lastChar; } else { $vendorPathToTargetDirCode .= " . '/autoload_real.php'"; } return <<<AUTOLOAD <?php // autoload.php @generated by Composer if (PHP_VERSION_ID < 50600) { echo 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL; exit(1); } require_once $vendorPathToTargetDirCode; return ComposerAutoloaderInit$suffix::getLoader(); AUTOLOAD; } /** * @param string $vendorPathCode unused in this method * @param string $appBaseDirCode unused in this method * @param string $prependAutoloader 'true'|'false' * @return string */ protected function getAutoloadRealFile(bool $useClassMap, bool $useIncludePath, ?string $targetDirLoader, bool $useIncludeFiles, string $vendorPathCode, string $appBaseDirCode, string $suffix, bool $useGlobalIncludePath, string $prependAutoloader, bool $checkPlatform) { $file = <<<HEADER <?php // autoload_real.php @generated by Composer class ComposerAutoloaderInit$suffix { private static \$loader; public static function loadClassLoader(\$class) { if ('Composer\\Autoload\\ClassLoader' === \$class) { require __DIR__ . '/ClassLoader.php'; } } /** * @return \Composer\Autoload\ClassLoader */ public static function getLoader() { if (null !== self::\$loader) { return self::\$loader; } HEADER; if ($checkPlatform) { $file .= <<<'PLATFORM_CHECK' require __DIR__ . '/platform_check.php'; PLATFORM_CHECK; } $file .= <<<CLASSLOADER_INIT spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'), true, $prependAutoloader); self::\$loader = \$loader = new \\Composer\\Autoload\\ClassLoader(\\dirname(__DIR__)); spl_autoload_unregister(array('ComposerAutoloaderInit$suffix', 'loadClassLoader')); CLASSLOADER_INIT; if ($useIncludePath) { $file .= <<<'INCLUDE_PATH' $includePaths = require __DIR__ . '/include_paths.php'; $includePaths[] = get_include_path(); set_include_path(implode(PATH_SEPARATOR, $includePaths)); INCLUDE_PATH; } // keeping PHP 5.6+ compatibility for the autoloader here by using call_user_func vs getInitializer()() $file .= <<<STATIC_INIT require __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInit$suffix::getInitializer(\$loader)); STATIC_INIT; if ($this->classMapAuthoritative) { $file .= <<<'CLASSMAPAUTHORITATIVE' $loader->setClassMapAuthoritative(true); CLASSMAPAUTHORITATIVE; } if ($this->apcu) { $apcuPrefix = var_export(($this->apcuPrefix !== null ? $this->apcuPrefix : substr(base64_encode(md5(uniqid('', true), true)), 0, -3)), true); $file .= <<<APCU \$loader->setApcuPrefix($apcuPrefix); APCU; } if ($useGlobalIncludePath) { $file .= <<<'INCLUDEPATH' $loader->setUseIncludePath(true); INCLUDEPATH; } if ($targetDirLoader) { $file .= <<<REGISTER_TARGET_DIR_AUTOLOAD spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'autoload'), true, true); REGISTER_TARGET_DIR_AUTOLOAD; } $file .= <<<REGISTER_LOADER \$loader->register($prependAutoloader); REGISTER_LOADER; if ($useIncludeFiles) { $file .= <<<INCLUDE_FILES \$filesToLoad = \Composer\Autoload\ComposerStaticInit$suffix::\$files; \$requireFile = static function (\$fileIdentifier, \$file) { if (empty(\$GLOBALS['__composer_autoload_files'][\$fileIdentifier])) { \$GLOBALS['__composer_autoload_files'][\$fileIdentifier] = true; require \$file; } }; foreach (\$filesToLoad as \$fileIdentifier => \$file) { (\$requireFile)(\$fileIdentifier, \$file); } INCLUDE_FILES; } $file .= <<<METHOD_FOOTER return \$loader; } METHOD_FOOTER; $file .= $targetDirLoader; return $file . <<<FOOTER } FOOTER; } /** * @param string $vendorPath input for findShortestPathCode * @param string $basePath input for findShortestPathCode * @return string */ protected function getStaticFile(string $suffix, string $targetDir, string $vendorPath, string $basePath) { $file = <<<HEADER <?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInit$suffix { HEADER; $loader = new ClassLoader(); $map = require $targetDir . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require $targetDir . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require $targetDir . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } $filesystem = new Filesystem(); $vendorPathCode = ' => ' . $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true, true) . " . '/"; $vendorPharPathCode = ' => \'phar://\' . ' . $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true, true) . " . '/"; $appBaseDirCode = ' => ' . $filesystem->findShortestPathCode(realpath($targetDir), $basePath, true, true) . " . '/"; $appBaseDirPharCode = ' => \'phar://\' . ' . $filesystem->findShortestPathCode(realpath($targetDir), $basePath, true, true) . " . '/"; $absoluteVendorPathCode = ' => ' . substr(var_export(rtrim($vendorDir, '\\/') . '/', true), 0, -1); $absoluteVendorPharPathCode = ' => ' . substr(var_export(rtrim('phar://' . $vendorDir, '\\/') . '/', true), 0, -1); $absoluteAppBaseDirCode = ' => ' . substr(var_export(rtrim($baseDir, '\\/') . '/', true), 0, -1); $absoluteAppBaseDirPharCode = ' => ' . substr(var_export(rtrim('phar://' . $baseDir, '\\/') . '/', true), 0, -1); $initializer = ''; $prefix = "\0Composer\Autoload\ClassLoader\0"; $prefixLen = strlen($prefix); if (file_exists($targetDir . '/autoload_files.php')) { $maps = ['files' => require $targetDir . '/autoload_files.php']; } else { $maps = []; } foreach ((array) $loader as $prop => $value) { if (!is_array($value) || \count($value) === 0 || !str_starts_with($prop, $prefix)) { continue; } $maps[substr($prop, $prefixLen)] = $value; } foreach ($maps as $prop => $value) { $value = strtr( var_export($value, true), [ $absoluteVendorPathCode => $vendorPathCode, $absoluteVendorPharPathCode => $vendorPharPathCode, $absoluteAppBaseDirCode => $appBaseDirCode, $absoluteAppBaseDirPharCode => $appBaseDirPharCode, ] ); $value = ltrim(Preg::replace('/^ */m', ' $0$0', $value)); $file .= sprintf(" public static $%s = %s;\n\n", $prop, $value); if ('files' !== $prop) { $initializer .= " \$loader->$prop = ComposerStaticInit$suffix::\$$prop;\n"; } } return $file . <<<INITIALIZER public static function getInitializer(ClassLoader \$loader) { return \Closure::bind(function () use (\$loader) { $initializer }, null, ClassLoader::class); } } INITIALIZER; } /** * @param array<int, array{0: PackageInterface, 1: string}> $packageMap * @param string $type one of: 'psr-0'|'psr-4'|'classmap'|'files' * @return array<int, string>|array<string, array<string>>|array<string, string> */ protected function parseAutoloadsType(array $packageMap, string $type, RootPackageInterface $rootPackage) { $autoloads = []; foreach ($packageMap as $item) { [$package, $installPath] = $item; $autoload = $package->getAutoload(); if ($this->devMode && $package === $rootPackage) { $autoload = array_merge_recursive($autoload, $package->getDevAutoload()); } // skip misconfigured packages if (!isset($autoload[$type]) || !is_array($autoload[$type])) { continue; } if (null !== $package->getTargetDir() && $package !== $rootPackage) { $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir())); } foreach ($autoload[$type] as $namespace => $paths) { foreach ((array) $paths as $path) { if (($type === 'files' || $type === 'classmap' || $type === 'exclude-from-classmap') && $package->getTargetDir() && !Filesystem::isReadable($installPath.'/'.$path)) { // remove target-dir from file paths of the root package if ($package === $rootPackage) { $targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(['/', '\\'], '<dirsep>', $package->getTargetDir()))); $path = ltrim(Preg::replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/'); } else { // add target-dir from file paths that don't have it $path = $package->getTargetDir() . '/' . $path; } } if ($type === 'exclude-from-classmap') { // first escape user input $path = Preg::replace('{/+}', '/', preg_quote(trim(strtr($path, '\\', '/'), '/'))); // add support for wildcards * and ** $path = strtr($path, ['\\*\\*' => '.+?', '\\*' => '[^/]+?']); // add support for up-level relative paths $updir = null; $path = Preg::replaceCallback( '{^((?:(?:\\\\\\.){1,2}+/)+)}', static function ($matches) use (&$updir): string { if (isset($matches[1])) { // undo preg_quote for the matched string $updir = str_replace('\\.', '.', $matches[1]); } return ''; }, $path ); if (empty($installPath)) { $installPath = strtr(Platform::getCwd(), '\\', '/'); } $resolvedPath = realpath($installPath . '/' . $updir); if (false === $resolvedPath) { continue; } $autoloads[] = preg_quote(strtr($resolvedPath, '\\', '/')) . '/' . $path . '($|/)'; continue; } $relativePath = empty($installPath) ? (empty($path) ? '.' : $path) : $installPath.'/'.$path; if ($type === 'files') { $autoloads[$this->getFileIdentifier($package, $path)] = $relativePath; continue; } if ($type === 'classmap') { $autoloads[] = $relativePath; continue; } $autoloads[$namespace][] = $relativePath; } } } return $autoloads; } /** * @return string */ protected function getFileIdentifier(PackageInterface $package, string $path) { return md5($package->getName() . ':' . $path); } /** * Filters out dev-dependencies * * @param array<int, array{0: PackageInterface, 1: string}> $packageMap * @return array<int, array{0: PackageInterface, 1: string}> * * @phpstan-param array<int, array{0: PackageInterface, 1: string}> $packageMap */ protected function filterPackageMap(array $packageMap, RootPackageInterface $rootPackage) { $packages = []; $include = []; $replacedBy = []; foreach ($packageMap as $item) { $package = $item[0]; $name = $package->getName(); $packages[$name] = $package; foreach ($package->getReplaces() as $replace) { $replacedBy[$replace->getTarget()] = $name; } } $add = static function (PackageInterface $package) use (&$add, $packages, &$include, $replacedBy): void { foreach ($package->getRequires() as $link) { $target = $link->getTarget(); if (isset($replacedBy[$target])) { $target = $replacedBy[$target]; } if (!isset($include[$target])) { $include[$target] = true; if (isset($packages[$target])) { $add($packages[$target]); } } } }; $add($rootPackage); return array_filter( $packageMap, static function ($item) use ($include): bool { $package = $item[0]; foreach ($package->getNames() as $name) { if (isset($include[$name])) { return true; } } return false; } ); } /** * Sorts packages by dependency weight * * Packages of equal weight are sorted alphabetically * * @param array<int, array{0: PackageInterface, 1: string}> $packageMap * @return array<int, array{0: PackageInterface, 1: string}> */ protected function sortPackageMap(array $packageMap) { $packages = []; $paths = []; foreach ($packageMap as $item) { [$package, $path] = $item; $name = $package->getName(); $packages[$name] = $package; $paths[$name] = $path; } $sortedPackages = PackageSorter::sortPackages($packages); $sortedPackageMap = []; foreach ($sortedPackages as $package) { $name = $package->getName(); $sortedPackageMap[] = [$packages[$name], $paths[$name]]; } return $sortedPackageMap; } } function composerRequire(string $fileIdentifier, string $file): void { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; require $file; } }
{ "content_hash": "1d1f32cc7ea402df63506b6d3e7c64c9", "timestamp": "", "source": "github", "line_count": 1318, "max_line_length": 301, "avg_line_length": 36.443854324734446, "alnum_prop": 0.5539108529552599, "repo_name": "staabm/composer", "id": "921ba6b6ee15f4bfd2a43edd657036fd9e75dc1d", "size": "48293", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/Composer/Autoload/AutoloadGenerator.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "3578498" } ], "symlink_target": "" }
package com.amazonaws.services.rds.model.transform; import org.w3c.dom.Node; import javax.annotation.Generated; import com.amazonaws.AmazonServiceException; import com.amazonaws.transform.StandardErrorUnmarshaller; import com.amazonaws.services.rds.model.SharedSnapshotQuotaExceededException; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class SharedSnapshotQuotaExceededExceptionUnmarshaller extends StandardErrorUnmarshaller { public SharedSnapshotQuotaExceededExceptionUnmarshaller() { super(SharedSnapshotQuotaExceededException.class); } @Override public AmazonServiceException unmarshall(Node node) throws Exception { // Bail out if this isn't the right error code that this // marshaller understands String errorCode = parseErrorCode(node); if (errorCode == null || !errorCode.equals("SharedSnapshotQuotaExceeded")) return null; SharedSnapshotQuotaExceededException e = (SharedSnapshotQuotaExceededException) super.unmarshall(node); return e; } }
{ "content_hash": "af5e379216e78069f319a42c6888f815", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 111, "avg_line_length": 33.40625, "alnum_prop": 0.7680074836295603, "repo_name": "dagnir/aws-sdk-java", "id": "7d186e277742a22d08c3f5ad230e001ab9988802", "size": "1649", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-rds/src/main/java/com/amazonaws/services/rds/model/transform/SharedSnapshotQuotaExceededExceptionUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "157317" }, { "name": "Gherkin", "bytes": "25556" }, { "name": "Java", "bytes": "165755153" }, { "name": "Scilab", "bytes": "3561" } ], "symlink_target": "" }
package mesosphere.marathon import java.time.Clock import mesosphere.AkkaUnitTest import mesosphere.marathon.core.instance.TestInstanceBuilder import mesosphere.marathon.core.instance.TestInstanceBuilder._ import mesosphere.marathon.core.instance.update.{ InstanceUpdateEffect, InstanceUpdateOperation } import mesosphere.marathon.core.launcher.impl.InstanceOpFactoryHelper import mesosphere.marathon.core.launcher.{ InstanceOpFactory, OfferMatchResult } import mesosphere.marathon.core.launchqueue.LaunchQueueModule import mesosphere.marathon.core.leadership.AlwaysElectedLeadershipModule import mesosphere.marathon.core.matcher.DummyOfferMatcherManager import mesosphere.marathon.core.matcher.base.util.OfferMatcherSpec import mesosphere.marathon.core.task.Task import mesosphere.marathon.core.task.bus.TaskStatusUpdateTestHelper import mesosphere.marathon.core.task.tracker.InstanceTracker import mesosphere.marathon.integration.setup.WaitTestSupport import mesosphere.marathon.state.PathId import mesosphere.marathon.test.MarathonTestHelper import org.mockito.Matchers import scala.concurrent.duration._ class LaunchQueueModuleTest extends AkkaUnitTest with OfferMatcherSpec { def fixture(fn: Fixture => Unit): Unit = { val f = new Fixture try fn(f) finally f.close() } "LaunchQueueModule" should { "empty queue returns no results" in fixture { f => import f._ When("querying queue") val apps = launchQueue.list Then("no apps are returned") apps should be(empty) And("there should be no more interactions") f.verifyNoMoreInteractions() } "An added queue item is returned in list" in fixture { f => import f._ Given("a launch queue with one item") instanceTracker.instancesBySpecSync returns InstanceTracker.InstancesBySpec.empty launchQueue.add(app) When("querying its contents") val list = launchQueue.list Then("we get back the added app") list should have size 1 list.head.runSpec should equal(app) list.head.instancesLeftToLaunch should equal(1) list.head.finalInstanceCount should equal(1) list.head.inProgress should equal(true) verify(instanceTracker).instancesBySpecSync And("there should be no more interactions") f.verifyNoMoreInteractions() } "An added queue item is reflected via count" in fixture { f => import f._ Given("a launch queue with one item") instanceTracker.instancesBySpecSync returns InstanceTracker.InstancesBySpec.empty launchQueue.add(app) When("querying its count") val count = launchQueue.count(app.id) Then("we get a count == 1") count should be(1) verify(instanceTracker).instancesBySpecSync And("there should be no more interactions") f.verifyNoMoreInteractions() } "A purged queue item has a count of 0" in fixture { f => import f._ Given("a launch queue with one item which is purged") instanceTracker.instancesBySpecSync returns InstanceTracker.InstancesBySpec.empty launchQueue.add(app) launchQueue.asyncPurge(app.id).futureValue When("querying its count") val count = launchQueue.count(app.id) Then("we get a count == 0") count should be(0) verify(instanceTracker).instancesBySpecSync And("there should be no more interactions") f.verifyNoMoreInteractions() } "A re-added queue item has a count of 1" in fixture { f => import f._ Given("a launch queue with one item which is purged") instanceTracker.instancesBySpecSync returns InstanceTracker.InstancesBySpec.empty launchQueue.add(app) launchQueue.asyncPurge(app.id).futureValue launchQueue.add(app) When("querying its count") val count = launchQueue.count(app.id) Then("we get a count == 1") count should be(1) verify(instanceTracker, times(2)).instancesBySpecSync And("there should be no more interactions") f.verifyNoMoreInteractions() } "adding a queue item registers new offer matcher" in fixture { f => import f._ Given("An empty task tracker") instanceTracker.instancesBySpecSync returns InstanceTracker.InstancesBySpec.empty When("Adding an app to the launchQueue") launchQueue.add(app) Then("A new offer matcher gets registered") WaitTestSupport.waitUntil("registered as offer matcher", 1.second) { offerMatcherManager.offerMatchers.size == 1 } verify(instanceTracker).instancesBySpecSync And("there should be no more interactions") f.verifyNoMoreInteractions() } "purging a queue item UNregisters offer matcher" in fixture { f => import f._ Given("An app in the queue") instanceTracker.instancesBySpecSync returns InstanceTracker.InstancesBySpec.empty launchQueue.add(app) When("The app is purged") launchQueue.asyncPurge(app.id).futureValue Then("No offer matchers remain registered") offerMatcherManager.offerMatchers should be(empty) verify(instanceTracker).instancesBySpecSync And("there should be no more interactions") f.verifyNoMoreInteractions() } "an offer gets unsuccessfully matched against an item in the queue" in fixture { f => import f._ Given("An app in the queue") instanceTracker.instancesBySpecSync returns InstanceTracker.InstancesBySpec.empty launchQueue.add(app) WaitTestSupport.waitUntil("registered as offer matcher", 1.second) { offerMatcherManager.offerMatchers.size == 1 } When("we ask for matching an offer") instanceOpFactory.matchOfferRequest(Matchers.any()) returns noMatchResult val matchFuture = offerMatcherManager.offerMatchers.head.matchOffer(offer) val matchedTasks = matchFuture.futureValue Then("the offer gets passed to the task factory and respects the answer") val request = InstanceOpFactory.Request(app, offer, Map.empty, additionalLaunches = 1) verify(instanceOpFactory).matchOfferRequest(request) matchedTasks.offerId should equal(offer.getId) matchedTasks.opsWithSource should equal(Seq.empty) verify(instanceTracker).instancesBySpecSync And("there should be no more interactions") f.verifyNoMoreInteractions() } "an offer gets successfully matched against an item in the queue" in fixture { f => import f._ Given("An app in the queue") instanceTracker.instancesBySpecSync returns InstanceTracker.InstancesBySpec.empty launchQueue.add(app) WaitTestSupport.waitUntil("registered as offer matcher", 1.second) { offerMatcherManager.offerMatchers.size == 1 } When("we ask for matching an offer") instanceOpFactory.matchOfferRequest(Matchers.any()) returns launchResult val matchFuture = offerMatcherManager.offerMatchers.head.matchOffer(offer) val matchedTasks = matchFuture.futureValue Then("the offer gets passed to the task factory and respects the answer") val request = InstanceOpFactory.Request(app, offer, Map.empty, additionalLaunches = 1) verify(instanceOpFactory).matchOfferRequest(request) matchedTasks.offerId should equal(offer.getId) launchedTaskInfos(matchedTasks) should equal(Seq(mesosTask)) verify(instanceTracker).instancesBySpecSync And("there should be no more interactions") f.verifyNoMoreInteractions() } "TaskChanged updates are answered immediately for suspended queue entries" in fixture { f => // otherwise we get a deadlock in some cases, see comment in LaunchQueueActor import f._ Given("An app in the queue") instanceTracker.instancesBySpecSync returns InstanceTracker.InstancesBySpec.empty launchQueue.add(app, 3) WaitTestSupport.waitUntil("registered as offer matcher", 1.second) { offerMatcherManager.offerMatchers.size == 1 } And("a task gets launched but not confirmed") instanceOpFactory.matchOfferRequest(Matchers.any()) returns launchResult val matchFuture = offerMatcherManager.offerMatchers.head.matchOffer(offer) matchFuture.futureValue And("test app gets purged (but not stopped yet because of in-flight tasks)") launchQueue.asyncPurge(app.id) WaitTestSupport.waitUntil("purge gets executed", 1.second) { !launchQueue.list.exists(_.runSpec.id == app.id) } reset(instanceTracker, instanceOpFactory) When("we send a related task change") launchQueue.notifyOfInstanceUpdate(instanceChange).futureValue Then("there should be no more interactions") f.verifyNoMoreInteractions() } } class Fixture extends AutoCloseable { val app = MarathonTestHelper.makeBasicApp().copy(id = PathId("/app")) val offer = MarathonTestHelper.makeBasicOffer().build() val runspecId = PathId("/test") val instance = TestInstanceBuilder.newBuilder(runspecId).addTaskWithBuilder().taskRunning().build().getInstance() val task: Task = instance.appTask val mesosTask = MarathonTestHelper.makeOneCPUTask(task.taskId).build() val launch = new InstanceOpFactoryHelper(Some("principal"), Some("role")). launchEphemeral(mesosTask, task, instance) val instanceChange = TaskStatusUpdateTestHelper( operation = InstanceUpdateOperation.LaunchEphemeral(instance), effect = InstanceUpdateEffect.Update(instance = instance, oldState = None, events = Nil)).wrapped lazy val clock: Clock = Clock.systemUTC() val noMatchResult = OfferMatchResult.NoMatch(app, offer, Seq.empty, clock.now()) val launchResult = OfferMatchResult.Match(app, offer, launch, clock.now()) lazy val offerMatcherManager: DummyOfferMatcherManager = new DummyOfferMatcherManager() lazy val instanceTracker: InstanceTracker = mock[InstanceTracker] lazy val instanceOpFactory: InstanceOpFactory = mock[InstanceOpFactory] lazy val config = MarathonTestHelper.defaultConfig() lazy val parentActor = newTestActor() lazy val localRegion = () => None lazy val module: LaunchQueueModule = new LaunchQueueModule( config, AlwaysElectedLeadershipModule.forRefFactory(parentActor.underlying), clock, subOfferMatcherManager = offerMatcherManager, maybeOfferReviver = None, instanceTracker, instanceOpFactory, localRegion ) def launchQueue = module.launchQueue def verifyNoMoreInteractions(): Unit = { noMoreInteractions(instanceTracker) noMoreInteractions(instanceOpFactory) } def close(): Unit = { parentActor.stop() } } }
{ "content_hash": "6ca9ee5b0786c67f0531202a8c61956b", "timestamp": "", "source": "github", "line_count": 288, "max_line_length": 117, "avg_line_length": 37.232638888888886, "alnum_prop": 0.7247039074885759, "repo_name": "guenter/marathon", "id": "b7ef2f31895966c4b61e4594a0844a3201bd3001", "size": "10723", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/scala/mesosphere/marathon/LaunchQueueModuleTest.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Clojure", "bytes": "59270" }, { "name": "Groovy", "bytes": "14255" }, { "name": "HTML", "bytes": "502" }, { "name": "Java", "bytes": "778" }, { "name": "Makefile", "bytes": "4005" }, { "name": "Python", "bytes": "169779" }, { "name": "Ruby", "bytes": "772" }, { "name": "Scala", "bytes": "4280011" }, { "name": "Shell", "bytes": "41549" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Dashboard extends CI_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see https://codeigniter.com/user_guide/general/urls.html */ public function __construct() { parent::__construct(); $this->load->library('upload'); } public function index() { $query = $this->db->query('SELECT COUNT(KodSekolah) AS val FROM senarai_sekolah'); $data['total_senarai_sekolah'] = $query->row(); $query = $this->db->query('SELECT COUNT(KodSekolah) AS val FROM senarai_sekolah AS ss INNER JOIN assessment AS a ON ss.KodSekolah = a.IDSchool'); $data['total_senarai_sekolah_rated'] = $query->row(); $data['total_senarai_sekolah_unrated'] = intval($data['total_senarai_sekolah']->val) - intval($data['total_senarai_sekolah_rated']->val); $query = $this->db->query('SELECT COUNT(KodSekolah) AS val FROM senarai_sekolah AS ss INNER JOIN assessment AS a ON ss.KodSekolah = a.IDSchool WHERE a.star_rate = 1'); $data['total_senarai_sekolah_1star'] = $query->row(); $query = $this->db->query('SELECT COUNT(KodSekolah) AS val FROM senarai_sekolah AS ss INNER JOIN assessment AS a ON ss.KodSekolah = a.IDSchool WHERE a.star_rate = 2'); $data['total_senarai_sekolah_2star'] = $query->row(); $query = $this->db->query('SELECT COUNT(KodSekolah) AS val FROM senarai_sekolah AS ss INNER JOIN assessment AS a ON ss.KodSekolah = a.IDSchool WHERE a.star_rate = 3'); $data['total_senarai_sekolah_3star'] = $query->row(); $query = $this->db->query('SELECT COUNT(KodSekolah) AS val FROM senarai_sekolah AS ss INNER JOIN assessment AS a ON ss.KodSekolah = a.IDSchool WHERE a.star_rate = 4'); $data['total_senarai_sekolah_4star'] = $query->row(); $query = $this->db->query('SELECT COUNT(KodSekolah) AS val FROM senarai_sekolah AS ss INNER JOIN assessment AS a ON ss.KodSekolah = a.IDSchool WHERE a.star_rate = 5'); $data['total_senarai_sekolah_5star'] = $query->row(); $query = $this->db->query('SELECT COUNT(KodSekolah) AS val FROM senarai_sekolah AS ss LEFT JOIN assessment AS a ON ss.KodSekolah = a.IDSchool WHERE a.IDSchool IS NULL'); $data['total_senarai_sekolah_nostar'] = $query->row(); $query = $this->db->query('SELECT COUNT(Negeri) AS val, Negeri FROM senarai_sekolah GROUP BY Negeri'); $data['total_senarai_sekolah_negeri'] = $query->result(); $query = $this->db->query('SELECT COUNT(PeringkatSekolah) AS val, PeringkatSekolah FROM senarai_sekolah GROUP BY PeringkatSekolah'); $data['total_senarai_sekolah_peringkat'] = $query->result(); $this->load->view('dashboard',$data); } public function ajax(){ $obj = json_decode($this->input->post('datastr')); $mode = $obj->mode; switch($mode){ case "InsertLatLong": $KodSekolah = $obj->KodSekolah; $Lat = $obj->Lat; $Long = $obj->Long; $data = array( 'Latitude' => $Lat, 'Longitude' => $Long ); $this->db->where('KodSekolah', $KodSekolah); $this->db->update('senarai_sekolah', $data); break; } } function POI_info($namaSekolah){ $query = $this->db->query("SELECT *,COUNT(assessment.IDSchool) AS ACount FROM senarai_sekolah LEFT JOIN assessment ON senarai_sekolah.KodSekolah = assessment.IDSchool WHERE senarai_sekolah.NamaSekolah = ?", array(rawurldecode($namaSekolah))); $case = $query->row(); $data['InfoSekolah'] = $case; $this->load->view('poi', $data); } }
{ "content_hash": "a18b641ca430c7bf5ee729667e6e0d80", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 244, "avg_line_length": 42.71111111111111, "alnum_prop": 0.6719562955254943, "repo_name": "muhammadruhaizat/s2s", "id": "fbb45f1694bc006b0646f890c72d4e23be365fc4", "size": "3844", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/controllers/Dashboard.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "442" }, { "name": "CSS", "bytes": "15332" }, { "name": "HTML", "bytes": "8515431" }, { "name": "JavaScript", "bytes": "56182" }, { "name": "PHP", "bytes": "1888280" } ], "symlink_target": "" }
package org.apache.maven.artifact.handler; import java.io.File; import java.util.List; import javax.inject.Inject; import org.codehaus.plexus.testing.PlexusTest; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.util.FileUtils; import org.junit.jupiter.api.Test; import static org.codehaus.plexus.testing.PlexusExtension.getTestFile; import static org.junit.jupiter.api.Assertions.assertEquals; @PlexusTest public class ArtifactHandlerTest { @Inject PlexusContainer container; @Test public void testAptConsistency() throws Exception { File apt = getTestFile( "src/site/apt/artifact-handlers.apt" ); List<String> lines = FileUtils.loadFile( apt ); for ( String line : lines ) { if ( line.startsWith( "||" ) ) { String[] cols = line.split( "\\|\\|" ); String[] expected = new String[] { "", "type", "classifier", "extension", "packaging", "language", "added to classpath", "includesDependencies", "" }; int i = 0; for ( String col : cols ) { assertEquals( expected[i++], col.trim(), "Wrong column header" ); } } else if ( line.startsWith( "|" ) ) { String[] cols = line.split( "\\|" ); String type = trimApt( cols[1] ); String classifier = trimApt( cols[2] ); String extension = trimApt( cols[3], type ); String packaging = trimApt( cols[4], type ); String language = trimApt( cols[5] ); String addedToClasspath = trimApt( cols[6] ); String includesDependencies = trimApt( cols[7] ); ArtifactHandler handler = container.lookup( ArtifactHandler.class, type ); assertEquals( handler.getExtension(), extension, type + " extension" ); assertEquals( handler.getPackaging(), packaging, type + " packaging" ); assertEquals( handler.getClassifier(), classifier, type + " classifier" ); assertEquals( handler.getLanguage(), language, type + " language" ); assertEquals( handler.isAddedToClasspath() ? "true" : null, addedToClasspath, type + " addedToClasspath" ); assertEquals( handler.isIncludesDependencies() ? "true" : null, includesDependencies, type + " includesDependencies" ); } } } private String trimApt( String content, String type ) { String value = trimApt( content ); return "= type".equals( value ) ? type : value; } private String trimApt( String content ) { content = content.replace( '<', ' ' ).replace( '>', ' ' ).trim(); return ( content.length() == 0 ) ? null : content; } }
{ "content_hash": "2f4271d9db6f4699360095cf7412e5fd", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 135, "avg_line_length": 35.6219512195122, "alnum_prop": 0.5669291338582677, "repo_name": "mcculls/maven", "id": "9dd5cf19d1366c96dcc62598d6b5c9c0c1480376", "size": "3727", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "maven-core/src/test/java/org/apache/maven/artifact/handler/ArtifactHandlerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8860" }, { "name": "HTML", "bytes": "2379" }, { "name": "Java", "bytes": "5194305" }, { "name": "Shell", "bytes": "5741" } ], "symlink_target": "" }
package com.intellij.dupLocator; import com.intellij.lang.LighterAST; import com.intellij.lang.LighterASTNode; import org.jetbrains.annotations.NotNull; /** * Created by Maxim.Mossienko on 10/1/2014. */ public interface LightDuplicateProfile { void process(@NotNull LighterAST ast, @NotNull Callback callback); interface Callback { void process(int hash, @NotNull LighterAST ast, @NotNull LighterASTNode... nodes); } }
{ "content_hash": "18060f8304fdf686e68d74190c56140d", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 86, "avg_line_length": 25.58823529411765, "alnum_prop": 0.7655172413793103, "repo_name": "TangHao1987/intellij-community", "id": "ba27b5544809788f08e6ed022bb79a4fda4d9bdd", "size": "1035", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "platform/duplicates-analysis/src/com/intellij/dupLocator/LightDuplicateProfile.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "20665" }, { "name": "AspectJ", "bytes": "182" }, { "name": "Batchfile", "bytes": "63518" }, { "name": "C", "bytes": "214180" }, { "name": "C#", "bytes": "1538" }, { "name": "C++", "bytes": "190028" }, { "name": "CSS", "bytes": "111474" }, { "name": "CoffeeScript", "bytes": "1759" }, { "name": "Cucumber", "bytes": "14382" }, { "name": "Erlang", "bytes": "10" }, { "name": "FLUX", "bytes": "57" }, { "name": "Groff", "bytes": "35232" }, { "name": "Groovy", "bytes": "2202843" }, { "name": "HTML", "bytes": "1727023" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "149255455" }, { "name": "JavaScript", "bytes": "125292" }, { "name": "Kotlin", "bytes": "601022" }, { "name": "Lex", "bytes": "166177" }, { "name": "Makefile", "bytes": "2352" }, { "name": "NSIS", "bytes": "86287" }, { "name": "Objective-C", "bytes": "28634" }, { "name": "Perl6", "bytes": "26" }, { "name": "Protocol Buffer", "bytes": "6570" }, { "name": "Python", "bytes": "21469995" }, { "name": "Ruby", "bytes": "1213" }, { "name": "Scala", "bytes": "11698" }, { "name": "Shell", "bytes": "63190" }, { "name": "Smalltalk", "bytes": "64" }, { "name": "TeX", "bytes": "60798" }, { "name": "TypeScript", "bytes": "6152" }, { "name": "XSLT", "bytes": "113040" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>containers: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">8.11.dev / containers - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> containers <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2020-07-27 01:07:00 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-27 01:07:00 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.11.dev Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.1 Official release 4.09.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/containers&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Containers&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: data structures&quot; &quot;keyword: type classes&quot; &quot;category: Computer Science/Data Types and Data Structures&quot; ] authors: [ &quot;Stéphane Lescuyer&quot; ] bug-reports: &quot;https://github.com/coq-contribs/containers/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/containers.git&quot; synopsis: &quot;Containers: a typeclass-based library of finite sets/maps&quot; description: &quot;This is a reimplementation of the FSets/FMaps library from the standard library, using typeclasses. See tests files for usage. A new vernacular command is provided by Generate.v and the plugin to automatically generate ordered types for user-defined inductive types.&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/containers/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=f954255c939acdebd61f245a70250a7d&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-containers.8.6.0 coq.8.11.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.dev). The following dependencies couldn&#39;t be met: - coq-containers -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-containers.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "a8d545a978ab62093f61728d78756bc0", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 280, "avg_line_length": 42.88414634146341, "alnum_prop": 0.5501208588084744, "repo_name": "coq-bench/coq-bench.github.io", "id": "3f0676fec73bd322dee252a9f8b58c167cd512db", "size": "7059", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.09.1-2.0.6/extra-dev/8.11.dev/containers/8.6.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
from fontTools.pens.basePen import BasePen from fontTools.misc.arrayTools import pointInRect def pointBoundTouche(point, bounds): found = pointInRect(point, bounds) if not found: # lazy check x values only minX, minY, maxX, maxY = bounds found = minX <= point[0] <= maxX return found class FindPossibleOverlappingSegmentsPen(BasePen): def __init__(self, glyphSet, bounds, moveSegment=(0, 0)): BasePen.__init__(self, glyphSet) self.allSegments = set() self.segments = set() self.bounds = bounds self.moveSegment = moveSegment def addSegment(self, segment): mx, my = self.moveSegment segment = tuple((x+mx, y+my) for x, y in segment) self.segments.add(segment) def _moveTo(self, pt): self.previousPoint = pt self.firstPoint = pt def _lineTo(self, pt): if pointBoundTouche(pt, self.bounds): self.addSegment((self.previousPoint, pt)) self.previousPoint = pt def _curveToOne(self, pt1, pt2, pt3): found = False if pointBoundTouche(pt1, self.bounds): found = True elif pointBoundTouche(pt2, self.bounds): found = True elif pointBoundTouche(pt3, self.bounds): found = True if found: self.addSegment((self.previousPoint, pt1, pt2, pt3)) self.previousPoint = pt3 def closePath(self): if self.firstPoint != self.previousPoint: self.lineTo(self.firstPoint)
{ "content_hash": "651ce711d2e56ce5bcc634705cb6fa75", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 64, "avg_line_length": 29.444444444444443, "alnum_prop": 0.5949685534591195, "repo_name": "ninastoessinger/Touche", "id": "2b581a1766f5efdadb3133808676f9de844cce90", "size": "1606", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Touche.roboFontExt/lib/touche/findPossibleOverlappingSegmentsPen.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "12597" } ], "symlink_target": "" }
import idx3d.*; import java.awt.*; import java.applet.*; import java.io.*; public final class idx3dMaterialLab extends Frame { idx3d_Scene objectView; idx3d_Screen textureScreen; idx3d_Screen envmapScreen; Image doubleBuffer1=null; //object View Image doubleBuffer2=null; //texture Image doubleBuffer3=null; //envmap idx3d_Material material; int oldx=0; int oldy=0; boolean initialized=false; Button readMaterial,writeMaterial,openScene, projectTop,projectFrontal, generateTexture,importTexture,noTexture, generateEnvmap,importEnvmap,noEnvmap; Label project,settings,label1,label2,label3,label4,label5,transp,refl; Scrollbar transparency,reflectivity; TextField color; Checkbox flat; Font normal; public static void main(String args[]) { new idx3dMaterialLab(); } public idx3dMaterialLab() { super("idx3d Material Lab"); resize(500+insets().left+insets().right,540+insets().top+insets().bottom); setResizable(false); setBackground(Color.lightGray); normal=new Font("Helvetica",0,11); material=new idx3d_Material(0x66FF); material.setTransparency(63); objectView=new idx3d_Scene(280,240); textureScreen=new idx3d_Screen(200,200); envmapScreen=new idx3d_Screen(200,200); objectView.setAmbient(0x333333); objectView.environment.setBackground(idx3d_TextureFactory.CHECKERBOARD(160,120,2,0x000000,0x999999)); objectView.addLight("Light1",new idx3d_Light(new idx3d_Vector(0.2f,0.2f,1f),0xFFFFFF,320,120)); //objectView.addLight("Light2",new idx3d_Light(new idx3d_Vector(-1f,-1f,1f),0xFFFFFF,160,200)); idx3d_Object trefoil=idx3d_ObjectFactory.TORUSKNOT(2f,3f,0.4f,1.2f,0.48f,1.2f,120,8); objectView.addObject("Trefoil",trefoil); objectView.object("Trefoil").rotate(0.2f,3.5f,-0.5f); objectView.object("Trefoil").setMaterial(material); objectView.object("Trefoil").scale(0.4f); objectView.object("Trefoil").removeDuplicateVertices(); idx3d_TextureProjector.projectTop(objectView.object("Trefoil")); show(); } public void paint(Graphics g) { repaint(); } private void initGUI() { initialized=true; readMaterial=new Button("Read Material"); writeMaterial=new Button("Write Material"); generateTexture=new Button("Generate"); importTexture=new Button("Import"); noTexture=new Button("None"); generateEnvmap=new Button("Generate"); importEnvmap=new Button("Import"); noEnvmap=new Button("None"); openScene=new Button("Import Scene from 3ds File"); projectTop=new Button("TOP"); projectFrontal=new Button("FRONTAL"); project=new Label("Project Texture:"); settings=new Label("Material Settings:"); label1=new Label("Color:"); label2=new Label("Transparency:"); label3=new Label("Reflectivity:"); label4=new Label("Texture:"); label5=new Label("Envmap:"); transp=new Label(); refl=new Label(); transparency=new Scrollbar(0,0,1,0,256); reflectivity=new Scrollbar(0,255,1,0,256); color=new TextField(); flat=new Checkbox("Flatshaded"); readMaterial.setFont(normal); writeMaterial.setFont(normal); generateTexture.setFont(normal); importTexture.setFont(normal); noTexture.setFont(normal); generateEnvmap.setFont(normal); importEnvmap.setFont(normal); noEnvmap.setFont(normal); openScene.setFont(normal); settings.setFont(normal); label1.setFont(normal); label2.setFont(normal); label3.setFont(normal); label4.setFont(normal); label5.setFont(normal); transp.setFont(normal); refl.setFont(normal); color.setFont(normal); flat.setFont(normal); projectTop.setFont(normal); projectFrontal.setFont(normal); project.setFont(normal); add(readMaterial); add(writeMaterial); add(generateTexture); add(importTexture); add(noTexture); add(generateEnvmap); add(importEnvmap); add(noEnvmap); add(openScene); add(settings); add(projectTop); add(projectFrontal); add(project); add(label1); add(label2); add(label3); add(label4); add(label5); add(transp); add(refl); add(color); add(transparency); add(reflectivity); add(flat); } public void update(Graphics g) { if (!initialized) initGUI(); int xoffset=insets().left; int yoffset=insets().top; textureScreen.clear(0); textureScreen.draw(material.getTexture(),0,0,200,200); envmapScreen.clear(0); envmapScreen.draw(material.getEnvmap(),0,0,200,200); updateMaterial(); objectView.render(); g.drawImage(objectView.getImage(),xoffset,yoffset,this); g.drawImage(textureScreen.getImage(),xoffset+10,yoffset+270,this); g.drawImage(envmapScreen.getImage(),xoffset+230,yoffset+270,this); g.draw3DRect(xoffset,yoffset,280,240,true); g.draw3DRect(xoffset+10,yoffset+270,200,200,true); g.draw3DRect(xoffset+230,yoffset+270,200,200,true); readMaterial.reshape(xoffset+290,yoffset+180,200,20); writeMaterial.reshape(xoffset+290,yoffset+200,200,20); openScene.reshape(xoffset+290,yoffset+220,200,20); generateTexture.reshape(xoffset+10,yoffset+470,80,20); importTexture.reshape(xoffset+90,yoffset+470,80,20); noTexture.reshape(xoffset+170,yoffset+470,40,20); generateEnvmap.reshape(xoffset+230,yoffset+470,80,20); importEnvmap.reshape(xoffset+310,yoffset+470,80,20); noEnvmap.reshape(xoffset+390,yoffset+470,40,20); settings.reshape(xoffset+290,yoffset+0,100,20); label1.reshape(xoffset+290,yoffset+30,80,20); label2.reshape(xoffset+290,yoffset+50,100,20); label3.reshape(xoffset+290,yoffset+100,100,20); label4.reshape(xoffset+10,yoffset+250,100,20); label5.reshape(xoffset+230,yoffset+250,100,20); transp.reshape(xoffset+460,yoffset+70,40,20); refl.reshape(xoffset+460,yoffset+120,40,20); project.reshape(xoffset+10,yoffset+490,80,20); projectTop.reshape(xoffset+90,yoffset+490,60,20); projectFrontal.reshape(xoffset+150,yoffset+490,60,20); transparency.reshape(xoffset+290,yoffset+70,160,20); reflectivity.reshape(xoffset+290,yoffset+120,160,20); color.reshape(xoffset+390,yoffset+30,100,20); flat.reshape(xoffset+290,yoffset+150,100,20); g.setColor(new Color(0xFF000000|material.getColor())); g.fillRect(xoffset+370,yoffset+30,20,20); } private void renderObjectView(Graphics g) { objectView.render(); g.drawImage(objectView.getImage(),0,0,this); } public boolean action(Event evt, Object obj) { if (evt.target==readMaterial) { readMaterial(); return true; } if (evt.target==writeMaterial) { writeMaterial(); return true; } if (evt.target==openScene) { openScene(); return true; } if (evt.target==importTexture) { importTexture(); return true; } if (evt.target==importEnvmap) { importEnvmap(); return true; } if (evt.target==generateTexture) { new TextureLab(this,material.textureSettings,true); return true; } if (evt.target==generateEnvmap) { new TextureLab(this,material.envmapSettings,false); return true; } if (evt.target==noTexture) { noTexture(); return true; } if (evt.target==noEnvmap) { noEnvmap(); return true; } if (evt.target==projectTop) { projectTop(); return true; } if (evt.target==projectFrontal) { projectFrontal(); return true; } return super.action(evt,obj); } public boolean handleEvent(Event evt) { if (evt.id==Event.WINDOW_DESTROY) { hide(); dispose(); System.exit(0); return true; } return super.handleEvent(evt); } public boolean keyDown(Event evt,int key) { if (evt.target instanceof TextField) return super.keyDown(evt,key); if (key==32) { System.out.println(objectView.getFPS()+""); return true; } if (key==Event.PGUP) {objectView.shift(0f,0f,0.2f); return true; } if (key==Event.PGDN) {objectView.shift(0f,0f,-0.2f); return true; } if (key==Event.UP) {objectView.shift(0f,0.2f,0f); return true; } if (key==Event.DOWN) {objectView.shift(0f,-0.2f,0f); return true; } if (key==Event.LEFT) {objectView.shift(-0.2f,0f,0f); return true; } if (key==Event.RIGHT) {objectView.shift(0.2f,0f,0f); return true; } if ((char)key=='+') {objectView.scale(1.2f); return true; } if ((char)key=='-') {objectView.scale(0.8f); return true; } if ((char)key=='m') {for (int i=0;i<objectView.objects;i++) objectView.object[i].meshSmooth(); return true; } if ((char)key=='a') {objectView.setAntialias(!objectView.antialias()); return true; } if ((char)key=='i') {idx3d.debug.Inspector.inspect(objectView); return true; } return true; } public boolean mouseDown(Event evt,int x,int y) { if (x>280 || y>240) return true; requestFocus(); oldx=x; oldy=y; repaint(); return true; } public boolean mouseDrag(Event evt,int x,int y) { if (x>280 || y>240) return true; float dx=(float)(y-oldy)/50; float dy=(float)(oldx-x)/50; objectView.rotate(dx,dy,0); oldx=x; oldy=y; repaint(); return true; } private void openScene() { File newFile=browseForFile("Read Scene from 3ds File",true); if (newFile==null) return; try{ objectView.removeAllObjects(); new idx3d_3ds_Importer().importFromStream(new FileInputStream(newFile),objectView); objectView.rebuild(); for (int i=0; i<objectView.objects;i++) objectView.object[i].setMaterial(material); objectView.normalize(); } catch(Exception e){System.err.println(e+"");} repaint(); } public void setSettings(idx3d_TextureSettings settings, boolean mode) { if (mode) { material.textureSettings=settings; material.setTexture(settings.texture); } else { material.envmapSettings=settings; material.setEnvmap(settings.texture); } } private void updateMaterial() { try{ material.setColor((int)Integer.parseInt(color.getText(),16)); } catch(Exception e) {material.setColor(0);} material.setTransparency(transparency.getValue()); material.setReflectivity(reflectivity.getValue()); material.setFlat(flat.getState()); transp.setText(material.getTransparency()+""); refl.setText(material.getReflectivity()+""); } private void projectTop() { for (int i=objectView.objects-1;i>=0;i--) idx3d_TextureProjector.projectTop(objectView.object[i]); } private void projectFrontal() { for (int i=objectView.objects-1;i>=0;i--) idx3d_TextureProjector.projectFrontal(objectView.object[i]); } private void importTexture() { File newFile=browseForFile("Import Texture",true); if (newFile==null) return; material.setTexture(new idx3d_Texture(newFile.getPath())); } private void importEnvmap() { File newFile=browseForFile("Import Envmap",true); if (newFile==null) return; material.setEnvmap(new idx3d_Texture(newFile.getPath())); } private void noTexture() { material.setTexture(null); } private void noEnvmap() { material.setEnvmap(null); } private File browseForFile(String dialogTitle, boolean mustExist) { FileDialog fd = new FileDialog(this, dialogTitle, mustExist? FileDialog.LOAD : FileDialog.SAVE); fd.show(); if (fd.getDirectory()==null) return null; if (fd.getFile()==null) return null; File newFile=new File(fd.getDirectory(), fd.getFile()); if (mustExist&&(newFile.length()==0)) newFile=null; return newFile; } private void writeMaterial() { File file=browseForFile("Save Material",false); if (file==null) return; int id; try { DataOutputStream out=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); out.writeInt(material.getColor()); out.writeByte(material.getTransparency()); out.writeByte(material.getReflectivity()); out.writeBoolean(material.isFlat()); idx3d_TextureSettings settings=null; // Texture if (material.getTexture()==null) id=0; else if (material.getTexture().path!=null) id=1; else id=2; out.writeByte(id); if (id==1) out.writeUTF(material.getTexture().path); if (id==2) { settings=material.textureSettings; out.writeInt(settings.width); out.writeInt(settings.height); out.writeByte(settings.type); out.writeFloat(settings.persistency); out.writeFloat(settings.density); out.writeByte(settings.samples); out.writeByte(settings.colors.length); for (int i=0;i<settings.colors.length;i++) out.writeInt(settings.colors[i]); } // Envmap if (material.getEnvmap()==null) id=0; else if (material.getEnvmap().path!=null) id=1; else id=2; out.writeByte(id); if (id==1) out.writeUTF(material.getEnvmap().path); if (id==2) { settings=material.envmapSettings; out.writeInt(settings.width); out.writeInt(settings.height); out.writeByte(settings.type); out.writeFloat(settings.persistency); out.writeFloat(settings.density); out.writeByte(settings.samples); out.writeByte(settings.colors.length); for (int i=0;i<settings.colors.length;i++) out.writeInt(settings.colors[i]); } out.flush(); out.close(); } catch (IOException ignored){} } private void readMaterial() { File file=browseForFile("Read Material",true); if (file==null) return; idx3d_Material newMaterial=null; try{ newMaterial=new idx3d_Material(file.getPath()); } catch(Exception ignored) {return;} color.setText(Integer.toHexString(newMaterial.getColor())); transparency.setValue(newMaterial.getTransparency()); reflectivity.setValue(newMaterial.getReflectivity()); flat.setState(newMaterial.isFlat()); material=newMaterial; for (int i=0; i<objectView.objects;i++) objectView.object[i].setMaterial(material); } }
{ "content_hash": "c9b31d1883d971dab2c4ba31ecbbf165", "timestamp": "", "source": "github", "line_count": 457, "max_line_length": 111, "avg_line_length": 29.288840262582056, "alnum_prop": 0.7095255883451626, "repo_name": "AlessandroBorges/IDX3D", "id": "a0a8c3268fb811da27e5b9c57f710a5a90ea2482", "size": "13385", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/idx3dMaterialLab.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "416939" }, { "name": "Java", "bytes": "265215" } ], "symlink_target": "" }
using System.Web.Mvc; using NServiceBus; #region Controller public class DefaultController : Controller { IBus bus; public DefaultController(IBus bus) { this.bus = bus; } public ActionResult Index() { return View(); } [AllowAnonymous] public ActionResult Send() { bus.Send("Samples.Mvc.Endpoint", new MyMessage()); return RedirectToAction("Index", "Default"); } } #endregion
{ "content_hash": "053e31e928a60a65cdfdd601fbe72fe1", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 58, "avg_line_length": 17.53846153846154, "alnum_prop": 0.6206140350877193, "repo_name": "WojcikMike/docs.particular.net", "id": "3bf0460ffc77f61840a6d68fa0269dd48375270c", "size": "458", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/web/asp-mvc-injecting-bus/Version_5/WebApplication/DefaultController.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "779873" }, { "name": "PowerShell", "bytes": "7937" } ], "symlink_target": "" }
/*** * The goal of this file is to know about the readline functions; * * * How to run this example: * 1. node readline-3.js * 2. See the message get displayed on prompt. */ var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); // Emitted whenever the input stream receives a \n, usually received when the user hits enter, or return. rl.on('line', function(cmd) { console.log('You just typed: ' + cmd); }); // Ctrl+C, Ctrl+D rl.on('pause', function() { console.log('Readline paused'); }); // Ctrl+D rl.on('close', function() { console.log('Readline closed'); }); rl.on('SIGINT', function() { rl.question('Are you sure you want to exit? ', function(answer) { if (answer.match(/^y(es)?$/i)) { rl.pause(); } }); });
{ "content_hash": "5d0622c7ac50bfd8ea87395454038d5c", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 106, "avg_line_length": 21.236842105263158, "alnum_prop": 0.6456009913258984, "repo_name": "hegdeashwin/Server-Side-Node.js", "id": "928ea719c31d712a1112ccd587b638d5b8deb63c", "size": "807", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "codes/Session-2/readline/readline-3.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "19" }, { "name": "HTML", "bytes": "921971" }, { "name": "JavaScript", "bytes": "48214" } ], "symlink_target": "" }
I was looking for a good place where to put my money. A while ago I came across Vaamo and decided to create a account and give it a try. The problem was that they don´t provide a graph about the development of the fond. The new data came in every day so i wrote down the numbers to a spreadsheet. Time passed and I got bugged out by this process. Apparently Vaamo don´t provide an API so i wrote this crawler to get the data from their website. I don´t give any gurantee for this script and I am not responsible for what you do with my script. I also added a script that upload this data to a Google Spreadsheet. If you want to use this, you need to follow the instructions of the following link to generate a authentication json file: https://www.npmjs.com/package/google-spreadsheet#authentication # Usage parser First set your username and password in the config.php file. Then run ``` composer install ``` (You can get composer at http://getcomposer.org) The you can start the script with ``` php -f parse.php ``` If you need the data in a different format, feel free to make these changes by yourself. # Usage upload If you have generated the authentication json file described in the Introduction you must set the name in the "upload-to-spreadsheet.js" like this: ``` ... var creds = require('./parse-vaamo-a988cb5f1c01.json'); ... ``` Make sure you have shared your spreadsheet with the service email address given in the json file. The you must gather the key of your spreadsheet. Its the long string in the URL of the open spreadsheet tab in your browser. Set this in you config.php ``` define('GOOGLE_SPREADSHEET', '...'); ``` With the mapping variable in the config.php you can set which "Sparziel" information will be set to which spreadsheet. The key is the "Sparziel" name and the Value the spreadsheet tab name. The last step is to install the npm module google-spreadsheet like this: ``` npm install google-spreadsheet npm install async ```
{ "content_hash": "a85a909fefa3374c01708d26fa483959", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 84, "avg_line_length": 31.806451612903224, "alnum_prop": 0.7647058823529411, "repo_name": "roenschg/vaamo-parser", "id": "7d1c08d75a54bc13cdea15b6a6a42845806ac34e", "size": "1990", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "1266" }, { "name": "PHP", "bytes": "4043" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_refresh" android:title="@string/action_refresh" app:showAsAction="always"/> </menu>
{ "content_hash": "7599785dd33a218e48b7c9e86d988a7b", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 64, "avg_line_length": 31.8, "alnum_prop": 0.6194968553459119, "repo_name": "inserteffect/dwx2015-android-testing", "id": "f1401a48a06c4b2d5d309d6b87847df570c63074", "size": "318", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/menu/menu_main.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "23200" } ], "symlink_target": "" }
<?php namespace Surfnet\StepupMiddleware\MiddlewareBundle\Console\Command; use Exception; use Rhumsaa\Uuid\Uuid; use Surfnet\Stepup\Identity\Value\Institution; use Surfnet\Stepup\Identity\Value\NameId; use Surfnet\StepupMiddleware\ApiBundle\Identity\Entity\UnverifiedSecondFactor; use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\ProveYubikeyPossessionCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken; final class BootstrapYubikeySecondFactorCommand extends AbstractBootstrapCommand { protected function configure() { $this ->setDescription('Creates a Yubikey second factor for a specified user') ->addArgument('name-id', InputArgument::REQUIRED, 'The NameID of the identity to create') ->addArgument('institution', InputArgument::REQUIRED, 'The institution of the identity to create') ->addArgument( 'yubikey', InputArgument::REQUIRED, 'The public ID of the Yubikey. Remove the last 32 characters of a Yubikey OTP to acquire this.' ) ->addArgument( 'registration-status', InputArgument::REQUIRED, 'Valid arguments: unverified, verified, vetted' ) ->addArgument('actor-id', InputArgument::REQUIRED, 'The id of the vetting actor'); } protected function execute(InputInterface $input, OutputInterface $output) { $this->tokenStorage->setToken( new AnonymousToken('cli.bootstrap-yubikey-token', 'cli', ['ROLE_SS', 'ROLE_RA']) ); $nameId = new NameId($input->getArgument('name-id')); $institutionText = $input->getArgument('institution'); $institution = new Institution($institutionText); $mailVerificationRequired = $this->requiresMailVerification($institutionText); $registrationStatus = $input->getArgument('registration-status'); $yubikey = $input->getArgument('yubikey'); $actorId = $input->getArgument('actor-id'); $this->enrichEventMetadata($actorId); if (!$this->tokenBootstrapService->hasIdentityWithNameIdAndInstitution($nameId, $institution)) { $output->writeln( sprintf( '<error>An identity with name ID "%s" from institution "%s" does not exist, create it first.</error>', $nameId->getNameId(), $institution->getInstitution() ) ); return; } $identity = $this->tokenBootstrapService->findOneByNameIdAndInstitution($nameId, $institution); $output->writeln(sprintf('<comment>Adding a %s Yubikey token for %s</comment>', $registrationStatus, $identity->commonName)); $this->beginTransaction(); $secondFactorId = Uuid::uuid4()->toString(); try { switch ($registrationStatus) { case "unverified": $output->writeln('<comment>Creating an unverified Yubikey token</comment>'); $this->provePossession($secondFactorId, $identity, $yubikey); break; case "verified": $output->writeln('<comment>Creating an unverified Yubikey token</comment>'); $this->provePossession($secondFactorId, $identity, $yubikey); $unverifiedSecondFactor = $this->tokenBootstrapService->findUnverifiedToken($identity->id, 'yubikey'); if ($mailVerificationRequired) { $output->writeln('<comment>Creating a verified Yubikey token</comment>'); $this->verifyEmail($identity, $unverifiedSecondFactor); } break; case "vetted": $output->writeln('<comment>Creating an unverified Yubikey token</comment>'); $this->provePossession($secondFactorId, $identity, $yubikey); /** @var UnverifiedSecondFactor $unverifiedSecondFactor */ $unverifiedSecondFactor = $this->tokenBootstrapService->findUnverifiedToken($identity->id, 'yubikey'); if ($mailVerificationRequired) { $output->writeln('<comment>Creating a verified Yubikey token</comment>'); $this->verifyEmail($identity, $unverifiedSecondFactor); } $verifiedSecondFactor = $this->tokenBootstrapService->findVerifiedToken($identity->id, 'yubikey'); $output->writeln('<comment>Vetting the verified Yubikey token</comment>'); $this->vetSecondFactor( 'yubikey', $actorId, $identity, $secondFactorId, $verifiedSecondFactor, $yubikey ); break; } $this->finishTransaction(); } catch (Exception $e) { $output->writeln( sprintf( '<error>An Error occurred when trying to bootstrap the Yubikey token: "%s"</error>', $e->getMessage() ) ); $this->rollback(); throw $e; } $output->writeln( sprintf( '<info>Successfully created identity with UUID %s and %s second factor with UUID %s</info>', $identity->id, $registrationStatus, $secondFactorId ) ); } private function provePossession($secondFactorId, $identity, $phoneNumber) { $command = new ProveYubikeyPossessionCommand(); $command->UUID = (string)Uuid::uuid4(); $command->secondFactorId = $secondFactorId; $command->identityId = $identity->id; $command->yubikeyPublicId = $phoneNumber; $this->process($command); } }
{ "content_hash": "ad2aa8c1850883aaaa1f3dbb6cea2346", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 133, "avg_line_length": 46.30597014925373, "alnum_prop": 0.5834004834810637, "repo_name": "SURFnet/Stepup-Middleware", "id": "1558f54b1c6811347d292c83a2462778aa2007f3", "size": "6799", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/Surfnet/StepupMiddleware/MiddlewareBundle/Console/Command/BootstrapYubikeySecondFactorCommand.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "715" }, { "name": "PHP", "bytes": "1560794" } ], "symlink_target": "" }
@interface TDProfessorCell : UITableViewCell @property (nonatomic,strong) UILabel *professorLabel; @end
{ "content_hash": "abeb79d3942034671c5332356b089241", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 53, "avg_line_length": 21.2, "alnum_prop": 0.8113207547169812, "repo_name": "Ben21hao/edx-app-ios-new", "id": "69a7c590614c28de6302b6b52b812c4dbff04c3f", "size": "260", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/ProFessorViewController/TDProfessorCell.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1147503" }, { "name": "C++", "bytes": "318178" }, { "name": "CSS", "bytes": "2468" }, { "name": "HTML", "bytes": "208520" }, { "name": "Objective-C", "bytes": "2123005" }, { "name": "Ruby", "bytes": "2686" }, { "name": "Swift", "bytes": "1422932" } ], "symlink_target": "" }
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { TestBed } from '@angular/core/testing'; import { SkyAutocompleteHarness } from './autocomplete-harness'; import { AutocompleteHarnessTestComponent } from './fixtures/autocomplete-harness-test.component'; import { AutocompleteHarnessTestModule } from './fixtures/autocomplete-harness-test.module'; import { ColorIdHarness } from './fixtures/color-id-harness'; import { MyExtendsAutocompleteHarness } from './fixtures/my-extends-harness'; describe('Autocomplete harness', () => { async function setupTest(options: { dataSkyId?: string } = {}) { await TestBed.configureTestingModule({ imports: [AutocompleteHarnessTestModule], }).compileComponents(); const fixture = TestBed.createComponent(AutocompleteHarnessTestComponent); const loader = TestbedHarnessEnvironment.loader(fixture); let autocompleteHarness: SkyAutocompleteHarness | undefined; if (options.dataSkyId) { autocompleteHarness = await loader.getHarness( SkyAutocompleteHarness.with({ dataSkyId: options.dataSkyId }) ); } return { autocompleteHarness, fixture, loader }; } it('should focus and blur input', async () => { const { autocompleteHarness } = await setupTest({ dataSkyId: 'my-autocomplete-1', }); await expectAsync(autocompleteHarness?.isFocused()).toBeResolvedTo(false); await autocompleteHarness?.focus(); await expectAsync(autocompleteHarness?.isFocused()).toBeResolvedTo(true); await autocompleteHarness?.blur(); await expectAsync(autocompleteHarness?.isFocused()).toBeResolvedTo(false); }); it('should check if autocomplete is disabled', async () => { const { fixture, autocompleteHarness } = await setupTest({ dataSkyId: 'my-autocomplete-1', }); await expectAsync(autocompleteHarness?.isDisabled()).toBeResolvedTo(false); fixture.componentInstance.disableForm(); await expectAsync(autocompleteHarness?.isDisabled()).toBeResolvedTo(true); }); it('should check if autocomplete is open', async () => { const { autocompleteHarness } = await setupTest({ dataSkyId: 'my-autocomplete-1', }); await autocompleteHarness?.enterText('r'); await expectAsync(autocompleteHarness?.isOpen()).toBeResolvedTo(true); }); it('should return search result harnesses', async () => { const { autocompleteHarness } = await setupTest({ dataSkyId: 'my-autocomplete-1', }); await autocompleteHarness?.enterText('d'); const results = (await autocompleteHarness?.getSearchResults()) ?? []; await expectAsync(results[0].getDescriptorValue()).toBeResolvedTo('Red'); await expectAsync(results[0].getText()).toBeResolvedTo('Red'); }); it('should return search results text content', async () => { const { autocompleteHarness } = await setupTest({ dataSkyId: 'my-autocomplete-1', }); await autocompleteHarness?.enterText('r'); await expectAsync( autocompleteHarness?.getSearchResultsText() ).toBeResolvedTo([ 'Red', 'Green', 'Orange', 'Purple', 'Brown', 'Turquoise', ]); }); it('should select a search result', async () => { const { autocompleteHarness } = await setupTest({ dataSkyId: 'my-autocomplete-1', }); await autocompleteHarness?.enterText('r'); const result = ((await autocompleteHarness?.getSearchResults()) ?? [])[0]; await result.select(); await expectAsync(autocompleteHarness?.getValue()).toBeResolvedTo('Red'); }); it('should select a search result using filters', async () => { const { autocompleteHarness } = await setupTest({ dataSkyId: 'my-autocomplete-1', }); await autocompleteHarness?.enterText('r'); await autocompleteHarness?.selectSearchResult({ text: 'Green', }); await expectAsync(autocompleteHarness?.getValue()).toBeResolvedTo('Green'); }); it('should clear the input value', async () => { const { autocompleteHarness } = await setupTest({ dataSkyId: 'my-autocomplete-1', }); // First, set a value on the autocomplete. await autocompleteHarness?.enterText('r'); await autocompleteHarness?.selectSearchResult({ text: 'Green', }); await expectAsync(autocompleteHarness?.getValue()).toBeResolvedTo('Green'); // Now, clear the value. await autocompleteHarness?.clear(); await expectAsync(autocompleteHarness?.getValue()).toBeResolvedTo(''); }); it('should throw error if getting search results when autocomplete not open', async () => { const { autocompleteHarness } = await setupTest({ dataSkyId: 'my-autocomplete-1', }); await expectAsync( autocompleteHarness?.getSearchResults() ).toBeRejectedWithError( 'Unable to retrieve search results. The autocomplete is closed.' ); }); it('should throw error if filtered search results are empty', async () => { const { autocompleteHarness } = await setupTest({ dataSkyId: 'my-autocomplete-1', }); await autocompleteHarness?.enterText('r'); await expectAsync( autocompleteHarness?.getSearchResults({ text: /invalidsearchtext/, }) ).toBeRejectedWithError( 'Could not find search results matching filter(s): {"text":"/invalidsearchtext/"}' ); }); it('should return an empty array if search results are not filtered', async () => { const { autocompleteHarness } = await setupTest({ dataSkyId: 'my-autocomplete-1', }); await autocompleteHarness?.enterText('invalidsearchtext'); await expectAsync(autocompleteHarness?.getSearchResults()).toBeResolvedTo( [] ); }); describe('custom search result template', () => { it('should get search result text and value', async () => { const { autocompleteHarness } = await setupTest({ dataSkyId: 'my-autocomplete-2', }); await autocompleteHarness?.enterText('d'); const results = (await autocompleteHarness?.getSearchResults()) ?? []; await expectAsync(results[0].getDescriptorValue()).toBeResolvedTo('Red'); await expectAsync(results[0].getText()).toBeResolvedTo('Red ID: 1'); }); it('should query child harnesses', async () => { const { autocompleteHarness } = await setupTest({ dataSkyId: 'my-autocomplete-2', }); await autocompleteHarness?.enterText('d'); const results = (await autocompleteHarness?.getSearchResults()) ?? []; const harness = await results[0].queryHarness(ColorIdHarness); await expectAsync((await harness?.host())?.text()).toBeResolvedTo('1'); }); }); describe('protected features', () => { it('should click the "Add" button', async () => { const { loader, fixture } = await setupTest(); const myHarness = loader.getHarness(MyExtendsAutocompleteHarness); const spy = spyOn(fixture.componentInstance, 'onAddClick'); await expectAsync( (await myHarness).clickAddButton() ).toBeRejectedWithError( 'Unable to find the "Add" button. The autocomplete is closed.' ); await (await myHarness).enterText('r'); await (await myHarness).clickAddButton(); expect(spy).toHaveBeenCalledWith(); }); it('should click the "Show more" button', async () => { const { loader, fixture } = await setupTest(); const myHarness = loader.getHarness(MyExtendsAutocompleteHarness); const spy = spyOn(fixture.componentInstance, 'onShowMoreClick'); await expectAsync( (await myHarness).clickShowMoreButton() ).toBeRejectedWithError( 'Unable to find the "Show more" button. The autocomplete is closed.' ); await (await myHarness).enterText('r'); await (await myHarness).clickShowMoreButton(); expect(spy).toHaveBeenCalledWith(); }); it('should throw errors when buttons are not enabled', async () => { const { loader, fixture } = await setupTest(); const myHarness = loader.getHarness(MyExtendsAutocompleteHarness); fixture.componentInstance.enableShowMore = false; fixture.componentInstance.showAddButton = false; await (await myHarness).enterText('r'); await expectAsync( (await myHarness).clickAddButton() ).toBeRejectedWithError( 'The "Add" button cannot be clicked because it does not exist.' ); await expectAsync( (await myHarness).clickShowMoreButton() ).toBeRejectedWithError( 'The "Show more" button cannot be clicked because it does not exist.' ); }); }); });
{ "content_hash": "b8ea6ed8d7a17dc5f1a2b8a89da2d749", "timestamp": "", "source": "github", "line_count": 267, "max_line_length": 98, "avg_line_length": 32.42322097378277, "alnum_prop": 0.669284971699203, "repo_name": "blackbaud/skyux", "id": "8c08f57e2c0ddcf84303f000b551fc267c9ea257", "size": "8657", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "libs/components/lookup/testing/src/autocomplete/autocomplete-harness.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "806202" }, { "name": "JavaScript", "bytes": "39129" }, { "name": "SCSS", "bytes": "320321" }, { "name": "TypeScript", "bytes": "7288448" } ], "symlink_target": "" }
'use strict' module.exports = function(app, middlewares, routeMiddlewares) { return {} }
{ "content_hash": "e29c3c9a38f98e39c0d96bdd6cb65d31", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 63, "avg_line_length": 18.2, "alnum_prop": 0.7252747252747253, "repo_name": "lukeulrich/path-routify", "id": "02bd2943bbf354de17595e242e4ba9dbfdd99610", "size": "91", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test-data/routing-errors/invalid-return/get.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "55651" } ], "symlink_target": "" }
This project have been written in QT and is licensed under MIT.
{ "content_hash": "baa9d7679b7a4b584eeb8762ab9a1e63", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 63, "avg_line_length": 64, "alnum_prop": 0.796875, "repo_name": "Ladone/2048", "id": "b617849f774c220bbfe1c82aa5f55c85d8424329", "size": "107", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "19437" }, { "name": "QMake", "bytes": "443" } ], "symlink_target": "" }
/* * SimpleRenderEngine (https://github.com/mortennobel/SimpleRenderEngine) * * Created by Morten Nobel-Jørgensen ( http://www.nobel-joergensen.com/ ) * License: MIT */ #pragma once #include <memory> #include <vector> #include <string> #include "glm/glm.hpp" #include "Texture.hpp" #include "impl/CPPShim.hpp" namespace sre { class RenderPass; class Texture; /** * A framebuffer object allows rendering into textures instead of the screen. * * A framebuffer is created with a destination texture. It is important that this texture is not used in * materials when rendering to the framebuffer (reading and writing to a texture at the same time is not supported). * * To use a framebuffer, pass it to RenderPassBuilder when a renderpass is being created. */ class Framebuffer { public: class FrameBufferBuilder { public: FrameBufferBuilder& withColorTexture(std::shared_ptr<Texture> texture); FrameBufferBuilder& withDepthTexture(std::shared_ptr<Texture> texture); FrameBufferBuilder& withName(std::string name); std::shared_ptr<Framebuffer> build(); private: std::vector<std::shared_ptr<Texture>> textures; std::shared_ptr<Texture> depthTexture; glm::uvec2 size; std::string name; FrameBufferBuilder() = default; FrameBufferBuilder(const FrameBufferBuilder&) = default; friend class Framebuffer; }; ~Framebuffer(); static FrameBufferBuilder create(); static int getMaximumDepthAttachments(); static int getMaximumColorAttachments(); void setColorTexture(std::shared_ptr<Texture> tex, int index = 0); void setDepthTexture(std::shared_ptr<Texture> tex); const std::string& getName(); private: void bind(); bool dirty = true; explicit Framebuffer(std::string name); std::vector<std::shared_ptr<Texture>> textures; std::shared_ptr<Texture> depthTexture; unsigned int frameBufferObjectId; uint32_t renderbuffer = 0; std::string name; glm::uvec2 size; friend class RenderPass; friend class Inspector; }; }
{ "content_hash": "397287990aa201044d35ef738ff87c1e", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 120, "avg_line_length": 31.356164383561644, "alnum_prop": 0.6439493228484054, "repo_name": "mortennobel/SimpleRenderEngine", "id": "401a21cd202ca321f33507f435b2b6c08fdc740f", "size": "2290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/sre/Framebuffer.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "799645" }, { "name": "CMake", "bytes": "22350" }, { "name": "GLSL", "bytes": "26089" }, { "name": "Shell", "bytes": "13120" } ], "symlink_target": "" }
using System; using NoiseLab.Common.Extensions; using Xunit; namespace NoiseLab.Common.UnitTests.Extensions { public class StringExtensionsTests { [Fact] public void ThrowIfNullOrWhitespace_ArgumentIsNull_ThrowsArgumentNullException() { // Arrange var value = (string)null; // Act & Assert Assert.Throws<ArgumentException>(() => value.ThrowIfNullOrWhitespace(nameof(value))); } [Fact] public void ThrowIfNullOrWhitespace_ArgumentIsEmptyString_ThrowsArgumentNullException() { // Arrange var value = string.Empty; // Act & Assert Assert.Throws<ArgumentException>(() => value.ThrowIfNullOrWhitespace(nameof(value))); } [Fact] public void ThrowIfNullOrWhitespace_ArgumentIsWhitespaceString_ThrowsArgumentNullException() { // Arrange var value = " \r\n\t"; // Act & Assert Assert.Throws<ArgumentException>(() => value.ThrowIfNullOrWhitespace(nameof(value))); } [Fact] public void ThrowIfNullOrWhitespace_ArgumentIsNotOrWhitespace_DoesNotThrow() { // Arrange var value = "test"; // Act & Assert value.ThrowIfNullOrWhitespace(nameof(value)); } } }
{ "content_hash": "bc2e87dd3c84a123b2d49482ab53b134", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 100, "avg_line_length": 28.163265306122447, "alnum_prop": 0.5927536231884057, "repo_name": "dr-noise/PolyGen", "id": "971230c71fa290928448e17447fbbbee0d3ac405", "size": "1380", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/NoiseLab.Common.UnitTests/Extensions/StringExtensionsTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "146462" } ], "symlink_target": "" }
package org.javarosa.core.model; import org.javarosa.core.log.WrappedException; import org.javarosa.core.model.actions.Action; import org.javarosa.core.model.actions.ActionController; import org.javarosa.core.model.condition.Condition; import org.javarosa.core.model.condition.Constraint; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.condition.IConditionExpr; import org.javarosa.core.model.condition.IFunctionHandler; import org.javarosa.core.model.condition.Recalculate; import org.javarosa.core.model.condition.Triggerable; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.IntegerData; import org.javarosa.core.model.data.SelectMultiData; import org.javarosa.core.model.data.SelectOneData; import org.javarosa.core.model.data.helper.Selection; import org.javarosa.core.model.instance.AbstractTreeElement; import org.javarosa.core.model.instance.DataInstance; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.model.instance.InstanceInitializationFactory; import org.javarosa.core.model.instance.InvalidReferenceException; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.model.trace.EvaluationTrace; import org.javarosa.core.model.util.restorable.RestoreUtils; import org.javarosa.core.model.utils.QuestionPreloader; import org.javarosa.core.services.locale.Localizer; import org.javarosa.core.services.storage.IMetaData; import org.javarosa.core.services.storage.Persistable; import org.javarosa.core.util.CacheTable; import org.javarosa.core.util.DataUtil; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.ExtUtil; import org.javarosa.core.util.externalizable.ExtWrapList; import org.javarosa.core.util.externalizable.ExtWrapListPoly; import org.javarosa.core.util.externalizable.ExtWrapMap; import org.javarosa.core.util.externalizable.ExtWrapNullable; import org.javarosa.core.util.externalizable.ExtWrapTagged; import org.javarosa.core.util.externalizable.PrototypeFactory; import org.javarosa.model.xform.XPathReference; import org.javarosa.xpath.XPathException; import org.javarosa.xpath.XPathTypeMismatchException; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.NoSuchElementException; import java.util.Vector; /** * Definition of a form. This has some meta data about the form definition and a * collection of groups together with question branching or skipping rules. * * @author Daniel Kayiwa, Drew Roos */ public class FormDef implements IFormElement, Persistable, IMetaData, ActionController.ActionResultProcessor { public static final String STORAGE_KEY = "FORMDEF"; public static final int TEMPLATING_RECURSION_LIMIT = 10; /** * Hierarchy of questions, groups and repeats in the form */ private Vector<IFormElement> children; /** * A collection of group definitions. */ private int id; /** * The numeric unique identifier of the form definition on the local device */ private String title; /** * The display title of the form. */ private String name; private Vector<XFormExtension> extensions; /** * A unique external name that is used to identify the form between machines */ private Localizer localizer; // This list is topologically ordered, meaning for any tA // and tB in the list, where tA comes before tB, evaluating tA cannot // depend on any result from evaluating tB private Vector<Triggerable> triggerables; // true if triggerables has been ordered topologically (DON'T DELETE ME // EVEN THOUGH I'M UNUSED) private boolean triggerablesInOrder; // <IConditionExpr> contents of <output> tags that serve as parameterized // arguments to captions private Vector outputFragments; /** * Map references to the calculate/relevancy conditions that depend on that * reference's value. Used to trigger re-evaluation of those conditionals * when the reference is updated. */ private Hashtable<TreeReference, Vector<Triggerable>> triggerIndex; /** * Associates repeatable nodes with the Condition that determines their * relevancy. */ private Hashtable<TreeReference, Condition> conditionRepeatTargetIndex; public EvaluationContext exprEvalContext; private QuestionPreloader preloader = new QuestionPreloader(); // XML ID's cannot start with numbers, so this should never conflict private static final String DEFAULT_SUBMISSION_PROFILE = "1"; private Hashtable<String, SubmissionProfile> submissionProfiles; /** * Secondary and external instance pointers */ private Hashtable<String, DataInstance> formInstances; private FormInstance mainInstance = null; boolean mDebugModeEnabled = false; private final Vector<Triggerable> triggeredDuringInsert = new Vector<Triggerable>(); private ActionController actionController; //If this instance is just being edited, don't fire end of form events private boolean isCompletedInstance; /** * Cache children that trigger target will cascade to. For speeding up * calculations that determine what needs to be triggered when a value * changes. */ private final CacheTable<TreeReference, Vector<TreeReference>> cachedCascadingChildren = new CacheTable<TreeReference, Vector<TreeReference>>(); public FormDef() { setID(-1); setChildren(null); triggerables = new Vector<Triggerable>(); triggerablesInOrder = true; triggerIndex = new Hashtable<TreeReference, Vector<Triggerable>>(); //This is kind of a wreck... setEvaluationContext(new EvaluationContext(null)); outputFragments = new Vector(); submissionProfiles = new Hashtable<String, SubmissionProfile>(); formInstances = new Hashtable<String, DataInstance>(); extensions = new Vector<XFormExtension>(); actionController = new ActionController(); } /** * Getters and setters for the vectors tha */ public void addNonMainInstance(DataInstance instance) { formInstances.put(instance.getInstanceId(), instance); this.setEvaluationContext(new EvaluationContext(null)); } /** * Get an instance based on a name */ public DataInstance getNonMainInstance(String name) { if (!formInstances.containsKey(name)) { return null; } return formInstances.get(name); } public Enumeration getNonMainInstances() { return formInstances.elements(); } /** * Set the main instance */ public void setInstance(FormInstance fi) { mainInstance = fi; fi.setFormId(getID()); this.setEvaluationContext(new EvaluationContext(null)); attachControlsToInstanceData(); } /** * Get the main instance */ public FormInstance getMainInstance() { return mainInstance; } public FormInstance getInstance() { return getMainInstance(); } // ---------- child elements public void addChild(IFormElement fe) { this.children.addElement(fe); } public IFormElement getChild(int i) { if (i < this.children.size()) return this.children.elementAt(i); throw new ArrayIndexOutOfBoundsException( "FormDef: invalid child index: " + i + " only " + children.size() + " children"); } public IFormElement getChild(FormIndex index) { IFormElement element = this; while (index != null && index.isInForm()) { element = element.getChild(index.getLocalIndex()); index = index.getNextLevel(); } return element; } /** * Dereference the form index and return a Vector of all interstitial nodes * (top-level parent first; index target last) * * Ignore 'new-repeat' node for now; just return/stop at ref to * yet-to-be-created repeat node (similar to repeats that already exist) */ public Vector explodeIndex(FormIndex index) { Vector<Integer> indexes = new Vector<Integer>(); Vector<Integer> multiplicities = new Vector<Integer>(); Vector<IFormElement> elements = new Vector<IFormElement>(); collapseIndex(index, indexes, multiplicities, elements); return elements; } // take a reference, find the instance node it refers to (factoring in // multiplicities) public TreeReference getChildInstanceRef(FormIndex index) { Vector<Integer> indexes = new Vector<Integer>(); Vector<Integer> multiplicities = new Vector<Integer>(); Vector<IFormElement> elements = new Vector<IFormElement>(); collapseIndex(index, indexes, multiplicities, elements); return getChildInstanceRef(elements, multiplicities); } /** * Return a tree reference which follows the path down the concrete elements provided * along with the multiplicities provided. */ public TreeReference getChildInstanceRef(Vector<IFormElement> elements, Vector<Integer> multiplicities) { if (elements.size() == 0) { return null; } // get reference for target element TreeReference ref = FormInstance.unpackReference(elements.lastElement().getBind()).clone(); for (int i = 0; i < ref.size(); i++) { //There has to be a better way to encapsulate this if (ref.getMultiplicity(i) != TreeReference.INDEX_ATTRIBUTE) { ref.setMultiplicity(i, 0); } } // fill in multiplicities for repeats along the way for (int i = 0; i < elements.size(); i++) { IFormElement temp = elements.elementAt(i); if (temp instanceof GroupDef && ((GroupDef)temp).getRepeat()) { TreeReference repRef = FormInstance.unpackReference(temp.getBind()); if (repRef.isParentOf(ref, false)) { int repMult = multiplicities.elementAt(i).intValue(); ref.setMultiplicity(repRef.size() - 1, repMult); } else { // question/repeat hierarchy is not consistent with // instance instance and bindings return null; } } } return ref; } public void setLocalizer(Localizer l) { if (this.localizer != null) { this.localizer.unregisterLocalizable(this); } this.localizer = l; if (this.localizer != null) { this.localizer.registerLocalizable(this); } } // don't think this should ever be called(!) public XPathReference getBind() { throw new RuntimeException("method not implemented"); } public void setValue(IAnswerData data, TreeReference ref) { setValue(data, ref, mainInstance.resolveReference(ref)); } public void setValue(IAnswerData data, TreeReference ref, TreeElement node) { setAnswer(data, node); triggerTriggerables(ref); //TODO: pre-populate fix-count repeats here? } public void setAnswer(IAnswerData data, TreeReference ref) { setAnswer(data, mainInstance.resolveReference(ref)); } public void setAnswer(IAnswerData data, TreeElement node) { node.setAnswer(data); } /** * Deletes the inner-most repeat that this node belongs to and returns the * corresponding FormIndex. Behavior is currently undefined if you call this * method on a node that is not contained within a repeat. */ public FormIndex deleteRepeat(FormIndex index) { Vector indexes = new Vector(); Vector multiplicities = new Vector(); Vector elements = new Vector(); collapseIndex(index, indexes, multiplicities, elements); // loop backwards through the elements, removing objects from each // vector, until we find a repeat // TODO: should probably check to make sure size > 0 for (int i = elements.size() - 1; i >= 0; i--) { IFormElement e = (IFormElement)elements.elementAt(i); if (e instanceof GroupDef && ((GroupDef)e).getRepeat()) { break; } else { indexes.removeElementAt(i); multiplicities.removeElementAt(i); elements.removeElementAt(i); } } // build new formIndex which includes everything // up to the node we're going to remove FormIndex newIndex = buildIndex(indexes, multiplicities, elements); TreeReference deleteRef = getChildInstanceRef(newIndex); TreeElement deleteElement = mainInstance.resolveReference(deleteRef); TreeReference parentRef = deleteRef.getParentRef(); TreeElement parentElement = mainInstance.resolveReference(parentRef); parentElement.removeChild(deleteElement); reduceTreeSiblingMultiplicities(parentElement, deleteElement); this.getMainInstance().cleanCache(); triggerTriggerables(deleteRef); return newIndex; } /** * When a repeat is deleted, we need to reduce the multiplicities of its siblings that were higher than it * by one. * @param parentElement the parent of the deleted element * @param deleteElement the deleted element */ private void reduceTreeSiblingMultiplicities(TreeElement parentElement, TreeElement deleteElement){ int childMult = deleteElement.getMult(); // update multiplicities of other child nodes for (int i = 0; i < parentElement.getNumChildren(); i++) { TreeElement child = parentElement.getChildAt(i); // We also need to check that this element matches the deleted element (besides multiplicity) // in the case where the deleted repeat's parent isn't a subgroup if (child.doFieldsMatch(deleteElement) && child.getMult() > childMult) { child.setMult(child.getMult() - 1); } } } public void createNewRepeat(FormIndex index) throws InvalidReferenceException { TreeReference repeatContextRef = getChildInstanceRef(index); TreeElement template = mainInstance.getTemplate(repeatContextRef); mainInstance.copyNode(template, repeatContextRef); preloadInstance(mainInstance.resolveReference(repeatContextRef)); // Fire jr-insert events before "calculate"s triggeredDuringInsert.removeAllElements(); actionController.triggerActionsFromEvent(Action.EVENT_JR_INSERT, this, repeatContextRef, this); // trigger conditions that depend on the creation of this new node triggerTriggerables(repeatContextRef); // trigger conditions for the node (and sub-nodes) initTriggerablesRootedBy(repeatContextRef, triggeredDuringInsert); } @Override public void processResultOfAction(TreeReference refSetByAction, String event) { if (Action.EVENT_JR_INSERT.equals(event)) { Vector<Triggerable> triggerables = triggerIndex.get(refSetByAction.genericize()); if (triggerables != null) { for (Triggerable elem : triggerables) { triggeredDuringInsert.addElement(elem); } } } } public boolean isRepeatRelevant(TreeReference repeatRef) { boolean relev = true; Condition c = conditionRepeatTargetIndex.get(repeatRef.genericize()); if (c != null) { relev = c.evalBool(mainInstance, new EvaluationContext(exprEvalContext, repeatRef)); } //check the relevancy of the immediate parent if (relev) { TreeElement templNode = mainInstance.getTemplate(repeatRef); TreeReference parentPath = templNode.getParent().getRef().genericize(); TreeElement parentNode = mainInstance.resolveReference(parentPath.contextualize(repeatRef)); relev = parentNode.isRelevant(); } return relev; } /** * Does the repeat group at the given index enable users to add more items, * and if so, has the user reached the item limit? * * @param repeatRef Reference pointing to a particular repeat item * @param repeatIndex Id for looking up the repeat group * @return Do the current constraints on the repeat group allow for adding * more children? */ public boolean canCreateRepeat(TreeReference repeatRef, FormIndex repeatIndex) { GroupDef repeat = (GroupDef)this.getChild(repeatIndex); //Check to see if this repeat can have children added by the user if (repeat.noAddRemove) { //Check to see if there's a count to use to determine how many children this repeat //should have if (repeat.getCountReference() != null) { int currentMultiplicity = repeatIndex.getElementMultiplicity(); TreeReference absPathToCount = repeat.getConextualizedCountReference(repeatRef); AbstractTreeElement countNode = this.getMainInstance().resolveReference(absPathToCount); if (countNode == null) { throw new XPathTypeMismatchException("Could not find the location " + absPathToCount.toString() + " where the repeat at " + repeatRef.toString(false) + " is looking for its count"); } //get the total multiplicity possible IAnswerData boxedCount = countNode.getValue(); int count; if (boxedCount == null) { count = 0; } else { try { count = ((Integer)new IntegerData().cast(boxedCount.uncast()).getValue()).intValue(); } catch (IllegalArgumentException iae) { throw new XPathTypeMismatchException("The repeat count value \"" + boxedCount.uncast().getString() + "\" at " + absPathToCount.toString() + " must be a number!"); } } if (count <= currentMultiplicity) { return false; } } else { //Otherwise the user can never add repeat instances return false; } } //TODO: If we think the node is still relevant, we also need to figure out a way to test that assumption against //the repeat's constraints. return true; } public void copyItemsetAnswer(QuestionDef q, TreeElement targetNode, IAnswerData data) throws InvalidReferenceException { ItemsetBinding itemset = q.getDynamicChoices(); TreeReference targetRef = targetNode.getRef(); TreeReference destRef = itemset.getDestRef().contextualize(targetRef); Vector<Selection> selections = null; Vector<String> selectedValues = new Vector<String>(); if (data instanceof SelectMultiData) { selections = (Vector<Selection>)data.getValue(); } else if (data instanceof SelectOneData) { selections = new Vector<Selection>(); selections.addElement((Selection)data.getValue()); } if (itemset.valueRef != null) { for (int i = 0; i < selections.size(); i++) { selectedValues.addElement(selections.elementAt(i).choice.getValue()); } } //delete existing dest nodes that are not in the answer selection Hashtable<String, TreeElement> existingValues = new Hashtable<String, TreeElement>(); Vector<TreeReference> existingNodes = exprEvalContext.expandReference(destRef); for (int i = 0; i < existingNodes.size(); i++) { TreeElement node = getMainInstance().resolveReference(existingNodes.elementAt(i)); if (itemset.valueRef != null) { String value = itemset.getRelativeValue().evalReadable(this.getMainInstance(), new EvaluationContext(exprEvalContext, node.getRef())); if (selectedValues.contains(value)) { existingValues.put(value, node); //cache node if in selection and already exists } } //delete from target targetNode.removeChild(node); } //copy in nodes for new answer; preserve ordering in answer for (int i = 0; i < selections.size(); i++) { Selection s = selections.elementAt(i); SelectChoice ch = s.choice; TreeElement cachedNode = null; if (itemset.valueRef != null) { String value = ch.getValue(); if (existingValues.containsKey(value)) { cachedNode = existingValues.get(value); } } if (cachedNode != null) { cachedNode.setMult(i); targetNode.addChild(cachedNode); } else { getMainInstance().copyItemsetNode(ch.copyNode, destRef, this); } } // trigger conditions that depend on the creation of these new nodes triggerTriggerables(destRef); // initialize conditions for the node (and sub-nodes) // NOTE PLM: the following trigger initialization doesn't cascade to // children because it is behaving like trigger initalization for new // repeat entries. If we begin actually using this method, the trigger // cascading logic should be fixed. initTriggerablesRootedBy(destRef, new Vector<Triggerable>()); // not 100% sure this will work since destRef is ambiguous as the last // step, but i think it's supposed to work } /** * Add a Condition to the form's Collection. */ public Triggerable addTriggerable(Triggerable t) { int existingIx = triggerables.indexOf(t); if (existingIx != -1) { // One node may control access to many nodes; this means many nodes // effectively have the same condition. Let's identify when // conditions are the same, and store and calculate it only once. // nov-2-2011: ctsims - We need to merge the context nodes together // whenever we do this (finding the highest common ground between // the two), otherwise we can end up failing to trigger when the // ignored context exists and the used one doesn't Triggerable existingTriggerable = triggerables.elementAt(existingIx); existingTriggerable.contextRef = existingTriggerable.contextRef.intersect(t.contextRef); return existingTriggerable; // NOTE: if the contextRef is unnecessarily deep, the condition // will be evaluated more times than needed. Perhaps detect when // 'identical' condition has a shorter contextRef, and use that one // instead? } else { triggerables.addElement(t); triggerablesInOrder = false; for (TreeReference trigger : t.getTriggers()) { TreeReference predicatelessTrigger = t.widenContextToAndClearPredicates(trigger); if (!triggerIndex.containsKey(predicatelessTrigger)) { triggerIndex.put(predicatelessTrigger.clone(), new Vector<Triggerable>()); } Vector<Triggerable> triggered = triggerIndex.get(predicatelessTrigger); if (!triggered.contains(t)) { triggered.addElement(t); } } return t; } } /** * Dependency-sorted enumerator for the triggerables present in the form. * * @return Enumerator of triggerables such that when an element X precedes * Y then X doesn't have any references that are dependent on Y. */ public Enumeration getTriggerables() { return triggerables.elements(); } /** * @return All references in the form that are depended on by * calculate/relevancy conditions. */ public Enumeration refWithTriggerDependencies() { return triggerIndex.keys(); } /** * Get the triggerable conditions, like relevancy/calculate, that depend on * the given reference. * * @param ref An absolute reference that is used in relevancy/calculate * expressions. * @return All the triggerables that depend on the given reference. */ public Vector conditionsTriggeredByRef(TreeReference ref) { return triggerIndex.get(ref); } /** * Finalize the DAG associated with the form's triggered conditions. This will create * the appropriate ordering and dependencies to ensure the conditions will be evaluated * in the appropriate orders. * * @throws IllegalStateException If the trigger ordering contains an illegal cycle and the * triggers can't be laid out appropriately */ public void finalizeTriggerables() throws IllegalStateException { Vector<Triggerable[]> partialOrdering = new Vector<Triggerable[]>(); buildPartialOrdering(partialOrdering); Vector<Triggerable> vertices = new Vector<Triggerable>(); for (Triggerable triggerable : triggerables) { vertices.addElement(triggerable); } triggerables.removeAllElements(); while (vertices.size() > 0) { Vector<Triggerable> roots = buildRootNodes(vertices, partialOrdering); if (roots.size() == 0) { // if no root nodes while graph still has nodes, graph has cycles throwGraphCyclesException(vertices); } setOrderOfTriggerable(roots, vertices, partialOrdering); } triggerablesInOrder = true; buildConditionRepeatTargetIndex(); } private void buildPartialOrdering(Vector<Triggerable[]> partialOrdering) { for (Triggerable t : triggerables) { Vector<Triggerable> deps = new Vector<Triggerable>(); fillTriggeredElements(t, deps, false); for (Triggerable u : deps) { Triggerable[] edge = {t, u}; partialOrdering.addElement(edge); } } } private static Vector<Triggerable> buildRootNodes(Vector<Triggerable> vertices, Vector<Triggerable[]> partialOrdering) { Vector<Triggerable> roots = new Vector<Triggerable>(); for (Triggerable vertex : vertices) { roots.addElement(vertex); } for (Triggerable[] edge : partialOrdering) { edge[1].updateStopContextualizingAtFromDominator(edge[0]); roots.removeElement(edge[1]); } return roots; } private void throwGraphCyclesException(Vector<Triggerable> vertices) { String hints = ""; for (Triggerable t : vertices) { for (TreeReference r : t.getTargets()) { hints += "\n" + r.toString(true); } } String message = "Cycle detected in form's relevant and calculation logic!"; if (!hints.equals("")) { message += "\nThe following nodes are likely involved in the loop:" + hints; } throw new IllegalStateException(message); } private void setOrderOfTriggerable(Vector<Triggerable> roots, Vector<Triggerable> vertices, Vector<Triggerable[]> partialOrdering) { for (Triggerable root : roots) { triggerables.addElement(root); vertices.removeElement(root); } for (int i = partialOrdering.size() - 1; i >= 0; i--) { Triggerable[] edge = partialOrdering.elementAt(i); if (roots.contains(edge[0])) partialOrdering.removeElementAt(i); } } private void buildConditionRepeatTargetIndex() { conditionRepeatTargetIndex = new Hashtable<TreeReference, Condition>(); for (Triggerable t : triggerables) { if (t instanceof Condition) { for (TreeReference target : t.getTargets()) { if (mainInstance.getTemplate(target) != null) { conditionRepeatTargetIndex.put(target, (Condition)t); } } } } } /** * Get all of the elements which will need to be evaluated (in order) when * the triggerable is fired. * * @param destination (mutated) Will have triggerables added to it. * @param isRepeatEntryInit Don't cascade triggers to children when * initializing a new repeat entry. Repeat entry * children have already been queued to be * triggered. */ private void fillTriggeredElements(Triggerable t, Vector<Triggerable> destination, boolean isRepeatEntryInit) { if (t.canCascade()) { for (TreeReference target : t.getTargets()) { Vector<TreeReference> updatedNodes = new Vector<TreeReference>(); updatedNodes.addElement(target); // Repeat sub-elements have already been added to 'destination' // when we grabbed all triggerables that target children of the // repeat entry (via initTriggerablesRootedBy). Hence skip them if (!isRepeatEntryInit && t.isCascadingToChildren()) { updatedNodes = findCascadeReferences(target, updatedNodes); } addTriggerablesTargetingNodes(updatedNodes, destination); } } } /** * Gather list of generic references to children of a target reference for * a triggerable that cascades to its children. This is needed when, for * example, changing the relevancy of the target will require the triggers * pointing to children be recalcualted. * * @param target Gather children of this by using a template or * manually traversing the tree * @param updatedNodes (potentially mutated) Gets generic child references * added to it. * @return Potentially cached version of updatedNodes argument that * contains the target and generic references to the children it might * cascade to. */ private Vector<TreeReference> findCascadeReferences(TreeReference target, Vector<TreeReference> updatedNodes) { Vector<TreeReference> cachedNodes = cachedCascadingChildren.retrieve(target); if (cachedNodes == null) { if (target.getMultLast() == TreeReference.INDEX_ATTRIBUTE) { // attributes don't have children that might change under // contextualization cachedCascadingChildren.register(target, updatedNodes); } else { Vector<TreeReference> expandedRefs = exprEvalContext.expandReference(target); if (expandedRefs.size() > 0) { AbstractTreeElement template = mainInstance.getTemplatePath(target); if (template != null) { addChildrenOfElement(template, updatedNodes); cachedCascadingChildren.register(target, updatedNodes); } else { // NOTE PLM: entirely possible this can be removed if // the getTemplatePath code is updated to handle // heterogeneous paths. Set a breakpoint here and run // the test suite to see an example // NOTE PLM: Though I'm pretty sure we could cache // this, I'm going to avoid doing so because I'm unsure // whether it is possible for children that are // cascaded to will change when expandedRefs changes // due to new data being added. addChildrenOfReference(expandedRefs, updatedNodes); } } } } else { updatedNodes = cachedNodes; } return updatedNodes; } /** * Resolve the expanded references and gather their generic children and * attributes into the genericRefs list. */ private void addChildrenOfReference(Vector<TreeReference> expandedRefs, Vector<TreeReference> genericRefs) { for (TreeReference ref : expandedRefs) { addChildrenOfElement(exprEvalContext.resolveReference(ref), genericRefs); } } /** * Gathers generic children and attribute references for the provided * element into the genericRefs list. */ private static void addChildrenOfElement(AbstractTreeElement treeElem, Vector<TreeReference> genericRefs) { // recursively add children of element for (int i = 0; i < treeElem.getNumChildren(); ++i) { AbstractTreeElement child = treeElem.getChildAt(i); TreeReference genericChild = child.getRef().genericize(); if (!genericRefs.contains(genericChild)) { genericRefs.addElement(genericChild); } addChildrenOfElement(child, genericRefs); } // add all the attributes of this element for (int i = 0; i < treeElem.getAttributeCount(); ++i) { AbstractTreeElement child = treeElem.getAttribute(treeElem.getAttributeNamespace(i), treeElem.getAttributeName(i)); TreeReference genericChild = child.getRef().genericize(); if (!genericRefs.contains(genericChild)) { genericRefs.addElement(genericChild); } } } private void addTriggerablesTargetingNodes(Vector<TreeReference> updatedNodes, Vector<Triggerable> destination) { //Now go through each of these updated nodes (generally just 1 for a normal calculation, //multiple nodes if there's a relevance cascade. for (TreeReference ref : updatedNodes) { //Check our index to see if that target is a Trigger for other conditions //IE: if they are an element of a different calculation or relevancy calc //We can't make this reference generic before now or we'll lose the target information, //so we'll be more inclusive than needed and see if any of our triggers are keyed on //the predicate-less path of this ref TreeReference predicatelessRef = ref; if (ref.hasPredicates()) { predicatelessRef = ref.removePredicates(); } Vector<Triggerable> triggered = triggerIndex.get(predicatelessRef); if (triggered != null) { //If so, walk all of these triggerables that we found for (Triggerable triggerable : triggered) { //And add them to the queue if they aren't there already if (!destination.contains(triggerable)) { destination.addElement(triggerable); } } } } } /** * Enables debug traces in this form, which can be requested as a map after * this call has been performed. Debug traces will be available until they * are explicitly disabled. * * This call also re-executes all triggerables in debug mode to make their * current traces available. * * Must be called after this form is initialized. */ public void enableDebugTraces() { if (!mDebugModeEnabled) { for (int i = 0; i < triggerables.size(); i++) { Triggerable t = triggerables.elementAt(i); t.setDebug(true); } // Re-execute all triggerables to collect traces initAllTriggerables(); mDebugModeEnabled = true; } } /** * Disable debug tracing for this form. Debug traces will no longer be * available after this call. */ public void disableDebugTraces() { if (mDebugModeEnabled) { for (int i = 0; i < triggerables.size(); i++) { Triggerable t = triggerables.elementAt(i); t.setDebug(false); } mDebugModeEnabled = false; } } /** * Aggregates a map of evaluation traces collected by the form's * triggerables. * * @return A mapping from TreeReferences to a set of evaluation traces. The * traces are separated out by triggerable category (calculate, relevant, * etc) and represent the execution of the last expression that was * executed for that trigger. * @throws IllegalStateException If debugging has not been enabled. */ public Hashtable<TreeReference, Hashtable<String, EvaluationTrace>> getDebugTraceMap() throws IllegalStateException { if (!mDebugModeEnabled) { throw new IllegalStateException("Debugging is not enabled"); } // TODO: sure would be nice to be able to cache this at some point, but // will have to have a way to invalidate by trigger or something Hashtable<TreeReference, Hashtable<String, EvaluationTrace>> debugInfo = new Hashtable<TreeReference, Hashtable<String, EvaluationTrace>>(); for (int i = 0; i < triggerables.size(); i++) { Triggerable t = triggerables.elementAt(i); Hashtable<TreeReference, EvaluationTrace> triggerOutputs = t.getEvaluationTraces(); for (Enumeration e = triggerOutputs.keys(); e.hasMoreElements(); ) { TreeReference elementRef = (TreeReference)e.nextElement(); String label = t.getDebugLabel(); Hashtable<String, EvaluationTrace> traces = debugInfo.get(elementRef); if (traces == null) { traces = new Hashtable<String, EvaluationTrace>(); } traces.put(label, triggerOutputs.get(elementRef)); debugInfo.put(elementRef, traces); } } return debugInfo; } private void initAllTriggerables() { // Use all triggerables because we can assume they are rooted by rootRef TreeReference rootRef = TreeReference.rootRef(); Vector<Triggerable> applicable = new Vector<Triggerable>(); for (Triggerable triggerable : triggerables) { applicable.addElement(triggerable); } evaluateTriggerables(applicable, rootRef, false); } /** * Evaluate triggerables targeting references that are children of the * provided newly created (repeat instance) ref. Ignore all triggerables * that were already fired by processing the jr-insert action. Ignored * triggerables can still be fired if a dependency is modified. * * @param triggeredDuringInsert Triggerables that don't need to be fired * because they have already been fired while processing insert events */ private void initTriggerablesRootedBy(TreeReference rootRef, Vector<Triggerable> triggeredDuringInsert) { TreeReference genericRoot = rootRef.genericize(); Vector<Triggerable> applicable = new Vector<Triggerable>(); for (Triggerable triggerable : triggerables) { for (TreeReference target : triggerable.getTargets()) { if (genericRoot.isParentOf(target, false)) { if (!triggeredDuringInsert.contains(triggerable)) { applicable.addElement(triggerable); break; } } } } evaluateTriggerables(applicable, rootRef, true); } /** * The entry point for the DAG cascade after a value is changed in the model. * * @param ref The full contextualized unambiguous reference of the value that was * changed. */ public void triggerTriggerables(TreeReference ref) { //turn unambiguous ref into a generic ref //to identify what nodes should be triggered by this //reference changing TreeReference genericRef = ref.genericize(); //get triggerables which are activated by the generic reference Vector<Triggerable> triggered = triggerIndex.get(genericRef); if (triggered == null) { return; } //Our vector doesn't have a shallow copy op, so make one Vector<Triggerable> triggeredCopy = new Vector<Triggerable>(); for (int i = 0; i < triggered.size(); i++) { triggeredCopy.addElement(triggered.elementAt(i)); } //Evaluate all of the triggerables in our new vector evaluateTriggerables(triggeredCopy, ref, false); } /** * Step 2 in evaluating DAG computation updates from a value being changed * in the instance. This step is responsible for taking the root set of * directly triggered conditions, identifying which conditions should * further be triggered due to their update, and then dispatching all of * the evaluations. * * @param tv A vector of all of the trigerrables directly * triggered by the value changed. Will be mutated * by this method. * @param anchorRef The reference to original value that was updated * @param isRepeatEntryInit Don't cascade triggers to children when * initializing a new repeat entry. Repeat entry * children have already been queued to be * triggered. */ private void evaluateTriggerables(Vector<Triggerable> tv, TreeReference anchorRef, boolean isRepeatEntryInit) { // Update the list of triggerables that need to be evaluated. for (int i = 0; i < tv.size(); i++) { // NOTE PLM: tv may grow in size through iteration. Triggerable t = tv.elementAt(i); fillTriggeredElements(t, tv, isRepeatEntryInit); } // tv should now contain all of the triggerable components which are // going to need to be addressed by this update. // 'triggerables' is topologically-ordered by dependencies, so evaluate // the triggerables in 'tv' in the order they appear in 'triggerables' for (Triggerable triggerable : triggerables) { if (tv.contains(triggerable)) { evaluateTriggerable(triggerable, anchorRef); } } } /** * Step 3 in DAG cascade. evaluate the individual triggerable expressions * against the anchor (the value that changed which triggered * recomputation) * * @param triggerable The triggerable to be updated * @param anchorRef The reference to the value which was changed. */ private void evaluateTriggerable(Triggerable triggerable, TreeReference anchorRef) { // Contextualize the reference used by the triggerable against the anchor TreeReference contextRef = triggerable.narrowContextBy(anchorRef); // Now identify all of the fully qualified nodes which this triggerable // updates. (Multiple nodes can be updated by the same trigger) Vector<TreeReference> expandedReferences = exprEvalContext.expandReference(contextRef); for (TreeReference treeReference : expandedReferences) { triggerable.apply(mainInstance, exprEvalContext, treeReference, this); } } public boolean evaluateConstraint(TreeReference ref, IAnswerData data) { if (data == null) { return true; } TreeElement node = mainInstance.resolveReference(ref); Constraint c = node.getConstraint(); if (c == null) { return true; } EvaluationContext ec = new EvaluationContext(exprEvalContext, ref); ec.isConstraint = true; ec.candidateValue = data; return c.constraint.eval(mainInstance, ec); } public void setEvaluationContext(EvaluationContext ec) { ec = new EvaluationContext(mainInstance, formInstances, ec); initEvalContext(ec); this.exprEvalContext = ec; } public EvaluationContext getEvaluationContext() { return this.exprEvalContext; } private void initEvalContext(EvaluationContext ec) { if (!ec.getFunctionHandlers().containsKey("jr:itext")) { final FormDef f = this; ec.addFunctionHandler(new IFunctionHandler() { @Override public String getName() { return "jr:itext"; } @Override public Object eval(Object[] args, EvaluationContext ec) { String textID = (String)args[0]; try { //SUUUUPER HACKY String form = ec.getOutputTextForm(); if (form != null) { textID = textID + ";" + form; String result = f.getLocalizer().getRawText(f.getLocalizer().getLocale(), textID); return result == null ? "" : result; } else { String text = f.getLocalizer().getText(textID); return text == null ? "[itext:" + textID + "]" : text; } } catch (NoSuchElementException nsee) { return "[nolocale]"; } } @Override public Vector getPrototypes() { Class[] proto = {String.class}; Vector<Class[]> v = new Vector<Class[]>(); v.addElement(proto); return v; } @Override public boolean rawArgs() { return false; } }); } /* function to reverse a select value into the display label for that choice in the question it came from * * arg 1: select value * arg 2: string xpath referring to origin question; must be absolute path * * this won't work at all if the original label needed to be processed/calculated in some way (<output>s, etc.) (is this even allowed?) * likely won't work with multi-media labels * _might_ work for itemsets, but probably not very well or at all; could potentially work better if we had some context info * DOES work with localization * * it's mainly intended for the simple case of reversing a question with compile-time-static fields, for use inside an <output> */ if (!ec.getFunctionHandlers().containsKey("jr:choice-name")) { final FormDef f = this; ec.addFunctionHandler(new IFunctionHandler() { @Override public String getName() { return "jr:choice-name"; } @Override public Object eval(Object[] args, EvaluationContext ec) { try { String value = (String)args[0]; String questionXpath = (String)args[1]; TreeReference ref = RestoreUtils.ref(questionXpath); QuestionDef q = FormDef.findQuestionByRef(ref, f); if (q == null || (q.getControlType() != Constants.CONTROL_SELECT_ONE && q.getControlType() != Constants.CONTROL_SELECT_MULTI)) { return ""; } System.out.println("here!!"); Vector<SelectChoice> choices = q.getChoices(); for (SelectChoice ch : choices) { if (ch.getValue().equals(value)) { //this is really not ideal. we should hook into the existing code (FormEntryPrompt) for pulling //display text for select choices. however, it's hard, because we don't really have //any context to work with, and all the situations where that context would be used //don't make sense for trying to reverse a select value back to a label in an unrelated //expression String textID = ch.getTextID(); if (textID != null) { return f.getLocalizer().getText(textID); } else { return ch.getLabelInnerText(); } } } return ""; } catch (Exception e) { throw new WrappedException("error in evaluation of xpath function [choice-name]", e); } } @Override public Vector getPrototypes() { Class[] proto = {String.class, String.class}; Vector<Class[]> v = new Vector<Class[]>(); v.addElement(proto); return v; } @Override public boolean rawArgs() { return false; } }); } } public String fillTemplateString(String template, TreeReference contextRef) { return fillTemplateString(template, contextRef, new Hashtable()); } /** * Performs substitutions on place-holder template from form text by * evaluating args in template using the current context. * * @param template String * @param contextRef TreeReference * @param variables Hashtable<String, ?> * @return String with the all args in the template filled with appropriate * context values. */ public String fillTemplateString(String template, TreeReference contextRef, Hashtable<String, ?> variables) { // argument to value mapping Hashtable<String, String> args = new Hashtable<String, String>(); int depth = 0; // grab all template arguments that need to have substitutions performed Vector outstandingArgs = Localizer.getArgs(template); String templateAfterSubstitution; // Step through outstandingArgs from the template, looking up the value // they map to, evaluating that under the evaluation context and // storing in the local args mapping. // Then perform substitutions over the template until a fixpoint is found while (outstandingArgs.size() > 0) { for (int i = 0; i < outstandingArgs.size(); i++) { String argName = (String)outstandingArgs.elementAt(i); // lookup value an arg points to if it isn't in our local mapping if (!args.containsKey(argName)) { int ix = -1; try { ix = Integer.parseInt(argName); } catch (NumberFormatException nfe) { System.err.println("Warning: expect arguments to be numeric [" + argName + "]"); } if (ix < 0 || ix >= outputFragments.size()) { continue; } IConditionExpr expr = (IConditionExpr)outputFragments.elementAt(ix); EvaluationContext ec = new EvaluationContext(exprEvalContext, contextRef); ec.setOriginalContext(contextRef); ec.setVariables(variables); String value = expr.evalReadable(this.getMainInstance(), ec); args.put(argName, value); } } templateAfterSubstitution = Localizer.processArguments(template, args); // The last substitution made no progress, probably because the // argument isn't in outputFragments, so stop looping and // attempting more subs! if (template.equals(templateAfterSubstitution)) { return template; } template = templateAfterSubstitution; // Since strings being substituted might themselves have arguments that // need to be further substituted, we must recompute the unperformed // substitutions and continue to loop. outstandingArgs = Localizer.getArgs(template); if (depth++ >= TEMPLATING_RECURSION_LIMIT) { throw new RuntimeException("Dependency cycle in <output>s; recursion limit exceeded!!"); } } return template; } /** * Identify the itemset in the backend model, and create a set of SelectChoice * objects at the current question reference based on the data in the model. * * Will modify the itemset binding to contain the relevant choices * * @param itemset The binding for an itemset, where the choices will be populated * @param curQRef A reference to the current question's element, which will be * used to determine the values to be chosen from. */ public void populateDynamicChoices(ItemsetBinding itemset, TreeReference curQRef) { Vector<SelectChoice> choices = new Vector<SelectChoice>(); DataInstance fi; if (itemset.nodesetRef.getInstanceName() != null) //We're not dealing with the default instance { fi = getNonMainInstance(itemset.nodesetRef.getInstanceName()); if (fi == null) { throw new XPathException("Instance " + itemset.nodesetRef.getInstanceName() + " not found"); } } else { fi = getMainInstance(); } Vector<TreeReference> matches = itemset.nodesetExpr.evalNodeset(fi, new EvaluationContext(exprEvalContext, itemset.contextRef.contextualize(curQRef))); if (matches == null) { String instanceName = itemset.nodesetRef.getInstanceName(); if (instanceName == null) { // itemset references a path rooted in the main instance throw new XPathException("No items found at '" + itemset.nodesetRef + "'"); } else { // itemset references a path rooted in a lookup table throw new XPathException("Make sure the '" + instanceName + "' lookup table is available, and that its contents are accessible to the current user."); } } for (int i = 0; i < matches.size(); i++) { TreeReference item = matches.elementAt(i); String label = itemset.labelExpr.evalReadable(fi, new EvaluationContext(exprEvalContext, item)); String value = null; TreeElement copyNode = null; if (itemset.copyMode) { copyNode = this.getMainInstance().resolveReference(itemset.copyRef.contextualize(item)); } if (itemset.valueRef != null) { value = itemset.valueExpr.evalReadable(fi, new EvaluationContext(exprEvalContext, item)); } SelectChoice choice = new SelectChoice(label, value != null ? value : "dynamic:" + i, itemset.labelIsItext); choice.setIndex(i); if (itemset.copyMode) choice.copyNode = copyNode; choices.addElement(choice); } itemset.setChoices(choices, this.getLocalizer()); } public QuestionPreloader getPreloader() { return preloader; } public void setPreloader(QuestionPreloader preloads) { this.preloader = preloads; } @Override public void localeChanged(String locale, Localizer localizer) { for (Enumeration e = children.elements(); e.hasMoreElements(); ) { ((IFormElement)e.nextElement()).localeChanged(locale, localizer); } } public String toString() { return getTitle(); } /** * Preload the Data Model with the preload values that are enumerated in the * data bindings. */ public void preloadInstance(TreeElement node) { // if (node.isLeaf()) { IAnswerData preload = null; if (node.getPreloadHandler() != null) { preload = preloader.getQuestionPreload(node.getPreloadHandler(), node.getPreloadParams()); } if (preload != null) { // what if we want to wipe out a value in the // instance? node.setAnswer(preload); } // } else { if (!node.isLeaf()) { for (int i = 0; i < node.getNumChildren(); i++) { TreeElement child = node.getChildAt(i); if (child.getMult() != TreeReference.INDEX_TEMPLATE) // don't preload templates; new repeats are preloaded as they're created preloadInstance(child); } } // } } public boolean postProcessInstance() { if(!isCompletedInstance) { actionController.triggerActionsFromEvent(Action.EVENT_XFORMS_REVALIDATE, this); } return postProcessInstance(mainInstance.getRoot()); } /** * Iterate over the form's data bindings, and evaluate all post procesing * calls. * * @return true if the instance was modified in any way. false otherwise. */ private boolean postProcessInstance(TreeElement node) { // we might have issues with ordering, for example, a handler that writes a value to a node, // and a handler that does something external with the node. if both handlers are bound to the // same node, we need to make sure the one that alters the node executes first. deal with that later. // can we even bind multiple handlers to the same node currently? // also have issues with conditions. it is hard to detect what conditions are affected by the actions // of the post-processor. normally, it wouldn't matter because we only post-process when we are exiting // the form, so the result of any triggered conditions is irrelevant. however, if we save a form in the // interim, post-processing occurs, and then we continue to edit the form. it seems like having conditions // dependent on data written during post-processing is a bad practice anyway, and maybe we shouldn't support it. if (node.isLeaf()) { if (node.getPreloadHandler() != null) { return preloader.questionPostProcess(node, node.getPreloadHandler(), node.getPreloadParams()); } else { return false; } } else { boolean instanceModified = false; for (int i = 0; i < node.getNumChildren(); i++) { TreeElement child = node.getChildAt(i); if (child.getMult() != TreeReference.INDEX_TEMPLATE) instanceModified |= postProcessInstance(child); } return instanceModified; } } /** * Reads the form definition object from the supplied stream. * * Requires that the instance has been set to a prototype of the instance that * should be used for deserialization. */ @Override public void readExternal(DataInputStream dis, PrototypeFactory pf) throws IOException, DeserializationException { setID(ExtUtil.readInt(dis)); setName(ExtUtil.nullIfEmpty(ExtUtil.readString(dis))); setTitle((String)ExtUtil.read(dis, new ExtWrapNullable(String.class), pf)); setChildren((Vector)ExtUtil.read(dis, new ExtWrapListPoly(), pf)); setInstance((FormInstance)ExtUtil.read(dis, FormInstance.class, pf)); setLocalizer((Localizer)ExtUtil.read(dis, new ExtWrapNullable(Localizer.class), pf)); Vector vcond = (Vector)ExtUtil.read(dis, new ExtWrapList(Condition.class), pf); for (Enumeration e = vcond.elements(); e.hasMoreElements(); ) { addTriggerable((Condition)e.nextElement()); } Vector vcalc = (Vector)ExtUtil.read(dis, new ExtWrapList(Recalculate.class), pf); for (Enumeration e = vcalc.elements(); e.hasMoreElements(); ) { addTriggerable((Recalculate)e.nextElement()); } finalizeTriggerables(); outputFragments = (Vector)ExtUtil.read(dis, new ExtWrapListPoly(), pf); submissionProfiles = (Hashtable<String, SubmissionProfile>)ExtUtil.read(dis, new ExtWrapMap(String.class, SubmissionProfile.class), pf); formInstances = (Hashtable<String, DataInstance>)ExtUtil.read(dis, new ExtWrapMap(String.class, new ExtWrapTagged()), pf); extensions = (Vector)ExtUtil.read(dis, new ExtWrapListPoly(), pf); setEvaluationContext(new EvaluationContext(null)); actionController = (ActionController)ExtUtil.read(dis, ActionController.class, pf); } /** * meant to be called after deserialization and initialization of handlers * * @param newInstance true if the form is to be used for a new entry interaction, * false if it is using an existing IDataModel * @param isCompletedInstance true if this is an already completed instance we are editing * (presumably in HQ) - so don't fire end of form event. */ public void initialize(boolean newInstance, boolean isCompletedInstance, InstanceInitializationFactory factory) { initialize(newInstance, isCompletedInstance, factory, null); } public void initialize(boolean newInstance, InstanceInitializationFactory factory) { initialize(newInstance, false, factory, null); } public void initialize(boolean newInstance, InstanceInitializationFactory factory, String locale) { initialize(newInstance, false, factory, locale); } /** * meant to be called after deserialization and initialization of handlers * * @param newInstance true if the form is to be used for a new entry interaction, * false if it is using an existing IDataModel * @param locale The default locale in the current environment, if provided. Can be null * to rely on the form's internal default. */ public void initialize(boolean newInstance, boolean isCompletedInstance, InstanceInitializationFactory factory, String locale) { for (Enumeration en = formInstances.keys(); en.hasMoreElements(); ) { String instanceId = (String)en.nextElement(); DataInstance instance = formInstances.get(instanceId); formInstances.put(instanceId, instance.initialize(factory, instanceId)); } if (newInstance) { // only preload new forms (we may have to revisit this) preloadInstance(mainInstance.getRoot()); } initLocale(locale); if (newInstance) { // only dispatch on a form's first opening, not subsequent loadings // of saved instances. Ensures setvalues triggered by xform-ready, // useful for recording form start dates. actionController.triggerActionsFromEvent(Action.EVENT_XFORMS_READY, this); } this.isCompletedInstance = isCompletedInstance; initAllTriggerables(); } private void initLocale(String locale) { if (localizer != null) { if (locale == null || !localizer.hasLocale(locale)) { if (localizer.getLocale() == null) { localizer.setToDefault(); } } else { localizer.setLocale(locale); } } } /** * Writes the form definition object to the supplied stream. */ @Override public void writeExternal(DataOutputStream dos) throws IOException { ExtUtil.writeNumeric(dos, getID()); ExtUtil.writeString(dos, ExtUtil.emptyIfNull(getName())); ExtUtil.write(dos, new ExtWrapNullable(getTitle())); ExtUtil.write(dos, new ExtWrapListPoly(getChildren())); ExtUtil.write(dos, getMainInstance()); ExtUtil.write(dos, new ExtWrapNullable(localizer)); Vector<Condition> conditions = new Vector<Condition>(); Vector<Recalculate> recalcs = new Vector<Recalculate>(); for (int i = 0; i < triggerables.size(); i++) { Triggerable t = triggerables.elementAt(i); if (t instanceof Condition) { conditions.addElement((Condition)t); } else if (t instanceof Recalculate) { recalcs.addElement((Recalculate)t); } } ExtUtil.write(dos, new ExtWrapList(conditions)); ExtUtil.write(dos, new ExtWrapList(recalcs)); ExtUtil.write(dos, new ExtWrapListPoly(outputFragments)); ExtUtil.write(dos, new ExtWrapMap(submissionProfiles)); //for support of multi-instance forms ExtUtil.write(dos, new ExtWrapMap(formInstances, new ExtWrapTagged())); ExtUtil.write(dos, new ExtWrapListPoly(extensions)); ExtUtil.write(dos, actionController); } public void collapseIndex(FormIndex index, Vector<Integer> indexes, Vector<Integer> multiplicities, Vector<IFormElement> elements) { if (!index.isInForm()) { return; } IFormElement element = this; while (index != null) { int i = index.getLocalIndex(); element = element.getChild(i); indexes.addElement(DataUtil.integer(i)); multiplicities.addElement(DataUtil.integer(index.getInstanceIndex() == -1 ? 0 : index.getInstanceIndex())); elements.addElement(element); index = index.getNextLevel(); } } public FormIndex buildIndex(Vector indexes, Vector multiplicities, Vector elements) { FormIndex cur = null; Vector curMultiplicities = new Vector(); for (int j = 0; j < multiplicities.size(); ++j) { curMultiplicities.addElement(multiplicities.elementAt(j)); } Vector curElements = new Vector(); for (int j = 0; j < elements.size(); ++j) { curElements.addElement(elements.elementAt(j)); } for (int i = indexes.size() - 1; i >= 0; i--) { int ix = ((Integer)indexes.elementAt(i)).intValue(); int mult = ((Integer)multiplicities.elementAt(i)).intValue(); if (!(elements.elementAt(i) instanceof GroupDef && ((GroupDef)elements.elementAt(i)).getRepeat())) { mult = -1; } cur = new FormIndex(cur, ix, mult, getChildInstanceRef(curElements, curMultiplicities)); curMultiplicities.removeElementAt(curMultiplicities.size() - 1); curElements.removeElementAt(curElements.size() - 1); } return cur; } public int getNumRepetitions(FormIndex index) { Vector<Integer> indexes = new Vector(); Vector<Integer> multiplicities = new Vector(); Vector<IFormElement> elements = new Vector(); if (!index.isInForm()) { throw new RuntimeException("not an in-form index"); } collapseIndex(index, indexes, multiplicities, elements); if (!(elements.lastElement() instanceof GroupDef) || !((GroupDef)elements.lastElement()).getRepeat()) { throw new RuntimeException("current element not a repeat"); } //so painful TreeElement templNode = mainInstance.getTemplate(index.getReference()); TreeReference parentPath = templNode.getParent().getRef().genericize(); TreeElement parentNode = mainInstance.resolveReference(parentPath.contextualize(index.getReference())); return parentNode.getChildMultiplicity(templNode.getName()); } //repIndex == -1 => next repetition about to be created public FormIndex descendIntoRepeat(FormIndex index, int repIndex) { int numRepetitions = getNumRepetitions(index); Vector<Integer> indexes = new Vector(); Vector<Integer> multiplicities = new Vector(); Vector<IFormElement> elements = new Vector(); collapseIndex(index, indexes, multiplicities, elements); if (repIndex == -1) { repIndex = numRepetitions; } else { if (repIndex < 0 || repIndex >= numRepetitions) { throw new RuntimeException("selection exceeds current number of repetitions"); } } multiplicities.setElementAt(DataUtil.integer(repIndex), multiplicities.size() - 1); return buildIndex(indexes, multiplicities, elements); } /* * (non-Javadoc) * * @see org.javarosa.core.model.IFormElement#getDeepChildCount() */ public int getDeepChildCount() { int total = 0; Enumeration e = children.elements(); while (e.hasMoreElements()) { total += ((IFormElement)e.nextElement()).getDeepChildCount(); } return total; } public void registerStateObserver(FormElementStateListener qsl) { // NO. (Or at least not yet). } public void unregisterStateObserver(FormElementStateListener qsl) { // NO. (Or at least not yet). } public Vector getChildren() { return children; } public void setChildren(Vector children) { this.children = (children == null ? new Vector() : children); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public int getID() { return id; } @Override public void setID(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Localizer getLocalizer() { return localizer; } public Vector getOutputFragments() { return outputFragments; } public void setOutputFragments(Vector outputFragments) { this.outputFragments = outputFragments; } public Object getMetaData(String fieldName) { if (fieldName.equals("DESCRIPTOR")) { return name; } if (fieldName.equals("XMLNS")) { return ExtUtil.emptyIfNull(mainInstance.schema); } else { throw new IllegalArgumentException(); } } public String[] getMetaDataFields() { return new String[]{"DESCRIPTOR", "XMLNS"}; } /** * Link a deserialized instance back up with its parent FormDef. this allows select/select1 questions to be * internationalizable in chatterbox, and (if using CHOICE_INDEX mode) allows the instance to be serialized * to xml */ public void attachControlsToInstanceData() { attachControlsToInstanceData(getMainInstance().getRoot()); } private void attachControlsToInstanceData(TreeElement node) { for (int i = 0; i < node.getNumChildren(); i++) { attachControlsToInstanceData(node.getChildAt(i)); } IAnswerData val = node.getValue(); Vector selections = null; if (val instanceof SelectOneData) { selections = new Vector(); selections.addElement(val.getValue()); } else if (val instanceof SelectMultiData) { selections = (Vector)val.getValue(); } if (selections != null) { QuestionDef q = findQuestionByRef(node.getRef(), this); if (q == null) { throw new RuntimeException("FormDef.attachControlsToInstanceData: can't find question to link"); } if (q.getDynamicChoices() != null) { //droos: i think we should do something like initializing the itemset here, so that default answers //can be linked to the selectchoices. however, there are complications. for example, the itemset might //not be ready to be evaluated at form initialization; it may require certain questions to be answered //first. e.g., if we evaluate an itemset and it has no choices, the xform engine will throw an error //itemset TODO } for (int i = 0; i < selections.size(); i++) { Selection s = (Selection)selections.elementAt(i); s.attachChoice(q); } } } public static QuestionDef findQuestionByRef(TreeReference ref, IFormElement fe) { if (fe instanceof FormDef) { ref = ref.genericize(); } if (fe instanceof QuestionDef) { QuestionDef q = (QuestionDef)fe; TreeReference bind = FormInstance.unpackReference(q.getBind()); return (ref.equals(bind) ? q : null); } else { for (int i = 0; i < fe.getChildren().size(); i++) { QuestionDef ret = findQuestionByRef(ref, fe.getChild(i)); if (ret != null) return ret; } return null; } } /** * Appearance isn't a valid attribute for form, but this method must be included * as a result of conforming to the IFormElement interface. */ public String getAppearanceAttr() { throw new RuntimeException("This method call is not relevant for FormDefs getAppearanceAttr ()"); } /** * Appearance isn't a valid attribute for form, but this method must be included * as a result of conforming to the IFormElement interface. */ public void setAppearanceAttr(String appearanceAttr) { throw new RuntimeException("This method call is not relevant for FormDefs setAppearanceAttr()"); } @Override public ActionController getActionController() { return this.actionController; } /** * Not applicable here. */ public String getLabelInnerText() { return null; } /** * Not applicable */ public String getTextID() { return null; } /** * Not applicable */ public void setTextID(String textID) { throw new RuntimeException("This method call is not relevant for FormDefs [setTextID()]"); } public void setDefaultSubmission(SubmissionProfile profile) { submissionProfiles.put(DEFAULT_SUBMISSION_PROFILE, profile); } public void addSubmissionProfile(String submissionId, SubmissionProfile profile) { submissionProfiles.put(submissionId, profile); } public SubmissionProfile getSubmissionProfile() { //At some point these profiles will be set by the <submit> control in the form. //In the mean time, though, we can only promise that the default one will be used. return submissionProfiles.get(DEFAULT_SUBMISSION_PROFILE); } public <X extends XFormExtension> X getExtension(Class<X> extension) { for (XFormExtension ex : extensions) { if (ex.getClass().isAssignableFrom(extension)) { return (X)ex; } } X newEx; try { newEx = extension.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Illegally Structured XForm Extension " + extension.getName()); } catch (IllegalAccessException e) { throw new RuntimeException("Illegally Structured XForm Extension " + extension.getName()); } extensions.addElement(newEx); return newEx; } /** * Frees all of the components of this form which are no longer needed once it is completed. * * Once this is called, the form is no longer capable of functioning, but all data should be retained. */ public void seal() { triggerables = null; triggerIndex = null; conditionRepeatTargetIndex = null; //We may need ths one, actually exprEvalContext = null; } }
{ "content_hash": "4f2b5fb0150c143c9cc24dd4f19e7fd4", "timestamp": "", "source": "github", "line_count": 1938, "max_line_length": 150, "avg_line_length": 40.154798761609904, "alnum_prop": 0.6090465176047288, "repo_name": "dimagi/javarosa", "id": "c7a72e689a67b374b562c1cb448778783031c5b8", "size": "77820", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javarosa/core/src/main/java/org/javarosa/core/model/FormDef.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "63723" }, { "name": "HTML", "bytes": "16742" }, { "name": "Java", "bytes": "4375182" }, { "name": "Lex", "bytes": "4309" }, { "name": "Python", "bytes": "36334" } ], "symlink_target": "" }
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ 'use strict'; (function() { var _ = navigator.mozL10n.get; // Consts const STK_SCREEN_DEFAULT = 0x00; const STK_SCREEN_MAINMENU = 0x01; const STK_SCREEN_HELP = 0x02; /** * Init */ var iccMenuItem = document.getElementById('menuItem-icc'); var iccStkList = document.getElementById('icc-stk-list'); var iccStkHeader = document.getElementById('icc-stk-header'); var iccStkSubheader = document.getElementById('icc-stk-subheader'); var iccLastCommand = null; var iccLastCommandProcessed = false; var stkOpenAppName = null; var stkLastSelectedTest = null; var goBackTimer = { timer: null, timeout: 1000 }; var icc; init(); /** * Init STK UI */ function init() { if (!window.navigator.mozMobileConnection) { return; } icc = window.navigator.mozMobileConnection.icc; icc.onstksessionend = function handleSTKSessionEnd(event) { updateMenu(); }; document.getElementById('icc-stk-app-back').onclick = stkResGoBack; document.getElementById('icc-stk-help-exit').onclick = updateMenu; window.onunload = function() { responseSTKCommand({ resultCode: icc.STK_RESULT_NO_RESPONSE_FROM_USER }, true); }; window.addEventListener('stkasynccommand', function do_handleAsyncSTKCmd(event) { handleSTKCommand(event.detail.command); }); /** * Open STK main application */ iccMenuItem.onclick = function onclick() { updateMenu(); }; // Load STK apps updateMenu(); } function stkResTerminate() { iccLastCommandProcessed = true; responseSTKCommand({ resultCode: icc.STK_RESULT_UICC_SESSION_TERM_BY_USER }); } function stkResGoBack() { iccLastCommandProcessed = true; responseSTKCommand({ resultCode: icc.STK_RESULT_BACKWARD_MOVE_BY_USER }); // We'll return to settings if no STK response received in a grace period goBackTimer.timer = setTimeout(function() { Settings.currentPanel = '#root'; }, goBackTimer.timeout); }; function stkCancelGoBack() { if (goBackTimer.timer) { window.clearTimeout(goBackTimer.timer); goBackTimer.timer = null; } } /** * Updates the STK header buttons */ function setSTKScreenType(type) { var exit = document.getElementById('icc-stk-exit'); var back = document.getElementById('icc-stk-app-back'); var helpExit = document.getElementById('icc-stk-help-exit'); switch (type) { case STK_SCREEN_MAINMENU: exit.classList.remove('hidden'); back.classList.add('hidden'); helpExit.classList.add('hidden'); break; case STK_SCREEN_HELP: exit.classList.add('hidden'); back.classList.add('hidden'); helpExit.classList.remove('hidden'); break; default: // STK_SCREEN_DEFAULT exit.classList.add('hidden'); back.classList.remove('hidden'); helpExit.classList.add('hidden'); } } /** * Response ICC Command */ function responseSTKCommand(response, force) { if (!force && (!iccLastCommand || !iccLastCommandProcessed)) { DUMP('sendStkResponse NO COMMAND TO RESPONSE. Ignoring'); return; } DUMP('sendStkResponse to command: ', iccLastCommand); DUMP('sendStkResponse -- # response = ', response); icc.sendStkResponse(iccLastCommand, response); iccLastCommand = null; iccLastCommandProcessed = false; } /** * Handle ICC Commands */ function handleSTKCommand(command) { DUMP('STK Proactive Command:', command); iccLastCommand = command; var options = command.options; stkCancelGoBack(); // By default a generic screen setSTKScreenType(STK_SCREEN_DEFAULT); reopenSettings(); switch (command.typeOfCommand) { case icc.STK_CMD_SELECT_ITEM: updateSelection(command); openSTKApplication(); iccLastCommandProcessed = true; break; default: DUMP('STK Message not managed... response OK'); iccLastCommandProcessed = true; responseSTKCommand({ resultCode: icc.STK_RESULT_OK }); } } /** * Navigate through all available STK applications */ function updateMenu() { DUMP('Showing STK main menu'); stkOpenAppName = null; stkCancelGoBack(); var reqApplications = window.navigator.mozSettings.createLock().get('icc.applications'); reqApplications.onsuccess = function icc_getApplications() { var json = reqApplications.result['icc.applications']; var menu = json && JSON.parse(json); clearList(); setSTKScreenType(STK_SCREEN_MAINMENU); if (!menu || !menu.items || (menu.items.length == 1 && menu.items[0] === null)) { DUMP('No STK available - hide & exit'); document.getElementById('icc-mainheader').hidden = true; document.getElementById('icc-mainentry').hidden = true; return; } DUMP('STK Main App Menu title: ' + menu.title); DUMP('STK Main App Menu default item: ' + menu.defaultItem); iccMenuItem.textContent = menu.title; showTitle(menu.title); menu.items.forEach(function(menuItem) { DUMP('STK Main App Menu item: ' + menuItem.text + ' # ' + menuItem.identifier); iccStkList.appendChild(buildMenuEntry({ id: 'stk-menuitem-' + menuItem.identifier, text: menuItem.text, nai: _(menuItem.nai), onclick: onMainMenuItemClick, attributes: [['stk-menu-item-identifier', menuItem.identifier]] })); }); // Optional Help menu if (menu.isHelpAvailable) { iccStkList.appendChild(buildMenuEntry({ id: 'stk-helpmenuitem', text: _('operatorServices-helpmenu'), onclick: showHelpMenu, attributes: [] })); } }; } function onMainMenuItemClick(event) { var identifier = event.target.getAttribute('stk-menu-item-identifier'); DUMP('sendStkMenuSelection: ', identifier); icc.sendStkMenuSelection(identifier, false); stkLastSelectedTest = event.target.textContent; stkOpenAppName = stkLastSelectedTest; } function showHelpMenu(event) { DUMP('Showing STK help menu'); stkOpenAppName = null; var reqApplications = window.navigator.mozSettings.createLock().get('icc.applications'); reqApplications.onsuccess = function icc_getApplications() { var menu = JSON.parse(reqApplications.result['icc.applications']); clearList(); setSTKScreenType(STK_SCREEN_HELP); iccMenuItem.textContent = menu.title; showTitle(_('operatorServices-helpmenu')); menu.items.forEach(function(menuItem) { DUMP('STK Main App Help item: ' + menuItem.text + ' # ' + menuItem.identifier); iccStkList.appendChild(buildMenuEntry({ id: 'stk-helpitem-' + menuItem.identifier, text: menuItem.text, onclick: onMainMenuHelpItemClick, attributes: [['stk-help-item-identifier', menuItem.identifier]] })); }); }; } function onMainMenuHelpItemClick(event) { var identifier = event.target.getAttribute('stk-help-item-identifier'); DUMP('sendStkHelpMenuSelection: ', identifier); icc.sendStkMenuSelection(identifier, true); stkLastSelectedTest = event.target.textContent; stkOpenAppName = stkLastSelectedTest; } /** * Navigate through the STK application options */ function updateSelection(command) { var menu = command.options; DUMP('Showing STK menu'); clearList(); DUMP('STK App Menu title: ' + menu.title); DUMP('STK App Menu default item: ' + menu.defaultItem); showTitle(menu.title); menu.items.forEach(function(menuItem) { DUMP('STK App Menu item: ' + menuItem.text + ' # ' + menuItem.identifier); iccStkList.appendChild(buildMenuEntry({ id: 'stk-menuitem-' + menuItem.identifier, text: menuItem.text, nai: _(menuItem.nai), onclick: onSelectOptionClick.bind(null, command), attributes: [['stk-select-option-identifier', menuItem.identifier]] })); }); } function onSelectOptionClick(command, event) { var identifier = event.target.getAttribute('stk-select-option-identifier'); responseSTKCommand({ resultCode: icc.STK_RESULT_OK, itemIdentifier: identifier }); stkLastSelectedTest = event.target.textContent; } /** * Auxiliar methods */ function showTitle(title) { // If the application is automatically opened (no come from main menu) if (!stkOpenAppName) { stkOpenAppName = title; } iccStkHeader.textContent = stkOpenAppName; // Show section if (stkOpenAppName != title) { iccStkSubheader.textContent = title; iccStkSubheader.parentNode.classList.remove('hiddenheader'); } else { iccStkSubheader.textContent = ''; iccStkSubheader.parentNode.classList.add('hiddenheader'); } } function clearList() { while (iccStkList.hasChildNodes()) { iccStkList.removeChild(iccStkList.lastChild); } } function buildMenuEntry(entry) { var li = document.createElement('li'); if (entry.nai) { var small = document.createElement('small'); small.textContent = entry.nai; li.appendChild(small); } var a = document.createElement('a'); a.id = entry.id; entry.attributes.forEach(function attrIterator(attr) { a.setAttribute(attr[0], attr[1]); }); a.textContent = entry.text; a.onclick = entry.onclick; li.appendChild(a); return li; } /** * Open settings application with ICC section opened */ function openSTKApplication() { Settings.currentPanel = '#icc'; window.navigator.mozApps.getSelf().onsuccess = function getSelfCB(evt) { var app = evt.target.result; app.launch('settings'); }; }; })();
{ "content_hash": "0bb23f354002e5f8df3eed46d7e67f3c", "timestamp": "", "source": "github", "line_count": 362, "max_line_length": 79, "avg_line_length": 27.96685082872928, "alnum_prop": 0.6413472935598578, "repo_name": "sergecodd/FireFox-OS", "id": "75c6209771085053ee457b2d6bdcd9b240f4cfe9", "size": "10124", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "B2G/gaia/apps/settings/js/icc.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "443" }, { "name": "ApacheConf", "bytes": "85" }, { "name": "Assembly", "bytes": "5123438" }, { "name": "Awk", "bytes": "46481" }, { "name": "Batchfile", "bytes": "56250" }, { "name": "C", "bytes": "101720951" }, { "name": "C#", "bytes": "38531" }, { "name": "C++", "bytes": "148896543" }, { "name": "CMake", "bytes": "23541" }, { "name": "CSS", "bytes": "2758664" }, { "name": "DIGITAL Command Language", "bytes": "56757" }, { "name": "Emacs Lisp", "bytes": "12694" }, { "name": "Erlang", "bytes": "889" }, { "name": "FLUX", "bytes": "34449" }, { "name": "GLSL", "bytes": "26344" }, { "name": "Gnuplot", "bytes": "710" }, { "name": "Groff", "bytes": "447012" }, { "name": "HTML", "bytes": "43343468" }, { "name": "IDL", "bytes": "1455122" }, { "name": "Java", "bytes": "43261012" }, { "name": "JavaScript", "bytes": "46646658" }, { "name": "Lex", "bytes": "38358" }, { "name": "Logos", "bytes": "21054" }, { "name": "Makefile", "bytes": "2733844" }, { "name": "Matlab", "bytes": "67316" }, { "name": "Max", "bytes": "3698" }, { "name": "NSIS", "bytes": "421625" }, { "name": "Objective-C", "bytes": "877657" }, { "name": "Objective-C++", "bytes": "737713" }, { "name": "PHP", "bytes": "17415" }, { "name": "Pascal", "bytes": "6780" }, { "name": "Perl", "bytes": "1153180" }, { "name": "Perl6", "bytes": "1255" }, { "name": "PostScript", "bytes": "1139" }, { "name": "PowerShell", "bytes": "8252" }, { "name": "Protocol Buffer", "bytes": "26553" }, { "name": "Python", "bytes": "8453201" }, { "name": "Ragel in Ruby Host", "bytes": "3481" }, { "name": "Ruby", "bytes": "5116" }, { "name": "Scilab", "bytes": "7" }, { "name": "Shell", "bytes": "3383832" }, { "name": "SourcePawn", "bytes": "23661" }, { "name": "TeX", "bytes": "879606" }, { "name": "WebIDL", "bytes": "1902" }, { "name": "XSLT", "bytes": "13134" }, { "name": "Yacc", "bytes": "112744" } ], "symlink_target": "" }
<?php namespace Uj\Mail; use Zend\ModuleManager\Feature\AutoloaderProviderInterface; use Zend\ModuleManager\Feature\ConfigProviderInterface; use Zend\ModuleManager\Feature\ServiceProviderInterface; /** * Unjudder Mail Module * * @since 0.1 * @package Uj\Mail */ class Module implements AutoloaderProviderInterface, ConfigProviderInterface, ServiceProviderInterface { /** * The module's namespace * * @var string */ const NS = __NAMESPACE__; /** * The module's base path * * @var string */ const BASE_PATH = __DIR__; /** * Return Uj\Mail autoload config. * * @see AutoloaderProviderInterface::getAutoloaderConfig() * @return array */ public function getAutoloaderConfig() { return array( 'Zend\Loader\ClassMapAutoloader' => array( self::BASE_PATH . '/autoload_classmap.php', ), 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( self::NS => self::BASE_PATH . '/src/' . self::NS, ) ), ); } /** * Return the Uj\Mail module config. * * @see ConfigProviderInterface::getConfig() * @return array */ public function getConfig() { return include self::BASE_PATH . '/config/module.config.php'; } /** * Return the Uj\Mail service config. * * @see ServiceProviderInterface::getServiceConfig() * @return array */ public function getServiceConfig() { return include self::BASE_PATH . '/config/service.config.php'; } }
{ "content_hash": "ed94295b725d4713335b15f450ee143d", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 70, "avg_line_length": 22.533333333333335, "alnum_prop": 0.5698224852071005, "repo_name": "unjudder/zf2-mail", "id": "4b37ba38b5ac61a6c9ebe5d94e11a9135003cc92", "size": "1957", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Module.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "14273" } ], "symlink_target": "" }
"""Spectral Embedding""" # Author: Gael Varoquaux <gael.varoquaux@normalesup.org> # Wei LI <kuantkid@gmail.com> # License: BSD 3 clause import warnings import numpy as np from scipy import sparse from scipy.linalg import eigh from scipy.sparse.linalg import eigsh, lobpcg from scipy.sparse.csgraph import connected_components from ..base import BaseEstimator from ..externals import six from ..utils import check_random_state, check_array, check_symmetric from ..utils.extmath import _deterministic_vector_sign_flip from ..metrics.pairwise import rbf_kernel from ..neighbors import kneighbors_graph def _graph_connected_component(graph, node_id): """Find the largest graph connected components that contains one given node Parameters ---------- graph : array-like, shape: (n_samples, n_samples) adjacency matrix of the graph, non-zero weight means an edge between the nodes node_id : int The index of the query node of the graph Returns ------- connected_components_matrix : array-like, shape: (n_samples,) An array of bool value indicating the indexes of the nodes belonging to the largest connected components of the given query node """ n_node = graph.shape[0] if sparse.issparse(graph): # speed up row-wise access to boolean connection mask graph = graph.tocsr() connected_nodes = np.zeros(n_node, dtype=np.bool) nodes_to_explore = np.zeros(n_node, dtype=np.bool) nodes_to_explore[node_id] = True for _ in range(n_node): last_num_component = connected_nodes.sum() np.logical_or(connected_nodes, nodes_to_explore, out=connected_nodes) if last_num_component >= connected_nodes.sum(): break indices = np.where(nodes_to_explore)[0] nodes_to_explore.fill(False) for i in indices: if sparse.issparse(graph): neighbors = graph[i].toarray().ravel() else: neighbors = graph[i] np.logical_or(nodes_to_explore, neighbors, out=nodes_to_explore) return connected_nodes def _graph_is_connected(graph): """ Return whether the graph is connected (True) or Not (False) Parameters ---------- graph : array-like or sparse matrix, shape: (n_samples, n_samples) adjacency matrix of the graph, non-zero weight means an edge between the nodes Returns ------- is_connected : bool True means the graph is fully connected and False means not """ if sparse.isspmatrix(graph): # sparse graph, find all the connected components n_connected_components, _ = connected_components(graph) return n_connected_components == 1 else: # dense graph, find all connected components start from node 0 return _graph_connected_component(graph, 0).sum() == graph.shape[0] def _set_diag(laplacian, value, norm_laplacian): """Set the diagonal of the laplacian matrix and convert it to a sparse format well suited for eigenvalue decomposition Parameters ---------- laplacian : array or sparse matrix The graph laplacian value : float The value of the diagonal norm_laplacian : bool Whether the value of the diagonal should be changed or not Returns ------- laplacian : array or sparse matrix An array of matrix in a form that is well suited to fast eigenvalue decomposition, depending on the band width of the matrix. """ n_nodes = laplacian.shape[0] # We need all entries in the diagonal to values if not sparse.isspmatrix(laplacian): if norm_laplacian: laplacian.flat[::n_nodes + 1] = value else: laplacian = laplacian.tocoo() if norm_laplacian: diag_idx = (laplacian.row == laplacian.col) laplacian.data[diag_idx] = value # If the matrix has a small number of diagonals (as in the # case of structured matrices coming from images), the # dia format might be best suited for matvec products: n_diags = np.unique(laplacian.row - laplacian.col).size if n_diags <= 7: # 3 or less outer diagonals on each side laplacian = laplacian.todia() else: # csr has the fastest matvec and is thus best suited to # arpack laplacian = laplacian.tocsr() return laplacian def spectral_embedding(adjacency, n_components=8, eigen_solver=None, random_state=None, eigen_tol=0.0, norm_laplacian=True, drop_first=True): """Project the sample on the first eigenvectors of the graph Laplacian. The adjacency matrix is used to compute a normalized graph Laplacian whose spectrum (especially the eigenvectors associated to the smallest eigenvalues) has an interpretation in terms of minimal number of cuts necessary to split the graph into comparably sized components. This embedding can also 'work' even if the ``adjacency`` variable is not strictly the adjacency matrix of a graph but more generally an affinity or similarity matrix between samples (for instance the heat kernel of a euclidean distance matrix or a k-NN matrix). However care must taken to always make the affinity matrix symmetric so that the eigenvector decomposition works as expected. Note : Laplacian Eigenmaps is the actual algorithm implemented here. Read more in the :ref:`User Guide <spectral_embedding>`. Parameters ---------- adjacency : array-like or sparse matrix, shape: (n_samples, n_samples) The adjacency matrix of the graph to embed. n_components : integer, optional, default 8 The dimension of the projection subspace. eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'}, default None The eigenvalue decomposition strategy to use. AMG requires pyamg to be installed. It can be faster on very large, sparse problems, but may also lead to instabilities. random_state : int, RandomState instance or None, optional, default: None A pseudo random number generator used for the initialization of the lobpcg eigenvectors decomposition. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Used when ``solver`` == 'amg'. eigen_tol : float, optional, default=0.0 Stopping criterion for eigendecomposition of the Laplacian matrix when using arpack eigen_solver. norm_laplacian : bool, optional, default=True If True, then compute normalized Laplacian. drop_first : bool, optional, default=True Whether to drop the first eigenvector. For spectral embedding, this should be True as the first eigenvector should be constant vector for connected graph, but for spectral clustering, this should be kept as False to retain the first eigenvector. Returns ------- embedding : array, shape=(n_samples, n_components) The reduced samples. Notes ----- Spectral Embedding (Laplacian Eigenmaps) is most useful when the graph has one connected component. If there graph has many components, the first few eigenvectors will simply uncover the connected components of the graph. References ---------- * https://en.wikipedia.org/wiki/LOBPCG * Toward the Optimal Preconditioned Eigensolver: Locally Optimal Block Preconditioned Conjugate Gradient Method Andrew V. Knyazev http://dx.doi.org/10.1137%2FS1064827500366124 """ adjacency = check_symmetric(adjacency) try: from pyamg import smoothed_aggregation_solver except ImportError: if eigen_solver == "amg": raise ValueError("The eigen_solver was set to 'amg', but pyamg is " "not available.") if eigen_solver is None: eigen_solver = 'arpack' elif eigen_solver not in ('arpack', 'lobpcg', 'amg'): raise ValueError("Unknown value for eigen_solver: '%s'." "Should be 'amg', 'arpack', or 'lobpcg'" % eigen_solver) random_state = check_random_state(random_state) n_nodes = adjacency.shape[0] # Whether to drop the first eigenvector if drop_first: n_components = n_components + 1 if not _graph_is_connected(adjacency): warnings.warn("Graph is not fully connected, spectral embedding" " may not work as expected.") laplacian, dd = sparse.csgraph.laplacian(adjacency, normed=norm_laplacian, return_diag=True) if (eigen_solver == 'arpack' or eigen_solver != 'lobpcg' and (not sparse.isspmatrix(laplacian) or n_nodes < 5 * n_components)): # lobpcg used with eigen_solver='amg' has bugs for low number of nodes # for details see the source code in scipy: # https://github.com/scipy/scipy/blob/v0.11.0/scipy/sparse/linalg/eigen # /lobpcg/lobpcg.py#L237 # or matlab: # http://www.mathworks.com/matlabcentral/fileexchange/48-lobpcg-m laplacian = _set_diag(laplacian, 1, norm_laplacian) # Here we'll use shift-invert mode for fast eigenvalues # (see http://docs.scipy.org/doc/scipy/reference/tutorial/arpack.html # for a short explanation of what this means) # Because the normalized Laplacian has eigenvalues between 0 and 2, # I - L has eigenvalues between -1 and 1. ARPACK is most efficient # when finding eigenvalues of largest magnitude (keyword which='LM') # and when these eigenvalues are very large compared to the rest. # For very large, very sparse graphs, I - L can have many, many # eigenvalues very near 1.0. This leads to slow convergence. So # instead, we'll use ARPACK's shift-invert mode, asking for the # eigenvalues near 1.0. This effectively spreads-out the spectrum # near 1.0 and leads to much faster convergence: potentially an # orders-of-magnitude speedup over simply using keyword which='LA' # in standard mode. try: # We are computing the opposite of the laplacian inplace so as # to spare a memory allocation of a possibly very large array laplacian *= -1 v0 = random_state.uniform(-1, 1, laplacian.shape[0]) lambdas, diffusion_map = eigsh(laplacian, k=n_components, sigma=1.0, which='LM', tol=eigen_tol, v0=v0) embedding = diffusion_map.T[n_components::-1] * dd except RuntimeError: # When submatrices are exactly singular, an LU decomposition # in arpack fails. We fallback to lobpcg eigen_solver = "lobpcg" # Revert the laplacian to its opposite to have lobpcg work laplacian *= -1 if eigen_solver == 'amg': # Use AMG to get a preconditioner and speed up the eigenvalue # problem. if not sparse.issparse(laplacian): warnings.warn("AMG works better for sparse matrices") # lobpcg needs double precision floats laplacian = check_array(laplacian, dtype=np.float64, accept_sparse=True) laplacian = _set_diag(laplacian, 1, norm_laplacian) ml = smoothed_aggregation_solver(check_array(laplacian, 'csr')) M = ml.aspreconditioner() X = random_state.rand(laplacian.shape[0], n_components + 1) X[:, 0] = dd.ravel() lambdas, diffusion_map = lobpcg(laplacian, X, M=M, tol=1.e-12, largest=False) embedding = diffusion_map.T * dd if embedding.shape[0] == 1: raise ValueError elif eigen_solver == "lobpcg": # lobpcg needs double precision floats laplacian = check_array(laplacian, dtype=np.float64, accept_sparse=True) if n_nodes < 5 * n_components + 1: # see note above under arpack why lobpcg has problems with small # number of nodes # lobpcg will fallback to eigh, so we short circuit it if sparse.isspmatrix(laplacian): laplacian = laplacian.toarray() lambdas, diffusion_map = eigh(laplacian) embedding = diffusion_map.T[:n_components] * dd else: laplacian = _set_diag(laplacian, 1, norm_laplacian) # We increase the number of eigenvectors requested, as lobpcg # doesn't behave well in low dimension X = random_state.rand(laplacian.shape[0], n_components + 1) X[:, 0] = dd.ravel() lambdas, diffusion_map = lobpcg(laplacian, X, tol=1e-15, largest=False, maxiter=2000) embedding = diffusion_map.T[:n_components] * dd if embedding.shape[0] == 1: raise ValueError embedding = _deterministic_vector_sign_flip(embedding) if drop_first: return embedding[1:n_components].T else: return embedding[:n_components].T class SpectralEmbedding(BaseEstimator): """Spectral embedding for non-linear dimensionality reduction. Forms an affinity matrix given by the specified function and applies spectral decomposition to the corresponding graph laplacian. The resulting transformation is given by the value of the eigenvectors for each data point. Note : Laplacian Eigenmaps is the actual algorithm implemented here. Read more in the :ref:`User Guide <spectral_embedding>`. Parameters ----------- n_components : integer, default: 2 The dimension of the projected subspace. affinity : string or callable, default : "nearest_neighbors" How to construct the affinity matrix. - 'nearest_neighbors' : construct affinity matrix by knn graph - 'rbf' : construct affinity matrix by rbf kernel - 'precomputed' : interpret X as precomputed affinity matrix - callable : use passed in function as affinity the function takes in data matrix (n_samples, n_features) and return affinity matrix (n_samples, n_samples). gamma : float, optional, default : 1/n_features Kernel coefficient for rbf kernel. random_state : int, RandomState instance or None, optional, default: None A pseudo random number generator used for the initialization of the lobpcg eigenvectors. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Used when ``solver`` == 'amg'. eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'} The eigenvalue decomposition strategy to use. AMG requires pyamg to be installed. It can be faster on very large, sparse problems, but may also lead to instabilities. n_neighbors : int, default : max(n_samples/10 , 1) Number of nearest neighbors for nearest_neighbors graph building. n_jobs : int, optional (default = 1) The number of parallel jobs to run. If ``-1``, then the number of jobs is set to the number of CPU cores. Attributes ---------- embedding_ : array, shape = (n_samples, n_components) Spectral embedding of the training matrix. affinity_matrix_ : array, shape = (n_samples, n_samples) Affinity_matrix constructed from samples or precomputed. References ---------- - A Tutorial on Spectral Clustering, 2007 Ulrike von Luxburg http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.165.9323 - On Spectral Clustering: Analysis and an algorithm, 2001 Andrew Y. Ng, Michael I. Jordan, Yair Weiss http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.8100 - Normalized cuts and image segmentation, 2000 Jianbo Shi, Jitendra Malik http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.160.2324 """ def __init__(self, n_components=2, affinity="nearest_neighbors", gamma=None, random_state=None, eigen_solver=None, n_neighbors=None, n_jobs=1): self.n_components = n_components self.affinity = affinity self.gamma = gamma self.random_state = random_state self.eigen_solver = eigen_solver self.n_neighbors = n_neighbors self.n_jobs = n_jobs @property def _pairwise(self): return self.affinity == "precomputed" def _get_affinity_matrix(self, X, Y=None): """Calculate the affinity matrix from data Parameters ---------- X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. If affinity is "precomputed" X : array-like, shape (n_samples, n_samples), Interpret X as precomputed adjacency graph computed from samples. Returns ------- affinity_matrix, shape (n_samples, n_samples) """ if self.affinity == 'precomputed': self.affinity_matrix_ = X return self.affinity_matrix_ if self.affinity == 'nearest_neighbors': if sparse.issparse(X): warnings.warn("Nearest neighbors affinity currently does " "not support sparse input, falling back to " "rbf affinity") self.affinity = "rbf" else: self.n_neighbors_ = (self.n_neighbors if self.n_neighbors is not None else max(int(X.shape[0] / 10), 1)) self.affinity_matrix_ = kneighbors_graph(X, self.n_neighbors_, include_self=True, n_jobs=self.n_jobs) # currently only symmetric affinity_matrix supported self.affinity_matrix_ = 0.5 * (self.affinity_matrix_ + self.affinity_matrix_.T) return self.affinity_matrix_ if self.affinity == 'rbf': self.gamma_ = (self.gamma if self.gamma is not None else 1.0 / X.shape[1]) self.affinity_matrix_ = rbf_kernel(X, gamma=self.gamma_) return self.affinity_matrix_ self.affinity_matrix_ = self.affinity(X) return self.affinity_matrix_ def fit(self, X, y=None): """Fit the model from data in X. Parameters ---------- X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. If affinity is "precomputed" X : array-like, shape (n_samples, n_samples), Interpret X as precomputed adjacency graph computed from samples. Returns ------- self : object Returns the instance itself. """ X = check_array(X, ensure_min_samples=2, estimator=self) random_state = check_random_state(self.random_state) if isinstance(self.affinity, six.string_types): if self.affinity not in set(("nearest_neighbors", "rbf", "precomputed")): raise ValueError(("%s is not a valid affinity. Expected " "'precomputed', 'rbf', 'nearest_neighbors' " "or a callable.") % self.affinity) elif not callable(self.affinity): raise ValueError(("'affinity' is expected to be an affinity " "name or a callable. Got: %s") % self.affinity) affinity_matrix = self._get_affinity_matrix(X) self.embedding_ = spectral_embedding(affinity_matrix, n_components=self.n_components, eigen_solver=self.eigen_solver, random_state=random_state) return self def fit_transform(self, X, y=None): """Fit the model from data in X and transform X. Parameters ---------- X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. If affinity is "precomputed" X : array-like, shape (n_samples, n_samples), Interpret X as precomputed adjacency graph computed from samples. Returns ------- X_new : array-like, shape (n_samples, n_components) """ self.fit(X) return self.embedding_
{ "content_hash": "d4dec768728fe9cac618ec2a40f68183", "timestamp": "", "source": "github", "line_count": 522, "max_line_length": 79, "avg_line_length": 41.088122605363985, "alnum_prop": 0.615721745617307, "repo_name": "wazeerzulfikar/scikit-learn", "id": "a330b7da7f8561bb0b0e02e03d438cbd6d958b31", "size": "21448", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "sklearn/manifold/spectral_embedding_.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "3366" }, { "name": "C", "bytes": "451996" }, { "name": "C++", "bytes": "140322" }, { "name": "Makefile", "bytes": "1512" }, { "name": "PowerShell", "bytes": "17042" }, { "name": "Python", "bytes": "7246657" }, { "name": "Shell", "bytes": "19959" } ], "symlink_target": "" }
export declare function populateClientExports(exports: any): void;
{ "content_hash": "28406843fa587bcec96e08f886289d2d", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 66, "avg_line_length": 67, "alnum_prop": 0.835820895522388, "repo_name": "rondwest/expressTemplate", "id": "2d460bb437d80af4c23f63ab098e64dca323daf2", "size": "267", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "public/javascripts/lib/clientExports.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "37676" }, { "name": "HTML", "bytes": "3188" }, { "name": "JavaScript", "bytes": "757790" }, { "name": "Shell", "bytes": "296" } ], "symlink_target": "" }
SET @preparedStatement = (SELECT IF( (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'jobs' AND table_schema = DATABASE() AND column_name = 'retry_count' ) > 0, "SELECT 1", "ALTER TABLE `jobs` ADD `retry_count` INT(11) NOT NULL DEFAULT '0';" )); PREPARE alterIfNotExists FROM @preparedStatement; EXECUTE alterIfNotExists; DEALLOCATE PREPARE alterIfNotExists; SET @preparedStatement = (SELECT IF( (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'jobs' AND table_schema = DATABASE() AND column_name = 'active_at' ) > 0, "SELECT 1", "ALTER TABLE `jobs` ADD `active_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;" )); PREPARE alterIfNotExists FROM @preparedStatement; EXECUTE alterIfNotExists; DEALLOCATE PREPARE alterIfNotExists; -- +migrate Down ALTER TABLE `jobs` DROP COLUMN retry_count; ALTER TABLE `jobs` DROP COLUMN active_at;
{ "content_hash": "c2ebeeb34475b89bf7cdbf0f035f71a8", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 86, "avg_line_length": 29.545454545454547, "alnum_prop": 0.678974358974359, "repo_name": "cloudfoundry-incubator/notifications", "id": "40407bd0b6f2ef972189318f33ed87de73e62605", "size": "990", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gobble/migrations/2_add_retry_count_to_jobs.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "937608" }, { "name": "Shell", "bytes": "2660" }, { "name": "TSQL", "bytes": "12026" } ], "symlink_target": "" }
**RactiveJS bindings for PureScript** Based on the original sources from <a href="https://github.com/AitorATuin/purescript-ractive" target="_blank">Aitor P. Iturri</a> This version is compatible with **psc 0.9.3**. The original Grunt mechanics were replaced by Gulp/WebPack. For quick testing a <a href="https://github.com/brakmic/purescript-ractive/blob/master/demo/scripts/app.purs">small demo app</a> with detailed comments is available. ### Screenshot <img src="http://fs5.directupload.net/images/160108/v6ohn28m.png" width="741" height="547"> My <a href="http://blog.brakmic.com/webapps-with-purescript-and-ractivejs/" target="_blank">article</a> on using PureScript with RactiveJS. ### All of the APIs from RactiveJS v0.7.3 are supported - <a href="http://docs.ractivejs.org/latest/ractive-add" target="_blank">add</a> - <a href="http://docs.ractivejs.org/latest/ractive-animate" target="_blank">animate</a> - <a href="http://docs.ractivejs.org/latest/ractive-detach" target="_blank">detach</a> - <a href="http://docs.ractivejs.org/latest/ractive-extend" target="_blank">extend</a> - <a href="http://docs.ractivejs.org/latest/ractive-find" target="_blank">find</a> - <a href="http://docs.ractivejs.org/latest/ractive-findall" target="_blank">findAll</a> - <a href="http://docs.ractivejs.org/latest/ractive-findallcomponents" target="_blank">findAllComponents</a> - <a href="http://docs.ractivejs.org/latest/ractive-findcomponent" target="_blank">findComponent</a> - <a href="http://docs.ractivejs.org/latest/ractive-findcontainer" target="_blank">findContainer</a> - <a href="http://docs.ractivejs.org/latest/ractive-findparent" target="_blank">findParent</a> - <a href="http://docs.ractivejs.org/latest/ractive-fire" target="_blank">fire</a> - <a href="http://docs.ractivejs.org/latest/ractive-get" target="_blank">get</a> - <a href="http://docs.ractivejs.org/latest/ractive-insert" target="_blank">insert</a> - <a href="http://docs.ractivejs.org/latest/ractive-observe" target="_blank">observe</a> - <a href="http://docs.ractivejs.org/latest/ractive-observeonce" target="_blank">observeOnce</a> - <a href="http://docs.ractivejs.org/latest/ractive-off" target="_blank">off</a> - <a href="http://docs.ractivejs.org/latest/ractive-on" target="_blank">on</a> - <a href="http://docs.ractivejs.org/latest/ractive-pop" target="_blank">pop</a> - <a href="http://docs.ractivejs.org/latest/ractive-push" target="_blank">push</a> - <a href="http://docs.ractivejs.org/latest/ractive-render" target="_blank">render</a> - <a href="http://docs.ractivejs.org/latest/ractive-reset" target="_blank">reset</a> - <a href="http://docs.ractivejs.org/latest/ractive-resetpartial" target="_blank">resetPartial</a> - <a href="http://docs.ractivejs.org/latest/ractive-set" target="_blank">set</a> - <a href="http://docs.ractivejs.org/latest/ractive-shift" target="_blank">shift</a> - <a href="http://docs.ractivejs.org/latest/ractive-subtract" target="_blank">subtract</a> - <a href="http://docs.ractivejs.org/latest/ractive-splice" target="_blank">splice</a> - <a href="http://docs.ractivejs.org/latest/ractive-teardown" target="_blank">teardown</a> - <a href="http://docs.ractivejs.org/latest/ractive-toggle" target="_blank">toggle</a> - <a href="http://docs.ractivejs.org/latest/ractive-tohtml" target="_blank">toHTML</a> - <a href="http://docs.ractivejs.org/latest/ractive-unrender" target="_blank">unrender</a> - <a href="http://docs.ractivejs.org/latest/ractive-unshift" target="_blank">unshift</a> - <a href="http://docs.ractivejs.org/latest/ractive-update" target="_blank">update</a> - <a href="http://docs.ractivejs.org/latest/ractive-updatemodel" target="_blank">updateModel</a> ### Component Support Creation of RactiveJS <a href="http://docs.ractivejs.org/latest/components" target="_blank">Components</a> is supported via the `extend` API. Read the <a href="https://github.com/brakmic/purescript-ractive/blob/master/tutorials/COMPONENTS.md">Tutorial</a> for more info. ### Future planning Follow the development of RactiveJS and continuously update the bindings. ### Building the Bindings ``` npm install [initial build only] bower update [initial build only] gulp ``` ### Building the Demo ``` gulp make-demo [initial build only] gulp build-demo open index.html from subdir demo ``` Or use HapiJS ``` npm start [will load index.js from subdir demo] ``` ### Testing ```shell pulp test ``` <a href="https://github.com/purescript/purescript-quickcheck" target="_blank">QuickCheck</a> is used for property-based testing while <a href="https://github.com/tmpvar/jsdom" target="_blank">JSDOM</a> is for headless testing of RactiveJS-APIs. <img src="http://fs5.directupload.net/images/160205/9lbb94kn.png"> ### License <a href="https://github.com/brakmic/purescript-ractive/blob/master/LICENSE">MIT</a>
{ "content_hash": "8b19998a362ee67c0c84294a803d9646", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 270, "avg_line_length": 51.784946236559136, "alnum_prop": 0.7286129568106312, "repo_name": "brakmic/purescript-ractive", "id": "7cd39903256e0af7766413dc5ae7c6ab9f520010", "size": "4839", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "248" }, { "name": "HTML", "bytes": "1886" }, { "name": "JavaScript", "bytes": "26845" }, { "name": "PureScript", "bytes": "19446" } ], "symlink_target": "" }
* [Utilities](#utilities) * [Base Mixin](#base-mixin) * [Listeners](#listeners) * [Margin Mixin](#margin-mixin) * [Color Mixin](#color-mixin) * [Coordinate Grid Mixin](#coordinate-grid-mixin) * [Stack Mixin](#stack-mixin) * [Cap Mixin](#cap-mixin) * [Bubble Mixin](#bubble-mixin) * [Pie Chart](#pie-chart) * [Bar Chart](#bar-chart) * [Line Chart](#line-chart) * [Data Count Widget](#data-count-widget) * [Data Table Widget](#data-table-widget) * [Bubble Chart](#bubble-chart) * [Composite Chart](#composite-chart) * [Series Chart](#series-chart) * [Geo Choropleth Chart](#geo-choropleth-chart) * [Bubble Overlay Chart](#bubble-overlay-chart) * [Row Chart](#row-chart) * [Legend](#legend) * [Scatter Plot](#scatter-plot) * [Number Display Widget](#number-display-widget) * [Heat Map](#heat-map) * [Box Plot](#box-plot) #### Version 2.0.0-dev The entire dc.js library is scoped under **dc** name space. It does not introduce anything else into the global name space. #### Function Chain Majority of dc functions are designed to allow function chaining, meaning it will return the current chart instance whenever it is appropriate. Therefore configuration of a chart can be written in the following style. ```js chart.width(300) .height(300) .filter("sunday") ``` The API references will highlight the fact if a particular function is not chainable. ## Utilities #### dc.filterAll([chartGroup]) Clear all filters on every chart within the given chart group. If the chart group is not given then only charts that belong to the default chart group will be reset. #### dc.refocusAll([chartGroup]) Reset zoom level / focus on all charts that belong to the given chart group. If the chart group is not given then only charts that belong to the default chart group will be reset. #### dc.renderAll([chartGroup]) Re-render all charts belong to the given chart group. If the chart group is not given then only charts that belong to the default chart group will be re-rendered. #### dc.redrawAll([chartGroup]) Redraw all charts belong to the given chart group. If the chart group is not given then only charts that belong to the default chart group will be re-drawn. Redraw is different from re-render since when redrawing dc charts try to update the graphic incrementally instead of starting from scratch. #### dc.units.integers This function can be used to in [Coordinate Grid Chart](#coordinate-grid-chart) to define units on x axis. dc.units.integers is the default x unit scale used by [Coordinate Grid Chart](#coordinate-grid-chart) and should be used when x range is a sequential of integers. #### dc.units.ordinal This function can be used to in [Coordinate Grid Chart](#coordinate-grid-chart) to define ordinal units on x axis. Usually this function is used in combination with d3.scale.ordinal() on x axis. #### dc.units.fp.precision(precision) This function generates xunit function in floating-point numbers with the given precision. For example if the function is invoked with 0.001 precision then the function created will divide a range [0.5, 1.0] with 500 units. #### dc.events.trigger(function[, delay]) This function is design to trigger throttled event function optionally with certain amount of delay(in milli-seconds). Events that are triggered repetitively due to user interaction such as the dragging of the brush might over flood library and cause too much rendering being scheduled. In this case, using this function to wrap your event function allows the library to smooth out the rendering by throttling event flood and only respond to the most recent event. ```js chart.renderlet(function(chart){ // smooth the rendering through event throttling dc.events.trigger(function(){ // focus some other chart to the range selected by user on this chart someOtherChart.focus(chart.filter()); }); }) ``` ## Base Mixin Base Mixin is an abstract functional object representing a basic dc chart object for all chart and widget implementations. Methods from the Base Mixin are inherited and available on all chart implementation in the DC library. #### .width([value]) Set or get width attribute of a chart. See `.height` below for further description of the behavior. #### .height([value]) Set or get height attribute of a chart. The height is applied to the SVG element generated by the chart when rendered (or rerendered). If a value is given, then it will be used to calculate the new height and the chart returned for method chaining. The value can either be a numeric, a function, or falsy. If no value specified then value of the current height attribute will be returned. By default, without an explicit height being given, the chart will select the width of its anchor element. If that isn't possible it defaults to 200; Examples: ```js chart.height(250); // Set the chart's height to 250px; chart.height(function(anchor) { return doSomethingWith(anchor); }); // set the chart's height with a function chart.height(null); // reset the height to the default auto calculation ``` #### .minWidth([value]) Set or get minimum width attribute of a chart. This only applicable if the width is calculated by DC. #### .minHeight([value]) Set or get minimum height attribute of a chart. This only applicable if the height is calculated by DC. #### .dimension([value]) - **mandatory** Set or get dimension attribute of a chart. In dc a dimension can be any valid [crossfilter dimension](https://github.com/square/crossfilter/wiki/API-Reference#wiki-dimension). If the value is given, then it will be used as the new dimension. If no value specified then the current dimension will be returned. #### .data([callback]) Get the data callback or retreive the charts data set. The data callback is passed the chart's group and by default will return `group.all()`. This behavior may be modified to, for instance, return only the top 5 groups: ``` chart.data(function(group) { return group.top(5); }); ``` #### .group([value, [name]]) - **mandatory** Set or get group attribute of a chart. In dc a group is a [crossfilter group](https://github.com/square/crossfilter/wiki/API-Reference#wiki-group). Usually the group should be created from the particular dimension associated with the same chart. If the value is given, then it will be used as the new group. If no value specified then the current group will be returned. If name is specified then it will be used to generate legend label. #### .ordering([orderFunction]) Get or set an accessor to order ordinal charts #### .filterAll() Clear all filters associated with this chart. #### .select(selector) Execute in scope d3 single selection using the given selector and return d3 selection result. Roughly the same as: ```js d3.select("#chart-id").select(selector); ``` This function is **not chainable** since it does not return a chart instance; however the d3 selection result is chainable from d3's perspective. #### .selectAll(selector) Execute in scope d3 selectAll using the given selector and return d3 selection result. Roughly the same as: ```js d3.select("#chart-id").selectAll(selector); ``` This function is **not chainable** since it does not return a chart instance; however the d3 selection result is chainable from d3's perspective. #### .anchor([anchorChart/anchorSelector], [chartGroup]) Set the svg root to either be an existing chart's root or the first element returned from a d3 css string selector. Optionally registers the chart within the chartGroup. This class is called internally on chart initialization, but be called again to relocate the chart. However, it will orphan any previously created SVG elements. #### .anchorName() Return the dom ID for chart's anchored location #### .root([rootElement]) Returns the root element where a chart resides. Usually it will be the parent div element where svg was created. You can also pass in a new root element however this is usually handled as part of the dc internal. Resetting root element on a chart outside of dc internal might have unexpected consequences. #### .svg([svgElement]) Returns the top svg element for this specific chart. You can also pass in a new svg element however this is usually handled as part of the dc internal. Resetting svg element on a chart outside of dc internal might have unexpected consequences. #### .resetSvg() Remove the chart's SVG elements from the dom and recreate the container SVG element. #### .filterPrinter([filterPrinterFunction]) Set or get filter printer function. Filter printer function is used to generate human friendly text for filter value(s) associated with the chart instance. By default dc charts shipped with a default filter printer implementation dc.printers.filter that provides simple printing support for both single value and ranged filters. #### .turnOnControls() & .turnOffControls() Turn on/off optional control elements within the root element. dc.js currently support the following html control elements. * root.selectAll(".reset") elements are turned on if the chart has an active filter. This type of control elements are usually used to store reset link to allow user to reset filter on a certain chart. This element will be turned off automatically if the filter is cleared. * root.selectAll(".filter") elements are turned on if the chart has an active filter. The text content of this element is then replaced with the current filter value using the filter printer function. This type of element will be turned off automatically if the filter is cleared. #### .transitionDuration([duration]) Set or get animation transition duration(in milliseconds) for specific chart instance. Default duration is 750ms. #### .render() Invoke this method will force the chart to re-render everything from scratch. Generally it should be only used to render the chart for the first time on the page or if you want to make sure everything is redrawn from scratch instead of relying on the default incremental redrawing behaviour. #### .redraw() Calling redraw will cause the chart to re-render delta in data change incrementally. If there is no change in the underlying data dimension then calling this method will have no effect on the chart. Most of the chart interaction in dc library will automatically trigger this method through its internal event engine, therefore you only need to manually invoke this function if data is manipulated outside of dc's control; for example if data is loaded on a periodic basis in the background using crossfilter.add(). #### .hasFilter([filter]) Check whether is any active filter or a specific filter is associated with particular chart instance. This function is **not chainable**. #### .filter([filterValue]) Filter the chart by the given value or return the current filter if the input parameter is missing. ```js // filter by a single string chart.filter("Sunday"); // filter by a single age chart.filter(18); ``` #### .filters() Return all current filters. This method does not perform defensive cloning of the internal filter array before returning therefore any modification of returned array will affact chart's internal filter storage. #### .onClick(datum) This function is passed to d3 as the onClick handler for each chart. By default it will filter the on the clicked datum (as passed back to the callback) and redraw the chart group. #### .filterHandler([function]) Set or get filter handler. Filter handler is a function that performs the filter action on a specific dimension. Using custom filter handler give you the flexibility to perform additional logic before or after filtering. ```js // default filter handler function(dimension, filter){ dimension.filter(filter); // perform filtering return filter; // return the actual filter value } // custom filter handler chart.filterHandler(function(dimension, filter){ var newFilter = filter + 10; dimension.filter(newFilter); return newFilter; // set the actual filter value to the new value }); ``` #### .keyAccessor([keyAccessorFunction]) Set or get the key accessor function. Key accessor function is used to retrieve key value in crossfilter group. Key values are used differently in different charts, for example keys correspond to slices in pie chart and x axis position in grid coordinate chart. ```js // default key accessor chart.keyAccessor(function(d) { return d.key; }); // custom key accessor for a multi-value crossfilter reduction chart.keyAccessor(function(p) { return p.value.absGain; }); ``` #### .valueAccessor([valueAccessorFunction]) Set or get the value accessor function. Value accessor function is used to retrieve value in crossfilter group. Group values are used differently in different charts, for example group values correspond to slices size in pie chart and y axis position in grid coordinate chart. ```js // default value accessor chart.valueAccessor(function(d) { return d.value; }); // custom value accessor for a multi-value crossfilter reduction chart.valueAccessor(function(p) { return p.value.percentageGain; }); ``` #### .label([labelFunction]) Set or get the label function. Chart class will use this function to render label for each child element in the chart, i.e. a slice in a pie chart or a bubble in a bubble chart. Not every chart supports label function for example bar chart and line chart do not use this function at all. ```js // default label function just return the key chart.label(function(d) { return d.key; }); // label function has access to the standard d3 data binding and can get quite complicated chart.label(function(d) { return d.data.key + "(" + Math.floor(d.data.value / all.value() * 100) + "%)"; }); ``` #### .renderLabel(boolean) Turn on/off label rendering #### .title([titleFunction]) Set or get the title function. Chart class will use this function to render svg title(usually interpreted by browser as tooltips) for each child element in the chart, i.e. a slice in a pie chart or a bubble in a bubble chart. Almost every chart supports title function however in grid coordinate chart you need to turn off brush in order to use title otherwise the brush layer will block tooltip trigger. ```js // default title function just return the key chart.title(function(d) { return d.key + ": " + d.value; }); // title function has access to the standard d3 data binding and can get quite complicated chart.title(function(p) { return p.key.getFullYear() + "\n" + "Index Gain: " + numberFormat(p.value.absGain) + "\n" + "Index Gain in Percentage: " + numberFormat(p.value.percentageGain) + "%\n" + "Fluctuation / Index Ratio: " + numberFormat(p.value.fluctuationPercentage) + "%"; }); ``` #### .renderTitle(boolean) Turn on/off title rendering #### .renderlet(renderletFunction) Renderlet is similar to an event listener on rendering event. Multiple renderlets can be added to an individual chart. Every time when chart is rerendered or redrawn renderlet then will be invoked right after the chart finishes its own drawing routine hence given you a way to override or modify certain behaviour. Renderlet function accepts the chart instance as the only input parameter and you can either rely on dc API or use raw d3 to achieve pretty much any effect. ```js // renderlet function chart.renderlet(function(chart){ // mix of dc API and d3 manipulation chart.select("g.y").style("display", "none"); // its a closure so you can also access other chart variable available in the closure scope moveChart.filter(chart.filter()); }); ``` #### .chartGroup([group]) Get or set the chart group with which this chart belongs. Chart groups share common rendering events since it is expected they share the same underlying crossfilter data set. #### .expireCache() Expire internal chart cache. dc.js chart cache some data internally on a per chart basis so it can speed up rendering and avoid unnecessary calculation however under certain circumstances it might be useful to clear the cache e.g. after you invoke crossfilter.add function or if you reset group or dimension post render it is always a good idea to clear the cache to make sure charts are rendered properly. #### .legend([dc.legend]) Attach dc.legend widget to this chart. Legend widget will automatically draw legend labels based on the color setting and names associated with each group. ```js chart.legend(dc.legend().x(400).y(10).itemHeight(13).gap(5)) ``` #### .chartID() Return the internal numeric ID of the chart. #### .options(optionsObject) Set chart options using a configuration object. Each object key will be call the fluent method of the same name to set that attribute for the chart. Example: ``` chart.options({dimension: myDimension, group: myGroup}); ``` ## Listeners All dc chart instance supports the following listeners. #### .on("preRender", function(chart){...}) This listener function will be invoked before chart rendering. #### .on("postRender", function(chart){...}) This listener function will be invoked after chart finish rendering including all renderlets' logic. #### .on("preRedraw", function(chart){...}) This listener function will be invoked before chart redrawing. #### .on("postRedraw", function(chart){...}) This listener function will be invoked after chart finish redrawing including all renderlets' logic. #### .on("filtered", function(chart, filter){...}) This listener function will be invoked after a filter is applied, added or removed. #### .on("zoomed", function(chart, filter){...}) This listener function will be invoked after a zoom is triggered. ## Margin Mixin Margin is a mixin that provides margin utility functions for both the Row Chart and Coordinate Grid Charts. #### .margins([margins]) Get or set the margins for a particular coordinate grid chart instance. The margins is stored as an associative Javascript array. Default margins: {top: 10, right: 50, bottom: 30, left: 30}. The margins can be accessed directly from the getter. ```js var leftMargin = chart.margins().left; // 30 by default chart.margins().left = 50; leftMargin = chart.margins().left; // now 50 ``` ## Color Mixin Color Mixin is an abstract chart functional class created to provide universal coloring support as a mix-in for any concrete chart implementation. #### .colors([colorScale]) Retrieve current color scale or set a new color scale. This methods accepts any function the operate like a d3 scale. If not set the default is `d3.scale.category20c()`. ```js // alternate categorical scale chart.colors(d3.scale.category20b()); // ordinal scale chart.colors(d3.scale.ordinal().range(['red','green','blue']); // convience method, the same as above chart.ordinalColors(['red','green','blue']); // set a linear scale chart.linearColors(["#4575b4", "#ffffbf", "#a50026"]); ``` #### .ordinalColors(r) Convenience method to set the color scale to d3.scale.ordinal with range `r`. #### .linearColors(r) Convenience method to set the color scale to an Hcl interpolated linear scale with range `r`. #### .colorAccessor([colorAccessorFunction]) Set or get color accessor function. This function will be used to map a data point on crossfilter group to a specific color value on the color scale. Default implementation of this function simply returns the next color on the scale using the index of a group. ```js // default index based color accessor .colorAccessor(function(d, i){return i;}) // color accessor for a multi-value crossfilter reduction .colorAccessor(function(d){return d.value.absGain;}) ``` #### .colorDomain([domain]) Set or get the current domain for the color mapping function. The domain must be supplied as an array. Note: previously this method accepted a callback function. Instead you may use a custom scale set by `.colors`. #### .calculateColorDomain() Set the domain by determining the min and max values as retrived by `.colorAccessor` over the chart's dataset. #### .getColor(d [, i]) Get the color for the datum d and counter i. This is used internaly by charts to retrieve a color. ## Coordinate Grid Mixin Includes: [Color Mixin](#color-mixin), [Margin Mixin](#margin-mixin), [Base Mixin](#base-mixin) Coordinate Grid is an abstract base chart designed to support a number of coordinate grid based concrete chart types, i.e. bar chart, line chart, and bubble chart. #### .rangeChart([chart]) Get or set the range selection chart associated with this instance. Setting the range selection chart using this function will automatically update its selection brush when the current chart zooms in. In return the given range chart will also automatically attach this chart as its focus chart hence zoom in when range brush updates. See the [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) example for this effect in action. #### .zoomScale([extent]) Get or set the scale extent for mouse zooms. #### .zoomOutRestrict([true/false]) Get or set the zoom restriction for the chart. If true limits the zoom to origional domain of the chart. #### .g([gElement]) Get or set the root g element. This method is usually used to retrieve the g element in order to overlay custom svg drawing programatically. **Caution**: The root g element is usually generated by dc.js internals, and resetting it might produce unpredictable result. #### .mouseZoomable([boolean]) Set or get mouse zoom capability flag (default: false). When turned on the chart will be zoomable through mouse wheel . If range selector chart is also attached zooming will also update the range selection brush on associated range selector chart. #### .chartBodyG() Retreive the svg group for the chart body. #### .x([xScale]) - **mandatory** Get or set the x scale. x scale could be any [d3 quatitive scales](https://github.com/mbostock/d3/wiki/Quantitative-Scales). For example a time scale for histogram or a linear/ordinal scale for visualizing data distribution. ```js // set x to a linear scale chart.x(d3.scale.linear().domain([-2500, 2500])) // set x to a time scale to generate histogram chart.x(d3.time.scale().domain([new Date(1985, 0, 1), new Date(2012, 11, 31)])) ``` #### .xUnits([xUnits function]) Set or get the xUnits function. xUnits function is the coordinate grid chart uses to calculate number of data projections on x axis such as number bars for a bar chart and number of dots for a line chart. This function is expected to return an Javascript array of all data points on x axis. d3 time range functions d3.time.days, d3.time.months, and d3.time.years are all valid xUnits function. dc.js also provides a few units function, see [Utilities](#utilities) section for a list of built-in units functions. Default xUnits function is dc.units.integers. ```js // set x units to day for a histogram chart.xUnits(d3.time.days); // set x units to month for a histogram chart.xUnits(d3.time.months); ``` Custom xUnits function can be easily created using as long as it follows the following inteface: ```js // units in integer function(start, end, xDomain) { // simply calculates how many integers in the domain return Math.abs(end - start); }; // fixed units function(start, end, xDomain) { // be aware using fixed units will disable the focus/zoom ability on the chart return 1000; }; ``` #### .xAxis([xAxis]) Set or get the x axis used by a particular coordinate grid chart instance. This function is most useful when certain x axis customization is required. x axis in dc.js is simply an instance of [d3 axis object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-axis) therefore it supports any valid d3 axis manipulation. **Caution**: The x axis is typically generated by dc chart internal, resetting it might cause unexpected outcome. ```js // customize x axis tick format chart.xAxis().tickFormat(function(v) {return v + "%";}); // customize x axis tick values chart.xAxis().tickValues([0, 100, 200, 300]); ``` #### .elasticX([boolean]) Turn on/off elastic x axis. If x axis elasticity is turned on, then the grid chart will attempt to generate and recalculate x axis range whenever redraw event is triggered. #### .xAxisPadding([padding]) Set or get x axis padding when elastic x axis is turned on. The padding will be added to both end of the x axis if and only if elasticX is turned on otherwise it will be simply ignored. * padding - could be integer or percentage in string (e.g. "10%"). Padding can be applied to number or date. When padding with date, integer represents number of days being padded while percentage string will be treated as number. #### .xUnitCount() Returns the number of units displayed on the x axis using the unit measure configured by .xUnits. #### isOrdinal() Returns true if the chart is using ordinal xUnits, false otherwise. Most charts must behave somewhat differently when with ordinal data and use the result of this method to trigger those special case. #### .xAxisLabel([labelText, [, padding]]) Set or get the x axis label. If setting the label, you may optionally include additional padding to the margin to make room for the label. By default the padded is set to 12 to accomodate the text height. #### .yAxisLabel([labelText, [, padding]]) Set or get the y axis label. If setting the label, you may optionally include additional padding to the margin to make room for the label. By default the padded is set to 12 to accomodate the text height. #### .y([yScale]) Get or set the y scale. y scale is typically automatically generated by the chart implementation. #### .yAxis([yAxis]) Set or get the y axis used by a particular coordinate grid chart instance. This function is most useful when certain y axis customization is required. y axis in dc.js is simply an instance of [d3 axis object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-_axis) therefore it supports any valid d3 axis manipulation. **Caution**: The y axis is typically generated by dc chart internal, resetting it might cause unexpected outcome. ```js // customize y axis tick format chart.yAxis().tickFormat(function(v) {return v + "%";}); // customize y axis tick values chart.yAxis().tickValues([0, 100, 200, 300]); ``` #### .elasticY([boolean]) Turn on/off elastic y axis. If y axis elasticity is turned on, then the grid chart will attempt to generate and recalculate y axis range whenever redraw event is triggered. #### .renderHorizontalGridLines([boolean]) Turn on/off horizontal grid lines. #### .renderVerticalGridLines([boolean]) Turn on/off vertical grid lines. #### .xAxisMin() Return the minimum x value to diplay in the chart. Includes xAxisPadding if set. #### .xAxisMax() Return the maximum x value to diplay in the chart. Includes xAxisPadding if set. #### .yAxisMin() Return the minimum y value to diplay in the chart. Includes yAxisPadding if set. #### .yAxisMax() Return the maximum y value to diplay in the chart. Includes yAxisPadding if set. #### .yAxisPadding([padding]) if elasticY is turned on otherwise it will be simply ignored. Set or get y axis padding when elastic y axis is turned on. The padding will be added to the top of the y axis if and only * padding - could be integer or percentage in string (e.g. "10%"). Padding can be applied to number or date. When padding with date, integer represents number of days being padded while percentage string will be treated as number. #### .round([rounding function]) Set or get the rounding function for x axis. Rounding is mainly used to provide stepping capability when in place selection based filter is enable. ```js // set x unit round to by month, this will make sure range selection brash will // extend on a month-by-month basis chart.round(d3.time.month.round); ``` #### .clipPadding([padding]) Get or set padding in pixel for clip path. Once set padding will be applied evenly to top, left, right, and bottom padding when clip path is generated. If set to zero, then the clip area will be exactly the chart body area minus the margins. Default: 5 #### .focus([range]) Zoom this chart to focus on the given range. The given range should be an array containing only 2 element([start, end]) defining an range in x domain. If the range is not given or set to null, then the zoom will be reset. _For focus to work elasticX has to be turned off otherwise focus will be ignored._ ```js chart.renderlet(function(chart){ // smooth the rendering through event throttling dc.events.trigger(function(){ // focus some other chart to the range selected by user on this chart someOtherChart.focus(chart.filter()); }); }) ``` #### .brushOn([boolean]) Turn on/off the brush based in-place range filter. When the brush is on then user will be able to simply drag the mouse across the chart to perform range filtering based on the extend of the brush. However turning on brush filter will essentially disable other interactive elements on the chart such as the highlighting, tool-tip, and reference lines on a chart. Zooming will still be possible if enabled, but only via scrolling (panning will be disabled.) Default value is "true". ## Stack Mixin Stack Mixin is an mixin that provides cross-chart support of stackability using d3.layout.stack. #### .stack(group[, name, accessor]) Stack a new crossfilter group into this chart with optionally a custom value accessor. All stacks in the same chart will share the same key accessor therefore share the same set of keys. In more concrete words, imagine in a stacked bar chart all bars will be positioned using the same set of keys on the x axis while stacked vertically. If name is specified then it will be used to generate legend label. ```js // stack group using default accessor chart.stack(valueSumGroup) // stack group using custom accessor .stack(avgByDayGroup, function(d){return d.value.avgByDay;}); ``` #### .hidableStacks([boolean]) Allow named stacks to be hidden or shown by clicking on legend items. This does not affect the behavior of hideStack or showStack. #### .hideStack(name) Hide all stacks on the chart with the given name. The chart must be re-rendered for this change to appear. #### .showStack(name) Show all stacks on the chart with the given name. The chart must be re-rendered for this change to appear. #### .title([stackName], [titleFunction]) Set or get the title function. Chart class will use this function to render svg title (usually interpreted by browser as tooltips) for each child element in the chart, i.e. a slice in a pie chart or a bubble in a bubble chart. Almost every chart supports title function however in grid coordinate chart you need to turn off brush in order to use title otherwise the brush layer will block tooltip trigger. If the first argument is a stack name, the title function will get or set the title for that stack. If stackName is not provided, the first stack is implied. ```js // set a title function on "first stack" chart.title("first stack", function(d) { return d.key + ": " + d.value; }); // get a title function from "second stack" var secondTitleFunction = chart.title("second stack"); ); ``` ## Cap Mixin Cap is a mixin that groups small data elements below a _cap_ into an *others* grouping for both the Row and Pie Charts. The top ordered elements in the group up to the cap amount will be kept in the chart and the sum of those below will be added to the *others* element. The keys of the elements below the cap limit are recorded in order to repsond to onClick events and trigger filtering of all the within that grouping. #### .cap([count]) Get or set the count of elements to that will be included in the cap. #### .othersLabel([label]) Get or set the label for *Others* slice when slices cap is specified. Default label is **Others**. #### .othersGrouper([grouperFunction]) Get or set the grouper function that will perform the insertion of data for the *Others* slice if the slices cap is specified. If set to a falsy value, no others will be added. By default the grouper function computes the sum of all values below the cap. ```js chart.othersGrouper(function (data) { // compute the value for others, presumably the sum of all values below the cap var othersSum = yourComputeOthersValueLogic(data) // the keys are needed to properly filter when the others element is clicked var othersKeys = yourComputeOthersKeysArrayLogic(data); // add the others row to the dataset data.push({"key": "Others", "value": othersSum, "others": othersKeys }); return data; }); ``` ## Bubble Mixin Includes: [Color Mixin](#color-mixin) This Mixin provides reusable functionalities for any chart that needs to visualize data using bubbles. #### .r([bubbleRadiusScale]) Get or set bubble radius scale. By default bubble chart uses ```d3.scale.linear().domain([0, 100])``` as it's r scale . #### .radiusValueAccessor([radiusValueAccessor]) Get or set the radius value accessor function. The radius value accessor function if set will be used to retrieve data value for each and every bubble rendered. The data retrieved then will be mapped using r scale to be used as the actual bubble radius. In other words, this allows you to encode a data dimension using bubble size. #### .minRadiusWithLabel([radius]) Get or set the minimum radius for label rendering. If a bubble's radius is less than this value then no label will be rendered. Default value: 10. #### .maxBubbleRelativeSize([relativeSize]) Get or set the maximum relative size of a bubble to the length of x axis. This value is useful when the radius differences among different bubbles are too great. Default value: 0.3 ## Pie Chart Includes: [Cap Mixin](#cap-mixin), [Color Mixin](#color-mixin), [Base Mixin](#base-mixin) The pie chart implementation is usually used to visualize small number of categorical distributions. Pie chart uses keyAccessor to generate slices, and valueAccessor to calculate the size of each slice(key) relatively to the total sum of all values. Slices are ordered by `.ordering` which defaults to sorting by key. Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) #### dc.pieChart(parent[, chartGroup]) Create a pie chart instance and attach it to the given parent element. Parameters: * parent : string - any valid d3 single selector representing typically a dom block element such as a div. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created pie chart instance ```js // create a pie chart under #chart-container1 element using the default global chart group var chart1 = dc.pieChart("#chart-container1"); // create a pie chart under #chart-container2 element using chart group A var chart2 = dc.pieChart("#chart-container2", "chartGroupA"); ``` #### .slicesCap([cap]) Get or set the maximum number of slices the pie chart will generate. The top slices are determined by value from high to low. Other slices exeeding the cap will be rolled up into one single *Others* slice. The resulting data will still be sorted by .ordering (default by key). #### .innerRadius([innerRadius]) Get or set the inner radius on a particular pie chart instance. If inner radius is greater than 0px then the pie chart will be essentially rendered as a doughnut chart. Default inner radius is 0px. #### .radius([radius]) Get or set the radius on a particular pie chart instance. Default radius is 90px. #### .cx() Get center x coordinate position. This function is **not chainable**. #### .cy() Get center y coordinate position. This function is **not chainable**. #### .minAngleForLabel([minAngle]) Get or set the minimal slice angle for label rendering. Any slice with a smaller angle will not render slice label. Default min angle is 0.5. ## Bar Chart Includes: [Stack Mixin](#stack Mixin), [Coordinate Grid Mixin](#coordinate-grid-mixin) Concrete bar chart/histogram implementation. Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * [Canadian City Crime Stats](http://dc-js.github.com/dc.js/crime/index.html) #### dc.barChart(parent[, chartGroup]) Create a bar chart instance and attach it to the given parent element. Parameters: * parent : string|compositeChart - any valid d3 single selector representing typically a dom block element such as a div, or if this bar chart is a sub-chart in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created bar chart instance ```js // create a bar chart under #chart-container1 element using the default global chart group var chart1 = dc.barChart("#chart-container1"); // create a bar chart under #chart-container2 element using chart group A var chart2 = dc.barChart("#chart-container2", "chartGroupA"); // create a sub-chart under a composite parent chart var chart3 = dc.barChart(compositeChart); ``` #### .centerBar(boolean) Whether the bar chart will render each bar centered around the data position on x axis. Default to false. #### .barPadding([padding]) Get or set the spacing between bars as a fraction of bar size. Valid values are within 0-1. Setting this value will also remove any previously set `gap`. See the [d3 docs](https://github.com/mbostock/d3/wiki/Ordinal-Scales#wiki-ordinal_rangeBands) for a visual description of how the padding is applied. #### .outerPadding([padding]) Get or set the outer padding on an ordinal bar chart. This setting has no effect on non-ordinal charts. Padding equivlent in width to `padding * barWidth` will be added on each side of the chart. Default: 0.5 #### .gap(gapBetweenBars) Manually set fixed gap (in px) between bars instead of relying on the default auto-generated gap. By default bar chart implementation will calculate and set the gap automatically based on the number of data points and the length of the x axis. #### .alwaysUseRounding([boolean]) Set or get the flag which determines whether rounding is enabled when bars are centered (default: false). If false, using rounding with centered bars will result in a warning and rounding will be ignored. This flag has no effect if bars are not centered. When using standard d3.js rounding methods, the brush often doesn't align correctly with centered bars since the bars are offset. The rounding function must add an offset to compensate, such as in the following example. ```js chart.round(function(n) {return Math.floor(n)+0.5}); ``` ## Line Chart Includes [Stack Mixin](#stack-mixin), [Coordinate Grid Mixin](#coordinate-grid-mixin) Concrete line/area chart implementation. Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * [Canadian City Crime Stats](http://dc-js.github.com/dc.js/crime/index.html) #### dc.lineChart(parent[, chartGroup]) Create a line chart instance and attach it to the given parent element. Parameters: * parent : string|compositeChart - any valid d3 single selector representing typically a dom block element such as a div, or if this line chart is a sub-chart in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created line chart instance ```js // create a line chart under #chart-container1 element using the default global chart group var chart1 = dc.lineChart("#chart-container1"); // create a line chart under #chart-container2 element using chart group A var chart2 = dc.lineChart("#chart-container2", "chartGroupA"); // create a sub-chart under a composite parent chart var chart3 = dc.lineChart(compositeChart); ``` #### .dashStyle([array]) Set the line's d3 dashstyle. This value becomes "stroke-dasharray" of line. Defaults to empty array (solid line). ```js // create a Dash Dot Dot Dot chart.dashStyle([3,1,1,1]); ``` #### .renderArea([boolean]) Get or set render area flag. If the flag is set to true then the chart will render the area beneath each line and effectively becomes an area chart. #### .dotRadius([dotRadius]) Get or set the radius (in px) for data points. Default dot radius is 5. #### .renderDataPoints([options]) Always show individual dots for each datapoint. Options, if given, is an object that can contain the following: * fillOpacity (default 0.8) * strokeOpacity (default 0.8) * radius (default 2) If `options` is falsy, it disables data point rendering. If no `options` are provided, the current `options` values are instead returned. Example: ``` chart.renderDataPoints({radius: 2, fillOpacity: 0.8, strokeOpacity: 0.8}) ``` ## Data Count Widget Includes: [Base Mixin](#base-mixin) Data count is a simple widget designed to display total number records in the data set vs. the number records selected by the current filters. Once created data count widget will automatically update the text content of the following elements under the parent element. * ".total-count" - total number of records * ".filter-count" - number of records matched by the current filters Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) #### dc.dataCount(parent[, chartGroup]) Create a data count widget instance and attach it to the given parent element. Parameters: * parent : string - any valid d3 single selector representing typically a dom block element such as a div. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created data count widget instance #### .dimension(allData) - **mandatory** For data count widget the only valid dimension is the entire data set. #### .group(groupAll) - **mandatory** For data count widget the only valid group is the all group. ```js var ndx = crossfilter(data); var all = ndx.groupAll(); dc.dataCount(".dc-data-count") .dimension(ndx) .group(all); ``` ## Data Table Widget Includes: [Base Mixin](#base-mixin) Data table is a simple widget designed to list crossfilter focused data set (rows being filtered) in a good old tabular fashion. Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) #### dc.dataTable(parent[, chartGroup]) Create a data table widget instance and attach it to the given parent element. Parameters: * parent : string - any valid d3 single selector representing typically a dom block element such as a div. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created data table widget instance #### .size([size]) Get or set the table size which determines the number of rows displayed by the widget. #### .columns([columnFunctionArray]) Get or set column functions. Data table widget uses an array of functions to generate dynamic columns. Column functions are simple javascript function with only one input argument d which represents a row in the data set, and the return value of these functions will be used directly to generate table content for each cell. ```js chart.columns([ function(d) { return d.date; }, function(d) { return d.open; }, function(d) { return d.close; }, function(d) { return numberFormat(d.close - d.open); }, function(d) { return d.volume; } ]); ``` #### .sortBy([sortByFunction]) Get or set sort-by function. This function works as a value accessor at row level and returns a particular field to be sorted by. Default value: ``` function(d) {return d;}; ``` ```js chart.sortBy(function(d) { return d.date; }); ``` #### .order([order]) Get or set sort order. Default value: ``` d3.ascending ``` ```js chart.order(d3.descending); ``` ## Bubble Chart Includes: [Bubble Mixin](#bubble-mixin), [Coordinate Grid Mixin](#coordinate-grid-mixin) A concrete implementation of a general purpose bubble chart that allows data visualization using the following dimensions: * x axis position * y axis position * bubble radius * color Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * [US Venture Capital Landscape 2011](http://dc-js.github.com/dc.js/vc/index.html) #### dc.bubbleChart(parent[, chartGroup]) Create a bubble chart instance and attach it to the given parent element. Parameters: * parent : string - any valid d3 single selector representing typically a dom block element such as a div. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created bubble chart instance ```js // create a bubble chart under #chart-container1 element using the default global chart group var bubbleChart1 = dc.bubbleChart("#chart-container1"); // create a bubble chart under #chart-container2 element using chart group A var bubbleChart2 = dc.bubbleChart("#chart-container2", "chartGroupA"); ``` #### .elasticRadius([boolean]) Turn on or off elastic bubble radius feature. If this feature is turned on, then bubble radiuses will be automatically rescaled to fit the chart better. ## Composite Chart Includes: [Coordinate Grid Mixin](#coordinate-grid-mixin) Composite charts are a special kind of chart that allow you to render multiple charts on the same Coordinate Grid. You can overlay(compose) different bar/line/area charts in a single composite chart to achieve some quite flexible charting effects. #### dc.compositeChart(parent[, chartGroup]) Create a composite chart instance and attach it to the given parent element. Parameters: * parent : string - any valid d3 single selector representing typically a dom block element such as a div. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created composite chart instance ```js // create a composite chart under #chart-container1 element using the default global chart group var compositeChart1 = dc.compositeChart("#chart-container1"); // create a composite chart under #chart-container2 element using chart group A var compositeChart2 = dc.compositeChart("#chart-container2", "chartGroupA"); ``` #### .useRightAxisGridLines(bool) Get or set whether to draw gridlines from the right y axis. Drawing from the left y axis is the default behavior. This option is only respected when subcharts with both left and right y-axes are present. #### .childOptions({object}) Get or set chart-specific options for all child charts. This is equivalent to calling `.options` on each child chart. #### .rightYAxisLabel([labelText]) Set or get the right y axis label. #### .compose(subChartArray) Combine the given charts into one single composite coordinate grid chart. ```js // compose the given charts in the array into one single composite chart moveChart.compose([ // when creating sub-chart you need to pass in the parent chart dc.lineChart(moveChart) .group(indexAvgByMonthGroup) // if group is missing then parent's group will be used .valueAccessor(function(d){return d.value.avg;}) // most of the normal functions will continue to work in a composed chart .renderArea(true) .stack(monthlyMoveGroup, function(d){return d.value;}) .title(function(d){ var value = d.value.avg?d.value.avg:d.value; if(isNaN(value)) value = 0; return dateFormat(d.key) + "\n" + numberFormat(value); }), dc.barChart(moveChart) .group(volumeByMonthGroup) .centerBar(true) ]); ``` #### .shareColors([boolean]) Get or set color sharing for the chart. If set, the `.colors()` value from this chart will be shared with composed children. Additionally if the child chart implements Stackable and has not set a custom .colorAccessor, then it will generate a color specific to its order in the composition. #### .shareTitle([[boolean]) Get or set title sharing for the chart. If set, the `.title()` value from this chart will be shared with composed children. Default value is true. #### .rightY([yScale]) Get or set the y scale for the right axis. Right y scale is typically automatically generated by the chart implementation. #### .rightYAxis([yAxis]) Set or get the right y axis used by the composite chart. This function is most useful when certain y axis customization is required. y axis in dc.js is simply an instance of [d3 axis object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-_axis) therefore it supports any valid d3 axis manipulation. **Caution**: The y axis is typically generated by dc chart internal, resetting it might cause unexpected outcome. ```js // customize y axis tick format chart.rightYAxis().tickFormat(function(v) {return v + "%";}); // customize y axis tick values chart.rightYAxis().tickValues([0, 100, 200, 300]); ``` ## Series Chart Includes: [Composite Chart](#composite chart) A series chart is a chart that shows multiple series of data as lines, where the series is specified in the data. It is a special implementation Composite Chart and inherits all composite features other than recomposing the chart. #### dc.seriesChart(parent[, chartGroup]) Create a series chart instance and attach it to the given parent element. Parameters: * parent : string - any valid d3 single selector representing typically a dom block element such as a div. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created series chart instance ```js // create a series chart under #chart-container1 element using the default global chart group var seriesChart1 = dc.seriesChart("#chart-container1"); // create a series chart under #chart-container2 element using chart group A var seriesChart2 = dc.seriesChart("#chart-container2", "chartGroupA"); ``` #### .seriesAccessor([accessor]) Get or set accessor function for the displayed series. Given a datum, this function should return the series that datum belongs to. #### .seriesSort([sortFunction]) Get or set a function to sort the list of series by, given series values. Example: ``` chart.seriesSort(d3.descending); ``` #### .valueSort([sortFunction]) Get or set a function to the sort each series values by. By default this is the key accessor which, for example, a will ensure lineChart a series connects its points in increasing key/x order, rather than haphazardly. ## Geo Choropleth Chart Includes: [Color Mixin](#color-mixin), [Base Mixin](#base-mixin) Geo choropleth chart is designed to make creating crossfilter driven choropleth map from GeoJson data an easy process. This chart implementation was inspired by [the great d3 choropleth example](http://bl.ocks.org/4060606). Examples: * [US Venture Capital Landscape 2011](http://dc-js.github.com/dc.js/vc/index.html) #### dc.geoChoroplethChart(parent[, chartGroup]) Create a choropleth chart instance and attach it to the given parent element. Parameters: * parent : string - any valid d3 single selector representing typically a dom block element such as a div. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created choropleth chart instance ```js // create a choropleth chart under "#us-chart" element using the default global chart group var chart1 = dc.geoChoroplethChart("#us-chart"); // create a choropleth chart under "#us-chart2" element using chart group A var chart2 = dc.compositeChart("#us-chart2", "chartGroupA"); ``` #### .overlayGeoJson(json, name, keyAccessor) - **mandatory** Use this function to insert a new GeoJson map layer. This function can be invoked multiple times if you have multiple GeoJson data layer to render on top of each other. If you overlay mutiple layers with the same name the new overlay will simply override the existing one. Parameters: * json - GeoJson feed * name - name of the layer * keyAccessor - accessor function used to extract "key" from the GeoJson data. Key extracted by this function should match the keys generated in crossfilter groups. ```js // insert a layer for rendering US states chart.overlayGeoJson(statesJson.features, "state", function(d) { return d.properties.name; }); ``` #### .projection(projection) Set custom geo projection function. Available [d3 geo projection functions](https://github.com/mbostock/d3/wiki/Geo-Projections). Default value: albersUsa. #### .geoJsons() Return all GeoJson layers currently registered with thit chart. The returned array is a reference to this chart's internal registration data structure without copying thus any modification to this array will also modify this chart's internal registration. Return: An array of objects containing fields {name, data, accessor} #### .removeGeoJson(name) Remove a GeoJson layer from this chart by name Return: chart instance ## Bubble Overlay Chart Includes: [Bubble Mixin](#bubble-mixin), [Base Mixin](#base-mixin) Bubble overlay chart is quite different from the typical bubble chart. With bubble overlay chart you can arbitrarily place a finite number of bubbles on an existing svg or bitmap image (overlay on top of it), thus losing the typical x and y positioning that we are used to whiling retaining the capability to visualize data using it's bubble radius and coloring. Examples: * [Canadian City Crime Stats](http://dc-js.github.com/dc.js/crime/index.html) #### dc.bubbleOverlay(parent[, chartGroup]) Create a bubble overlay chart instance and attach it to the given parent element. Parameters: * parent : string - any valid d3 single selector representing typically a dom block element such as a div. Typically this element should also be the parent of the underlying image. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created bubble overlay chart instance ```js // create a bubble overlay chart on top of "#chart-container1 svg" element using the default global chart group var bubbleChart1 = dc.bubbleOverlayChart("#chart-container1").svg(d3.select("#chart-container1 svg")); // create a bubble overlay chart on top of "#chart-container2 svg" element using chart group A var bubbleChart2 = dc.compositeChart("#chart-container2", "chartGroupA").svg(d3.select("#chart-container2 svg")); ``` #### .svg(imageElement) - **mandatory** Set the underlying svg image element. Unlike other dc charts this chart will not generate svg element therefore bubble overlay chart will not work if this function is not properly invoked. If the underlying image is a bitmap, then an empty svg will need to be manually created on top of the image. ```js // set up underlying svg element chart.svg(d3.select("#chart svg")); ``` #### .point(name, x, y) - **mandatory** Set up a data point on the overlay. The name of a data point should match a specific "key" among data groups generated using keyAccessor. If a match is found (point name <-> data group key) then a bubble will be automatically generated at the position specified by the function. x and y value specified here are relative to the underlying svg. ## Row Chart Includes: [Cap Mixin](#cap-mixin), [Margin Mixin](#margin-mixin), [Color Mixin](#color-mixin), [Base Mixin](#base-mixin) Concrete row chart implementation. #### dc.rowChart(parent[, chartGroup]) Create a row chart instance and attach it to the given parent element. Parameters: * parent : string - any valid d3 single selector representing typically a dom block element such as a div. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return a newly created row chart instance ```js // create a row chart under #chart-container1 element using the default global chart group var chart1 = dc.rowChart("#chart-container1"); // create a row chart under #chart-container2 element using chart group A var chart2 = dc.rowChart("#chart-container2", "chartGroupA"); ``` #### .renderTitleLabel(boolean) Turn on/off Title label rendering (values) using SVG style of text-anchor 'end' #### .xAxis() Get the x axis for the row chart instance. Note: not settable for row charts. See the [d3 axis object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-axis) documention for more information. ```js // customize x axis tick format chart.xAxis().tickFormat(function(v) {return v + "%";}); // customize x axis tick values chart.xAxis().tickValues([0, 100, 200, 300]); ``` #### .fixedBarHeight([height]) Get or set the fixed bar height. Default is [false] which will auto-scale bars. For example, if you want to fix the height for a specific number of bars (useful in TopN charts) you could fix height as follows (where count = total number of bars in your TopN and gap is your vertical gap space). ```js chart.fixedBarHeight( chartheight - (count + 1) * gap / count); ``` #### .gap([gap]) Get or set the vertical gap space between rows on a particular row chart instance. Default gap is 5px; #### .elasticX([boolean]) Get or set the elasticity on x axis. If this attribute is set to true, then the x axis will rescle to auto-fit the data range when filtered. #### .labelOffsetX([x]) Get or set the x offset (horizontal space to the top left corner of a row) for labels on a particular row chart. Default x offset is 10px; #### .labelOffsetY([y]) Get or set the y offset (vertical space to the top left corner of a row) for labels on a particular row chart. Default y offset is 15px; #### .titleLabelOffsetx([x]) Get of set the x offset (horizontal space between right edge of row and right edge or text. Default x offset is 2px; ## Legend Legend is a attachable widget that can be added to other dc charts to render horizontal legend labels. ```js chart.legend(dc.legend().x(400).y(10).itemHeight(13).gap(5)) ``` Examples: * [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * [Canadian City Crime Stats](http://dc-js.github.com/dc.js/crime/index.html) #### .x([value]) Set or get x coordinate for legend widget. Default value: 0. #### .y([value]) Set or get y coordinate for legend widget. Default value: 0. #### .gap([value]) Set or get gap between legend items. Default value: 5. #### .itemHeight([value]) Set or get legend item height. Default value: 12. #### .horizontal([boolean]) Position legend horizontally instead of vertically #### .legendWidth([value]) Maximum width for horizontal legend. Default value: 560. #### .itemWidth([value]) legendItem width for horizontal legend. Default value: 70. ## Scatter Plot Includes: [Coordinate Grid Mixin](#coordinate-grid-mixin) A scatter plot chart #### dc.scatterPlot(parent[, chartGroup]) Create a scatter plot instance and attach it to the given parent element. Parameters: * parent : string|compositeChart - any valid d3 single selector representing typically a dom block element such as a div, or if this scatter plot is a sub-chart in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created scatter plot instance ```js // create a scatter plot under #chart-container1 element using the default global chart group var chart1 = dc.scatterPlot("#chart-container1"); // create a scatter plot under #chart-container2 element using chart group A var chart2 = dc.scatterPlot("#chart-container2", "chartGroupA"); // create a sub-chart under a composite parent chart var chart3 = dc.scatterPlot(compositeChart); ``` #### .symbol([type]) Get or set the symbol type used for each point. By default a circle. See the D3 [docs](https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-symbol_type) for acceptable types; Type can be a constant or an accessor. #### .symbolSize([radius]) Set or get radius for symbols, default: 3. #### .highlightedSize([radius]) Set or get radius for highlighted symbols, default: 4. ## Number Display Widget Includes: [Base Mixin](#base-mixin) A display of a single numeric value. Examples: * [Test Example](http://dc-js.github.io/dc.js/examples/number.html) #### dc.numberDisplay(parent[, chartGroup]) Create a Number Display instance and attach it to the given parent element. Unlike other charts, you do not need to set a dimension. Instead a valid group object must be provided and valueAccessor that is expected to return a single value. Parameters: * parent : string - any valid d3 single selector representing typically a dom block element such as a div or span * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created number display instance ```js // create a number display under #chart-container1 element using the default global chart group var display1 = dc.numberDisplay("#chart-container1"); ``` #### .value() Calculate and return the underlying value of the display #### .formatNumber([formatter]) Get or set a function to format the value for the display. By default `d3.format(".2s");` is used. ## Heat Map Includes: [Color Mixin](#color-mixin), [Margin Mixin](#margin-mixin), [Base Mixin](#base-mixin) A heat map is matrix that represents the values of two dimensions of data using colors. #### dc.heatMap(parent[, chartGroup]) Create a heat map instance and attach it to the given parent element. Parameters: * parent : string - any valid d3 single selector representing typically a dom block element such as a div. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created heat map instance ```js // create a heat map under #chart-container1 element using the default global chart group var heatMap1 = dc.heatMap("#chart-container1"); // create a heat map under #chart-container2 element using chart group A var heatMap2 = dc.heatMap("#chart-container2", "chartGroupA"); ``` ## Box Plot Includes: [Coordinate Grid Mixin](#coordinate-grid-mixin) A box plot is a chart that depicts numerical data via their quartile ranges. #### dc.boxPlot(parent[, chartGroup]) Create a box plot instance and attach it to the given parent element. Parameters: * parent : string - any valid d3 single selector representing typically a dom block element such as a div. * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. Return: A newly created box plot instance ```js // create a box plot under #chart-container1 element using the default global chart group var boxPlot1 = dc.boxPlot("#chart-container1"); // create a box plot under #chart-container2 element using chart group A var boxPlot2 = dc.boxPlot("#chart-container2", "chartGroupA"); ``` #### .boxPadding([padding]) Get or set the spacing between boxes as a fraction of bar size. Valid values are within 0-1. See the [d3 docs](https://github.com/mbostock/d3/wiki/Ordinal-Scales#wiki-ordinal_rangeBands) for a visual description of how the padding is applied. Default: 0.8 #### .outerPadding([padding]) Get or set the outer padding on an ordinal box chart. This setting has no effect on non-ordinal charts or on charts with a custom `.boxWidth`. Padding equivlent in width to `padding * barWidth` will be added on each side of the chart. Default: 0.5 #### .boxWidth(width || function(innerChartWidth, xUnits) { ... }) Get or set the numerical width of the boxplot box. Provided width may also be a function. This function takes as parameters the chart width without the right and left margins as well as the number of x units. #### .tickFormat() Set the numerical format of the boxplot median, whiskers and quartile labels. Defaults to integer. ```js // format ticks to 2 decimal places chart.tickFormat(d3.format(".2f")); ```
{ "content_hash": "ebeaa8d8ed1d9a68855805642881d12c", "timestamp": "", "source": "github", "line_count": 1544, "max_line_length": 330, "avg_line_length": 42.70531088082902, "alnum_prop": 0.7536132975415928, "repo_name": "adebali/adebali.github.io", "id": "824a5d0b2ebf9a2f7a3defa6404c69a95283eb44", "size": "65946", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "workbench/dc.js/web/docs/api-latest.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "241033" }, { "name": "HTML", "bytes": "3941048" }, { "name": "JavaScript", "bytes": "2906900" }, { "name": "Makefile", "bytes": "9829" }, { "name": "Python", "bytes": "147" }, { "name": "Ruby", "bytes": "3534" }, { "name": "Shell", "bytes": "216" } ], "symlink_target": "" }
package pl.karol202.evolution.entity.behaviour; import pl.karol202.evolution.entity.ComponentManager; import pl.karol202.evolution.entity.Entity; import pl.karol202.evolution.ui.main.ViewInfo; import java.awt.*; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; public class BehaviourManager { private Entity entity; private ComponentManager componentManager; private Map<Integer, Behaviour> behaviours; private Behaviour currentBehaviour; public BehaviourManager(Entity entity, ComponentManager componentManager) { this.entity = entity; this.componentManager = componentManager; behaviours = new HashMap<>(); } public void addBehaviours() { addBehaviour(new RandomMovingBehaviour(entity, componentManager, this)); addBehaviour(new FoodSeekBehaviour(entity, componentManager, this)); addBehaviour(new ReproduceBehaviour(entity, componentManager, this)); currentBehaviour = findBehaviour(RandomMovingBehaviour.BEHAVIOUR_ID); } private void addBehaviour(Behaviour behaviour) { behaviours.put(behaviour.getId(), behaviour); } private Behaviour findBehaviour(int id) { return behaviours.get(id); } public void update() { if(currentBehaviour == null) chooseBehaviourWhenNotBusy(); else chooseBehaviourWhenBusy(); currentBehaviour.update(); } private void chooseBehaviourWhenNotBusy() { if(entity.shouldEat()) currentBehaviour = findBehaviour(FoodSeekBehaviour.BEHAVIOUR_ID); else if(entity.isReadyToReproduce()) currentBehaviour = findBehaviour(ReproduceBehaviour.BEHAVIOUR_ID); else currentBehaviour = findBehaviour(RandomMovingBehaviour.BEHAVIOUR_ID); } private void chooseBehaviourWhenBusy() { if(isEating() || isReproducing()) return; if(entity.shouldEat()) currentBehaviour = findBehaviour(FoodSeekBehaviour.BEHAVIOUR_ID); else if(entity.isReadyToReproduce()) currentBehaviour = findBehaviour(ReproduceBehaviour.BEHAVIOUR_ID); } void abandonCurrentBehaviour() { currentBehaviour = null; } private ReproduceBehaviour getReproduceBehaviour() { return (ReproduceBehaviour) findBehaviour(ReproduceBehaviour.BEHAVIOUR_ID); } public ReproduceBehaviour reproduce() { if(!(currentBehaviour instanceof ReproduceBehaviour)) currentBehaviour = getReproduceBehaviour(); return (ReproduceBehaviour) currentBehaviour; } private boolean isEating() { return currentBehaviour instanceof FoodSeekBehaviour; } public boolean isInRut() { return currentBehaviour instanceof ReproduceBehaviour; } public boolean isReproducing() { return isInRut() && getReproduceBehaviour().isBusy(); } public void drawCurrentBehaviour(Graphics2D g, ViewInfo viewInfo, boolean selected) { if(currentBehaviour != null) currentBehaviour.drawBehaviour(g, viewInfo, selected); } public String getCurrentBehaviourName() { if(currentBehaviour == null) return ""; return currentBehaviour.getName(); } public int getCurrentBehaviourId() { if(currentBehaviour == null) return -1; return currentBehaviour.getId(); } public void setCurrentBehaviourId(int id) { currentBehaviour = behaviours.get(id); } public Stream<SavableBehaviour> getSavableBehavioursStream() { return behaviours.values().stream().filter(b -> b instanceof SavableBehaviour).map(b -> (SavableBehaviour) b); } }
{ "content_hash": "1707e6414fa37932a781e444aa592c8e", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 112, "avg_line_length": 26.236220472440944, "alnum_prop": 0.7722088835534213, "repo_name": "karol-202/Evolution", "id": "05f762109ad3554067e28508e7c2a00b4c91e993", "size": "3929", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/pl/karol202/evolution/entity/behaviour/BehaviourManager.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "249691" } ], "symlink_target": "" }
using System.Composition; using Microsoft.NetCore.Analyzers.Runtime; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; namespace Microsoft.NetCore.CSharp.Analyzers.Runtime { /// <summary> /// RS0014: Do not use Enumerable methods on indexable collections. Instead use the collection directly /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp), Shared] public class CSharpDoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectlyFixer : DoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectlyFixer { } }
{ "content_hash": "dd067db2996b54f05824510755ade408", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 192, "avg_line_length": 40.266666666666666, "alnum_prop": 0.8178807947019867, "repo_name": "heejaechang/roslyn-analyzers", "id": "6977075ce708021303fff4bb93112d8ebcdd78ca", "size": "766", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Microsoft.NetCore.Analyzers/CSharp/Runtime/CSharpDoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectly.Fixer.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "428" }, { "name": "C#", "bytes": "5601917" }, { "name": "Groovy", "bytes": "2454" }, { "name": "PowerShell", "bytes": "7662" }, { "name": "Visual Basic", "bytes": "173853" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.github.wesleyegberto.javaeetesting</groupId> <artifactId>junit-hamcrest</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> </project>
{ "content_hash": "d6c688529fe69466c670baadd0ef64e4", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 104, "avg_line_length": 34.791666666666664, "alnum_prop": 0.7305389221556886, "repo_name": "wesleyegberto/courses-projects", "id": "e489b4943ba6ee6593df30c258faad7f091c7bf7", "size": "835", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/javaeetesting/junit-hamcrest/pom.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "160809" }, { "name": "Dockerfile", "bytes": "2215" }, { "name": "EJS", "bytes": "4300" }, { "name": "HTML", "bytes": "577164" }, { "name": "Java", "bytes": "617578" }, { "name": "JavaScript", "bytes": "5560654" }, { "name": "Jupyter Notebook", "bytes": "176930" }, { "name": "Procfile", "bytes": "117" }, { "name": "Puppet", "bytes": "2496" }, { "name": "Python", "bytes": "50952" }, { "name": "SCSS", "bytes": "18154" }, { "name": "Shell", "bytes": "2489" }, { "name": "TypeScript", "bytes": "825418" }, { "name": "Vue", "bytes": "3210" }, { "name": "XSLT", "bytes": "1733" } ], "symlink_target": "" }
package common import ( "crypto/rand" "errors" "strconv" ) var ( ErrSaltPrefix = errors.New("invalid magic prefix") ErrSaltFormat = errors.New("invalid salt format") ErrSaltRounds = errors.New("invalid rounds") ) // Salt represents a salt. type Salt struct { MagicPrefix []byte SaltLenMin int SaltLenMax int RoundsMin int RoundsMax int RoundsDefault int } // Generate generates a random salt of a given length. // // The length is set thus: // // length > SaltLenMax: length = SaltLenMax // length < SaltLenMin: length = SaltLenMin func (s *Salt) Generate(length int) []byte { if length > s.SaltLenMax { length = s.SaltLenMax } else if length < s.SaltLenMin { length = s.SaltLenMin } saltLen := (length * 6 / 8) if (length*6)%8 != 0 { saltLen += 1 } salt := make([]byte, saltLen) rand.Read(salt) out := make([]byte, len(s.MagicPrefix)+length) copy(out, s.MagicPrefix) copy(out[len(s.MagicPrefix):], Base64_24Bit(salt)) return out } // GenerateWRounds creates a random salt with the random bytes being of the // length provided, and the rounds parameter set as specified. // // The parameters are set thus: // // length > SaltLenMax: length = SaltLenMax // length < SaltLenMin: length = SaltLenMin // // rounds < 0: rounds = RoundsDefault // rounds < RoundsMin: rounds = RoundsMin // rounds > RoundsMax: rounds = RoundsMax // // If rounds is equal to RoundsDefault, then the "rounds=" part of the salt is // removed. func (s *Salt) GenerateWRounds(length, rounds int) []byte { if length > s.SaltLenMax { length = s.SaltLenMax } else if length < s.SaltLenMin { length = s.SaltLenMin } if rounds < 0 { rounds = s.RoundsDefault } else if rounds < s.RoundsMin { rounds = s.RoundsMin } else if rounds > s.RoundsMax { rounds = s.RoundsMax } saltLen := (length * 6 / 8) if (length*6)%8 != 0 { saltLen += 1 } salt := make([]byte, saltLen) rand.Read(salt) roundsText := "" if rounds != s.RoundsDefault { roundsText = "rounds=" + strconv.Itoa(rounds) } out := make([]byte, len(s.MagicPrefix)+len(roundsText)+length) copy(out, s.MagicPrefix) copy(out[len(s.MagicPrefix):], []byte(roundsText)) copy(out[len(s.MagicPrefix)+len(roundsText):], Base64_24Bit(salt)) return out }
{ "content_hash": "e6cbbf1168ba2857263d7f02cab64881", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 78, "avg_line_length": 23.051020408163264, "alnum_prop": 0.6755201416555998, "repo_name": "lucasvanhalst/identityserver", "id": "afd77d359f36f6ba9199b2b676a058582235b747", "size": "2523", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "credentials/password/keyderivation/crypt/common/salt.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "9721" }, { "name": "Go", "bytes": "265776" }, { "name": "HTML", "bytes": "107850" }, { "name": "JavaScript", "bytes": "107459" }, { "name": "RAML", "bytes": "32281" }, { "name": "Shell", "bytes": "276" } ], "symlink_target": "" }
{% extends "base.html" %} {% block meta_title %}OSDC Demo Registration{% endblock %} {% block header %} <header class="jumbotron subhead"> <h2>OSDC Demo Registration</h2> </header> {% endblock %} {% block main %} <div class="span12"> <form action="/demoregister/" method="post" enctype="multipart/form-data" class="form-horizontal">{% csrf_token %} <fieldset> <div class="control-group {% if form.first_name.errors %}error{% endif %}"> <label class="control-label" for="id_name">First Name*</label> <div class="controls"> {{ form.first_name }} <span class="help-inline">{{form.first_name.errors}}</span> </div> </div> <div class="control-group {% if form.last_name.errors %}error{% endif %}"> <label class="control-label" for="id_name">Last Name*</label> <div class="controls"> {{ form.last_name }} <span class="help-inline">{{form.last_name.errors}}</span> </div> </div> <div class="control-group {% if form.email.errors %}error{% endif %}"> <label class="control-label" for="id_email">E-mail*</label> <div class="controls"> {{ form.email}} <span class="help-inline">{{form.email.errors}}</span> </div> </div> <div class="control-group {% if form.organization.errors %}error{% endif %}"> <label class="control-label" for="id_organization">Organization/University*</label> <div class="controls"> {{ form.organization }} <span class="help-inline">{{form.organization.errors}}</span> </div> </div> <div class="control-group {% if form.projectlead.errors %}error{% endif %}"> <label class="control-label" for="id_projectlead">Project Lead*</label> <div class="controls"> {{ form.projectlead }} <span class="help-inline">{{form.projectlead.errors}}</span> </div> </div> <div class="control-group {% if form.how.errors %}error{% endif %}"> <label class="control-label" for="id_how">How did you hear about this OSDC Demo?</label> <div class="controls"> {{ form.how }} <span class="help-inline">{{form.how.errors}}</span> </div> </div> <!-- <div class="control-group {% if form.captcha.errors %}error{% endif %}"> <label class="control-label" for="id_recaptcha">ReCaptcha</label> <div class="controls"> {{ form.captcha }} <span class="help-inline">{{form.captcha.errors}}</span> </div> </div> --> <div class="control-group"> <div class="controls"> <button type="submit" class="btn btn-warning">Submit Registration</button> </div> </div> </fieldset> </form> </div> {% endblock %} {% block js %} {% include "horizon/_scripts.html" %} {% endblock %}
{ "content_hash": "abd23cbb94f499cafdef7183612ce973", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 114, "avg_line_length": 32.348837209302324, "alnum_prop": 0.5927390366642703, "repo_name": "LabAdvComp/tukey_portal", "id": "1b5e4812549e2b528df7fb350e55659eb52dd8f4", "size": "2782", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tukey/templates/webforms/demo_form.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "171933" }, { "name": "HTML", "bytes": "453330" }, { "name": "JavaScript", "bytes": "207554" }, { "name": "Python", "bytes": "260989" }, { "name": "Shell", "bytes": "5039" } ], "symlink_target": "" }
/** * This is code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * * (c) Daniel Lemire, http://lemire.me/en/ */ #ifndef BITPACK_SIMDBINARYPACKING_H_ #define BITPACK_SIMDBINARYPACKING_H_ #include "codecs.h" #include <util/compression/int/fastpfor/simdbitpacking.h> #include "util.h" /** * * Designed by D. Lemire with ideas from Leonid Boystov. This scheme is NOT patented. * * Code data in miniblocks of 128 integers. * To preserve alignment, we use regroup * 8 such miniblocks into a block of 8 * 128 = 1024 * integers. */ class SIMDBinaryPacking: public IntegerCODEC { public: static const uint32_t CookiePadder = 123456; static const uint32_t MiniBlockSize = 128; static const uint32_t HowManyMiniBlocks = 16; static const uint32_t BlockSize = HowManyMiniBlocks * MiniBlockSize; /** * The way this code is written, it will automatically "pad" the * header according to the alignment of the out pointer. So if you * move the data around, you should preserve the alignment. */ void encodeArray(const uint32_t *in, const size_t length, uint32_t *out, size_t &nvalue) const { checkifdivisibleby(length, BlockSize); const uint32_t * const initout(out); *out++ = length; while(needPaddingTo128Bits(out)) *out++ = CookiePadder; uint32_t Bs[HowManyMiniBlocks]; for (const uint32_t * const final = in + length; in + BlockSize <= final; in += BlockSize) { for (uint32_t i = 0; i < HowManyMiniBlocks; ++i) Bs[i] = maxbits(in + i * MiniBlockSize, in + (i + 1) * MiniBlockSize); *out++ = (Bs[0] << 24) | (Bs[1] << 16) | (Bs[2] << 8) | Bs[3]; *out++ = (Bs[4] << 24) | (Bs[5] << 16) | (Bs[6] << 8) | Bs[7]; *out++ = (Bs[8] << 24) | (Bs[9] << 16) | (Bs[10] << 8) | Bs[11]; *out++ = (Bs[12] << 24) | (Bs[13] << 16) | (Bs[14] << 8) | Bs[15]; for (uint32_t i = 0; i < HowManyMiniBlocks; ++i) { // D.L. : is the reinterpret_cast safe here? SIMD_fastpackwithoutmask_32(in + i * MiniBlockSize, reinterpret_cast<__m128i *>(out), Bs[i]); out += MiniBlockSize/32 * Bs[i]; } } nvalue = out - initout; } const uint32_t * decodeArray(const uint32_t *in, const size_t /*length*/, uint32_t *out, size_t & nvalue) const { const uint32_t actuallength = *in++; if(needPaddingTo128Bits(out)) throw runtime_error("bad initial output align"); while(needPaddingTo128Bits(in)) { if(in[0] != CookiePadder) throw logic_error("SIMDBinaryPacking alignment issue."); ++in; } const uint32_t * const initout(out); uint32_t Bs[HowManyMiniBlocks]; for (; out < initout + actuallength; out += BlockSize) { for(uint32_t i = 0; i < 4 ; ++i,++in) { Bs[0 + 4 * i] = static_cast<uint8_t>(in[0] >> 24); Bs[1 + 4 * i] = static_cast<uint8_t>(in[0] >> 16); Bs[2 + 4 * i] = static_cast<uint8_t>(in[0] >> 8); Bs[3 + 4 * i] = static_cast<uint8_t>(in[0]); } for (uint32_t i = 0; i < HowManyMiniBlocks; ++i) { // D.L. : is the reinterpret_cast safe here? SIMD_fastunpack_32(reinterpret_cast<const __m128i *>(in), out + i * MiniBlockSize, Bs[i]); in += MiniBlockSize/32 * Bs[i]; } } nvalue = out - initout; return in; } string name() const { return "SIMDBinaryPacking"; } }; class SIMDGlobalBinaryPacking: public IntegerCODEC { public: static const uint32_t CookiePadder = 123456; static const uint32_t BlockSize = 128; /** * The way this code is written, it will automatically "pad" the * header according to the alignment of the out pointer. So if you * move the data around, you should preserve the alignment. */ void encodeArray(const uint32_t *in, const size_t length, uint32_t *out, size_t &nvalue) { checkifdivisibleby(length, BlockSize); const uint32_t * const initout(out); *out++ = length; uint32_t Bs = maxbits(in,in + length); *out++ = Bs; while(needPaddingTo128Bits(out)) *out++ = CookiePadder; for (const uint32_t * const final = in + length; in + BlockSize <= final; in += BlockSize, out += 4 * Bs) { SIMD_fastpackwithoutmask_32(in, reinterpret_cast<__m128i *>(out), Bs); } nvalue = out - initout; } const uint32_t * decodeArray(const uint32_t *in, const size_t /*length*/, uint32_t *out, size_t & nvalue) { const uint32_t actuallength = *in++; const uint32_t Bs = *in++; if(needPaddingTo128Bits(out)) throw runtime_error("bad initial output align"); while(needPaddingTo128Bits(in)) { if(in[0] != CookiePadder) throw logic_error("SIMDBinaryPacking alignment issue."); ++in; } for (uint32_t k = 0; k < actuallength / 128; ++k) { SIMD_fastunpack_32(reinterpret_cast<const __m128i *>(in + 4 * Bs * k), out + 128 * k, Bs); } nvalue = actuallength; return in + 4* Bs * actuallength / 128; /*const uint32_t * const initout(out); for (; out < initout + actuallength; out += BlockSize, in += 4 * Bs) { SIMD_fastunpack_32(reinterpret_cast<const __m128i *>(in), out , Bs); } nvalue = out - initout; return in;*/ } string name() const { return "SIMDGlobalBinaryPacking"; } }; #endif /* SIMDBINARYPACKING_H_ */
{ "content_hash": "6bb26da68898b11efa703818174fb00d", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 106, "avg_line_length": 35.76162790697674, "alnum_prop": 0.5278816452609332, "repo_name": "izenecloud/izenelib", "id": "d98be957fa0baf7c20f6a08ed45b1b2d648fb7ad", "size": "6151", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "include/util/compression/int/compressedset/bitpacking/simdbinarypacking.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "81555" }, { "name": "C++", "bytes": "15025100" }, { "name": "Makefile", "bytes": "21662" }, { "name": "Ruby", "bytes": "699" }, { "name": "Shell", "bytes": "1359" } ], "symlink_target": "" }
std::vector<tensorflow::uint8> LoadImageFromFile(const char* file_name, int* out_width, int* out_height, int* out_channels); std::vector<tensorflow::uint8> LoadImageFromBase64(NSString* base64data, int* out_width, int* out_height, int* out_channels); std::vector<tensorflow::uint8> LoadImageFromData(CFDataRef data_ref, const char* suffix, int* out_width, int* out_height, int* out_channels); #endif // TENSORFLOW_EXAMPLES_IOS_IOS_IMAGE_LOAD_H_
{ "content_hash": "7bf72c682726758ab47068d2dfb33aec", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 72, "avg_line_length": 30.529411764705884, "alnum_prop": 0.6570327552986512, "repo_name": "heigeo/cordova-plugin-tensorflow", "id": "b8fd728e0d7f2375fbeaa7746808559cd5bd143c", "size": "1294", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ios/tf_libs/ios_image_load.h", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "4114" }, { "name": "Java", "bytes": "13595" }, { "name": "JavaScript", "bytes": "7442" }, { "name": "Objective-C", "bytes": "1039" }, { "name": "Objective-C++", "bytes": "16716" } ], "symlink_target": "" }
""" Django settings for staas project. Generated by 'django-admin startproject' using Django 1.9.6. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '9)@z+#q5^acyq-)=23l*%8ymeigyd=w5eug0*ihi!1g4gho9wh' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] LOGIN_REDIRECT_URL = '/cloud/' MEDIA_URL = '/storage/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Application definition # 'cloud.apps.CloudConfig', INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cloud' ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'staas.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'staas.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/'
{ "content_hash": "610d946796814a318834ec6de1712ab8", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 91, "avg_line_length": 26.04724409448819, "alnum_prop": 0.686819830713422, "repo_name": "sk364/staas_cloud", "id": "f6dec6dda37858fb0f6e081ca1822c2e489aedd9", "size": "3308", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "staas/settings.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "627" }, { "name": "HTML", "bytes": "15319" }, { "name": "Python", "bytes": "19634" } ], "symlink_target": "" }
/* -*- C++ -*- */ /** * @file Find_Worker_T.h * * $Id: Find_Worker_T.h 14 2007-02-01 15:49:12Z mitza $ * * @author Pradeep Gore <pradeep@oomworks.com> * * */ #ifndef TAO_Notify_FIND_WORKER_T_H #define TAO_Notify_FIND_WORKER_T_H #include /**/ "ace/pre.h" #include "orbsvcs/Notify/notify_serv_export.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #include "orbsvcs/ESF/ESF_Proxy_Collection.h" #include "orbsvcs/ESF/ESF_Worker.h" #include "orbsvcs/Notify/Container_T.h" #include "orbsvcs/Notify/Object.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL /** * @class TAO_Notify_Find_Worker_T * * @brief Helper to locate a TYPE given its ID. * */ template <class TYPE, class INTERFACE, class INTERFACE_PTR, class EXCEPTION> class TAO_Notify_Serv_Export TAO_Notify_Find_Worker_T : public TAO_ESF_Worker<TYPE> { typedef TAO_Notify_Container_T<TYPE> CONTAINER; typedef TAO_ESF_Proxy_Collection<TYPE> COLLECTION; public: /// Constructor TAO_Notify_Find_Worker_T (void); /// Find the Type. TYPE* find (const TAO_Notify_Object::ID id, CONTAINER& container); /// Find and resolve to the Interface. INTERFACE_PTR resolve (const TAO_Notify_Object::ID id, CONTAINER& container); protected: ///= TAO_ESF_Worker method void work (TYPE* object); /// The id we're looking for. TAO_Notify_Object::ID id_; /// The result TYPE* result_; }; TAO_END_VERSIONED_NAMESPACE_DECL #if defined (__ACE_INLINE__) #include "orbsvcs/Notify/Find_Worker_T.inl" #endif /* __ACE_INLINE__ */ #if defined (ACE_TEMPLATES_REQUIRE_SOURCE) #include "orbsvcs/Notify/Find_Worker_T.cpp" #endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ #if defined (ACE_TEMPLATES_REQUIRE_PRAGMA) #pragma implementation ("Find_Worker_T.cpp") #endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ #include /**/ "ace/post.h" #endif /* TAO_Notify_FIND_WORKER_T_H */
{ "content_hash": "e95a61e315ad3e1115a28e2e9dc0fefe", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 83, "avg_line_length": 24.25974025974026, "alnum_prop": 0.6937901498929336, "repo_name": "binary42/OCI", "id": "564dbc68f46875dd592cb2d3aa9824549bd390de", "size": "1868", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "orbsvcs/Notify/Find_Worker_T.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "176672" }, { "name": "C++", "bytes": "28193015" }, { "name": "HTML", "bytes": "19914" }, { "name": "IDL", "bytes": "89802" }, { "name": "LLVM", "bytes": "4067" }, { "name": "Lex", "bytes": "6305" }, { "name": "Makefile", "bytes": "509509" }, { "name": "Yacc", "bytes": "18367" } ], "symlink_target": "" }
#ifndef __OPENCV_VIDEOSTAB_STABILIZER_HPP__ #define __OPENCV_VIDEOSTAB_STABILIZER_HPP__ #include <vector> #include <ctime> #include BOSS_OPENCV_U_opencv2__core_hpp //original-code:"opencv2/core.hpp" #include BOSS_OPENCV_U_opencv2__imgproc_hpp //original-code:"opencv2/imgproc.hpp" #include "opencv2/videostab/global_motion.hpp" #include "opencv2/videostab/motion_stabilizing.hpp" #include "opencv2/videostab/frame_source.hpp" #include "opencv2/videostab/log.hpp" #include "opencv2/videostab/inpainting.hpp" #include "opencv2/videostab/deblurring.hpp" #include "opencv2/videostab/wobble_suppression.hpp" namespace cv { namespace videostab { //! @addtogroup videostab //! @{ class CV_EXPORTS StabilizerBase { public: virtual ~StabilizerBase() {} void setLog(Ptr<ILog> ilog) { log_ = ilog; } Ptr<ILog> log() const { return log_; } void setRadius(int val) { radius_ = val; } int radius() const { return radius_; } void setFrameSource(Ptr<IFrameSource> val) { frameSource_ = val; } Ptr<IFrameSource> frameSource() const { return frameSource_; } void setMotionEstimator(Ptr<ImageMotionEstimatorBase> val) { motionEstimator_ = val; } Ptr<ImageMotionEstimatorBase> motionEstimator() const { return motionEstimator_; } void setDeblurer(Ptr<DeblurerBase> val) { deblurer_ = val; } Ptr<DeblurerBase> deblurrer() const { return deblurer_; } void setTrimRatio(float val) { trimRatio_ = val; } float trimRatio() const { return trimRatio_; } void setCorrectionForInclusion(bool val) { doCorrectionForInclusion_ = val; } bool doCorrectionForInclusion() const { return doCorrectionForInclusion_; } void setBorderMode(int val) { borderMode_ = val; } int borderMode() const { return borderMode_; } void setInpainter(Ptr<InpainterBase> val) { inpainter_ = val; } Ptr<InpainterBase> inpainter() const { return inpainter_; } protected: StabilizerBase(); void reset(); Mat nextStabilizedFrame(); bool doOneIteration(); virtual void setUp(const Mat &firstFrame); virtual Mat estimateMotion() = 0; virtual Mat estimateStabilizationMotion() = 0; void stabilizeFrame(); virtual Mat postProcessFrame(const Mat &frame); void logProcessingTime(); Ptr<ILog> log_; Ptr<IFrameSource> frameSource_; Ptr<ImageMotionEstimatorBase> motionEstimator_; Ptr<DeblurerBase> deblurer_; Ptr<InpainterBase> inpainter_; int radius_; float trimRatio_; bool doCorrectionForInclusion_; int borderMode_; Size frameSize_; Mat frameMask_; int curPos_; int curStabilizedPos_; bool doDeblurring_; Mat preProcessedFrame_; bool doInpainting_; Mat inpaintingMask_; Mat finalFrame_; std::vector<Mat> frames_; std::vector<Mat> motions_; // motions_[i] is the motion from i-th to i+1-th frame std::vector<float> blurrinessRates_; std::vector<Mat> stabilizedFrames_; std::vector<Mat> stabilizedMasks_; std::vector<Mat> stabilizationMotions_; clock_t processingStartTime_; }; class CV_EXPORTS OnePassStabilizer : public StabilizerBase, public IFrameSource { public: OnePassStabilizer(); void setMotionFilter(Ptr<MotionFilterBase> val) { motionFilter_ = val; } Ptr<MotionFilterBase> motionFilter() const { return motionFilter_; } virtual void reset(); virtual Mat nextFrame() { return nextStabilizedFrame(); } protected: virtual void setUp(const Mat &firstFrame); virtual Mat estimateMotion(); virtual Mat estimateStabilizationMotion(); virtual Mat postProcessFrame(const Mat &frame); Ptr<MotionFilterBase> motionFilter_; }; class CV_EXPORTS TwoPassStabilizer : public StabilizerBase, public IFrameSource { public: TwoPassStabilizer(); void setMotionStabilizer(Ptr<IMotionStabilizer> val) { motionStabilizer_ = val; } Ptr<IMotionStabilizer> motionStabilizer() const { return motionStabilizer_; } void setWobbleSuppressor(Ptr<WobbleSuppressorBase> val) { wobbleSuppressor_ = val; } Ptr<WobbleSuppressorBase> wobbleSuppressor() const { return wobbleSuppressor_; } void setEstimateTrimRatio(bool val) { mustEstTrimRatio_ = val; } bool mustEstimateTrimaRatio() const { return mustEstTrimRatio_; } virtual void reset(); virtual Mat nextFrame(); protected: void runPrePassIfNecessary(); virtual void setUp(const Mat &firstFrame); virtual Mat estimateMotion(); virtual Mat estimateStabilizationMotion(); virtual Mat postProcessFrame(const Mat &frame); Ptr<IMotionStabilizer> motionStabilizer_; Ptr<WobbleSuppressorBase> wobbleSuppressor_; bool mustEstTrimRatio_; int frameCount_; bool isPrePassDone_; bool doWobbleSuppression_; std::vector<Mat> motions2_; Mat suppressedFrame_; }; //! @} } // namespace videostab } // namespace cv #endif
{ "content_hash": "79289cc061d4e4ad0aed5083f803d5ca", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 90, "avg_line_length": 30.29375, "alnum_prop": 0.7159067464410976, "repo_name": "koobonil/Boss2D", "id": "de8c60cdd469b198a83adce60c7dbfd5ddf20e4c", "size": "7007", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Boss2D/addon/opencv-3.1.0_for_boss/modules/videostab/include/opencv2/videostab/stabilizer.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "4820445" }, { "name": "Awk", "bytes": "4272" }, { "name": "Batchfile", "bytes": "89930" }, { "name": "C", "bytes": "119747922" }, { "name": "C#", "bytes": "87505" }, { "name": "C++", "bytes": "272329620" }, { "name": "CMake", "bytes": "1199656" }, { "name": "CSS", "bytes": "42679" }, { "name": "Clojure", "bytes": "1487" }, { "name": "Cuda", "bytes": "1651996" }, { "name": "DIGITAL Command Language", "bytes": "239527" }, { "name": "Dockerfile", "bytes": "9638" }, { "name": "Emacs Lisp", "bytes": "15570" }, { "name": "Go", "bytes": "858185" }, { "name": "HLSL", "bytes": "3314" }, { "name": "HTML", "bytes": "2958385" }, { "name": "Java", "bytes": "2921052" }, { "name": "JavaScript", "bytes": "178190" }, { "name": "Jupyter Notebook", "bytes": "1833654" }, { "name": "LLVM", "bytes": "6536" }, { "name": "M4", "bytes": "775724" }, { "name": "MATLAB", "bytes": "74606" }, { "name": "Makefile", "bytes": "3941551" }, { "name": "Meson", "bytes": "2847" }, { "name": "Module Management System", "bytes": "2626" }, { "name": "NSIS", "bytes": "4505" }, { "name": "Objective-C", "bytes": "4090702" }, { "name": "Objective-C++", "bytes": "1702390" }, { "name": "PHP", "bytes": "3530" }, { "name": "Perl", "bytes": "11096338" }, { "name": "Perl 6", "bytes": "11802" }, { "name": "PowerShell", "bytes": "38571" }, { "name": "Python", "bytes": "24123805" }, { "name": "QMake", "bytes": "18188" }, { "name": "Roff", "bytes": "1261269" }, { "name": "Ruby", "bytes": "5890" }, { "name": "Scala", "bytes": "5683" }, { "name": "Shell", "bytes": "2879948" }, { "name": "TeX", "bytes": "243507" }, { "name": "TypeScript", "bytes": "1593696" }, { "name": "Verilog", "bytes": "1215" }, { "name": "Vim Script", "bytes": "3759" }, { "name": "Visual Basic", "bytes": "16186" }, { "name": "eC", "bytes": "9705" } ], "symlink_target": "" }
package transport import ( "io" "math" "net" "strings" "sync" "sync/atomic" "time" "golang.org/x/net/context" "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" "google.golang.org/grpc/channelz" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" ) // http2Client implements the ClientTransport interface with HTTP2. type http2Client struct { ctx context.Context cancel context.CancelFunc ctxDone <-chan struct{} // Cache the ctx.Done() chan. userAgent string md interface{} conn net.Conn // underlying communication channel loopy *loopyWriter remoteAddr net.Addr localAddr net.Addr authInfo credentials.AuthInfo // auth info about the connection readerDone chan struct{} // sync point to enable testing. writerDone chan struct{} // sync point to enable testing. // goAway is closed to notify the upper layer (i.e., addrConn.transportMonitor) // that the server sent GoAway on this transport. goAway chan struct{} // awakenKeepalive is used to wake up keepalive when after it has gone dormant. awakenKeepalive chan struct{} framer *framer // controlBuf delivers all the control related tasks (e.g., window // updates, reset streams, and various settings) to the controller. controlBuf *controlBuffer fc *trInFlow // The scheme used: https if TLS is on, http otherwise. scheme string isSecure bool creds []credentials.PerRPCCredentials // Boolean to keep track of reading activity on transport. // 1 is true and 0 is false. activity uint32 // Accessed atomically. kp keepalive.ClientParameters statsHandler stats.Handler initialWindowSize int32 bdpEst *bdpEstimator // onSuccess is a callback that client transport calls upon // receiving server preface to signal that a succefull HTTP2 // connection was established. onSuccess func() maxConcurrentStreams uint32 streamQuota int64 streamsQuotaAvailable chan struct{} waitingStreams uint32 nextID uint32 mu sync.Mutex // guard the following variables state transportState activeStreams map[uint32]*Stream // prevGoAway ID records the Last-Stream-ID in the previous GOAway frame. prevGoAwayID uint32 // goAwayReason records the http2.ErrCode and debug data received with the // GoAway frame. goAwayReason GoAwayReason // Fields below are for channelz metric collection. channelzID int64 // channelz unique identification number czmu sync.RWMutex kpCount int64 // The number of streams that have started, including already finished ones. streamsStarted int64 // The number of streams that have ended successfully by receiving EoS bit set // frame from server. streamsSucceeded int64 streamsFailed int64 lastStreamCreated time.Time msgSent int64 msgRecv int64 lastMsgSent time.Time lastMsgRecv time.Time } func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error), addr string) (net.Conn, error) { if fn != nil { return fn(ctx, addr) } return dialContext(ctx, "tcp", addr) } func isTemporary(err error) bool { switch err := err.(type) { case interface { Temporary() bool }: return err.Temporary() case interface { Timeout() bool }: // Timeouts may be resolved upon retry, and are thus treated as // temporary. return err.Timeout() } return true } // newHTTP2Client constructs a connected ClientTransport to addr based on HTTP2 // and starts to receive messages on it. Non-nil error returns if construction // fails. func newHTTP2Client(connectCtx, ctx context.Context, addr TargetInfo, opts ConnectOptions, onSuccess func()) (_ ClientTransport, err error) { scheme := "http" ctx, cancel := context.WithCancel(ctx) defer func() { if err != nil { cancel() } }() conn, err := dial(connectCtx, opts.Dialer, addr.Addr) if err != nil { if opts.FailOnNonTempDialError { return nil, connectionErrorf(isTemporary(err), err, "transport: error while dialing: %v", err) } return nil, connectionErrorf(true, err, "transport: Error while dialing %v", err) } // Any further errors will close the underlying connection defer func(conn net.Conn) { if err != nil { conn.Close() } }(conn) var ( isSecure bool authInfo credentials.AuthInfo ) if creds := opts.TransportCredentials; creds != nil { scheme = "https" conn, authInfo, err = creds.ClientHandshake(connectCtx, addr.Authority, conn) if err != nil { return nil, connectionErrorf(isTemporary(err), err, "transport: authentication handshake failed: %v", err) } isSecure = true } kp := opts.KeepaliveParams // Validate keepalive parameters. if kp.Time == 0 { kp.Time = defaultClientKeepaliveTime } if kp.Timeout == 0 { kp.Timeout = defaultClientKeepaliveTimeout } dynamicWindow := true icwz := int32(initialWindowSize) if opts.InitialConnWindowSize >= defaultWindowSize { icwz = opts.InitialConnWindowSize dynamicWindow = false } writeBufSize := defaultWriteBufSize if opts.WriteBufferSize > 0 { writeBufSize = opts.WriteBufferSize } readBufSize := defaultReadBufSize if opts.ReadBufferSize > 0 { readBufSize = opts.ReadBufferSize } t := &http2Client{ ctx: ctx, ctxDone: ctx.Done(), // Cache Done chan. cancel: cancel, userAgent: opts.UserAgent, md: addr.Metadata, conn: conn, remoteAddr: conn.RemoteAddr(), localAddr: conn.LocalAddr(), authInfo: authInfo, readerDone: make(chan struct{}), writerDone: make(chan struct{}), goAway: make(chan struct{}), awakenKeepalive: make(chan struct{}, 1), framer: newFramer(conn, writeBufSize, readBufSize), fc: &trInFlow{limit: uint32(icwz)}, scheme: scheme, activeStreams: make(map[uint32]*Stream), isSecure: isSecure, creds: opts.PerRPCCredentials, kp: kp, statsHandler: opts.StatsHandler, initialWindowSize: initialWindowSize, onSuccess: onSuccess, nextID: 1, maxConcurrentStreams: defaultMaxStreamsClient, streamQuota: defaultMaxStreamsClient, streamsQuotaAvailable: make(chan struct{}, 1), } t.controlBuf = newControlBuffer(t.ctxDone) if opts.InitialWindowSize >= defaultWindowSize { t.initialWindowSize = opts.InitialWindowSize dynamicWindow = false } if dynamicWindow { t.bdpEst = &bdpEstimator{ bdp: initialWindowSize, updateFlowControl: t.updateFlowControl, } } // Make sure awakenKeepalive can't be written upon. // keepalive routine will make it writable, if need be. t.awakenKeepalive <- struct{}{} if t.statsHandler != nil { t.ctx = t.statsHandler.TagConn(t.ctx, &stats.ConnTagInfo{ RemoteAddr: t.remoteAddr, LocalAddr: t.localAddr, }) connBegin := &stats.ConnBegin{ Client: true, } t.statsHandler.HandleConn(t.ctx, connBegin) } if channelz.IsOn() { t.channelzID = channelz.RegisterNormalSocket(t, opts.ChannelzParentID, "") } // Start the reader goroutine for incoming message. Each transport has // a dedicated goroutine which reads HTTP2 frame from network. Then it // dispatches the frame to the corresponding stream entity. go t.reader() // Send connection preface to server. n, err := t.conn.Write(clientPreface) if err != nil { t.Close() return nil, connectionErrorf(true, err, "transport: failed to write client preface: %v", err) } if n != len(clientPreface) { t.Close() return nil, connectionErrorf(true, err, "transport: preface mismatch, wrote %d bytes; want %d", n, len(clientPreface)) } if t.initialWindowSize != defaultWindowSize { err = t.framer.fr.WriteSettings(http2.Setting{ ID: http2.SettingInitialWindowSize, Val: uint32(t.initialWindowSize), }) } else { err = t.framer.fr.WriteSettings() } if err != nil { t.Close() return nil, connectionErrorf(true, err, "transport: failed to write initial settings frame: %v", err) } // Adjust the connection flow control window if needed. if delta := uint32(icwz - defaultWindowSize); delta > 0 { if err := t.framer.fr.WriteWindowUpdate(0, delta); err != nil { t.Close() return nil, connectionErrorf(true, err, "transport: failed to write window update: %v", err) } } t.framer.writer.Flush() go func() { t.loopy = newLoopyWriter(clientSide, t.framer, t.controlBuf, t.bdpEst) err := t.loopy.run() if err != nil { errorf("transport: loopyWriter.run returning. Err: %v", err) } // If it's a connection error, let reader goroutine handle it // since there might be data in the buffers. if _, ok := err.(net.Error); !ok { t.conn.Close() } close(t.writerDone) }() if t.kp.Time != infinity { go t.keepalive() } return t, nil } func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream { // TODO(zhaoq): Handle uint32 overflow of Stream.id. s := &Stream{ done: make(chan struct{}), method: callHdr.Method, sendCompress: callHdr.SendCompress, buf: newRecvBuffer(), headerChan: make(chan struct{}), contentSubtype: callHdr.ContentSubtype, } s.wq = newWriteQuota(defaultWriteQuota, s.done) s.requestRead = func(n int) { t.adjustWindow(s, uint32(n)) } // The client side stream context should have exactly the same life cycle with the user provided context. // That means, s.ctx should be read-only. And s.ctx is done iff ctx is done. // So we use the original context here instead of creating a copy. s.ctx = ctx s.trReader = &transportReader{ reader: &recvBufferReader{ ctx: s.ctx, ctxDone: s.ctx.Done(), recv: s.buf, }, windowHandler: func(n int) { t.updateWindow(s, uint32(n)) }, } return s } func (t *http2Client) getPeer() *peer.Peer { pr := &peer.Peer{ Addr: t.remoteAddr, } // Attach Auth info if there is any. if t.authInfo != nil { pr.AuthInfo = t.authInfo } return pr } func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) ([]hpack.HeaderField, error) { aud := t.createAudience(callHdr) authData, err := t.getTrAuthData(ctx, aud) if err != nil { return nil, err } callAuthData, err := t.getCallAuthData(ctx, aud, callHdr) if err != nil { return nil, err } // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields // first and create a slice of that exact size. // Make the slice of certain predictable size to reduce allocations made by append. hfLen := 7 // :method, :scheme, :path, :authority, content-type, user-agent, te hfLen += len(authData) + len(callAuthData) headerFields := make([]hpack.HeaderField, 0, hfLen) headerFields = append(headerFields, hpack.HeaderField{Name: ":method", Value: "POST"}) headerFields = append(headerFields, hpack.HeaderField{Name: ":scheme", Value: t.scheme}) headerFields = append(headerFields, hpack.HeaderField{Name: ":path", Value: callHdr.Method}) headerFields = append(headerFields, hpack.HeaderField{Name: ":authority", Value: callHdr.Host}) headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: contentType(callHdr.ContentSubtype)}) headerFields = append(headerFields, hpack.HeaderField{Name: "user-agent", Value: t.userAgent}) headerFields = append(headerFields, hpack.HeaderField{Name: "te", Value: "trailers"}) if callHdr.SendCompress != "" { headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: callHdr.SendCompress}) } if dl, ok := ctx.Deadline(); ok { // Send out timeout regardless its value. The server can detect timeout context by itself. // TODO(mmukhi): Perhaps this field should be updated when actually writing out to the wire. timeout := dl.Sub(time.Now()) headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-timeout", Value: encodeTimeout(timeout)}) } for k, v := range authData { headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } for k, v := range callAuthData { headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } if b := stats.OutgoingTags(ctx); b != nil { headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-tags-bin", Value: encodeBinHeader(b)}) } if b := stats.OutgoingTrace(ctx); b != nil { headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-trace-bin", Value: encodeBinHeader(b)}) } if md, added, ok := metadata.FromOutgoingContextRaw(ctx); ok { var k string for _, vv := range added { for i, v := range vv { if i%2 == 0 { k = v continue } // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set. if isReservedHeader(k) { continue } headerFields = append(headerFields, hpack.HeaderField{Name: strings.ToLower(k), Value: encodeMetadataHeader(k, v)}) } } for k, vv := range md { // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set. if isReservedHeader(k) { continue } for _, v := range vv { headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } } } if md, ok := t.md.(*metadata.MD); ok { for k, vv := range *md { if isReservedHeader(k) { continue } for _, v := range vv { headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } } } return headerFields, nil } func (t *http2Client) createAudience(callHdr *CallHdr) string { // Create an audience string only if needed. if len(t.creds) == 0 && callHdr.Creds == nil { return "" } // Construct URI required to get auth request metadata. // Omit port if it is the default one. host := strings.TrimSuffix(callHdr.Host, ":443") pos := strings.LastIndex(callHdr.Method, "/") if pos == -1 { pos = len(callHdr.Method) } return "https://" + host + callHdr.Method[:pos] } func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[string]string, error) { authData := map[string]string{} for _, c := range t.creds { data, err := c.GetRequestMetadata(ctx, audience) if err != nil { if _, ok := status.FromError(err); ok { return nil, err } return nil, streamErrorf(codes.Unauthenticated, "transport: %v", err) } for k, v := range data { // Capital header names are illegal in HTTP/2. k = strings.ToLower(k) authData[k] = v } } return authData, nil } func (t *http2Client) getCallAuthData(ctx context.Context, audience string, callHdr *CallHdr) (map[string]string, error) { callAuthData := map[string]string{} // Check if credentials.PerRPCCredentials were provided via call options. // Note: if these credentials are provided both via dial options and call // options, then both sets of credentials will be applied. if callCreds := callHdr.Creds; callCreds != nil { if !t.isSecure && callCreds.RequireTransportSecurity() { return nil, streamErrorf(codes.Unauthenticated, "transport: cannot send secure credentials on an insecure connection") } data, err := callCreds.GetRequestMetadata(ctx, audience) if err != nil { return nil, streamErrorf(codes.Internal, "transport: %v", err) } for k, v := range data { // Capital header names are illegal in HTTP/2 k = strings.ToLower(k) callAuthData[k] = v } } return callAuthData, nil } // NewStream creates a stream and registers it into the transport as "active" // streams. func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) { ctx = peer.NewContext(ctx, t.getPeer()) headerFields, err := t.createHeaderFields(ctx, callHdr) if err != nil { return nil, err } s := t.newStream(ctx, callHdr) cleanup := func(err error) { if s.swapState(streamDone) == streamDone { // If it was already done, return. return } // The stream was unprocessed by the server. atomic.StoreUint32(&s.unprocessed, 1) s.write(recvMsg{err: err}) close(s.done) // If headerChan isn't closed, then close it. if atomic.SwapUint32(&s.headerDone, 1) == 0 { close(s.headerChan) } } hdr := &headerFrame{ hf: headerFields, endStream: false, initStream: func(id uint32) (bool, error) { t.mu.Lock() if state := t.state; state != reachable { t.mu.Unlock() // Do a quick cleanup. err := error(errStreamDrain) if state == closing { err = ErrConnClosing } cleanup(err) return false, err } t.activeStreams[id] = s if channelz.IsOn() { t.czmu.Lock() t.streamsStarted++ t.lastStreamCreated = time.Now() t.czmu.Unlock() } var sendPing bool // If the number of active streams change from 0 to 1, then check if keepalive // has gone dormant. If so, wake it up. if len(t.activeStreams) == 1 { select { case t.awakenKeepalive <- struct{}{}: sendPing = true // Fill the awakenKeepalive channel again as this channel must be // kept non-writable except at the point that the keepalive() // goroutine is waiting either to be awaken or shutdown. t.awakenKeepalive <- struct{}{} default: } } t.mu.Unlock() return sendPing, nil }, onOrphaned: cleanup, wq: s.wq, } firstTry := true var ch chan struct{} checkForStreamQuota := func(it interface{}) bool { if t.streamQuota <= 0 { // Can go negative if server decreases it. if firstTry { t.waitingStreams++ } ch = t.streamsQuotaAvailable return false } if !firstTry { t.waitingStreams-- } t.streamQuota-- h := it.(*headerFrame) h.streamID = t.nextID t.nextID += 2 s.id = h.streamID s.fc = &inFlow{limit: uint32(t.initialWindowSize)} if t.streamQuota > 0 && t.waitingStreams > 0 { select { case t.streamsQuotaAvailable <- struct{}{}: default: } } return true } for { success, err := t.controlBuf.executeAndPut(checkForStreamQuota, hdr) if err != nil { return nil, err } if success { break } firstTry = false select { case <-ch: case <-s.ctx.Done(): return nil, ContextErr(s.ctx.Err()) case <-t.goAway: return nil, errStreamDrain case <-t.ctx.Done(): return nil, ErrConnClosing } } if t.statsHandler != nil { outHeader := &stats.OutHeader{ Client: true, FullMethod: callHdr.Method, RemoteAddr: t.remoteAddr, LocalAddr: t.localAddr, Compression: callHdr.SendCompress, } t.statsHandler.HandleRPC(s.ctx, outHeader) } return s, nil } // CloseStream clears the footprint of a stream when the stream is not needed any more. // This must not be executed in reader's goroutine. func (t *http2Client) CloseStream(s *Stream, err error) { var ( rst bool rstCode http2.ErrCode ) if err != nil { rst = true rstCode = http2.ErrCodeCancel } t.closeStream(s, err, rst, rstCode, nil, nil, false) } func (t *http2Client) closeStream(s *Stream, err error, rst bool, rstCode http2.ErrCode, st *status.Status, mdata map[string][]string, eosReceived bool) { // Set stream status to done. if s.swapState(streamDone) == streamDone { // If it was already done, return. return } // status and trailers can be updated here without any synchronization because the stream goroutine will // only read it after it sees an io.EOF error from read or write and we'll write those errors // only after updating this. s.status = st if len(mdata) > 0 { s.trailer = mdata } if err != nil { // This will unblock reads eventually. s.write(recvMsg{err: err}) } // This will unblock write. close(s.done) // If headerChan isn't closed, then close it. if atomic.SwapUint32(&s.headerDone, 1) == 0 { close(s.headerChan) } cleanup := &cleanupStream{ streamID: s.id, onWrite: func() { t.mu.Lock() if t.activeStreams != nil { delete(t.activeStreams, s.id) } t.mu.Unlock() if channelz.IsOn() { t.czmu.Lock() if eosReceived { t.streamsSucceeded++ } else { t.streamsFailed++ } t.czmu.Unlock() } }, rst: rst, rstCode: rstCode, } addBackStreamQuota := func(interface{}) bool { t.streamQuota++ if t.streamQuota > 0 && t.waitingStreams > 0 { select { case t.streamsQuotaAvailable <- struct{}{}: default: } } return true } t.controlBuf.executeAndPut(addBackStreamQuota, cleanup) } // Close kicks off the shutdown process of the transport. This should be called // only once on a transport. Once it is called, the transport should not be // accessed any more. func (t *http2Client) Close() error { t.mu.Lock() // Make sure we only Close once. if t.state == closing { t.mu.Unlock() return nil } t.state = closing streams := t.activeStreams t.activeStreams = nil t.mu.Unlock() t.controlBuf.finish() t.cancel() err := t.conn.Close() if channelz.IsOn() { channelz.RemoveEntry(t.channelzID) } // Notify all active streams. for _, s := range streams { t.closeStream(s, ErrConnClosing, false, http2.ErrCodeNo, nil, nil, false) } if t.statsHandler != nil { connEnd := &stats.ConnEnd{ Client: true, } t.statsHandler.HandleConn(t.ctx, connEnd) } return err } // GracefulClose sets the state to draining, which prevents new streams from // being created and causes the transport to be closed when the last active // stream is closed. If there are no active streams, the transport is closed // immediately. This does nothing if the transport is already draining or // closing. func (t *http2Client) GracefulClose() error { t.mu.Lock() // Make sure we move to draining only from active. if t.state == draining || t.state == closing { t.mu.Unlock() return nil } t.state = draining active := len(t.activeStreams) t.mu.Unlock() if active == 0 { return t.Close() } return nil } // Write formats the data into HTTP2 data frame(s) and sends it out. The caller // should proceed only if Write returns nil. func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { if opts.Last { // If it's the last message, update stream state. if !s.compareAndSwapState(streamActive, streamWriteDone) { return errStreamDone } } else if s.getState() != streamActive { return errStreamDone } df := &dataFrame{ streamID: s.id, endStream: opts.Last, } if hdr != nil || data != nil { // If it's not an empty data frame. // Add some data to grpc message header so that we can equally // distribute bytes across frames. emptyLen := http2MaxFrameLen - len(hdr) if emptyLen > len(data) { emptyLen = len(data) } hdr = append(hdr, data[:emptyLen]...) data = data[emptyLen:] df.h, df.d = hdr, data // TODO(mmukhi): The above logic in this if can be moved to loopyWriter's data handler. if err := s.wq.get(int32(len(hdr) + len(data))); err != nil { return err } } return t.controlBuf.put(df) } func (t *http2Client) getStream(f http2.Frame) (*Stream, bool) { t.mu.Lock() defer t.mu.Unlock() s, ok := t.activeStreams[f.Header().StreamID] return s, ok } // adjustWindow sends out extra window update over the initial window size // of stream if the application is requesting data larger in size than // the window. func (t *http2Client) adjustWindow(s *Stream, n uint32) { if w := s.fc.maybeAdjust(n); w > 0 { t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) } } // updateWindow adjusts the inbound quota for the stream. // Window updates will be sent out when the cumulative quota // exceeds the corresponding threshold. func (t *http2Client) updateWindow(s *Stream, n uint32) { if w := s.fc.onRead(n); w > 0 { t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) } } // updateFlowControl updates the incoming flow control windows // for the transport and the stream based on the current bdp // estimation. func (t *http2Client) updateFlowControl(n uint32) { t.mu.Lock() for _, s := range t.activeStreams { s.fc.newLimit(n) } t.mu.Unlock() updateIWS := func(interface{}) bool { t.initialWindowSize = int32(n) return true } t.controlBuf.executeAndPut(updateIWS, &outgoingWindowUpdate{streamID: 0, increment: t.fc.newLimit(n)}) t.controlBuf.put(&outgoingSettings{ ss: []http2.Setting{ { ID: http2.SettingInitialWindowSize, Val: n, }, }, }) } func (t *http2Client) handleData(f *http2.DataFrame) { size := f.Header().Length var sendBDPPing bool if t.bdpEst != nil { sendBDPPing = t.bdpEst.add(size) } // Decouple connection's flow control from application's read. // An update on connection's flow control should not depend on // whether user application has read the data or not. Such a // restriction is already imposed on the stream's flow control, // and therefore the sender will be blocked anyways. // Decoupling the connection flow control will prevent other // active(fast) streams from starving in presence of slow or // inactive streams. // if w := t.fc.onData(size); w > 0 { t.controlBuf.put(&outgoingWindowUpdate{ streamID: 0, increment: w, }) } if sendBDPPing { // Avoid excessive ping detection (e.g. in an L7 proxy) // by sending a window update prior to the BDP ping. if w := t.fc.reset(); w > 0 { t.controlBuf.put(&outgoingWindowUpdate{ streamID: 0, increment: w, }) } t.controlBuf.put(bdpPing) } // Select the right stream to dispatch. s, ok := t.getStream(f) if !ok { return } if size > 0 { if err := s.fc.onData(size); err != nil { t.closeStream(s, io.EOF, true, http2.ErrCodeFlowControl, status.New(codes.Internal, err.Error()), nil, false) return } if f.Header().Flags.Has(http2.FlagDataPadded) { if w := s.fc.onRead(size - uint32(len(f.Data()))); w > 0 { t.controlBuf.put(&outgoingWindowUpdate{s.id, w}) } } // TODO(bradfitz, zhaoq): A copy is required here because there is no // guarantee f.Data() is consumed before the arrival of next frame. // Can this copy be eliminated? if len(f.Data()) > 0 { data := make([]byte, len(f.Data())) copy(data, f.Data()) s.write(recvMsg{data: data}) } } // The server has closed the stream without sending trailers. Record that // the read direction is closed, and set the status appropriately. if f.FrameHeader.Flags.Has(http2.FlagDataEndStream) { t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.New(codes.Internal, "server closed the stream without sending trailers"), nil, true) } } func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) { s, ok := t.getStream(f) if !ok { return } if f.ErrCode == http2.ErrCodeRefusedStream { // The stream was unprocessed by the server. atomic.StoreUint32(&s.unprocessed, 1) } statusCode, ok := http2ErrConvTab[f.ErrCode] if !ok { warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error %v", f.ErrCode) statusCode = codes.Unknown } t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.Newf(statusCode, "stream terminated by RST_STREAM with error code: %v", f.ErrCode), nil, false) } func (t *http2Client) handleSettings(f *http2.SettingsFrame, isFirst bool) { if f.IsAck() { return } var maxStreams *uint32 var ss []http2.Setting f.ForeachSetting(func(s http2.Setting) error { if s.ID == http2.SettingMaxConcurrentStreams { maxStreams = new(uint32) *maxStreams = s.Val return nil } ss = append(ss, s) return nil }) if isFirst && maxStreams == nil { maxStreams = new(uint32) *maxStreams = math.MaxUint32 } sf := &incomingSettings{ ss: ss, } if maxStreams == nil { t.controlBuf.put(sf) return } updateStreamQuota := func(interface{}) bool { delta := int64(*maxStreams) - int64(t.maxConcurrentStreams) t.maxConcurrentStreams = *maxStreams t.streamQuota += delta if delta > 0 && t.waitingStreams > 0 { close(t.streamsQuotaAvailable) // wake all of them up. t.streamsQuotaAvailable = make(chan struct{}, 1) } return true } t.controlBuf.executeAndPut(updateStreamQuota, sf) } func (t *http2Client) handlePing(f *http2.PingFrame) { if f.IsAck() { // Maybe it's a BDP ping. if t.bdpEst != nil { t.bdpEst.calculate(f.Data) } return } pingAck := &ping{ack: true} copy(pingAck.data[:], f.Data[:]) t.controlBuf.put(pingAck) } func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { t.mu.Lock() if t.state == closing { t.mu.Unlock() return } if f.ErrCode == http2.ErrCodeEnhanceYourCalm { infof("Client received GoAway with http2.ErrCodeEnhanceYourCalm.") } id := f.LastStreamID if id > 0 && id%2 != 1 { t.mu.Unlock() t.Close() return } // A client can receive multiple GoAways from the server (see // https://github.com/grpc/grpc-go/issues/1387). The idea is that the first // GoAway will be sent with an ID of MaxInt32 and the second GoAway will be // sent after an RTT delay with the ID of the last stream the server will // process. // // Therefore, when we get the first GoAway we don't necessarily close any // streams. While in case of second GoAway we close all streams created after // the GoAwayId. This way streams that were in-flight while the GoAway from // server was being sent don't get killed. select { case <-t.goAway: // t.goAway has been closed (i.e.,multiple GoAways). // If there are multiple GoAways the first one should always have an ID greater than the following ones. if id > t.prevGoAwayID { t.mu.Unlock() t.Close() return } default: t.setGoAwayReason(f) close(t.goAway) t.state = draining t.controlBuf.put(&incomingGoAway{}) } // All streams with IDs greater than the GoAwayId // and smaller than the previous GoAway ID should be killed. upperLimit := t.prevGoAwayID if upperLimit == 0 { // This is the first GoAway Frame. upperLimit = math.MaxUint32 // Kill all streams after the GoAway ID. } for streamID, stream := range t.activeStreams { if streamID > id && streamID <= upperLimit { // The stream was unprocessed by the server. atomic.StoreUint32(&stream.unprocessed, 1) t.closeStream(stream, errStreamDrain, false, http2.ErrCodeNo, statusGoAway, nil, false) } } t.prevGoAwayID = id active := len(t.activeStreams) t.mu.Unlock() if active == 0 { t.Close() } } // setGoAwayReason sets the value of t.goAwayReason based // on the GoAway frame received. // It expects a lock on transport's mutext to be held by // the caller. func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) { t.goAwayReason = GoAwayNoReason switch f.ErrCode { case http2.ErrCodeEnhanceYourCalm: if string(f.DebugData()) == "too_many_pings" { t.goAwayReason = GoAwayTooManyPings } } } func (t *http2Client) GetGoAwayReason() GoAwayReason { t.mu.Lock() defer t.mu.Unlock() return t.goAwayReason } func (t *http2Client) handleWindowUpdate(f *http2.WindowUpdateFrame) { t.controlBuf.put(&incomingWindowUpdate{ streamID: f.Header().StreamID, increment: f.Increment, }) } // operateHeaders takes action on the decoded headers. func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { s, ok := t.getStream(frame) if !ok { return } atomic.StoreUint32(&s.bytesReceived, 1) var state decodeState if err := state.decodeResponseHeader(frame); err != nil { t.closeStream(s, err, true, http2.ErrCodeProtocol, nil, nil, false) // Something wrong. Stops reading even when there is remaining. return } endStream := frame.StreamEnded() var isHeader bool defer func() { if t.statsHandler != nil { if isHeader { inHeader := &stats.InHeader{ Client: true, WireLength: int(frame.Header().Length), } t.statsHandler.HandleRPC(s.ctx, inHeader) } else { inTrailer := &stats.InTrailer{ Client: true, WireLength: int(frame.Header().Length), } t.statsHandler.HandleRPC(s.ctx, inTrailer) } } }() // If headers haven't been received yet. if atomic.SwapUint32(&s.headerDone, 1) == 0 { if !endStream { // Headers frame is not actually a trailers-only frame. isHeader = true // These values can be set without any synchronization because // stream goroutine will read it only after seeing a closed // headerChan which we'll close after setting this. s.recvCompress = state.encoding if len(state.mdata) > 0 { s.header = state.mdata } } close(s.headerChan) } if !endStream { return } t.closeStream(s, io.EOF, false, http2.ErrCodeNo, state.status(), state.mdata, true) } // reader runs as a separate goroutine in charge of reading data from network // connection. // // TODO(zhaoq): currently one reader per transport. Investigate whether this is // optimal. // TODO(zhaoq): Check the validity of the incoming frame sequence. func (t *http2Client) reader() { defer close(t.readerDone) // Check the validity of server preface. frame, err := t.framer.fr.ReadFrame() if err != nil { t.Close() return } atomic.CompareAndSwapUint32(&t.activity, 0, 1) sf, ok := frame.(*http2.SettingsFrame) if !ok { t.Close() return } t.onSuccess() t.handleSettings(sf, true) // loop to keep reading incoming messages on this transport. for { frame, err := t.framer.fr.ReadFrame() atomic.CompareAndSwapUint32(&t.activity, 0, 1) if err != nil { // Abort an active stream if the http2.Framer returns a // http2.StreamError. This can happen only if the server's response // is malformed http2. if se, ok := err.(http2.StreamError); ok { t.mu.Lock() s := t.activeStreams[se.StreamID] t.mu.Unlock() if s != nil { // use error detail to provide better err message t.closeStream(s, streamErrorf(http2ErrConvTab[se.Code], "%v", t.framer.fr.ErrorDetail()), true, http2.ErrCodeProtocol, nil, nil, false) } continue } else { // Transport error. t.Close() return } } switch frame := frame.(type) { case *http2.MetaHeadersFrame: t.operateHeaders(frame) case *http2.DataFrame: t.handleData(frame) case *http2.RSTStreamFrame: t.handleRSTStream(frame) case *http2.SettingsFrame: t.handleSettings(frame, false) case *http2.PingFrame: t.handlePing(frame) case *http2.GoAwayFrame: t.handleGoAway(frame) case *http2.WindowUpdateFrame: t.handleWindowUpdate(frame) default: errorf("transport: http2Client.reader got unhandled frame type %v.", frame) } } } // keepalive running in a separate goroutune makes sure the connection is alive by sending pings. func (t *http2Client) keepalive() { p := &ping{data: [8]byte{}} timer := time.NewTimer(t.kp.Time) for { select { case <-timer.C: if atomic.CompareAndSwapUint32(&t.activity, 1, 0) { timer.Reset(t.kp.Time) continue } // Check if keepalive should go dormant. t.mu.Lock() if len(t.activeStreams) < 1 && !t.kp.PermitWithoutStream { // Make awakenKeepalive writable. <-t.awakenKeepalive t.mu.Unlock() select { case <-t.awakenKeepalive: // If the control gets here a ping has been sent // need to reset the timer with keepalive.Timeout. case <-t.ctx.Done(): return } } else { t.mu.Unlock() if channelz.IsOn() { t.czmu.Lock() t.kpCount++ t.czmu.Unlock() } // Send ping. t.controlBuf.put(p) } // By the time control gets here a ping has been sent one way or the other. timer.Reset(t.kp.Timeout) select { case <-timer.C: if atomic.CompareAndSwapUint32(&t.activity, 1, 0) { timer.Reset(t.kp.Time) continue } t.Close() return case <-t.ctx.Done(): if !timer.Stop() { <-timer.C } return } case <-t.ctx.Done(): if !timer.Stop() { <-timer.C } return } } } func (t *http2Client) Error() <-chan struct{} { return t.ctx.Done() } func (t *http2Client) GoAway() <-chan struct{} { return t.goAway } func (t *http2Client) ChannelzMetric() *channelz.SocketInternalMetric { t.czmu.RLock() s := channelz.SocketInternalMetric{ StreamsStarted: t.streamsStarted, StreamsSucceeded: t.streamsSucceeded, StreamsFailed: t.streamsFailed, MessagesSent: t.msgSent, MessagesReceived: t.msgRecv, KeepAlivesSent: t.kpCount, LastLocalStreamCreatedTimestamp: t.lastStreamCreated, LastMessageSentTimestamp: t.lastMsgSent, LastMessageReceivedTimestamp: t.lastMsgRecv, LocalFlowControlWindow: int64(t.fc.getSize()), //socket options LocalAddr: t.localAddr, RemoteAddr: t.remoteAddr, // Security // RemoteName : } t.czmu.RUnlock() s.RemoteFlowControlWindow = t.getOutFlowWindow() return &s } func (t *http2Client) IncrMsgSent() { t.czmu.Lock() t.msgSent++ t.lastMsgSent = time.Now() t.czmu.Unlock() } func (t *http2Client) IncrMsgRecv() { t.czmu.Lock() t.msgRecv++ t.lastMsgRecv = time.Now() t.czmu.Unlock() } func (t *http2Client) getOutFlowWindow() int64 { resp := make(chan uint32, 1) timer := time.NewTimer(time.Second) defer timer.Stop() t.controlBuf.put(&outFlowControlSizeRequest{resp}) select { case sz := <-resp: return int64(sz) case <-t.ctxDone: return -1 case <-timer.C: return -2 } }
{ "content_hash": "baebf0c00e91498044c0620feddaa508", "timestamp": "", "source": "github", "line_count": 1275, "max_line_length": 154, "avg_line_length": 29.366274509803922, "alnum_prop": 0.6803856631590193, "repo_name": "Thib17/graphite-remote-adapter", "id": "92a3311813c7ded2f2d053e016f136646cb6c287", "size": "38044", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/google.golang.org/grpc/transport/http2_client.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "351" }, { "name": "Go", "bytes": "97371" }, { "name": "HTML", "bytes": "3462" }, { "name": "JavaScript", "bytes": "3135" }, { "name": "Makefile", "bytes": "2180" } ], "symlink_target": "" }
using kws::cmd::Argument; TEST(ArgumentTest, IsBoolean) { int arg_int_val = -1; Argument<int> arg_int("int", "int help", &arg_int_val); EXPECT_FALSE(arg_int.IsBoolean()); bool arg_bool_val = true; Argument<bool> arg_bool("bool", "bool help", &arg_bool_val); EXPECT_TRUE(arg_bool.IsBoolean()); } TEST(ArgumentTest, Help) { int arg_int_val = -1; Argument<int> arg_int("int", "int help", &arg_int_val); EXPECT_EQ("int : int help (type = int32_t)", arg_int.Help()); EXPECT_EQ("int : int help (type = int32_t)", arg_int.Help(10)); bool arg_bool_val = true; Argument<bool> arg_bool("bool", "bool help", &arg_bool_val); EXPECT_EQ("bool : bool help (type = bool)", arg_bool.Help()); EXPECT_EQ("bool : bool help (type = bool)", arg_bool.Help(10)); } TEST(ArgumentTest, Parse) { int arg_int_val = -1; Argument<int> arg_int("int", "int help", &arg_int_val); EXPECT_TRUE(arg_int.Parse("-1244")); EXPECT_EQ(-1244, arg_int_val); EXPECT_FALSE(arg_int.Parse("-12.4")); EXPECT_FALSE(arg_int.Parse("12 asdsad")); bool arg_bool_val = true; Argument<bool> arg_bool("bool", "bool help", &arg_bool_val); EXPECT_FALSE(arg_bool.Parse("")); // Boolean arguments CANNOT omit value EXPECT_TRUE(arg_bool.Parse("false")); EXPECT_EQ(false, arg_bool_val); EXPECT_TRUE(arg_bool.Parse("true")); EXPECT_EQ(true, arg_bool_val); EXPECT_TRUE(arg_bool.Parse("0")); EXPECT_EQ(false, arg_bool_val); EXPECT_TRUE(arg_bool.Parse("1")); EXPECT_EQ(true, arg_bool_val); EXPECT_FALSE(arg_bool.Parse("FALSE")); EXPECT_FALSE(arg_bool.Parse("TRUE")); EXPECT_FALSE(arg_bool.Parse("1234")); EXPECT_FALSE(arg_bool.Parse("-inf")); }
{ "content_hash": "713f4a55b55ef7478a6134376b96ff7b", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 78, "avg_line_length": 34.8125, "alnum_prop": 0.6409335727109515, "repo_name": "jpuigcerver/kws-eval", "id": "7c34ac2c64b25f1b8d1ee6da2dceaaaaf7f35d34", "size": "1724", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cmd/ArgumentTest.cc", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "141709" }, { "name": "CMake", "bytes": "13990" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>updeep perf</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div>Running tests...</div> <div id='perf'></div> <script src='/assets/perf.js'></script> <p>Done!</p> </body> </html>
{ "content_hash": "6dd21f258e710976eb980b9f693c25f1", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 74, "avg_line_length": 26.142857142857142, "alnum_prop": 0.6038251366120219, "repo_name": "frederickfogerty/updeep", "id": "b1a7bddb0fc08cbad8eeac4480e704b3fa5cd2d6", "size": "366", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "perf/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "366" }, { "name": "JavaScript", "bytes": "34842" } ], "symlink_target": "" }
#include <cstdio> #include <cstdlib> #include <cmath> #include <ctime> #include <iostream> #include <iterator> #if defined(_MSC_VER) #include <io.h> #endif #include <boost/foreach.hpp> #include <boost/regex.hpp> #include <OpenEXR/half.h> #include <OpenEXR/ImathVec.h> #include "OpenImageIO/argparse.h" #include "OpenImageIO/strutil.h" #include "OpenImageIO/sysutil.h" #include "OpenImageIO/imageio.h" #include "OpenImageIO/imagebuf.h" #include "OpenImageIO/imagebufalgo.h" #include "OpenImageIO/deepdata.h" #include "OpenImageIO/hash.h" #include "OpenImageIO/fmath.h" #include "OpenImageIO/array_view.h" #include "oiiotool.h" OIIO_NAMESPACE_USING; using namespace OiioTool; using namespace ImageBufAlgo; static void print_sha1 (ImageInput *input) { SHA1 sha; const ImageSpec &spec (input->spec()); if (spec.deep) { // Special handling of deep data DeepData dd; if (! input->read_native_deep_image (dd)) { printf (" SHA-1: unable to compute, could not read image\n"); return; } // Hash both the sample counts and the data block sha.append (dd.all_samples()); sha.append (dd.all_data()); } else { imagesize_t size = input->spec().image_bytes (true /*native*/); if (size >= std::numeric_limits<size_t>::max()) { printf (" SHA-1: unable to compute, image is too big\n"); return; } else if (size != 0) { boost::scoped_array<char> buf (new char [size]); if (! input->read_image (TypeDesc::UNKNOWN /*native*/, &buf[0])) { printf (" SHA-1: unable to compute, could not read image\n"); return; } sha.append (&buf[0], size); } } printf (" SHA-1: %s\n", sha.digest().c_str()); } static void dump_data (ImageInput *input, const print_info_options &opt) { const ImageSpec &spec (input->spec()); if (spec.deep) { // Special handling of deep data DeepData dd; if (! input->read_native_deep_image (dd)) { printf (" dump data: could not read image\n"); return; } int nc = spec.nchannels; for (int z = 0, pixel = 0; z < spec.depth; ++z) { for (int y = 0; y < spec.height; ++y) { for (int x = 0; x < spec.width; ++x, ++pixel) { int nsamples = dd.samples(pixel); if (nsamples == 0 && ! opt.dumpdata_showempty) continue; std::cout << " Pixel ("; if (spec.depth > 1 || spec.z != 0) std::cout << Strutil::format("%d, %d, %d", x+spec.x, y+spec.y, z+spec.z); else std::cout << Strutil::format("%d, %d", x+spec.x, y+spec.y); std::cout << "): " << nsamples << " samples" << (nsamples ? ":" : ""); for (int s = 0; s < nsamples; ++s) { if (s) std::cout << " / "; for (int c = 0; c < nc; ++c) { std::cout << " " << spec.channelnames[c] << "="; if (dd.channeltype(c) == TypeDesc::UINT) std::cout << dd.deep_value_uint(pixel, c, s); else std::cout << dd.deep_value (pixel, c, s); } } std::cout << "\n"; } } } } else { std::vector<float> buf(spec.image_pixels() * spec.nchannels); if (! input->read_image (TypeDesc::FLOAT, &buf[0])) { printf (" dump data: could not read image\n"); return; } const float *ptr = &buf[0]; for (int z = 0; z < spec.depth; ++z) { for (int y = 0; y < spec.height; ++y) { for (int x = 0; x < spec.width; ++x) { if (! opt.dumpdata_showempty) { bool allzero = true; for (int c = 0; c < spec.nchannels && allzero; ++c) allzero &= (ptr[c] == 0.0f); if (allzero) { ptr += spec.nchannels; continue; } } if (spec.depth > 1 || spec.z != 0) std::cout << Strutil::format(" Pixel (%d, %d, %d):", x+spec.x, y+spec.y, z+spec.z); else std::cout << Strutil::format(" Pixel (%d, %d):", x+spec.x, y+spec.y); for (int c = 0; c < spec.nchannels; ++c, ++ptr) { std::cout << ' ' << (*ptr); } std::cout << "\n"; } } } } } /////////////////////////////////////////////////////////////////////////////// // Stats static bool read_input (const std::string &filename, ImageBuf &img, int subimage=0, int miplevel=0) { if (img.subimage() >= 0 && img.subimage() == subimage) return true; if (img.init_spec (filename, subimage, miplevel)) { // Force a read now for reasonable-sized first images in the // file. This can greatly speed up the multithread case for // tiled images by not having multiple threads working on the // same image lock against each other on the file handle. // We guess that "reasonable size" is 200 MB, that's enough to // hold a 4k RGBA float image. Larger things will // simply fall back on ImageCache. bool forceread = (img.spec().image_bytes() < 200*1024*1024); return img.read (subimage, miplevel, forceread, TypeDesc::FLOAT); } return false; } static void print_stats_num (float val, int maxval, bool round) { // Ensure uniform printing of NaN and Inf on all platforms if (isnan(val)) printf ("nan"); else if (isinf(val)) printf ("inf"); else if (maxval == 0) { printf("%f",val); } else { float fval = val * static_cast<float>(maxval); if (round) { int v = static_cast<int>(roundf (fval)); printf ("%d", v); } else { printf ("%0.2f", fval); } } } // First check oiio:BitsPerSample int attribute. If not set, // fall back on the TypeDesc. return 0 for float types // or those that exceed the int range (long long, etc) static unsigned long long get_intsample_maxval (const ImageSpec &spec) { TypeDesc type = spec.format; int bits = spec.get_int_attribute ("oiio:BitsPerSample"); if (bits > 0) { if (type.basetype == TypeDesc::UINT8 || type.basetype == TypeDesc::UINT16 || type.basetype == TypeDesc::UINT32) return ((1LL) << bits) - 1; if (type.basetype == TypeDesc::INT8 || type.basetype == TypeDesc::INT16 || type.basetype == TypeDesc::INT32) return ((1LL) << (bits-1)) - 1; } // These correspond to all the int enums in typedesc.h <= int if (type.basetype == TypeDesc::UCHAR) return 0xff; if (type.basetype == TypeDesc::CHAR) return 0x7f; if (type.basetype == TypeDesc::USHORT) return 0xffff; if (type.basetype == TypeDesc::SHORT) return 0x7fff; if (type.basetype == TypeDesc::UINT) return 0xffffffff; if (type.basetype == TypeDesc::INT) return 0x7fffffff; return 0; } static void print_stats_footer (unsigned int maxval) { if (maxval==0) printf ("(float)"); else printf ("(of %u)", maxval); } static void print_stats (Oiiotool &ot, const std::string &filename, const ImageSpec &originalspec, int subimage=0, int miplevel=0, bool indentmip=false) { const char *indent = indentmip ? " " : " "; ImageBuf input; if (! read_input (filename, input, subimage, miplevel)) { ot.error ("stats", input.geterror()); return; } PixelStats stats; if (! computePixelStats (stats, input)) { std::string err = input.geterror(); ot.error ("stats", Strutil::format ("unable to compute: %s", err.empty() ? "unspecified error" : err.c_str())); return; } // The original spec is used, otherwise the bit depth will // be reported incorrectly (as FLOAT) unsigned int maxval = (unsigned int)get_intsample_maxval (originalspec); printf ("%sStats Min: ", indent); for (unsigned int i=0; i<stats.min.size(); ++i) { print_stats_num (stats.min[i], maxval, true); printf (" "); } print_stats_footer (maxval); printf ("\n"); printf ("%sStats Max: ", indent); for (unsigned int i=0; i<stats.max.size(); ++i) { print_stats_num (stats.max[i], maxval, true); printf (" "); } print_stats_footer (maxval); printf ("\n"); printf ("%sStats Avg: ", indent); for (unsigned int i=0; i<stats.avg.size(); ++i) { print_stats_num (stats.avg[i], maxval, false); printf (" "); } print_stats_footer (maxval); printf ("\n"); printf ("%sStats StdDev: ", indent); for (unsigned int i=0; i<stats.stddev.size(); ++i) { print_stats_num (stats.stddev[i], maxval, false); printf (" "); } print_stats_footer (maxval); printf ("\n"); printf ("%sStats NanCount: ", indent); for (unsigned int i=0; i<stats.nancount.size(); ++i) { printf ("%llu ", (unsigned long long)stats.nancount[i]); } printf ("\n"); printf ("%sStats InfCount: ", indent); for (unsigned int i=0; i<stats.infcount.size(); ++i) { printf ("%llu ", (unsigned long long)stats.infcount[i]); } printf ("\n"); printf ("%sStats FiniteCount: ", indent); for (unsigned int i=0; i<stats.finitecount.size(); ++i) { printf ("%llu ", (unsigned long long)stats.finitecount[i]); } printf ("\n"); if (input.deep()) { const DeepData *dd (input.deepdata()); size_t npixels = dd->pixels(); size_t totalsamples = 0, emptypixels = 0; size_t maxsamples = 0, minsamples = std::numeric_limits<size_t>::max(); size_t maxsamples_npixels = 0; float mindepth = std::numeric_limits<float>::max(); float maxdepth = -std::numeric_limits<float>::max(); Imath::V3i maxsamples_pixel(-1,-1,-1), minsamples_pixel(-1,-1,-1); Imath::V3i mindepth_pixel(-1,-1,-1), maxdepth_pixel(-1,-1,-1); Imath::V3i nonfinite_pixel(-1,-1,-1); int nonfinite_pixel_samp(-1), nonfinite_pixel_chan(-1); size_t sampoffset = 0; int nchannels = dd->channels(); int depthchannel = -1; long long nonfinites = 0; for (int c = 0; c < nchannels; ++c) if (Strutil::iequals (originalspec.channelnames[c], "Z")) depthchannel = c; int xend = originalspec.x + originalspec.width; int yend = originalspec.y + originalspec.height; int zend = originalspec.z + originalspec.depth; size_t p = 0; std::vector<size_t> nsamples_histogram; for (int z = originalspec.z; z < zend; ++z) { for (int y = originalspec.y; y < yend; ++y) { for (int x = originalspec.x; x < xend; ++x, ++p) { size_t samples = input.deep_samples (x, y, z); totalsamples += samples; if (samples == maxsamples) ++maxsamples_npixels; if (samples > maxsamples) { maxsamples = samples; maxsamples_pixel.setValue (x, y, z); maxsamples_npixels = 1; } if (samples < minsamples) minsamples = samples; if (samples == 0) ++emptypixels; if (samples >= nsamples_histogram.size()) nsamples_histogram.resize (samples+1, 0); nsamples_histogram[samples] += 1; for (unsigned int s = 0; s < samples; ++s) { for (int c = 0; c < nchannels; ++c) { float d = input.deep_value (x, y, z, c, s); if (! isfinite(d)) { if (nonfinites++ == 0) { nonfinite_pixel.setValue (x, y, z); nonfinite_pixel_samp = s; nonfinite_pixel_chan = c; } } if (depthchannel == c) { if (d < mindepth) { mindepth = d; mindepth_pixel.setValue (x, y, z); } if (d > maxdepth) { maxdepth = d; maxdepth_pixel.setValue (x, y, z); } } } } sampoffset += samples; } } } printf ("%sMin deep samples in any pixel : %llu\n", indent, (unsigned long long)minsamples); printf ("%sMax deep samples in any pixel : %llu\n", indent, (unsigned long long)maxsamples); printf ("%s%llu pixel%s had the max of %llu samples, including (x=%d, y=%d)\n", indent, (unsigned long long)maxsamples_npixels, maxsamples_npixels > 1 ? "s" : "", (unsigned long long)maxsamples, maxsamples_pixel.x, maxsamples_pixel.y); printf ("%sAverage deep samples per pixel: %.2f\n", indent, double(totalsamples)/double(npixels)); printf ("%sTotal deep samples in all pixels: %llu\n", indent, (unsigned long long)totalsamples); printf ("%sPixels with deep samples : %llu\n", indent, (unsigned long long)(npixels-emptypixels)); printf ("%sPixels with no deep samples: %llu\n", indent, (unsigned long long)emptypixels); printf ("%sSamples/pixel histogram:\n", indent); size_t grandtotal = 0; for (size_t i = 0, e = nsamples_histogram.size(); i < e; ++i) grandtotal += nsamples_histogram[i]; size_t binstart = 0, bintotal = 0; for (size_t i = 0, e = nsamples_histogram.size(); i < e; ++i) { bintotal += nsamples_histogram[i]; if (i < 8 || i == (e-1) || OIIO::ispow2(i+1)) { // batch by powers of 2, unless it's a small number if (i == binstart) printf ("%s %3lld ", indent, (long long)i); else printf ("%s %3lld-%3lld", indent, (long long)binstart, (long long)i); printf (" : %8lld (%4.1f%%)\n", (long long)bintotal, (100.0*bintotal)/grandtotal); binstart = i+1; bintotal = 0; } } if (depthchannel >= 0) { printf ("%sMinimum depth was %g at (%d, %d)\n", indent, mindepth, mindepth_pixel.x, mindepth_pixel.y); printf ("%sMaximum depth was %g at (%d, %d)\n", indent, maxdepth, maxdepth_pixel.x, maxdepth_pixel.y); } if (nonfinites > 0) { printf ("%sNonfinite values: %lld, including (x=%d, y=%d, chan=%s, samp=%d)\n", indent, nonfinites, nonfinite_pixel.x, nonfinite_pixel.y, input.spec().channelnames[nonfinite_pixel_chan].c_str(), nonfinite_pixel_samp); } } else { std::vector<float> constantValues(input.spec().nchannels); if (isConstantColor(input, &constantValues[0])) { printf ("%sConstant: Yes\n", indent); printf ("%sConstant Color: ", indent); for (unsigned int i=0; i<constantValues.size(); ++i) { print_stats_num (constantValues[i], maxval, false); printf (" "); } print_stats_footer (maxval); printf ("\n"); } else { printf ("%sConstant: No\n", indent); } if( isMonochrome(input)) { printf ("%sMonochrome: Yes\n", indent); } else { printf ("%sMonochrome: No\n", indent); } } } static void print_metadata (const ImageSpec &spec, const std::string &filename, const print_info_options &opt, boost::regex &field_re, boost::regex &field_exclude_re) { bool printed = false; if (opt.metamatch.empty() || boost::regex_search ("channels", field_re) || boost::regex_search ("channel list", field_re)) { if (opt.filenameprefix) printf ("%s : ", filename.c_str()); printf (" channel list: "); for (int i = 0; i < spec.nchannels; ++i) { if (i < (int)spec.channelnames.size()) printf ("%s", spec.channelnames[i].c_str()); else printf ("unknown"); if (i < (int)spec.channelformats.size()) printf (" (%s)", spec.channelformats[i].c_str()); if (i < spec.nchannels-1) printf (", "); } printf ("\n"); printed = true; } if (spec.x || spec.y || spec.z) { if (opt.metamatch.empty() || boost::regex_search ("pixel data origin", field_re)) { if (opt.filenameprefix) printf ("%s : ", filename.c_str()); printf (" pixel data origin: x=%d, y=%d", spec.x, spec.y); if (spec.depth > 1) printf (", z=%d", spec.z); printf ("\n"); printed = true; } } if (spec.full_x || spec.full_y || spec.full_z || (spec.full_width != spec.width && spec.full_width != 0) || (spec.full_height != spec.height && spec.full_height != 0) || (spec.full_depth != spec.depth && spec.full_depth != 0)) { if (opt.metamatch.empty() || boost::regex_search ("full/display size", field_re)) { if (opt.filenameprefix) printf ("%s : ", filename.c_str()); printf (" full/display size: %d x %d", spec.full_width, spec.full_height); if (spec.depth > 1) printf (" x %d", spec.full_depth); printf ("\n"); printed = true; } if (opt.metamatch.empty() || boost::regex_search ("full/display origin", field_re)) { if (opt.filenameprefix) printf ("%s : ", filename.c_str()); printf (" full/display origin: %d, %d", spec.full_x, spec.full_y); if (spec.depth > 1) printf (", %d", spec.full_z); printf ("\n"); printed = true; } } if (spec.tile_width) { if (opt.metamatch.empty() || boost::regex_search ("tile", field_re)) { if (opt.filenameprefix) printf ("%s : ", filename.c_str()); printf (" tile size: %d x %d", spec.tile_width, spec.tile_height); if (spec.depth > 1) printf (" x %d", spec.tile_depth); printf ("\n"); printed = true; } } BOOST_FOREACH (const ImageIOParameter &p, spec.extra_attribs) { if (! opt.metamatch.empty() && ! boost::regex_search (p.name().c_str(), field_re)) continue; if (! opt.nometamatch.empty() && boost::regex_search (p.name().c_str(), field_exclude_re)) continue; std::string s = spec.metadata_val (p, true); if (opt.filenameprefix) printf ("%s : ", filename.c_str()); printf (" %s: ", p.name().c_str()); if (! strcmp (s.c_str(), "1.#INF")) printf ("inf"); else printf ("%s", s.c_str()); printf ("\n"); printed = true; } if (! printed && !opt.metamatch.empty()) { if (opt.filenameprefix) printf ("%s : ", filename.c_str()); printf (" %s: <unknown>\n", opt.metamatch.c_str()); } } static const char * extended_format_name (TypeDesc type, int bits) { if (bits && bits < (int)type.size()*8) { // The "oiio:BitsPerSample" betrays a different bit depth in the // file than the data type we are passing. if (type == TypeDesc::UINT8 || type == TypeDesc::UINT16 || type == TypeDesc::UINT32 || type == TypeDesc::UINT64) return ustring::format("uint%d", bits).c_str(); if (type == TypeDesc::INT8 || type == TypeDesc::INT16 || type == TypeDesc::INT32 || type == TypeDesc::INT64) return ustring::format("int%d", bits).c_str(); } return type.c_str(); // use the name implied by type } static const char * brief_format_name (TypeDesc type, int bits=0) { if (! bits) bits = (int)type.size()*8; if (type.is_floating_point()) { if (type.basetype == TypeDesc::FLOAT) return "f"; if (type.basetype == TypeDesc::HALF) return "h"; return ustring::format("f%d", bits).c_str(); } else if (type.is_signed()) { return ustring::format("i%d", bits).c_str(); } else { return ustring::format("u%d", bits).c_str(); } return type.c_str(); // use the name implied by type } // prints basic info (resolution, width, height, depth, channels, data format, // and format name) about given subimage. static void print_info_subimage (Oiiotool &ot, int current_subimage, int max_subimages, ImageSpec &spec, ImageInput *input, const std::string &filename, const print_info_options &opt, boost::regex &field_re, boost::regex &field_exclude_re) { if ( ! input->seek_subimage (current_subimage, 0, spec) ) return; int nmip = 1; bool printres = opt.verbose && (opt.metamatch.empty() || boost::regex_search ("resolution, width, height, depth, channels", field_re)); if (printres && max_subimages > 1 && opt.subimages) { printf (" subimage %2d: ", current_subimage); printf ("%4d x %4d", spec.width, spec.height); if (spec.depth > 1) printf (" x %4d", spec.depth); printf (", %d channel, %s%s", spec.nchannels, spec.deep ? "deep " : "", spec.depth > 1 ? "volume " : ""); if (spec.channelformats.size()) { for (size_t c = 0; c < spec.channelformats.size(); ++c) printf ("%s%s", c ? "/" : "", spec.channelformats[c].c_str()); } else { int bits = spec.get_int_attribute ("oiio:BitsPerSample", 0); printf ("%s", extended_format_name(spec.format, bits)); } printf (" %s", input->format_name()); printf ("\n"); } // Count MIP levels ImageSpec mipspec; while (input->seek_subimage (current_subimage, nmip, mipspec)) { if (printres) { if (nmip == 1) printf (" MIP-map levels: %dx%d", spec.width, spec.height); printf (" %dx%d", mipspec.width, mipspec.height); } ++nmip; } if (printres && nmip > 1) printf ("\n"); if (opt.compute_sha1 && (opt.metamatch.empty() || boost::regex_search ("sha-1", field_re))) { if (opt.filenameprefix) printf ("%s : ", filename.c_str()); // Before sha-1, be sure to point back to the highest-res MIP level ImageSpec tmpspec; input->seek_subimage (current_subimage, 0, tmpspec); print_sha1 (input); } if (opt.verbose) print_metadata (spec, filename, opt, field_re, field_exclude_re); if (opt.dumpdata) { ImageSpec tmp; input->seek_subimage (current_subimage, 0, tmp); dump_data (input, opt); } if (opt.compute_stats && (opt.metamatch.empty() || boost::regex_search ("stats", field_re))) { for (int m = 0; m < nmip; ++m) { ImageSpec mipspec; input->seek_subimage (current_subimage, m, mipspec); if (opt.filenameprefix) printf ("%s : ", filename.c_str()); if (nmip > 1) { printf (" MIP %d of %d (%d x %d):\n", m, nmip, mipspec.width, mipspec.height); } print_stats (ot, filename, spec, current_subimage, m, nmip>1); } } if ( ! input->seek_subimage (current_subimage, 0, spec) ) return; } bool OiioTool::print_info (Oiiotool &ot, const std::string &filename, const print_info_options &opt, long long &totalsize, std::string &error) { error.clear(); ImageInput *input = ImageInput::open (filename.c_str()); if (! input) { error = geterror(); if (error.empty()) error = Strutil::format ("Could not open \"%s\"", filename.c_str()); return false; } ImageSpec spec = input->spec(); boost::regex field_re; boost::regex field_exclude_re; if (! opt.metamatch.empty()) { try { field_re.assign (opt.metamatch, boost::regex::extended | boost::regex_constants::icase); } catch (const std::exception &e) { error = Strutil::format ("Regex error '%s' on metamatch regex \"%s\"", e.what(), opt.metamatch); return false; } } if (! opt.nometamatch.empty()) { try { field_exclude_re.assign (opt.nometamatch, boost::regex::extended | boost::regex_constants::icase); } catch (const std::exception &e) { error = Strutil::format ("Regex error '%s' on metamatch regex \"%s\"", e.what(), opt.nometamatch); return false; } } int padlen = std::max (0, (int)opt.namefieldlength - (int)filename.length()); std::string padding (padlen, ' '); // checking how many subimages and mipmap levels are stored in the file int num_of_subimages = 1; bool any_mipmapping = false; std::vector<int> num_of_miplevels; { int nmip = 1; while (input->seek_subimage (input->current_subimage(), nmip, spec)) { ++nmip; any_mipmapping = true; } num_of_miplevels.push_back (nmip); } while (input->seek_subimage (num_of_subimages, 0, spec)) { // maybe we should do this more gently? ++num_of_subimages; int nmip = 1; while (input->seek_subimage (input->current_subimage(), nmip, spec)) { ++nmip; any_mipmapping = true; } num_of_miplevels.push_back (nmip); } input->seek_subimage (0, 0, spec); // re-seek to the first if (opt.metamatch.empty() || boost::regex_search ("resolution, width, height, depth, channels", field_re)) { printf ("%s%s : %4d x %4d", filename.c_str(), padding.c_str(), spec.width, spec.height); if (spec.depth > 1) printf (" x %4d", spec.depth); printf (", %d channel, %s%s", spec.nchannels, spec.deep ? "deep " : "", spec.depth > 1 ? "volume " : ""); if (spec.channelformats.size()) { for (size_t c = 0; c < spec.channelformats.size(); ++c) printf ("%s%s", c ? "/" : "", spec.channelformats[c].c_str()); } else { int bits = spec.get_int_attribute ("oiio:BitsPerSample", 0); printf ("%s", extended_format_name(spec.format, bits)); } printf (" %s", input->format_name()); if (opt.sum) { imagesize_t imagebytes = spec.image_bytes (true); totalsize += imagebytes; printf (" (%.2f MB)", (float)imagebytes / (1024.0*1024.0)); } // we print info about how many subimages are stored in file // only when we have more then one subimage if ( ! opt.verbose && num_of_subimages != 1) printf (" (%d subimages%s)", num_of_subimages, any_mipmapping ? " +mipmap)" : ""); if (! opt.verbose && num_of_subimages == 1 && any_mipmapping) printf (" (+mipmap)"); printf ("\n"); } int movie = spec.get_int_attribute ("oiio:Movie"); if (opt.verbose && num_of_subimages != 1) { // info about num of subimages and their resolutions printf (" %d subimages: ", num_of_subimages); for (int i = 0; i < num_of_subimages; ++i) { input->seek_subimage (i, 0, spec); int bits = spec.get_int_attribute ("oiio:BitsPerSample", spec.format.size()*8); if (i) printf (", "); if (spec.depth > 1) printf ("%dx%dx%d ", spec.width, spec.height, spec.depth); else printf ("%dx%d ", spec.width, spec.height); // printf ("["); for (int c = 0; c < spec.nchannels; ++c) printf ("%c%s", c ? ',' : '[', brief_format_name(spec.channelformat(c), bits)); printf ("]"); if (movie) break; } printf ("\n"); } // if the '-a' flag is not set we print info // about first subimage only if ( ! opt.subimages) num_of_subimages = 1; for (int i = 0; i < num_of_subimages; ++i) { print_info_subimage (ot, i, num_of_subimages, spec, input, filename, opt, field_re, field_exclude_re); } input->close (); delete input; return true; }
{ "content_hash": "6c2fd210e0430fc4aed51508fd9170ed", "timestamp": "", "source": "github", "line_count": 828, "max_line_length": 110, "avg_line_length": 37.22826086956522, "alnum_prop": 0.4851581508515815, "repo_name": "micler/oiio", "id": "e48978391f6c254f38ee7a67e002be5547bd8bfa", "size": "32436", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/oiiotool/printinfo.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "51010" }, { "name": "C++", "bytes": "5224874" }, { "name": "CMake", "bytes": "133488" }, { "name": "Makefile", "bytes": "19247" }, { "name": "Python", "bytes": "183080" }, { "name": "Shell", "bytes": "6782" }, { "name": "TeX", "bytes": "819005" } ], "symlink_target": "" }
<?php if ( ! class_exists( 'GFForms' ) ) { die(); } class GFFormSettings { public static function form_settings_page() { $subview = rgget( 'subview' ) ? rgget( 'subview' ) : 'settings'; switch ( $subview ) { case 'settings': self::form_settings_ui(); break; case 'confirmation': self::confirmations_page(); break; case 'notification': self::notification_page(); break; default: do_action( "gform_form_settings_page_{$subview}" ); } } public static function form_settings_ui() { require_once( GFCommon::get_base_path() . '/form_detail.php' ); require_once( GFCommon::get_base_path() . '/currency.php' ); $form_id = rgget( 'id' ); $form = RGFormsModel::get_form_meta( $form_id ); $update_result = array(); if ( rgpost( 'gform_meta' ) ) { // die if not posted from correct page check_admin_referer( "gform_save_form_settings_{$form_id}", 'gform_save_form_settings' ); $updated_form = json_decode( rgpost( 'gform_meta' ), true ); $updated_form['fields'] = $form['fields']; // -- standard form settings -- $updated_form['title'] = rgpost( 'form_title_input' ); $updated_form['description'] = rgpost( 'form_description_input' ); $updated_form['labelPlacement'] = rgpost( 'form_label_placement' ); $updated_form['descriptionPlacement'] = rgpost( 'form_description_placement' ); $updated_form['subLabelPlacement'] = rgpost( 'form_sub_label_placement' ); // -- advanced form settings -- $updated_form['cssClass'] = rgpost( 'form_css_class' ); $updated_form['enableHoneypot'] = rgpost( 'form_enable_honeypot' ); $updated_form['enableAnimation'] = rgpost( 'form_enable_animation' ); // form button settings $updated_form['button']['type'] = rgpost( 'form_button' ); $updated_form['button']['text'] = rgpost( 'form_button' ) == 'text' ? rgpost( 'form_button_text_input' ) : ''; $updated_form['button']['imageUrl'] = rgpost( 'form_button' ) == 'image' ? rgpost( 'form_button_image_url' ) : ''; // Save and Continue settings $updated_form['save']['enabled'] = rgpost( 'form_save_enabled' ); $updated_form['save']['button']['type'] = 'link'; $updated_form['save']['button']['text'] = rgpost( 'form_save_button_text' ); // limit entries settings $updated_form['limitEntries'] = rgpost( 'form_limit_entries' ); $updated_form['limitEntriesCount'] = $updated_form['limitEntries'] ? rgpost( 'form_limit_entries_count' ) : ''; $updated_form['limitEntriesPeriod'] = $updated_form['limitEntries'] ? rgpost( 'form_limit_entries_period' ) : ''; $updated_form['limitEntriesMessage'] = $updated_form['limitEntries'] ? rgpost( 'form_limit_entries_message' ) : ''; // form scheduling settings $updated_form['scheduleForm'] = rgpost( 'form_schedule_form' ); $updated_form['scheduleStart'] = $updated_form['scheduleForm'] ? rgpost( 'gform_schedule_start' ) : ''; $updated_form['scheduleStartHour'] = $updated_form['scheduleForm'] ? rgpost( 'form_schedule_start_hour' ) : ''; $updated_form['scheduleStartMinute'] = $updated_form['scheduleForm'] ? rgpost( 'form_schedule_start_minute' ) : ''; $updated_form['scheduleStartAmpm'] = $updated_form['scheduleForm'] ? rgpost( 'form_schedule_start_ampm' ) : ''; $updated_form['scheduleEnd'] = $updated_form['scheduleForm'] ? rgpost( 'form_schedule_end' ) : ''; $updated_form['scheduleEndHour'] = $updated_form['scheduleForm'] ? rgpost( 'form_schedule_end_hour' ) : ''; $updated_form['scheduleEndMinute'] = $updated_form['scheduleForm'] ? rgpost( 'form_schedule_end_minute' ) : ''; $updated_form['scheduleEndAmpm'] = $updated_form['scheduleForm'] ? rgpost( 'form_schedule_end_ampm' ) : ''; $updated_form['schedulePendingMessage'] = $updated_form['scheduleForm'] ? rgpost( 'form_schedule_pending_message' ) : ''; $updated_form['scheduleMessage'] = $updated_form['scheduleForm'] ? rgpost( 'form_schedule_message' ) : ''; // require login settings $updated_form['requireLogin'] = rgpost( 'form_require_login' ); $updated_form['requireLoginMessage'] = $updated_form['requireLogin'] ? rgpost( 'form_require_login_message' ) : ''; $updated_form = GFFormsModel::maybe_sanitize_form_settings( $updated_form ); if ( $updated_form['save']['enabled'] ) { $updated_form = self::activate_save( $updated_form ); } else { $updated_form = self::deactivate_save( $updated_form ); } $updated_form = apply_filters( 'gform_pre_form_settings_save', $updated_form ); $update_result = GFFormDetail::save_form_info( $form_id, addslashes( json_encode( $updated_form ) ) ); // update working form object with updated form object $form = $updated_form; } $form = gf_apply_filters( array( 'gform_admin_pre_render', $form_id ), $form ); self::page_header( __( 'Form Settings', 'gravityforms' ) ); ?> <script type="text/javascript"> <?php GFCommon::gf_global(); ?> var form = <?php echo json_encode( $form ); ?>; var fieldSettings = []; jQuery(document).ready(function ($) { HandleUnsavedChanges('#gform_form_settings'); jQuery('.datepicker').datepicker({showOn: 'both', changeMonth: true, changeYear: true, buttonImage: "<?php echo GFCommon::get_base_url() ?>/images/calendar.png", buttonImageOnly: true}); ToggleConditionalLogic(true, 'form_button'); jQuery('tr:hidden .gf_animate_sub_settings').hide(); jQuery(document).trigger('gform_load_form_settings', [form]); }); /** * New Form Settings Functions */ function SaveFormSettings() { hasUnsavedChanges = false; // allow users to update form with custom function before save if (window['gform_before_update']) { form = window['gform_before_update'](form); if (window.console) console.log('"gform_before_update" is deprecated since version 1.7! Use "gform_pre_form_settings_save" php hook instead.'); } // set fields to empty array to avoid issues with post data being too long form.fields = []; jQuery("#gform_meta").val(jQuery.toJSON(form)); jQuery("form#gform_form_settings").submit(); } function UpdateLabelPlacement() { var placement = jQuery("#form_label_placement").val(); if (placement == 'top_label') { jQuery('#description_placement_setting').show('slow'); } else { jQuery('#description_placement_setting').hide('slow'); jQuery('#form_description_placement').val('below'); UpdateDescriptionPlacement(); } } function UpdateDescriptionPlacement() { var placement = jQuery("#form_description_placement").val(); //jQuery("#gform_fields").removeClass("description_below").removeClass("description_above").addClass("description_" + placement); jQuery(".gfield_description").each(function () { var prevElement = placement == 'above' ? '.gfield_label' : '.ginput_container:visible'; jQuery(this).siblings(prevElement).after(jQuery(this).remove()); }); } function ToggleButton() { var isText = jQuery("#form_button_text").is(":checked"); var show_element = isText ? '#form_button_text_setting' : '#form_button_image_path_setting'; var hide_element = isText ? '#form_button_image_path_setting' : '#form_button_text_setting'; jQuery(hide_element).hide(); jQuery(show_element).fadeIn(); } function ToggleEnableSave() { if (jQuery("#form_save_enabled").is(":checked")) { ShowSettingRow('#form_save_button_text_setting'); ShowSettingRow('#form_save_warning'); } else { HideSettingRow('#form_save_warning'); HideSettingRow('#form_save_button_text_setting'); } } function ToggleLimitEntry() { if (jQuery("#gform_limit_entries").is(":checked")) { ShowSettingRow('#limit_entries_count_setting'); ShowSettingRow('#limit_entries_message_setting'); } else { HideSettingRow('#limit_entries_count_setting'); HideSettingRow('#limit_entries_message_setting'); } } function ShowSettingRow(elemId) { jQuery(elemId).show().find('.gf_animate_sub_settings').slideDown(); } function HideSettingRow(elemId) { var elem = jQuery(elemId); elem.find('.gf_animate_sub_settings').slideUp(function () { elem.hide(); }); } function ToggleSchedule() { if (jQuery("#gform_schedule_form").is(":checked")) { ShowSettingRow('#schedule_start_setting'); ShowSettingRow('#schedule_end_setting'); ShowSettingRow('#schedule_pending_message_setting'); ShowSettingRow('#schedule_message_setting'); } else { HideSettingRow('#schedule_start_setting'); HideSettingRow('#schedule_end_setting'); HideSettingRow('#schedule_pending_message_setting'); HideSettingRow('#schedule_message_setting'); } } function ToggleRequireLogin() { if (jQuery("#gform_require_login").is(":checked")) { ShowSettingRow('#require_login_message_setting'); } else { HideSettingRow('#require_login_message_setting'); } } function SetButtonConditionalLogic(isChecked) { form.button.conditionalLogic = isChecked ? new ConditionalLogic() : null; } function HandleUnsavedChanges(elemId) { hasUnsavedChanges = false; jQuery(elemId).find('input, select, textarea').change(function () { hasUnsavedChanges = true; }); window.onbeforeunload = function () { if (hasUnsavedChanges){ return '<?php echo esc_js( 'You have unsaved changes.', 'gravityforms' ); ?>'; } } } function ShowAdvancedFormSettings() { jQuery('#form_setting_advanced').slideDown(); jQuery('.show_advanced_settings_container').slideUp(); } <?php self::output_field_scripts() ?> </script> <?php switch ( rgar( $update_result, 'status' ) ) { case 'invalid_json' : ?> <div class="error below-h2" id="after_update_error_dialog"> <p> <?php _e( 'There was an error while saving your form.', 'gravityforms' ) ?> <?php printf( __( 'Please %scontact our support team%s.', 'gravityforms' ), '<a href="http://www.gravityhelp.com">', '</a>' ) ?> </p> </div> <?php break; case 'duplicate_title': ?> <div class="error below-h2" id="after_update_error_dialog"> <p> <?php _e( 'The form title you have entered has already been used. Please enter a unique form title.', 'gravityforms' ) ?> </p> </div> <?php break; default: if ( ! empty( $update_result ) ) { ?> <div class="updated below-h2" id="after_update_dialog"> <p> <strong><?php _e( 'Form settings updated successfully.', 'gravityforms' ); ?></strong> </p> </div> <?php } break; } /** * These variables are used to convenient "wrap" child form settings in the appropriate HTML. */ $subsetting_open = ' <td colspan="2" class="gf_sub_settings_cell"> <div class="gf_animate_sub_settings"> <table> <tr>'; $subsetting_close = ' </tr> </table> </div> </td>'; //create form settings table rows and put them into an array //form title $tr_form_title = ' <tr> <th> ' . __( 'Form title', 'gravityforms' ) . ' ' . gform_tooltip( 'form_title', '', true ) . ' </th> <td> <input type="text" id="form_title_input" name="form_title_input" class="fieldwidth-3" value="' . esc_attr( $form['title'] ) . '" /> </td> </tr>'; //form description $tr_form_description = ' <tr> <th> ' . __( 'Form description', 'gravityforms' ) . ' ' . gform_tooltip( 'form_description', '', true ) . ' </th> <td> <textarea id="form_description_input" name="form_description_input" class="fieldwidth-3 fieldheight-2">' . esc_html( rgar( $form, 'description' ) ) . '</textarea> </td> </tr>'; //form label placement $alignment_options = array( 'top_label' => __( 'Top aligned', 'gravityforms' ), 'left_label' => __( 'Left aligned', 'gravityforms' ), 'right_label' => __( 'Right aligned', 'gravityforms' ) ); $label_dd = ''; foreach ( $alignment_options as $value => $label ) { $selected = $form['labelPlacement'] == $value ? 'selected="selected"' : ''; $label_dd .= '<option value="' . $value . '" ' . $selected . '>' . $label . '</option>'; } $tr_form_label_placement = ' <tr> <th> ' . __( 'Label placement', 'gravityforms' ) . ' ' . gform_tooltip( 'form_label_placement', '', true ) . ' </th> <td> <select id="form_label_placement" name="form_label_placement" onchange="UpdateLabelPlacement();">' . $label_dd . '</select> </td> </tr>'; //form description placement $style = $form['labelPlacement'] != 'top_label' ? 'display:none;' : ''; $description_dd = ''; $description_options = array( 'below' => __( 'Below inputs', 'gravityforms' ), 'above' => __( 'Above inputs', 'gravityforms' ) ); foreach ( $description_options as $value => $label ) { $selected = rgar( $form, 'descriptionPlacement' ) == $value ? 'selected="selected"' : ''; $description_dd .= '<option value="' . $value . '" ' . $selected . '>' . $label . '</option>'; } $tr_form_description_placement = ' <tr id="description_placement_setting" style="' . $style . '"> <th> ' . __( 'Description placement', 'gravityforms' ) . ' ' . gform_tooltip( 'form_description_placement', '', true ) . ' </th> <td> <select id="form_description_placement" name="form_description_placement">' . $description_dd . '</select> </td> </tr>'; //Sub Label placement $sub_label_placement_dd = ''; $sub_label_placement_options = array( 'below' => __( 'Below inputs', 'gravityforms' ), 'above' => __( 'Above inputs', 'gravityforms' ) ); foreach ( $sub_label_placement_options as $value => $label ) { $selected = rgar( $form, 'subLabelPlacement' ) == $value ? 'selected="selected"' : ''; $sub_label_placement_dd .= '<option value="' . $value . '" ' . $selected . '>' . $label . '</option>'; } $tr_sub_label_placement = ' <tr id="sub_label_placement_setting"> <th> ' . __( 'Sub-Label Placement', 'gravityforms' ) . ' ' . gform_tooltip( 'form_sub_label_placement', '', true ) . ' </th> <td> <select id="form_sub_label_placement" name="form_sub_label_placement">' . $sub_label_placement_dd . '</select> </td> </tr>'; //css class name $tr_css_class_name = ' <tr> <th> <label for="form_css_class" style="display:block;">' . __( 'CSS Class Name', 'gravityforms' ) . ' ' . gform_tooltip( 'form_css_class', '', true ) . '</label> </th> <td> <input type="text" id="form_css_class" name="form_css_class" class="fieldwidth-3" value="' . esc_attr( rgar( $form, 'cssClass' ) ) . '" /> </td> </tr>'; //create form advanced settings table rows //create form button rows $form_button_type = rgars( $form, 'button/type' ); $text_button_checked = ''; $image_button_checked = ''; $text_style_display = ''; $image_style_display = ''; if ( $form_button_type == 'text' ) { $text_button_checked = 'checked="checked"'; $image_style_display = 'display:none;'; } else if ( $form_button_type == 'image' ) { $image_button_checked = 'checked="checked"'; $text_style_display = 'display:none;'; } //form button $tr_form_button = ' <tr> <th> ' . __( 'Input type', 'gravityforms' ) . ' </th> <td> <input type="radio" id="form_button_text" name="form_button" value="text" onclick="ToggleButton();" ' . $text_button_checked . ' /> <label for="form_button_text" class="inline">' . __( 'Text', 'gravityforms' ) . '</label> &nbsp;&nbsp; <input type="radio" id="form_button_image" name="form_button" value="image" onclick="ToggleButton();" ' . $image_button_checked . ' /> <label for="form_button_image" class="inline">' . __( 'Image', 'gravityforms' ) . '</label> </td> </tr>'; //form button text $tr_form_button_text = $subsetting_open . ' <tr id="form_button_text_setting" class="child_setting_row" style="' . $text_style_display . '"> <th> ' . __( 'Button text', 'gravityforms' ) . ' ' . gform_tooltip( 'form_button_text', '', true ) . ' </th> <td> <input type="text" id="form_button_text_input" name="form_button_text_input" class="fieldwidth-3" value="' . esc_attr( rgars( $form, 'button/text' ) ) . '" /> </td> </tr>'; //form button image path $tr_form_button_image_path = ' <tr id="form_button_image_path_setting" class="child_setting_row" style="' . $image_style_display . '"> <th> ' . __( 'Button image path', 'gravityforms' ) . ' ' . gform_tooltip( 'form_button_image', '', true ) . ' </th> <td> <input type="text" id="form_button_image_url" name="form_button_image_url" class="fieldwidth-3" value="' . esc_attr( rgars( $form, 'button/imageUrl' ) ) . '" /> </td> </tr>' . $subsetting_close; //form button conditional logic $button_conditional_checked = ''; if ( rgars( $form, 'button/conditionalLogic' ) ) { $button_conditional_checked = 'checked="checked"'; } $tr_form_button_conditional = ' <tr> <th> ' . __( 'Button conditional logic', 'gravityforms' ) . ' ' . gform_tooltip( 'form_button_conditional_logic', '', true ) . ' </th> <td> <input type="checkbox" id="form_button_conditional_logic" onclick="SetButtonConditionalLogic(this.checked); ToggleConditionalLogic(false, \'form_button\');"' . $button_conditional_checked . ' /> <label for="form_button_conditional_logic" class="inline">' . ' ' . __( 'Enable Conditional Logic', 'gravityforms' ) . '</label> </td> </tr> <tr> <td colspan="2"> <div id="form_button_conditional_logic_container" class="gf_animate_sub_settings" style="display:none;"> <!-- content dynamically created from js.php --> </div> </td> </tr>'; //create save and continue rows $save_enabled_checked = ''; $save_enabled_style = ''; if ( rgars( $form, 'save/enabled' ) ) { $save_enabled_checked = 'checked="checked"'; } else { $save_enabled_style = 'style="display:none;"'; } $save_button_text = isset( $form['save']['button']['text'] ) ? esc_attr( rgars( $form, 'save/button/text' ) ) : __( 'Save and Continue Later', 'gravityforms' ); $tr_enable_save = ' <tr> <th> ' . __( 'Save and Continue', 'gravityforms' ) . ' ' . gform_tooltip( 'form_enable_save', '', true ) . ' </th> <td> <input type="checkbox" id="form_save_enabled" name="form_save_enabled" onclick="ToggleEnableSave();" value="1" ' . $save_enabled_checked . ' /> <label for="form_save_enabled">' . __( 'Enable Save and Continue', 'gravityforms' ) . '</label> </td> </tr>'; // Warning $tr_save_warning = ' <tr id="form_save_warning" class="child_setting_row" ' . $save_enabled_style . '> ' . $subsetting_open . ' <th> </th> <td> <div class="gforms_help_alert fieldwidth-3"> <div> <i class="fa fa-warning"></i> '. __('This feature stores potentially private and sensitive data on this server and protects it with a unique link which is displayed to the user on the page in plain, unencrypted text. The link is similar to a password so it\'s strongly advisable to ensure that the page enforces a secure connection (HTTPS) before activating this setting.', 'gravityforms'). '</div> <br /> <div> <i class="fa fa-warning"></i> '. __('When this setting is activated two confirmations and one notification are automatically generated and can be modified in their respective editors. When this setting is deactivated the confirmations and the notification will be deleted automatically and any modifications will be lost.', 'gravityforms'). '</div> </div> </td> </tr>'; //save button text $tr_save_button_text = ' <tr id="form_save_button_text_setting" class="child_setting_row" ' . $save_enabled_style . '> <th> ' . __( 'Link text', 'gravityforms' ) . ' ' . gform_tooltip( 'form_save_button_text', '', true ) . ' </th> <td> <input type="text" id="form_save_button_text" name="form_save_button_text" class="fieldwidth-3" value="' . $save_button_text . '" /> </td> ' . $subsetting_close . ' </tr>'; //limit entries $limit_entry_checked = ''; $limit_entry_style = ''; $limit_entries_dd = ''; if ( rgar( $form, 'limitEntries' ) ) { $limit_entry_checked = 'checked="checked"'; } else { $limit_entry_style = 'display:none'; } $limit_periods = array( '' => __( 'total entries', 'gravityforms' ), 'day' => __( 'per day', 'gravityforms' ), 'week' => __( 'per week', 'gravityforms' ), 'month' => __( 'per month', 'gravityforms' ), 'year' => __( 'per year', 'gravityforms' ) ); foreach ( $limit_periods as $value => $label ) { $selected = rgar( $form, 'limitEntriesPeriod' ) == $value ? 'selected="selected"' : ''; $limit_entries_dd .= '<option value="' . $value . '" ' . $selected . '>' . $label . '</option>'; } $tr_limit_entries = ' <tr> <th> ' . __( 'Limit number of entries', 'gravityforms' ) . ' ' . gform_tooltip( 'form_limit_entries', '', true ) . ' </th> <td> <input type="checkbox" id="gform_limit_entries" name="form_limit_entries" onclick="ToggleLimitEntry();" value="1" ' . $limit_entry_checked . ' /> <label for="gform_limit_entries">' . __( 'Enable entry limit', 'gravityforms' ) . '</label> </td> </tr>'; //limit entries count $tr_limit_entries_count = ' <tr id="limit_entries_count_setting" class="child_setting_row" style="' . esc_attr( $limit_entry_style ) . '"> ' . $subsetting_open . ' <th> ' . __( 'Number of Entries', 'gravityforms' ) . ' </th> <td> <input type="text" id="gform_limit_entries_count" name="form_limit_entries_count" style="width:70px;" value="' . esc_attr( rgar( $form, 'limitEntriesCount' ) ) . '" /> &nbsp; <select id="gform_limit_entries_period" name="form_limit_entries_period" style="height:22px;">' . $limit_entries_dd . '</select> </td> ' . $subsetting_close . ' </tr>'; //limit entries message $tr_limit_entries_message = ' <tr id="limit_entries_message_setting" class="child_setting_row" style="' . $limit_entry_style . '"> ' . $subsetting_open . ' <th> <label for="form_limit_entries_message">' . __( 'Entry Limit Reached Message', 'gravityforms' ) . '</label> </th> <td> <textarea id="form_limit_entries_message" name="form_limit_entries_message" class="fieldwidth-3">' . esc_html( rgar( $form, 'limitEntriesMessage' ) ) . '</textarea> </td> ' . $subsetting_close . ' </tr> '; //schedule form $schedule_form_checked = ''; $schedule_form_style = ''; $start_hour_dd = ''; $start_minute_dd = ''; $start_am_selected = ''; $start_pm_selected = ''; $end_hour_dd = ''; $end_minute_dd = ''; $end_am_selected = ''; $end_pm_selected = ''; if ( rgar( $form, 'scheduleForm' ) ) { $schedule_form_checked = 'checked="checked"'; } else { $schedule_form_style = 'display:none'; } //create start hour dd options for ( $i = 1; $i <= 12; $i ++ ) { $selected = rgar( $form, 'scheduleStartHour' ) == $i ? 'selected="selected"' : ''; $start_hour_dd .= '<option value="' . $i . '" ' . $selected . '>' . $i . '</option>'; } //create start minute dd options foreach ( array( '00', '15', '30', '45' ) as $value ) { $selected = rgar( $form, 'scheduleStartMinute' ) == $value ? 'selected="selected"' : ''; $start_minute_dd .= '<option value="' . $value . '" ' . $selected . '>' . $value . '</option>'; } //set start am/pm if ( rgar( $form, 'scheduleStartAmpm' ) == 'am' ) { $start_am_selected = 'selected="selected"'; } elseif ( rgar( $form, 'scheduleStartAmpm' ) == 'pm' ) { $start_pm_selected = 'selected="selected"'; } //create end hour dd options for ( $i = 1; $i <= 12; $i ++ ) { $selected = rgar( $form, 'scheduleEndHour' ) == $i ? 'selected="selected"' : ''; $end_hour_dd .= '<option value="' . $i . ' "' . $selected . '>' . $i . '</option>'; } //create end minute dd options foreach ( array( '00', '15', '30', '45' ) as $value ) { $selected = rgar( $form, 'scheduleEndMinute' ) == $value ? 'selected="selected"' : ''; $end_minute_dd .= '<option value="' . $value . '" ' . $selected . '>' . $value . '</option>'; } //set end am/pm if ( rgar( $form, 'scheduleEndAmpm' ) == 'am' ) { $end_am_selected = 'selected="selected"'; } elseif ( rgar( $form, 'scheduleEndAmpm' ) == 'pm' ) { $end_pm_selected = 'selected="selected"'; } //schedule form $tr_schedule_form = ' <tr> <th> ' . __( 'Schedule form', 'gravityforms' ) . ' ' . gform_tooltip( 'form_schedule_form', '', true ) . ' </th> <td> <input type="checkbox" id="gform_schedule_form" name="form_schedule_form" value="1" onclick="ToggleSchedule();"' . $schedule_form_checked . '/> <label for="gform_schedule_form">' . __( 'Schedule form', 'gravityforms' ) . '</label> </td> </tr>'; //schedule start $tr_schedule_start = ' <tr id="schedule_start_setting" class="child_setting_row" style="' . $schedule_form_style . '"> ' . $subsetting_open . ' <th> <label for="gform_schedule_start">' . __( 'Schedule Start Date/Time', 'gravityforms' ) . '</label> </th> <td> <input type="text" id="gform_schedule_start" name="gform_schedule_start" class="datepicker" value="' . esc_attr( rgar( $form, 'scheduleStart' ) ) . '" /> &nbsp;&nbsp; <select id="gform_schedule_start_hour" name="form_schedule_start_hour">' . $start_hour_dd . '</select> : <select id="gform_schedule_start_minute" name="form_schedule_start_minute">' . $start_minute_dd . '</select> <select id="gform_schedule_start_ampm" name="form_schedule_start_ampm"> <option value="am" ' . $start_am_selected . '>AM</option> <option value="pm" ' . $start_pm_selected . '>PM</option> </select> </td> ' . $subsetting_close . ' </tr>'; //schedule end $tr_schedule_end = ' <tr id="schedule_end_setting" class="child_setting_row" style="' . esc_attr( $schedule_form_style ) . '"> ' . $subsetting_open . ' <th> ' . __( 'Schedule Form End Date/Time', 'gravityforms' ) . ' </th> <td> <input type="text" id="gform_schedule_end" name="form_schedule_end" class="datepicker" value="' . esc_attr( rgar( $form, 'scheduleEnd' ) ) . '" /> &nbsp;&nbsp; <select id="gform_schedule_end_hour" name="form_schedule_end_hour">' . $end_hour_dd . '</select> : <select id="gform_schedule_end_minute" name="form_schedule_end_minute">' . $end_minute_dd . '</select> <select id="gform_schedule_end_ampm" name="form_schedule_end_ampm"> <option value="am" ' . $end_am_selected . '>AM</option> <option value="pm" ' . $end_pm_selected . '>PM</option> </select> </td> ' . $subsetting_close . ' </tr>'; //schedule message $tr_schedule_pending_message = ' <tr id="schedule_pending_message_setting" class="child_setting_row" style="' . esc_attr( $schedule_form_style ) . '"> ' . $subsetting_open . ' <th> ' . __( 'Form Pending Message', 'gravityforms' ) . ' </th> <td> <textarea id="gform_schedule_pending_message" name="form_schedule_pending_message" class="fieldwidth-3">' . esc_html( rgar( $form, 'schedulePendingMessage' ) ) . '</textarea> </td> ' . $subsetting_close . ' </td>'; //schedule message $tr_schedule_message = ' <tr id="schedule_message_setting" class="child_setting_row" style="' . esc_attr( $schedule_form_style ) . '"> ' . $subsetting_open . ' <th> ' . __( 'Form Expired Message', 'gravityforms' ) . ' </th> <td> <textarea id="gform_schedule_message" name="form_schedule_message" class="fieldwidth-3">' . esc_html( rgar( $form, 'scheduleMessage' ) ) . '</textarea> </td> ' . $subsetting_close . ' </td>'; //honey pot $honey_pot_checked = ''; if ( rgar( $form, 'enableHoneypot' ) ) { $honey_pot_checked = 'checked="checked"'; } $tr_honey_pot = ' <tr> <th> ' . __( 'Anti-spam honeypot', 'gravityforms' ) . ' ' . gform_tooltip( 'form_honeypot', '', true ) . ' </th> <td> <input type="checkbox" id="gform_enable_honeypot" name="form_enable_honeypot" value="1" ' . $honey_pot_checked . '/> <label for="gform_enable_honeypot">' . __( 'Enable anti-spam honeypot', 'gravityforms' ) . '</label> </td> </tr>'; //enable animation $enable_animation_checked = ''; if ( rgar( $form, 'enableAnimation' ) ) { $enable_animation_checked = 'checked="checked"'; } $tr_enable_animation = ' <tr> <th> ' . __( 'Animated transitions', 'gravityforms' ) . ' ' . gform_tooltip( 'form_animation', '', true ) . ' </th> <td> <input type="checkbox" id="gform_enable_animation" name="form_enable_animation" value="1" ' . $enable_animation_checked . ' /> <label for="gform_enable_animation">' . __( 'Enable animations', 'gravityforms' ) . '</label> </td> </tr>'; //require login $require_login_checked = ''; $require_login_style = ''; if ( rgar( $form, 'requireLogin' ) ) { $require_login_checked = 'checked="checked"'; } else { $require_login_style = 'display:none'; } $tr_requires_login = ' <tr> <th> ' . __( 'Require user to be logged in', 'gravityforms' ) . ' ' . gform_tooltip( 'form_require_login', '', true ) . ' </th> <td> <input type="checkbox" id="gform_require_login" name="form_require_login" value="1" onclick="ToggleRequireLogin();"' . $require_login_checked . ' /> <label for="gform_require_login">' . __( 'Require user to be logged in', 'gravityforms' ) . '</label> </td> </tr>'; //require login message $tr_requires_login_message = ' <tr id="require_login_message_setting" class="child_setting_row" style="' . esc_attr( $require_login_style ) . '"> ' . $subsetting_open . ' <th> ' . __( 'Require Login Message', 'gravityforms' ) . ' ' . gform_tooltip( 'form_require_login_message', '', true ) . ' </th> <td> <textarea id="gform_require_login_message" name="form_require_login_message" class="fieldwidth-3">' . esc_html( rgar( $form, 'requireLoginMessage' ) ) . '</textarea> </td> ' . $subsetting_close . ' </td>'; //populate arrays with table rows $form_basics = array( 'form_title' => $tr_form_title, 'form_description' => $tr_form_description ); $form_layout = array( 'form_label_placement' => $tr_form_label_placement, 'form_description_placement' => $tr_form_description_placement, 'form_sub_label_placement' => $tr_sub_label_placement, 'css_class_name' => $tr_css_class_name ); $form_button = array( 'form_button_type' => $tr_form_button, 'form_button_text' => $tr_form_button_text, 'form_button_image_path' => $tr_form_button_image_path, 'form_button_conditional' => $tr_form_button_conditional ); $save_button = array( 'save_enabled' => $tr_enable_save, 'save_warning' => $tr_save_warning, 'save_button_text' => $tr_save_button_text ); $form_restrictions = array( 'limit_entries' => $tr_limit_entries, 'number_of_entries' => $tr_limit_entries_count, 'entry_limit_message' => $tr_limit_entries_message, 'schedule_form' => $tr_schedule_form, 'schedule_start' => $tr_schedule_start, 'schedule_end' => $tr_schedule_end, 'schedule_pending_message' => $tr_schedule_pending_message, 'schedule_message' => $tr_schedule_message, 'requires_login' => $tr_requires_login, 'requires_login_message' => $tr_requires_login_message ); $form_options = array( 'honey_pot' => $tr_honey_pot, 'enable_animation' => $tr_enable_animation ); $form_settings = array( __( 'Form Basics', 'gravityforms' ) => $form_basics, __( 'Form Layout', 'gravityforms' ) => $form_layout, __( 'Form Button', 'gravityforms' ) => $form_button, __( 'Save and Continue', 'gravityforms' ) => $save_button, __( 'Restrictions', 'gravityforms' ) => $form_restrictions, __( 'Form Options', 'gravityforms' ) => $form_options, ); $form_settings = apply_filters( 'gform_form_settings', $form_settings, $form ); ?> <div class="gform_panel gform_panel_form_settings" id="form_settings"> <h3><span><i class="fa fa-cogs"></i> <?php _e( 'Form Settings', 'gravityforms' ) ?></span></h3> <form action="" method="post" id="gform_form_settings"> <table class="gforms_form_settings" cellspacing="0" cellpadding="0"> <?php //write out array of table rows if ( is_array( $form_settings ) ) { //foreach($form_settings as $row) { foreach ( $form_settings as $key => $value ) { ?> <tr> <td colspan="2"> <h4 class="gf_settings_subgroup_title"><?php _e( $key, 'gravityforms' ); ?></h4> </td> </tr> <?php if ( is_array( $value ) ) { foreach ( $value as $tr ) { echo $tr; } } } } ?> </table> <div id="gform_custom_settings"> <!--form settings--> <?php do_action( 'gform_properties_settings', 100, $form_id ); ?> <?php do_action( 'gform_properties_settings', 200, $form_id ); ?> <?php do_action( 'gform_properties_settings', 300, $form_id ); ?> <?php do_action( 'gform_properties_settings', 400, $form_id ); ?> <?php do_action( 'gform_properties_settings', 500, $form_id ); ?> <!--advanced settings--> <?php do_action( 'gform_advanced_settings', 100, $form_id ); ?> <?php do_action( 'gform_advanced_settings', 200, $form_id ); ?> <?php do_action( 'gform_advanced_settings', 300, $form_id ); ?> <?php do_action( 'gform_advanced_settings', 400, $form_id ); ?> <?php do_action( 'gform_advanced_settings', 500, $form_id ); ?> <?php do_action( 'gform_advanced_settings', 600, $form_id ); ?> <?php do_action( 'gform_advanced_settings', 700, $form_id ); ?> <?php do_action( 'gform_advanced_settings', 800, $form_id ); ?> </div> <?php wp_nonce_field( "gform_save_form_settings_{$form_id}", 'gform_save_form_settings' ); ?> <input type="hidden" id="gform_meta" name="gform_meta" /> <input type="button" id="gform_save_settings" name="gform_save_settings" value="<?php _e( 'Update Form Settings', 'gravityforms' ); ?>" class="button-primary gfbutton" onclick="SaveFormSettings();" /> </form> </div> <!-- / gform_panel_form_settings --> <?php self::page_footer(); } public static function confirmations_page() { $form_id = rgget( 'id' ); $confirmation_id = rgget( 'cid' ); if ( ! rgblank( $confirmation_id ) ) { self::confirmations_edit_page( $form_id, $confirmation_id ); } else { self::confirmations_list_page( $form_id ); } } public static function confirmations_list_page( $form_id ) { self::maybe_process_confirmation_list_action(); self::page_header( __( 'Confirmations', 'gravityforms' ) ); $add_new_url = add_query_arg( array( 'cid' => 0 ) ); ?> <h3><span><i class="fa fa-envelope-o"></i> <?php _e( 'Confirmations', 'gravityforms' ) ?> <a id="add-new-confirmation" class="add-new-h2" href="<?php echo esc_url( $add_new_url ) ?>"><?php _e( 'Add New', 'gravityforms' ) ?></a></span> </h3> <?php $form = GFFormsModel::get_form_meta( $form_id ); ?> <script type="text/javascript"> var form = <?php echo json_encode( $form ); ?>; function ToggleActive(img, confirmation_id) { var is_active = img.src.indexOf("active1.png") >= 0 if (is_active) { img.src = img.src.replace("active1.png", 'active0.png'); jQuery(img).attr('title', '<?php _e( 'Inactive', 'gravityforms' ) ?>').attr('alt', '<?php _e( 'Inactive', 'gravityforms' ) ?>'); } else { img.src = img.src.replace("active0.png", 'active1.png'); jQuery(img).attr('title', '<?php _e( 'Active', 'gravityforms' ) ?>').attr('alt', '<?php _e( 'Active', 'gravityforms' ) ?>'); } var mysack = new sack("<?php echo admin_url( 'admin-ajax.php' )?>"); mysack.execute = 1; mysack.method = 'POST'; mysack.setVar("action", "rg_update_confirmation_active"); mysack.setVar("rg_update_confirmation_active", "<?php echo wp_create_nonce( 'rg_update_confirmation_active' ) ?>"); mysack.setVar("form_id", <?php echo intval( $form_id ) ?>); mysack.setVar("confirmation_id", confirmation_id); mysack.setVar("is_active", is_active ? 0 : 1); mysack.onError = function () { alert('<?php echo esc_js( __( 'Ajax error while updating confirmation', 'gravityforms' ) ) ?>') }; mysack.runAJAX(); return true; } </script> <?php $confirmation_table = new GFConfirmationTable( $form ); $confirmation_table->prepare_items(); ?> <form id="confirmation_list_form" method="post"> <?php $confirmation_table->display(); ?> <input id="action_argument" name="action_argument" type="hidden" /> <input id="action" name="action" type="hidden" /> <?php wp_nonce_field( 'gform_confirmation_list_action', 'gform_confirmation_list_action' ) ?> </form> <?php self::page_footer(); } public static function confirmations_edit_page( $form_id, $confirmation_id ) { $form = gf_apply_filters( array( 'gform_admin_pre_render', $form_id ), GFFormsModel::get_form_meta( $form_id ) ); $duplicated_cid = rgget( 'duplicatedcid' ); $is_duplicate = empty( $_POST ) && ! empty( $duplicated_cid ); if ( $is_duplicate ) { $confirmation_id = $duplicated_cid; } $confirmation = self::handle_confirmation_edit_submission( rgar( $form['confirmations'], $confirmation_id ), $form ); if ( $is_duplicate ) { $count = 2; $name = $confirmation['name']; $new_name = $name . ' - Copy 1'; while ( ! self::is_unique_name( $new_name, $form['confirmations'] ) ) { $new_name = $name . " - Copy $count"; $count ++; } $confirmation['name'] = $new_name; $confirmation['id'] = 'new'; if ( $confirmation['isDefault'] ) { $confirmation['isDefault'] = false; $confirmation['conditionalLogic'] = ''; } } $confirmation_ui_settings = self::get_confirmation_ui_settings( $confirmation ); $entry_meta = GFFormsModel::get_entry_meta( $form_id ); $entry_meta = apply_filters( 'gform_entry_meta_conditional_logic_confirmations', $entry_meta, $form, $confirmation_id ); self::page_header( __( 'Confirmations', 'gravityforms' ) ); ?> <script type="text/javascript"> var confirmation = <?php echo $confirmation ? json_encode( $confirmation ) : 'new ConfirmationObj()' ?>; var form = <?php echo json_encode( $form ); ?>; var entry_meta = <?php echo GFCommon::json_encode( $entry_meta ) ?>; jQuery(document).ready(function ($) { if ( confirmation.event == 'form_saved' || confirmation.event == 'form_save_email_sent' ) { $('#form_confirmation_redirect, #form_confirmation_show_page').attr('disabled', true); } SetConfirmationConditionalLogic(); <?php if ( ! rgar( $confirmation, 'isDefault' ) ) : ?> ToggleConditionalLogic(true, 'confirmation'); <?php endif; ?> ToggleConfirmation(); <?php if ( $is_duplicate ) :?> $('#confirmation_conditional_logic_container').pointer({ content : '<h3><?php _e( 'Important', 'gravityforms' ) ?></h3><p><?php _e( 'Ensure that the conditional logic for this confirmation is different from all the other confirmations for this form and then press save to create the new confirmation.', 'gravityforms' ) ?></p>', position : { edge : 'bottom', // arrow direction align: 'center' // vertical alignment }, pointerWidth: 300 }).pointer('open'); <?php endif; ?> }); gform.addFilter("gform_merge_tags", "MaybeAddSaveMergeTags"); function MaybeAddSaveMergeTags(mergeTags, elementId, hideAllFields, excludeFieldTypes, isPrepop, option){ var event = confirmation.event; if ( event == 'form_saved' || event == 'form_save_email_sent' ) { mergeTags["other"].tags.push({ tag: '{save_link}', label: '<?php _e( 'Save &amp; Continue Link', 'gravityforms' ) ?>' }); mergeTags["other"].tags.push({ tag: '{save_token}', label: '<?php _e( 'Save &amp; Continue Token', 'gravityforms' ) ?>' }); } if( event == 'form_saved' ) { mergeTags["other"].tags.push({ tag: '{save_email_input}', label: '<?php _e( 'Save &amp; Continue Email Input', 'gravityforms' ) ?>' }); } return mergeTags; } <?php self::output_field_scripts() ?> </script> <style type="text/css"> #confirmation_action_type { display: none; } </style> <div id="confirmation-editor"> <form id="confirmation_edit_form" method="post"> <table class="form-table gforms_form_settings"> <?php array_map( array( __class__, 'output' ), $confirmation_ui_settings ); ?> </table> <?php //DEPRECATED SINCE 1.7 - use gform_confirmation_ui_settings instead do_action( 'gform_confirmation_settings', 100, $form_id ); do_action( 'gform_confirmation_settings', 200, $form_id ); ?> <input type="hidden" id="confirmation_id" name="confirmation_id" value="<?php echo $confirmation_id; ?>" /> <input type="hidden" id="form_id" name="form_id" value="<?php echo $form_id; ?>" /> <input type="hidden" id="is_default" name="is_default" value="<?php echo rgget( 'isDefault', $confirmation ) ?>" /> <input type="hidden" id="conditional_logic" name="conditional_logic" value="<?php echo htmlentities( json_encode( rgget( 'conditionalLogic', $confirmation ) ) ); ?>" /> <p class="submit"> <input type="submit" name="save" value="<?php _e( 'Save Confirmation', 'gravityforms' ); ?>" onclick="StashConditionalLogic(event);" class="button-primary"> </p> <?php wp_nonce_field( 'gform_confirmation_edit', 'gform_confirmation_edit' ); ?> </form> </div> <!-- / confirmation-editor --> <?php self::page_footer(); } public static function get_confirmation_ui_settings( $confirmation ) { /** * These variables are used to convenient "wrap" child form settings in the appropriate HTML. */ $subsetting_open = ' <td colspan="2" class="gf_sub_settings_cell"> <div class="gf_animate_sub_settings"> <table style="width:100%"> <tr>'; $subsetting_close = ' </tr> </table> </div> </td>'; $ui_settings = array(); $confirmation_type = rgar( $confirmation, 'type' ) ? rgar( $confirmation, 'type' ) : 'message'; $is_valid = ! empty( GFCommon::$errors ); $is_default = rgar( $confirmation, 'isDefault' ); $form_id = rgget( 'id' ); $form = RGFormsModel::get_form_meta( $form_id ); ob_start(); ?> <?php $class = ! $is_default && ! $is_valid && $confirmation_type == 'page' && ! rgar( $confirmation, 'name' ) ? 'gfield_error' : ''; ?> <tr <?php echo $is_default ? 'style="display:none;"' : ''; ?> class="<?php echo $class; ?>"> <th><?php _e( 'Confirmation Name', 'gravityforms' ); ?></th> <td> <input type="text" id="form_confirmation_name" name="form_confirmation_name" value="<?php echo rgar( $confirmation, 'name' ); ?>" /> </td> </tr> <!-- / confirmation name --> <?php $ui_settings['confirmation_name'] = ob_get_contents(); ob_clean(); ?> <tr> <th><?php _e( 'Confirmation Type', 'gravityforms' ); ?></th> <td> <input type="radio" id="form_confirmation_show_message" name="form_confirmation" <?php checked( 'message', $confirmation_type ); ?> value="message" onclick="ToggleConfirmation();" /> <label for="form_confirmation_show_message" class="inline"> <?php _e( 'Text', 'gravityforms' ); ?> <?php gform_tooltip( 'form_confirmation_message' ) ?> </label> &nbsp;&nbsp; <input type="radio" id="form_confirmation_show_page" name="form_confirmation" <?php checked( 'page', $confirmation_type ); ?> value="page" onclick="ToggleConfirmation();" /> <label for="form_confirmation_show_page" class="inline"> <?php _e( 'Page', 'gravityforms' ); ?> <?php gform_tooltip( 'form_redirect_to_webpage' ) ?> </label> &nbsp;&nbsp; <input type="radio" id="form_confirmation_redirect" name="form_confirmation" <?php checked( 'redirect', $confirmation_type ); ?> value="redirect" onclick="ToggleConfirmation();" /> <label for="form_confirmation_redirect" class="inline"> <?php _e( 'Redirect', 'gravityforms' ); ?> <?php gform_tooltip( 'form_redirect_to_url' ) ?> </label> </td> </tr> <!-- / confirmation type --> <?php $ui_settings['confirmation_type'] = ob_get_contents(); ob_clean(); ?> <tr id="form_confirmation_message_container" <?php echo $confirmation_type != 'message' ? 'style="display:none;"' : ''; ?> > <?php echo $subsetting_open; ?> <th><?php _e( 'Message', 'gravityforms' ); ?></th> <td> <span class="mt-form_confirmation_message"></span> <?php if ( GFCommon::is_wp_version( '3.3' ) ) { wp_editor( rgar( $confirmation, 'message' ), 'form_confirmation_message', array( 'autop' => false, 'editor_class' => 'merge-tag-support mt-wp_editor mt-manual_position mt-position-right' ) ); } else { ?> <textarea name="form_confirmation_message" id="form_confirmation_message" class="fieldwidth-1 fieldheight-1"><?php echo esc_html( $confirmation['message'] ) ?></textarea><?php } ?> <div style="margin-top:5px;"> <input type="checkbox" id="form_disable_autoformatting" name="form_disable_autoformatting" value="1" <?php echo empty( $confirmation['disableAutoformat'] ) ? '' : "checked='checked'" ?> /> <label for="form_disable_autoformatting"><?php _e( 'Disable Auto-formatting', 'gravityforms' ) ?> <?php gform_tooltip( 'form_confirmation_autoformat' ) ?></label> </div> </td> <?php echo $subsetting_close; ?> </tr> <!-- / confirmation message --> <?php $ui_settings['confirmation_message'] = ob_get_contents(); ob_clean(); ?> <?php $class = ! $is_valid && $confirmation_type == 'page' && ! rgar( $confirmation, 'pageId' ) ? 'gfield_error' : ''; ?> <tr class="form_confirmation_page_container" <?php echo $confirmation_type != 'page' ? 'style="display:none;"' : '' ?> class="<?php echo $class; ?>"> <?php echo $subsetting_open; ?> <th><?php _e( 'Page', 'gravityforms' ); ?></th> <td> <?php wp_dropdown_pages( array( 'name' => 'form_confirmation_page', 'selected' => rgar( $confirmation, 'pageId' ), 'show_option_none' => __( 'Select a page', 'gravityforms' ) ) ); ?> </td> <?php echo $subsetting_close; ?> </tr> <!-- / confirmation page --> <?php $ui_settings['confirmation_page'] = ob_get_contents(); ob_clean(); ?> <tr class="form_confirmation_page_container" <?php echo $confirmation_type != 'page' ? 'style="display:none;"' : '' ?> class="<?php echo $class; ?>"> <?php echo $subsetting_open; ?> <th><?php _e( 'Redirect Query String', 'gravityforms' ); ?> <?php gform_tooltip( 'form_redirect_querystring' ) ?></th> <td> <input type="checkbox" id="form_page_use_querystring" name="form_page_use_querystring" <?php echo empty( $confirmation['queryString'] ) ? '' : "checked='checked'" ?> onclick="TogglePageQueryString()" /> <label for="form_page_use_querystring"><?php _e( 'Pass Field Data Via Query String', 'gravityforms' ) ?></label> <div id="form_page_querystring_container" <?php echo empty( $confirmation['queryString'] ) ? 'style="display:none;"' : ''; ?> > <?php $query_string = rgget( 'queryString', $confirmation ); ?> <textarea name="form_page_querystring" id="form_page_querystring" class="merge-tag-support mt-position-right mt-hide_all_fields mt-option-url" style="width:98%; height:100px;"><?php echo esc_html( $query_string ); ?></textarea><br /> <div class="instruction"><?php _e( 'Sample: phone={Phone:1}&email={Email:2}', 'gravityforms' ); ?></div> </div> </td> <?php echo $subsetting_close; ?> </tr> <!-- / confirmation page use querystring --> <?php $ui_settings['confirmation_page_querystring'] = ob_get_contents(); ob_clean(); ?> <?php $class = ! $is_valid && $confirmation_type == 'redirect' && ! rgar( $confirmation, 'url' ) ? 'gfield_error' : ''; ?> <tr class="form_confirmation_redirect_container <?php echo $class; ?>" <?php echo $confirmation_type != 'redirect' ? 'style="display:none;"' : '' ?> > <?php echo $subsetting_open; ?> <th><?php _e( 'Redirect URL', 'gravityforms' ); ?></th> <td> <input type="text" id="form_confirmation_url" name="form_confirmation_url" value="<?php echo esc_attr( rgget( 'url', $confirmation ) ); ?>" style="width:98%;" /> </td> <?php echo $subsetting_close; ?> </tr> <!-- / confirmation url --> <?php $ui_settings['confirmation_url'] = ob_get_contents(); ob_clean(); ?> <tr class="form_confirmation_redirect_container" <?php echo $confirmation_type != 'redirect' ? 'style="display:none;"' : '' ?> > <?php echo $subsetting_open; ?> <th><?php _e( 'Redirect Query String', 'gravityforms' ); ?> <?php gform_tooltip( 'form_redirect_querystring' ) ?></th> <td> <input type="checkbox" id="form_redirect_use_querystring" name="form_redirect_use_querystring" <?php echo empty( $confirmation['queryString'] ) ? '' : "checked='checked'" ?> onclick="ToggleQueryString()" /> <label for="form_redirect_use_querystring"><?php _e( 'Pass Field Data Via Query String', 'gravityforms' ) ?></label> <div id="form_redirect_querystring_container" <?php echo empty( $confirmation['queryString'] ) ? 'style="display:none;"' : ''; ?> > <?php $query_string = rgget( 'queryString', $confirmation ); ?> <textarea name="form_redirect_querystring" id="form_redirect_querystring" class="merge-tag-support mt-position-right mt-hide_all_fields mt-option-url" style="width:98%; height:100px;"><?php echo esc_html( $query_string ); ?></textarea><br /> <div class="instruction"><?php _e( 'Sample: phone={Phone:1}&email={Email:2}', 'gravityforms' ); ?></div> </div> </td> <?php echo $subsetting_close; ?> </tr> <!-- / confirmation use querystring --> <?php $ui_settings['confirmation_querystring'] = ob_get_contents(); ob_clean(); ?> <tr <?php echo rgget( 'isDefault', $confirmation ) ? 'style="display:none;"' : ''; ?> > <th><?php _e( 'Conditional Logic', 'gravityforms' ); ?></th> <td> <input type="checkbox" id="confirmation_conditional_logic" name="confirmation_conditional_logic" style="display:none;" checked="checked" /> <div id="confirmation_conditional_logic_container"> <!-- content populated dynamically by form_admin.js --> </div> </td> </tr> <!-- conditional logic --> <?php $ui_settings['confirmation_conditional_logic'] = ob_get_contents(); ob_clean(); ?> <?php ob_end_clean(); $ui_settings = gf_apply_filters( array( 'gform_confirmation_ui_settings', $form_id ), $ui_settings, $confirmation, $form ); return $ui_settings; } public static function notification_page() { require_once( 'notification.php' ); //page header loaded in below function because admin messages were not yet available to the header to display GFNotification::notification_page(); } public static function page_header( $title = '' ) { // register admin styles wp_register_style( 'gform_admin', GFCommon::get_base_url() . '/css/admin.css' ); wp_print_styles( array( 'jquery-ui-styles', 'gform_admin', 'wp-pointer' ) ); $form = GFFormsModel::get_form_meta( rgget( 'id' ) ); $current_tab = rgempty( 'subview', $_GET ) ? 'settings' : rgget( 'subview' ); $setting_tabs = GFFormSettings::get_tabs( $form['id'] ); // kind of boring having to pass the title, optionally get it from the settings tab if ( ! $title ) { foreach ( $setting_tabs as $tab ) { if ( $tab['name'] == $current_tab ) { $title = $tab['label']; } } } ?> <div class="wrap gforms_edit_form <?php echo GFCommon::get_browser_class() ?>"> <h2 class="gf_admin_page_title"> <span><?php echo $title ?></span><span class="gf_admin_page_subtitle"><span class="gf_admin_page_formid">ID: <?php echo $form['id']; ?></span><span class="gf_admin_page_formname"><?php _e( 'Form Name', 'gravityforms' ) ?>: <?php echo $form['title']; ?></span></span> </h2> <?php GFCommon::display_admin_message(); ?> <?php RGForms::top_toolbar(); ?> <div id="gform_tab_group" class="gform_tab_group vertical_tabs"> <ul id="gform_tabs" class="gform_tabs"> <?php foreach ( $setting_tabs as $tab ) { $query = array( 'subview' => $tab['name'] ); if ( isset( $tab['query'] ) ) $query = array_merge( $query, $tab['query'] ); $url = add_query_arg( $query ); ?> <li <?php echo $current_tab == $tab['name'] ? "class='active'" : '' ?>> <a href="<?php echo esc_url( $url ); ?>"><?php echo esc_html( $tab['label'] ) ?></a><span></span> </li> <?php } ?> </ul> <div id="gform_tab_container_1" class="gform_tab_container"> <div class="gform_tab_content" id="tab_<?php echo esc_attr( $current_tab ) ?>"> <?php } public static function page_footer(){ ?> </div> <!-- / gform_tab_content --> </div> <!-- / gform_tab_container --> </div> <!-- / gform_tab_group --> <br class="clear" style="clear: both;" /> </div> <!-- / wrap --> <script type="text/javascript"> jQuery(document).ready(function ($) { $('.gform_tab_container').css('minHeight', jQuery('#gform_tabs').height() + 100); }); </script> <?php } public static function get_tabs( $form_id ) { $setting_tabs = array( '10' => array( 'name' => 'settings', 'label' => __( 'Form Settings', 'gravityforms' ) ), '20' => array( 'name' => 'confirmation', 'label' => __( 'Confirmations', 'gravityforms' ), 'query' => array( 'cid' => null, 'duplicatedcid' => null ) ), '30' => array( 'name' => 'notification', 'label' => __( 'Notifications', 'gravityforms' ), 'query' => array( 'nid' => null ) ) ); $setting_tabs = apply_filters( 'gform_form_settings_menu', $setting_tabs, $form_id ); ksort( $setting_tabs, SORT_NUMERIC ); return $setting_tabs; } public static function handle_confirmation_edit_submission( $confirmation, $form ) { if ( empty( $_POST ) || ! check_admin_referer( 'gform_confirmation_edit', 'gform_confirmation_edit' ) ) return $confirmation; $is_new_confirmation = ! $confirmation; if ( $is_new_confirmation ) { $confirmation['id'] = uniqid(); } $name = sanitize_text_field( rgpost( 'form_confirmation_name' ) ); $confirmation['name'] = $name; $type = rgpost( 'form_confirmation' ); if ( ! in_array( $type, array( 'message', 'page', 'redirect' ) ) ) { $type = 'message'; } $confirmation['type'] = $type; $confirmation['message'] = rgpost( 'form_confirmation_message' ); $confirmation['disableAutoformat'] = (bool) rgpost( 'form_disable_autoformatting' ); $confirmation['pageId'] = absint( rgpost( 'form_confirmation_page' ) ); $confirmation['url'] = rgpost( 'form_confirmation_url' ); $query_string = '' != rgpost( 'form_redirect_querystring' ) ? rgpost( 'form_redirect_querystring' ) : rgpost( 'form_page_querystring' ); $confirmation['queryString'] = wp_strip_all_tags( $query_string ); $confirmation['isDefault'] = (bool) rgpost( 'is_default' ); // if is default confirmation, override any submitted conditional logic with empty array $confirmation['conditionalLogic'] = $confirmation['isDefault'] ? array() : json_decode( rgpost( 'conditional_logic' ), ARRAY_A ); $confirmation['conditionalLogic'] = GFFormsModel::sanitize_conditional_logic( $confirmation['conditionalLogic'] ); $failed_validation = false; if ( ! $confirmation['name'] ) { $failed_validation = true; GFCommon::add_error_message( __( 'You must specify a Confirmation Name.', 'gravityforms' ) ); } switch ( $type ) { case 'page': if ( empty( $confirmation['pageId'] ) ) { $failed_validation = true; GFCommon::add_error_message( __( 'You must select a Confirmation Page.', 'gravityforms' ) ); } break; case 'redirect': if ( ( empty( $confirmation['url'] ) || ! GFCommon::is_valid_url( $confirmation['url'] ) ) && ! GFCommon::has_merge_tag( $confirmation['url'] ) ) { $failed_validation = true; GFCommon::add_error_message( __( 'You must specify a valid Redirect URL.', 'gravityforms' ) ); } break; } if ( $failed_validation ) return $confirmation; // allow user to filter confirmation before save $confirmation = gf_apply_filters( array( 'gform_pre_confirmation_save', $form['id'] ), $confirmation, $form, $is_new_confirmation ); // trim values $confirmation = GFFormsModel::trim_conditional_logic_values_from_element( $confirmation, $form ); // add current confirmation to confirmations array $form['confirmations'][ $confirmation['id'] ] = $confirmation; // save updated confirmations array $result = GFFormsModel::save_form_confirmations( $form['id'], $form['confirmations'] ); if ( $result !== false ) { $url = remove_query_arg( array( 'cid', 'duplicatedcid' ) ); GFCommon::add_message( sprintf( __( 'Confirmation saved successfully. %sBack to confirmations.%s', 'gravityforms' ), '<a href="' . esc_url( $url ) . '">', '</a>' ) ); } else { GFCommon::add_error_message( __( 'There was an issue saving this confirmation.', 'gravityforms' ) ); } return $confirmation; } public static function maybe_process_confirmation_list_action() { if ( empty( $_POST ) || ! check_admin_referer( 'gform_confirmation_list_action', 'gform_confirmation_list_action' ) ) return; $action = rgpost( 'action' ); $object_id = rgpost( 'action_argument' ); switch ( $action ) { case 'delete': $confirmation_deleted = self::delete_confirmation( $object_id, rgget( 'id' ) ); if ( $confirmation_deleted ) { GFCommon::add_message( __( 'Confirmation deleted.', 'gravityforms' ) ); } else { GFCommon::add_error_message( __( 'There was an issue deleting this confirmation.', 'gravityforms' ) ); } break; } } /** * Delete a form confirmation by ID. * * @param mixed $confirmation_id * @param mixed $form_id Can pass a form ID or a form object * * @return mixed The result of the database operation */ public static function delete_confirmation( $confirmation_id, $form_id ) { if ( ! $form_id ) return false; $form = ! is_array( $form_id ) ? RGFormsModel::get_form_meta( $form_id ) : $form_id; /** * Fires right before the confirmation that a form is deleted * * @param int $form['confirmations'][ $confirmation_id ] The delete confirmation object ID * @para array $form The Form object to filter through */ do_action( 'gform_pre_confirmation_deleted', $form['confirmations'][ $confirmation_id ], $form ); unset( $form['confirmations'][ $confirmation_id ] ); // clear form cache so next retrieval of form meta will reflect deleted notification RGFormsModel::flush_current_forms(); return RGFormsModel::save_form_confirmations( $form['id'], $form['confirmations'] ); } public static function output( $a ) { echo $a; } public static function is_unique_name( $name, $confirmations ) { foreach ( $confirmations as $confirmation ) { if ( strtolower( rgar( $confirmation, 'name' ) ) == strtolower( $name ) ) return false; } return true; } public static function output_field_scripts( $echo = true ){ $script_str = ''; $conditional_logic_fields = array(); foreach ( GF_Fields::get_all() as $gf_field ) { if ( $gf_field->is_conditional_logic_supported() ) { $conditional_logic_fields[] = $gf_field->type; } } $script_str .= sprintf( 'function GetConditionalLogicFields(){return %s;}', json_encode( $conditional_logic_fields ) ) . PHP_EOL; if ( ! empty( $script_str ) && $echo ){ echo $script_str; } return $script_str; } public static function activate_save( $form ) { $form_id = $form['id']; $has_save_notification = false; foreach ( $form['notifications'] as $notification ) { if ( rgar( $notification, 'event' ) == 'form_save_email_requested' ) { $has_save_notification = true; break; } } if ( ! $has_save_notification ) { $notification_id = uniqid(); $form['notifications'][ $notification_id ] = array( 'id' => $notification_id, 'isDefault' => true, 'name' => __( 'Save and Continue Email', 'gravityforms' ), 'event' => 'form_save_email_requested', 'toType' => 'hidden', 'from' => '{admin_email}', 'subject' => __( 'Link to continue {form_title}' ), 'message' => __( 'Thank you for saving {form_title}. Please use the unique link below to return to the form from any computer. <br /><br /> {save_link} <br /><br /> Remember that the link will expire after 30 days so please return via the provided link to complete your form submission.', 'gravityforms' ), ); GFFormsModel::save_form_notifications( $form_id, $form['notifications'] ); } $has_save_confirmation = false; foreach ( $form['confirmations'] as $confirmation ) { if ( rgar( $confirmation, 'event' ) == 'form_saved' ) { $has_save_confirmation = true; break; } } if ( ! $has_save_confirmation ) { $confirmation_id = uniqid( 'sc1' ); $form['confirmations'][ $confirmation_id ] = array( 'id' => $confirmation_id, 'event' => 'form_saved', 'name' => __( 'Save and Continue Confirmation', 'gravityforms' ), 'isDefault' => true, 'type' => 'message', 'message' => __( 'Please use the following link to return to your form from any computer. <br /> {save_link} <br /> This link will expire after 30 days. <br />Enter your email address to send the link by email. <br /> {save_email_input}', 'gravityforms' ), 'url' => '', 'pageId' => '', 'queryString' => '', ); $confirmation_id = uniqid( 'sc2' ); $form['confirmations'][ $confirmation_id ] = array( 'id' => $confirmation_id, 'event' => 'form_save_email_sent', 'name' => __( 'Save and Continue Email Sent Confirmation', 'gravityforms' ), 'isDefault' => true, 'type' => 'message', 'message' => __( 'The link was sent to the following email address: {save_email}', 'gravityforms' ), 'url' => '', 'pageId' => '', 'queryString' => '', ); GFFormsModel::save_form_confirmations( $form_id, $form['confirmations'] ); } return $form; } public static function deactivate_save( $form ) { $form_id = $form['id']; foreach ( $form['notifications'] as $notification_id => $notification ) { if ( rgar( $notification, 'isDefault' ) && rgar( $notification, 'event' ) == 'form_save_email_requested' ) { unset( $form['notifications'][ $notification_id ] ); GFFormsModel::save_form_notifications( $form_id, $form['notifications'] ); break; } } $changed = false; foreach ( $form['confirmations'] as $confirmation_id => $confirmation ) { $event = rgar( $confirmation, 'event' ); if ( rgar( $confirmation, 'isDefault' ) && ( $event == 'form_saved' || $event == 'form_save_email_sent' ) ) { unset( $form['confirmations'][ $confirmation_id ] ); $changed = true; } } if ( $changed ) { GFFormsModel::save_form_confirmations( $form_id, $form['confirmations'] ); } return $form; } } require_once( ABSPATH . '/wp-admin/includes/class-wp-list-table.php' ); class GFConfirmationTable extends WP_List_Table { public $form; function __construct( $form ) { $this->form = $form; $this->_column_headers = array( array( 'cb' => '', 'name' => __( 'Name', 'gravityforms' ), 'type' => __( 'Type', 'gravityforms' ), 'content' => __( 'Content', 'gravityforms' ) ), array(), array(), 'name', ); parent::__construct(); } function prepare_items() { $this->items = $this->form['confirmations']; } function display() { $singular = rgar( $this->_args, 'singular' ); ?> <table class="wp-list-table <?php echo implode( ' ', $this->get_table_classes() ); ?>" cellspacing="0"> <thead> <tr> <?php $this->print_column_headers(); ?> </tr> </thead> <tfoot> <tr> <?php $this->print_column_headers( false ); ?> </tr> </tfoot> <tbody id="the-list"<?php if ( $singular ) echo " class='list:$singular'"; ?>> <?php $this->display_rows_or_placeholder(); ?> </tbody> </table> <?php } function single_row( $item ) { static $row_class = ''; $row_class = ( $row_class == '' ? ' class="alternate"' : '' ); echo '<tr id="confirmation-' . $item['id'] . '" ' . $row_class . '>'; echo $this->single_row_columns( $item ); echo '</tr>'; } function get_columns() { return $this->_column_headers[0]; } function column_content( $item ) { return self::get_column_content( $item ); } function column_default( $item, $column ) { echo rgar( $item, $column ); } function column_type( $item ) { return self::get_column_type( $item ); } function column_cb( $item ) { if ( isset( $item['isDefault'] ) && $item['isDefault'] ) return; $is_active = isset( $item['isActive'] ) ? $item['isActive'] : true; ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/active<?php echo intval( $is_active ) ?>.png" style="cursor: pointer;margin:-5px 0 0 8px;" alt="<?php $is_active ? __( 'Active', 'gravityforms' ) : __( 'Inactive', 'gravityforms' ); ?>" title="<?php echo $is_active ? __( 'Active', 'gravityforms' ) : __( 'Inactive', 'gravityforms' ); ?>" onclick="ToggleActive(this, '<?php echo $item['id'] ?>'); " /> <?php } function column_name( $item ) { $edit_url = add_query_arg( array( 'cid' => $item['id'] ) ); $duplicate_url = add_query_arg( array( 'cid' => 0, 'duplicatedcid' => $item['id'] ) ); $actions = apply_filters( 'gform_confirmation_actions', array( 'edit' => '<a title="' . __( 'Edit this item', 'gravityforms' ) . '" href="' . esc_url( $edit_url ) . '">' . __( 'Edit', 'gravityforms' ) . '</a>', 'duplicate' => '<a title="' . __( 'Duplicate this confirmation', 'gravityforms' ) . '" href="' . esc_url( $duplicate_url ) . '">' . __( 'Duplicate', 'gravityforms' ) . '</a>', 'delete' => '<a title="' . __( 'Delete this item', 'gravityforms' ) . '" class="submitdelete" onclick="javascript: if(confirm(\'' . __( 'WARNING: You are about to delete this confirmation.', 'gravityforms' ) . __( "\'Cancel\' to stop, \'OK\' to delete.", 'gravityforms' ) . '\')){ DeleteConfirmation(\'' . esc_js( $item['id'] ) . '\'); }" style="cursor:pointer;">' . __( 'Delete', 'gravityforms' ) . '</a>' ) ); if ( isset( $item['isDefault'] ) && $item['isDefault'] ){ unset( $actions['delete'] ); } ?> <a href="<?php echo esc_url( $edit_url ); ?>"><strong><?php echo esc_html( rgar( $item, 'name' ) ); ?></strong></a> <div class="row-actions"> <?php if ( is_array( $actions ) && ! empty( $actions ) ) { $keys = array_keys( $actions ); $last_key = array_pop( $keys ); foreach ( $actions as $key => $html ) { $divider = $key == $last_key ? '' : ' | '; ?> <span class="<?php echo $key; ?>"> <?php echo $html . $divider; ?> </span> <?php } } ?> </div> <?php } public static function get_column_content( $item ) { switch ( rgar( $item, 'type' ) ) { case 'message': return '<a class="limit-text" title="' . strip_tags( $item['message'] ) . '">' . strip_tags( $item['message'] ) . '</a>'; case 'page': $page = get_post( $item['pageId'] ); if ( empty( $page ) ) return __( '<em>This page does not exist.</em>', 'gravityforms' ); return '<a href="' . get_permalink( $item['pageId'] ) . '">' . $page->post_title . '</a>'; case 'redirect': $url_pieces = parse_url( $item['url'] ); $url_connector = rgar( $url_pieces, 'query' ) ? '&' : '?'; $url = rgar( $item, 'queryString' ) ? "{$item['url']}{$url_connector}{$item['queryString']}" : $item['url']; return '<a class="limit-text" title="' . $url . '">' . $url . '</a>'; } return ''; } public static function get_column_type( $item ) { switch ( rgar( $item, 'type' ) ) { case 'message': return __( 'Text', 'gravityforms' ); case 'page': return __( 'Page', 'gravityforms' ); case 'redirect': return __( 'Redirect', 'gravityforms' ); } return ''; } }
{ "content_hash": "a837cf9f566c130054e6d0cfc0b79ef5", "timestamp": "", "source": "github", "line_count": 1888, "max_line_length": 483, "avg_line_length": 38.50264830508475, "alnum_prop": 0.5678125816791163, "repo_name": "se2/minhnguyendesign", "id": "be3a1853cbe4f7bf1a3dc22f31bcd206846b9e21", "size": "72693", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "plugins/gravityforms/form_settings.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "623554" }, { "name": "HTML", "bytes": "39054" }, { "name": "JavaScript", "bytes": "1739022" }, { "name": "PHP", "bytes": "4790915" }, { "name": "Shell", "bytes": "1490" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.michaelszymczak.speccare</groupId> <artifactId>speccare-specminer</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>specminer (part of speccare)</name> <properties> <spring.version>3.2.2.RELEASE</spring.version> <cobertura.version>2.6</cobertura.version> <cucumber.java.version>1.1.8</cucumber.java.version> <jetty.version>9.2.1.v20140609</jetty.version> <jetty.port>9999</jetty.port> <selenium.version>2.40.0</selenium.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties> <repositories> <repository> <id>spring-milestone</id> <url>https://repo.spring.io/milestone</url> </repository> </repositories> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.4</version> </dependency> <dependency> <groupId>com.googlecode.juniversalchardet</groupId> <artifactId>juniversalchardet</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>com.eclipsesource.minimal-json</groupId> <artifactId>minimal-json</artifactId> <version>0.9.1</version> </dependency> <!-- Cucumber --> <dependency> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>${jetty.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test-mvc-htmlunit</artifactId> <version>1.0.0.M1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.9.5</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>${cucumber.java.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>${cucumber.java.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-spring</artifactId> <version>${cucumber.java.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.17</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-htmlunit-driver</artifactId> <version>${selenium.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-support</artifactId> <version>${selenium.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-firefox-driver</artifactId> <version>${selenium.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> <version>1.4.01</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> <exclusions> <exclusion> <artifactId>xml-apis</artifactId> <groupId>xml-apis</groupId> </exclusion> </exclusions> </dependency> </dependencies> <build> <finalName>speccare-specminer</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.17</version> <configuration> <includes> <include>**/*Tests.java</include> <include>**/*Test.java</include> <include>**/*Should.java</include> </includes> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warName>${project.artifactId}-${project.version}</warName> <archive> <manifest> <mainClass>Main</mainClass> </manifest> </archive> </configuration> <executions> <execution> <id>default-war</id> <phase>package</phase> <goals> <goal>war</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.3</version> <executions> <execution> <phase>package</phase> <goals><goal>copy</goal></goals> <configuration> <artifactItems> <artifactItem> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-runner</artifactId> <version>${jetty.version}</version> <destFileName>jetty-runner.jar</destFileName> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> <!-- Failsafe plugin --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.17</version> <configuration> <systemPropertyVariables> <jetty.port>${jetty.port}</jetty.port> </systemPropertyVariables> </configuration> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>${cobertura.version}</version> <configuration> <check> <haltOnFailure>false</haltOnFailure> <totalLineRate>90</totalLineRate> <totalBranchRate>90</totalBranchRate> </check> <formats> <format>html</format> <format>xml</format> </formats> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>clean</goal> <goal>cobertura</goal> <goal>check</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.pitest</groupId> <artifactId>pitest-maven</artifactId> <version>1.0.0</version> <configuration> <targetClasses> <param>com.michaelszymczak.speccare.specminer*</param> </targetClasses> <targetTests> <param>com.michaelszymczak.speccare.specminer*</param> </targetTests> </configuration> </plugin> <!-- app server --> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>${jetty.version}</version> <configuration> <scanIntervalSeconds>5</scanIntervalSeconds> <stopKey>someStopKeyABC1234</stopKey> <stopPort>9998</stopPort> <systemProperties> <systemProperty> <name>jetty.port</name> <value>${jetty.port}</value> </systemProperty> </systemProperties> </configuration> <executions> <execution> <id>start-jetty</id> <phase>pre-integration-test</phase> <goals> <goal>start</goal> </goals> <configuration> <scanIntervalSeconds>0</scanIntervalSeconds> <daemon>true</daemon> </configuration> </execution> <execution> <id>stop-jetty</id> <phase>post-integration-test</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <profiles> <profile> <id>integration-tests</id> <build> <plugins> <plugin> <artifactId>maven-failsafe-plugin</artifactId> <version>2.12</version> <configuration> <includes> <include>**/*Tests.java</include> </includes> </configuration> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.7</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals> <goal>add-test-source</goal> </goals> <configuration> <sources> <source>src/it/java</source> </sources> </configuration> </execution> <execution> <id>add-resource</id> <phase>generate-sources</phase> <goals> <goal>add-test-resource</goal> </goals> <configuration> <resources> <resource> <directory>src/it/resources</directory> </resource> </resources> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project>
{ "content_hash": "f385f09c2eb741548a646e97e7e19f95", "timestamp": "", "source": "github", "line_count": 440, "max_line_length": 105, "avg_line_length": 35.65681818181818, "alnum_prop": 0.4420294473835171, "repo_name": "michaelszymczak/speccare-specminer", "id": "7838eb039d41d218e9a1d3329729ad53ab153a0c", "size": "15689", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pom.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "128450" }, { "name": "Shell", "bytes": "527" } ], "symlink_target": "" }
class TabbedPane; class SprocketWebContents; namespace views { class Label; class LabelButton; } // The tab view shown in the tab strip. class Tab : public views::View { public: // Internal class name. static const char kViewClassName[]; static const char kEmptyTab[]; Tab(TabbedPane* tabbed_pane, SprocketWebContents* sprocket_web_contents, views::View* contents); ~Tab() override; void SetTitle(const base::string16& title); views::View* contents() const { return contents_; } SprocketWebContents* sprocket_web_contents() const { return sprocket_web_contents_; } bool selected() const { return contents_->visible(); } void SetSelected(bool selected); // Overridden from views::View: bool OnMousePressed(const ui::MouseEvent& event) override; void OnMouseEntered(const ui::MouseEvent& event) override; void OnMouseExited(const ui::MouseEvent& event) override; gfx::Size GetPreferredSize() const override; void Layout() override; const char* GetClassName() const override; private: enum TabState { TAB_INACTIVE, TAB_ACTIVE, TAB_HOVERED, }; void SetState(TabState tab_state); TabbedPane* tabbed_pane_; views::LabelButton* close_button_; views::Label* title_; gfx::Size preferred_title_size_; TabState tab_state_; // The content view associated with this tab. views::View* contents_; SprocketWebContents* sprocket_web_contents_; DISALLOW_COPY_AND_ASSIGN(Tab); }; #endif // SPROCKET_BROWSER_UI_TAB_H
{ "content_hash": "d8237c5930c840ed4e73c7a68f91e7e4", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 87, "avg_line_length": 25.322033898305083, "alnum_prop": 0.7175368139223561, "repo_name": "szeged/sprocket", "id": "289601e711bac96832774423fed38f31dd205c10", "size": "1844", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/browser/ui/tab.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "601" }, { "name": "C++", "bytes": "177293" }, { "name": "HTML", "bytes": "136038" }, { "name": "Java", "bytes": "39208" } ], "symlink_target": "" }
////////////////////////////////////////////////////////////////// #ifndef H_SG_VV6DIFF__PRIVATE_TYPEDEFS_H #define H_SG_VV6DIFF__PRIVATE_TYPEDEFS_H BEGIN_EXTERN_C; ////////////////////////////////////////////////////////////////// struct _sg_vv6diff__diff_to_stream_data { SG_repo * pRepo; SG_pathname * pPathSessionTempDir; const char * pszTool; // name of file-tool to override suffix-based computed defaults. const char * pszDiffToolContext; // see SG_DIFFTOOL__CONTEXT__ "console" or "gui" const char * pszSubsectionLeft; const char * pszSubsectionRight; SG_vhash * pvhResultCodes; SG_bool bInteractive; // when GUI }; typedef struct _sg_vv6diff__diff_to_stream_data sg_vv6diff__diff_to_stream_data; ////////////////////////////////////////////////////////////////// END_EXTERN_C; #endif//H_SG_VV6DIFF__PRIVATE_TYPEDEFS_H
{ "content_hash": "a30696cb2d5db649d1adf35e8888bae8", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 89, "avg_line_length": 25.529411764705884, "alnum_prop": 0.5483870967741935, "repo_name": "glycerine/vj", "id": "b13e42771fbc4d972c9fad91366a239c8489d5a8", "size": "1430", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/veracity/src/libraries/vv2/vv6diff/sg_vv6diff__private_typedefs.h", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "305113" }, { "name": "C", "bytes": "16794809" }, { "name": "C++", "bytes": "23785718" }, { "name": "CMake", "bytes": "95243" }, { "name": "CSS", "bytes": "149452" }, { "name": "Gnuplot", "bytes": "691" }, { "name": "Groff", "bytes": "19029" }, { "name": "HTML", "bytes": "199269" }, { "name": "Java", "bytes": "849244" }, { "name": "JavaScript", "bytes": "8559068" }, { "name": "Makefile", "bytes": "274053" }, { "name": "Objective-C", "bytes": "91611" }, { "name": "Perl", "bytes": "170709" }, { "name": "Python", "bytes": "128973" }, { "name": "QMake", "bytes": "274" }, { "name": "Shell", "bytes": "424637" }, { "name": "TeX", "bytes": "230259" } ], "symlink_target": "" }
using System; using System.Web.Mvc; namespace FailTracker.Web.Infrastructure.ModelMetadata { public class RenderAttribute : Attribute, IMetadataAware { public bool ShowForEdit { get; set; } public bool ShowForDisplay { get; set; } public RenderAttribute() { ShowForEdit = true; ShowForDisplay = true; } public void OnMetadataCreated(System.Web.Mvc.ModelMetadata metadata) { metadata.ShowForEdit = ShowForEdit; metadata.ShowForDisplay = ShowForDisplay; } } }
{ "content_hash": "8df08b90bf819e4ed148f3fc9eb1fab4", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 70, "avg_line_length": 22.347826086956523, "alnum_prop": 0.708171206225681, "repo_name": "MattHoneycutt/Fail-Tracker", "id": "ba2e8e74af8d39bccb99431a9c3a920646b4c802", "size": "516", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "FailTracker.Web/Infrastructure/ModelMetadata/RenderAttribute.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "107" }, { "name": "C#", "bytes": "87043" }, { "name": "CSS", "bytes": "140545" }, { "name": "HTML", "bytes": "5275" }, { "name": "JavaScript", "bytes": "61217" } ], "symlink_target": "" }
package net.mindengine.blogix.config; import java.util.HashMap; import java.util.Map; import java.util.Properties; import net.mindengine.blogix.utils.BlogixFileUtils; import org.apache.commons.io.FileUtils; public class BlogixConfig { private static final String BLOGIX_SERVER_PORT = "blogix.server.port"; private static final String CUSTOM_USER_PROPERTY_PREFIX = "custom."; private static final int CUSTOM_USER_PROPERTY_LENGTH = CUSTOM_USER_PROPERTY_PREFIX.length(); private static final String MARKUP_CLASS = "markup.class"; private static final String DEFAULT_CONTROLLER_PACKAGES = "default.controller.packages"; private static final String DEFAULT_PROVIDER_PACKAGES = "default.provider.packages"; private static final String DEFAULT_PUBLIC_PATH = "public"; private static final String PUBLIC_PATH = "public.path"; private static final String BLOGIX_FILEDB_PATH = "blogix.db.path"; private Properties properties = new Properties(); private Map<String, String> userCustomProperties; private static final BlogixConfig _instance = new BlogixConfig(); private static final String MARKUP_PLUGINS_FOLDER = "markup.plugins.folder"; private BlogixConfig() { try { properties.load(FileUtils.openInputStream(BlogixFileUtils.findFile("conf/properties"))); userCustomProperties = loadUserCustomProperties(); } catch (Exception e) { throw new RuntimeException("Cannot load blogix properties", e); } } private Map<String, String> loadUserCustomProperties() { Map<String, String> map = new HashMap<String, String>(); for (Map.Entry<Object, Object> entry : properties.entrySet()) { String name = entry.getKey().toString(); if (isPropertyUserCustom(name)) { map.put(stripUserProperty(name), entry.getValue().toString()); } } return map; } private String stripUserProperty(String name) { return name.substring(CUSTOM_USER_PROPERTY_LENGTH); } private boolean isPropertyUserCustom(String name) { return name.startsWith(CUSTOM_USER_PROPERTY_PREFIX); } public static BlogixConfig getConfig() { return _instance; } public String[] getDefaultProviderPackages() { String value = (String) properties.get(DEFAULT_PROVIDER_PACKAGES); if ( value != null && !value.isEmpty() ) { return value.trim().split(","); } return new String[]{}; } public String[] getDefaultControllerPackages() { String value = (String) properties.get(DEFAULT_CONTROLLER_PACKAGES); if ( value != null && !value.isEmpty() ) { return value.trim().split(","); } return new String[]{}; } public String getPublicPath() { return properties.getProperty(PUBLIC_PATH, DEFAULT_PUBLIC_PATH); } public String getMarkupClass() { return (String) properties.get(MARKUP_CLASS); } public String getBlogixFileDbPath() { return properties.getProperty(BLOGIX_FILEDB_PATH); } public void removeProperty(String propertyName) { properties.remove(propertyName); } public void setProperty(String name, String value) { properties.setProperty(MARKUP_CLASS, value); } public String getProperty(String name, String defaultValue) { return properties.getProperty(name, defaultValue); } public Map<String, String> getUserCustomProperties() { return userCustomProperties; } public String getMarkupPluginsFolder() { return (String) properties.getProperty(MARKUP_PLUGINS_FOLDER); } public int getBlogixServerPort() { return Integer.parseInt(properties.getProperty(BLOGIX_SERVER_PORT, "8080")); } }
{ "content_hash": "97b5ea4304b13d14d075f82572e486a2", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 100, "avg_line_length": 33.66086956521739, "alnum_prop": 0.6677861017824851, "repo_name": "ishubin/blogix", "id": "cbf05ab8fd7633d0e280a208660e21a542f16b2f", "size": "4629", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/net/mindengine/blogix/config/BlogixConfig.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "13789" }, { "name": "Java", "bytes": "311995" }, { "name": "JavaScript", "bytes": "40910" }, { "name": "Shell", "bytes": "2678" } ], "symlink_target": "" }
- New APIS to support thumbnail previews in Push Notifications: `[Bit6PushNotificationCenter isIncomingMessageNotification:]`, `[Bit6 messageWithIdentifier:completion:]` and `[Bit6Message downloadThumbnailWithCompletionHandler:]`. It's necessary to define an App Group Identifier for the application and set it with `[Bit6 setAppGroupIdentifier:]`. - Support for new UNUserNotificationCenter in iOS10 - `Bit6.activeCalls()` doesn't return all the calls attached to a Bit6CallViewController subclass. Please use `Bit6CallViewController.callControllers` instead. ### Bugfixes (Core) - switching between cameras before the call starts doesn't work - crashes when interacting with the push notification actions in the incoming call push notifications. - Bit6.session.activeDisplayName wasn't used as caller name. - For group calls Bit6CallController.otherDisplayName wasn't set correctly to the subject of the group. ### Features (UI) - Easy to implement PeekAndPop for thumbnails in `BXUMessageTableViewController` by implementing the `UIViewControllerPreviewingDelegate` protocol. Added `BXUAttachmentImageView.message` property to get the message linked to the thumbnail. ## 0.10.0 [2016-09-08] ### Breaking Changes - The `Bit6.pushNotification` methods to handle push notifications have been renamed, for example from `didReceiveRemoteNotification:fetchCompletionHandler:` to `didReceiveNotificationUserInfo:fetchCompletionHandler:`. See the sample apps for the complete implementation. - On iOS10 it's necessary to implement `[UIApplicationDelegate application:didReceiveRemoteNotification:]` and in it to call `[Bit6.pushNotification didReceiveNotificationUserInfo:];` - Dropped iOS7 support. - `Bit6.callcontrollers` now return all the calls: inactive / actives / ended. To get the list of active calls use `Bit6.activeCalls` instead. - `Bit6CallState_MISSED` and `Bit6CallState_ERROR` were replaced by `Bit6CallController.missed` and `Bit6CallController.error` properties. - `Bit6RTStatus` enum replaced by `Bit6WebSocketReadyState`. - Bit6CallController.decline() has been replaced by Bit6CallController.hangup() - Incoming calls from `Bit6IncomingCallNotification` no longer set the remoteStreams automatically. Before answering the call remember to do `call.remoteStreams = call.availableStreamsForIncomingCall;` and `call.localStreams = call.availableStreamsForIncomingCall`. - Bit6TransferUpdateNotification has been removed. Use `Bit6CallControllerDelegate` instead. ### Features (Core) - VoIP Push Notifications support for incoming calls. Please follow this [guide](http://docs.bit6.com/guides/push-apns/#environments) to configure it. Also now, in your ApplicationDelegate you need to handle local notifications, please see [Push Notifications](http://docs.bit6.com/guides/ios-intro/#application-delegate). - New methods to detect when the local video feed is interrupted by the system. - new method Bit6Group.setRole:forMember:completion: to change a member role in a group. ### Bugfixes (Core) - Issues with resize of video feeds for rotation in Bit6CallViewController - Issues to mark individual messages as READ. - The automatic download of attachments could happen before setting Bit6.setDownloadAudioRecordings() property and others - Issues with video interruptions during a call could cause the local video feed to not be restored. - Bit6Group.createGroupWithMetadata:completion: wasn't setting the metadata after creating the group. ### Features (UI) - support for Bit6.setDownloadAudioRecordings() - BXUMessageTableViewController now has methods to customize the supported attachments. - BXUMessageTableViewController now can show a single emoji message 3x its size using the property `biggerEmojis`. ### Bugfixes (UI) - BXUContactAvatarImageView initials label weren't shown centered - On BXUConversationList, if the cell is showing "typing" and the user selects the cell you can see the last message on top of "typing" label. ## 0.9.8 [2016-05-24] ### Changes (Core) - `[Bit6CallController callStateChangedNotificationForCall:]` and `[Bit6CallController secondsChangedNotificationForCall]` are now deprecated in favor of `Bit6CallControllerDelegate`. - It's not recommented the usage of KVO to listen to Bit6CallController notifications. Now `[callController addObserver:... forKeyPath:@"state" options:NSKeyValueObservingOptionOld context:NULL]` should be replaced by the usage of `Bit6CallControllerDelegate`. ### Changes (UI) - BXUWebSocketStatusLabel now uses a delegate to customize its behavior instead of `viewsWhileConnecting` and `viewsWhenConnected` properties. - BXUIncomingCallPrompt is now customizable by using `setContentViewGenerator(frame)` instead of `setContentView()`. ### Bugfixes (Core) - DataChannel transfer fails in the initial seconds of a call - callController.otherDisplayName could be reset to nil for Missed Calls - calls might not connect if Bit6.session.activeDisplayName was used ### Bugfixes (UI) - BXUIncomingCallPrompt now can answer audio and video calls with data stream component. - Setting callController.otherDisplayName in BXUIncomingCallPrompt only works for existing BXUContacts - BXUIncomingCallPrompt wasn't shown in the center of the application if the application was running in iOS9 SlideOver or SplitView. ## 0.9.7 [2016-04-22] ### Breaking Changes - All UI related classes (like Bit6ThumbnailImageView and Bit6ImageView) have been moved to UI lib. - To handle incoming calls and to prepare the in-call UI you need to register for `Bit6IncomingCallNotification` and `Bit6CallAddedNotification`. To handle errors because of video and mic restricted access you can listen to `Bit6CallPermissionsMissingNotification`. - [Bit6 createCallTo:streams:] replaced with [Bit6 startCallTo:streams:] and [Bit6 createCallToPhoneNumber:] replaced with [Bit6 startPhoneCallTo:]. - To use an in-call viewcontroller its classname must be set in your target's info.plist and then call `[Bit6 createViewControllerForCall]` to create the object. - Bit6CallViewController subclasses need to implement `callStateChangedNotificationForCall:` and `secondsChangedNotificationForCall:` instead of `callStateChangedNotificationForCallController:` and `secondsChangedNotificationForCallController:`. Please check the startup guide for a complete list of necessary methods to implement. - Added localization to messages and calls. A Localizable.strings file is needed in the project (see sample apps) - Bit6CallController.callState has been renamed to Bit6CallController.state, please make sure this is considered if listening to KVO notifications. ### Features - Support for quick reply in message push notifications - Methods to handle the cache directory: cacheSize(), numberOfItemsInCache() and clearCache() ### Bugfixes - Bit6.presentCallViewController() doesn't present the in-call screen if there's a UIViewController being presented modally. - 'decline' option in push notifications for incoming calls doesn't work. - Bit6Session.publicProfile has no content after a login through facebook and other services. - fails to detect when a push notification has been tapped by the user or not. - push notifications aren't sent correcly when apps are running in AdHoc distributions - issues with video feeds inside in-call screen when using it for many calls. ## 0.9.6 [2016-02-13] ### Features - Framework is built using Modules, so it's easy to import to your Swift projects. - Many API improvements in the SDK to make it work better when working with Optionals and collections in Swift. - Simpler API to start the Bit6 service. - Easier to clear the unread messages badge from a conversation object. - A more generic API using Bit6CallStreams to do calls with different streams: Audio, Video and Data. - Cleaner APIs for the creation of Bit6Address objects. - Bit6AudioPlayerController and Bit6AudioRecorderController now work without requering a Bit6Message object. - More robust list of statuses for Bit6CallController objects. - Added API to enable audio through bluetooth devices during a call. - Improved API to start a Bit6OutgoingTransfer. - Easier implementation of a custom incoming call handlers. - New customizable Bit6IncomingCallPrompt to show a nice looking prompt when an incoming call arrives. - New Bit6FileDownloader class to add downloads of any file to the main queue. - Cleaner API to get the path and status attachment of Bit6Message. - Bit6Session now supports external authentication providers like Digits, Telerik, Parse and others. ### Bugfixes - Calls not connecting - Syncing of groups members and roles fail from time to time. - Ringtone sound goes through earphone instead of speaker.
{ "content_hash": "fb9d474402cbaa227e9a22ec87e43ff5", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 348, "avg_line_length": 74.89655172413794, "alnum_prop": 0.8108885819521179, "repo_name": "bit6/bit6-ios-sdk", "id": "ce13be2d46b3cb33f176a117eaf940a5a58974e4", "size": "8732", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1308" }, { "name": "CSS", "bytes": "18960" }, { "name": "HTML", "bytes": "1104884" }, { "name": "Objective-C", "bytes": "901419" }, { "name": "Ruby", "bytes": "2251" }, { "name": "Swift", "bytes": "104051" } ], "symlink_target": "" }
namespace Azure.Graph.Rbac.Models { /// <summary> Request parameters for updating an existing work or school account user. </summary> public partial class UserUpdateParameters : UserBase { /// <summary> Initializes a new instance of UserUpdateParameters. </summary> public UserUpdateParameters() { } /// <summary> Whether the account is enabled. </summary> public bool? AccountEnabled { get; set; } /// <summary> The display name of the user. </summary> public string DisplayName { get; set; } /// <summary> The password profile of the user. </summary> public PasswordProfile PasswordProfile { get; set; } /// <summary> The user principal name (someuser@contoso.com). It must contain one of the verified domains for the tenant. </summary> public string UserPrincipalName { get; set; } /// <summary> The mail alias for the user. </summary> public string MailNickname { get; set; } /// <summary> The primary email address of the user. </summary> public string Mail { get; set; } } }
{ "content_hash": "48d8e76e8942ccf8cba331d41691f20a", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 140, "avg_line_length": 46.916666666666664, "alnum_prop": 0.6412078152753108, "repo_name": "Azure/azure-sdk-for-net", "id": "1a8b06fa5d1c18781d7bcb758502124c9408f858", "size": "1264", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/testcommon/Azure.Graph.Rbac/src/Generated/Models/UserUpdateParameters.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import os import sys sys.path.insert(0, os.path.abspath('../..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = 'zof' copyright = '2017, William W. Fisher' author = 'William W. Fisher' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '' # The full version, including alpha/beta/rc tags. release = '' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'zofdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'zof.tex', 'zof Documentation', 'William W. Fisher', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'zof', 'zof Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'zof', 'zof Documentation', author, 'zof', 'One line description of project.', 'Miscellaneous'), ]
{ "content_hash": "5d14602da3c357e01a03e5e02579a6a6", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 78, "avg_line_length": 29.3768115942029, "alnum_prop": 0.6566354218056241, "repo_name": "byllyfish/pylibofp", "id": "382632a31df23cdda16663a95f8e9aec6e8768a8", "size": "4733", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/sphinx/conf.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "155886" }, { "name": "Shell", "bytes": "443" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Vonage\Voice\NCCO; use InvalidArgumentException; use Vonage\Voice\Endpoint\EndpointFactory; use Vonage\Voice\NCCO\Action\ActionInterface; use Vonage\Voice\NCCO\Action\Connect; use Vonage\Voice\NCCO\Action\Conversation; use Vonage\Voice\NCCO\Action\Input; use Vonage\Voice\NCCO\Action\Notify; use Vonage\Voice\NCCO\Action\Record; use Vonage\Voice\NCCO\Action\Stream; use Vonage\Voice\NCCO\Action\Talk; class NCCOFactory { /** * @param $data */ public function build($data): ActionInterface { switch ($data['action']) { case 'connect': $factory = new EndpointFactory(); $endpoint = $factory->create($data['endpoint'][0]); if (null !== $endpoint) { return Connect::factory($endpoint); } throw new InvalidArgumentException("Malformed NCCO Action " . $data['endpoint'][0]); case 'conversation': return Conversation::factory($data['name'], $data); case 'input': return Input::factory($data); case 'notify': return Notify::factory($data['payload'], $data); case 'record': return Record::factory($data); case 'stream': return Stream::factory($data['streamUrl'], $data); case 'talk': return Talk::factory($data['text'], $data); default: throw new InvalidArgumentException("Unknown NCCO Action " . $data['action']); } } }
{ "content_hash": "1da94f9950f7eb03c6cff9e5d9d9b119", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 100, "avg_line_length": 30.39622641509434, "alnum_prop": 0.5760397268777157, "repo_name": "Nexmo/nexmo-php", "id": "27f4a530adb5ef7911ef5a4ce782be61408fa501", "size": "1826", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Voice/NCCO/NCCOFactory.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "612032" } ], "symlink_target": "" }
class <%= class_name %>Classifier < ApplicationService end
{ "content_hash": "8dbd326cbc58cef0d56e9c01dbddfd91", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 54, "avg_line_length": 20, "alnum_prop": 0.75, "repo_name": "yuma300/railsenginetest", "id": "976750b6fb233879f63535e3678adc7e2afa6bac", "size": "60", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/generators/classifier/templates/classifier.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1092" }, { "name": "JavaScript", "bytes": "1198" }, { "name": "Ruby", "bytes": "14560" } ], "symlink_target": "" }
import sys sys.path.insert(1,"../../") import h2o from tests import pyunit_utils def scale_pca_rf_pipe(): from h2o.transforms.preprocessing import H2OScaler from h2o.transforms.decomposition import H2OPCA from h2o.estimators.random_forest import H2ORandomForestEstimator from sklearn.pipeline import Pipeline iris = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris_wheader.csv")) # build transformation pipeline using sklearn's Pipeline and H2O transforms pipe = Pipeline([("standardize", H2OScaler()), ("pca", H2OPCA(k=2)), ("rf", H2ORandomForestEstimator(seed=42,ntrees=50))]) pipe.fit(iris[:4],iris[4]) pca = pipe.named_steps['pca'] assert pca.model_id == pca._delegate.model_id assert pca._model_json == pca._delegate._model_json pca.download_pojo() def scale_pca_rf_pipe_new_import(): from h2o.transforms.preprocessing import H2OScaler from h2o.estimators.pca import H2OPrincipalComponentAnalysisEstimator from h2o.estimators.random_forest import H2ORandomForestEstimator from sklearn.pipeline import Pipeline iris = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris_wheader.csv")) # build transformation pipeline using sklearn's Pipeline and H2O estimators without H2OPrincipalComponentAnalysisEstimator.init_for_pipeline() # it should fail # Note: if you use PCA algo in a different combination of pipeline tasks, it could not fail, for example # if you comment line with H2ORandomForestEstimator task, the fit method doesn't fail because the pipeline doesn't # use _fit_transform_one method thus does not use H2OPrincipalComponentAnalysisEstimator.transform method try: pipe = Pipeline([ ("standardize", H2OScaler()), ("pca", H2OPrincipalComponentAnalysisEstimator(k=2)), ("rf", H2ORandomForestEstimator(seed=42,ntrees=5)) ]) pipe.fit(iris[:4], iris[4]) assert False, "Pipeline should fail without using H2OPrincipalComponentAnalysisEstimator.init_for_pipeline()" except TypeError: pass # build transformation pipeline using sklearn's Pipeline and H2O estimators with H2OPrincipalComponentAnalysisEstimator.init_for_pipeline() pipe = Pipeline([("standardize", H2OScaler()), ("pca", H2OPrincipalComponentAnalysisEstimator(k=2).init_for_pipeline()), ("rf", H2ORandomForestEstimator(seed=42,ntrees=5))]) pipe.fit(iris[:4], iris[4]) print(pipe) # set H2OPCA transform property pca = H2OPrincipalComponentAnalysisEstimator(k=2) pca.transform = "standardize" pipe = Pipeline([("standardize", H2OScaler()), ("pca", pca.init_for_pipeline()), ("rf", H2ORandomForestEstimator(seed=42,ntrees=5))]) pipe.fit(iris[:4], iris[4]) print(pipe) if __name__ == "__main__": pyunit_utils.standalone_test(scale_pca_rf_pipe) pyunit_utils.standalone_test(scale_pca_rf_pipe_new_import) else: scale_pca_rf_pipe() scale_pca_rf_pipe_new_import()
{ "content_hash": "10e314c7958eda19f078bf6bb0a6e710", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 144, "avg_line_length": 40.85333333333333, "alnum_prop": 0.7033289817232375, "repo_name": "michalkurka/h2o-3", "id": "111c5b1286557d763ca839da55f51c94bf2a3d62", "size": "3064", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "h2o-py/tests/testdir_pipeline/pyunit_scale_pca_rf.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "12629" }, { "name": "CSS", "bytes": "231770" }, { "name": "CoffeeScript", "bytes": "7550" }, { "name": "Dockerfile", "bytes": "10302" }, { "name": "Emacs Lisp", "bytes": "2226" }, { "name": "Groovy", "bytes": "166480" }, { "name": "HCL", "bytes": "15007" }, { "name": "HTML", "bytes": "251906" }, { "name": "HiveQL", "bytes": "3965" }, { "name": "Java", "bytes": "11932863" }, { "name": "JavaScript", "bytes": "89484" }, { "name": "Jupyter Notebook", "bytes": "13867219" }, { "name": "Makefile", "bytes": "50635" }, { "name": "Python", "bytes": "6801044" }, { "name": "R", "bytes": "3223113" }, { "name": "Ruby", "bytes": "3506" }, { "name": "Scala", "bytes": "33647" }, { "name": "Shell", "bytes": "186559" }, { "name": "TeX", "bytes": "634412" } ], "symlink_target": "" }
DROP FUNCTION IF EXISTS account.can_register_with_google(); CREATE FUNCTION account.can_register_with_google() RETURNS boolean AS $$ BEGIN IF EXISTS ( SELECT 1 FROM account.configuration_profiles WHERE is_active AND allow_registration AND allow_google_registration ) THEN RETURN true; END IF; RETURN false; END $$ LANGUAGE plpgsql;
{ "content_hash": "5dd240d09f4f2b1421869972ab02adf2", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 59, "avg_line_length": 18.952380952380953, "alnum_prop": 0.6658291457286433, "repo_name": "nubiancc/frapid", "id": "5b6b8cedebc658a7d871e8c9c5d3052c308652ea", "size": "398", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Frapid.Web/Areas/Frapid.Account/db/1.x/1.0/src/02.functions-and-logic/account.can_register_with_google.sql", "mode": "33188", "license": "mit", "language": [ { "name": "ABAP", "bytes": "962" }, { "name": "ASP", "bytes": "101" }, { "name": "ActionScript", "bytes": "1133" }, { "name": "Ada", "bytes": "99" }, { "name": "Assembly", "bytes": "549" }, { "name": "AutoHotkey", "bytes": "720" }, { "name": "Batchfile", "bytes": "1029" }, { "name": "C#", "bytes": "5093309" }, { "name": "C++", "bytes": "806" }, { "name": "COBOL", "bytes": "4" }, { "name": "CSS", "bytes": "8735933" }, { "name": "Cirru", "bytes": "520" }, { "name": "Clojure", "bytes": "794" }, { "name": "CoffeeScript", "bytes": "403" }, { "name": "ColdFusion", "bytes": "86" }, { "name": "Common Lisp", "bytes": "632" }, { "name": "Cucumber", "bytes": "699" }, { "name": "D", "bytes": "324" }, { "name": "Dart", "bytes": "489" }, { "name": "Eiffel", "bytes": "375" }, { "name": "Elixir", "bytes": "692" }, { "name": "Elm", "bytes": "487" }, { "name": "Erlang", "bytes": "487" }, { "name": "Forth", "bytes": "979" }, { "name": "FreeMarker", "bytes": "1017" }, { "name": "GLSL", "bytes": "512" }, { "name": "Go", "bytes": "641" }, { "name": "Groff", "bytes": "2072" }, { "name": "Groovy", "bytes": "1080" }, { "name": "HTML", "bytes": "635450" }, { "name": "Haskell", "bytes": "512" }, { "name": "Haxe", "bytes": "447" }, { "name": "Io", "bytes": "140" }, { "name": "JSONiq", "bytes": "4" }, { "name": "Java", "bytes": "1550" }, { "name": "JavaScript", "bytes": "30339436" }, { "name": "Julia", "bytes": "210" }, { "name": "LSL", "bytes": "2080" }, { "name": "Lean", "bytes": "213" }, { "name": "Liquid", "bytes": "1883" }, { "name": "LiveScript", "bytes": "5790" }, { "name": "Lua", "bytes": "981" }, { "name": "Makefile", "bytes": "4774" }, { "name": "Mask", "bytes": "597" }, { "name": "Matlab", "bytes": "203" }, { "name": "Nix", "bytes": "2212" }, { "name": "OCaml", "bytes": "539" }, { "name": "Objective-C", "bytes": "2672" }, { "name": "OpenSCAD", "bytes": "333" }, { "name": "PHP", "bytes": "351" }, { "name": "Pascal", "bytes": "263174" }, { "name": "Perl", "bytes": "678" }, { "name": "PowerShell", "bytes": "346828" }, { "name": "Protocol Buffer", "bytes": "274" }, { "name": "Puppet", "bytes": "6404" }, { "name": "Python", "bytes": "478" }, { "name": "R", "bytes": "2445" }, { "name": "Ruby", "bytes": "531" }, { "name": "Rust", "bytes": "495" }, { "name": "SQLPL", "bytes": "30159" }, { "name": "Scala", "bytes": "1541" }, { "name": "Scheme", "bytes": "559" }, { "name": "Shell", "bytes": "1154" }, { "name": "Swift", "bytes": "476" }, { "name": "Tcl", "bytes": "899" }, { "name": "TeX", "bytes": "1345" }, { "name": "TypeScript", "bytes": "1607" }, { "name": "VHDL", "bytes": "830" }, { "name": "Vala", "bytes": "485" }, { "name": "Verilog", "bytes": "274" }, { "name": "Visual Basic", "bytes": "916" }, { "name": "XQuery", "bytes": "114" } ], "symlink_target": "" }
<?php use yii\apidoc\helpers\ApiMarkdown; use yii\apidoc\models\ClassDoc; use yii\apidoc\models\InterfaceDoc; use yii\apidoc\models\TraitDoc; use yii\apidoc\templates\bootstrap\ApiRenderer; use yii\web\View; /* @var ClassDoc[]|InterfaceDoc[]|TraitDoc[] $types */ /* @var string|null $readme */ /* @var View $this */ /** @var ApiRenderer $renderer */ $renderer = $this->context; ksort($types); if (isset($readme)) { echo ApiMarkdown::process($readme); } ?> <h1>Class Reference</h1> <table class="summaryTable docIndex table table-bordered table-striped table-hover"> <colgroup> <col class="col-class"> <col class="col-description"> </colgroup> <thead> <tr> <th>Class</th> <th>Description</th> </tr> </thead> <tbody> <?php foreach ($types as $class) { ?> <tr> <td><?= $renderer->createTypeLink($class, $class, $class->name) ?></td> <td><?= ApiMarkdown::process($class->shortDescription, $class, true) ?></td> </tr> <?php } ?> </tbody> </table>
{ "content_hash": "443c15b9fa7adfa0eb29d94b9b991f48", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 92, "avg_line_length": 25.09090909090909, "alnum_prop": 0.5869565217391305, "repo_name": "yiisoft/yii2-apidoc", "id": "95f91e4db3b27dbf8b8808c5303521b4c8fb153d", "size": "1104", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/bootstrap/views/index.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "518" }, { "name": "CSS", "bytes": "5257" }, { "name": "Makefile", "bytes": "597" }, { "name": "PHP", "bytes": "213114" }, { "name": "TeX", "bytes": "4255" } ], "symlink_target": "" }
<html dir="LTR"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" /> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" /> <title>Next Method</title> <xml> </xml> <link rel="stylesheet" type="text/css" href="MSDN.css" /> </head> <body id="bodyID" class="dtBODY"> <div id="nsbanner"> <div id="bannerrow1"> <table class="bannerparthead" cellspacing="0"> <tr id="hdr"> <td class="runninghead">Apache Lucene.Net 2.4.0 Class Library API</td> <td class="product"> </td> </tr> </table> </div> <div id="TitleRow"> <h1 class="dtH1">PorterStemFilter.Next Method</h1> </div> </div> <div id="nstext"> <p> </p> <h4 class="dtH4">Overload List</h4> <p>Inherited from <a href="Lucene.Net.Analysis.TokenStream.html">TokenStream</a>.</p> <blockquote class="dtBlock"> <a href="Lucene.Net.Analysis.TokenStream.Next_overloads.html">public virtual Token Next();</a> </blockquote> <p> </p> <blockquote class="dtBlock"> <a href="Lucene.Net.Analysis.PorterStemFilter.Next_overload_1.html">public override Token Next(Token);</a> </blockquote> <h4 class="dtH4">See Also</h4> <p> <a href="Lucene.Net.Analysis.PorterStemFilter.html">PorterStemFilter Class</a> | <a href="Lucene.Net.Analysis.html">Lucene.Net.Analysis Namespace</a></p> <hr /> <div id="footer"> <p> </p> <p>Generated from assembly Lucene.Net [2.4.0.2]</p> </div> </div> </body> </html>
{ "content_hash": "ad9be5a5f6f27db6f3a0138fe4b572cd", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 161, "avg_line_length": 35.791666666666664, "alnum_prop": 0.5628637951105937, "repo_name": "Mpdreamz/lucene.net", "id": "71d0c1d5554e90a0ab237bf3ae4d243cc13e9c57", "size": "1718", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/core/Lucene.Net.Analysis.PorterStemFilter.Next_overloads.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package io.aos.endpoint.socket.nio.fwk2; /* * @(#)RequestHandler.java 1.5 10/03/23 * * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Oracle or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */ import java.io.*; import java.nio.*; import java.nio.channels.*; /** * Primary driver class used by non-blocking Servers to receive, * prepare, send, and shutdown requests. * * @author Mark Reinhold * @author Brad R. Wetmore * @version 1.5, 10/03/23 */ class RequestHandler implements Handler { private ChannelIO cio; private ByteBuffer rbb = null; private boolean requestReceived = false; private Request request = null; private Reply reply = null; private static int created = 0; RequestHandler(ChannelIO cio) { this.cio = cio; // Simple heartbeat to let user know we're alive. synchronized (RequestHandler.class) { created++; if ((created % 50) == 0) { System.out.println("."); created = 0; } else { System.out.print("."); } } } // Returns true when request is complete // May expand rbb if more room required // private boolean receive(SelectionKey sk) throws IOException { ByteBuffer tmp = null; if (requestReceived) { return true; } if (!cio.doHandshake(sk)) { return false; } if ((cio.read() < 0) || Request.isComplete(cio.getReadBuf())) { rbb = cio.getReadBuf(); return (requestReceived = true); } return false; } // When parse is successfull, saves request and returns true // private boolean parse() throws IOException { try { request = Request.parse(rbb); return true; } catch (MalformedRequestException x) { reply = new Reply(Reply.Code.BAD_REQUEST, new StringContent(x)); } return false; } // Ensures that reply field is non-null // private void build() throws IOException { Request.Action action = request.action(); if ((action != Request.Action.GET) && (action != Request.Action.HEAD)) { reply = new Reply(Reply.Code.METHOD_NOT_ALLOWED, new StringContent(request.toString())); } reply = new Reply(Reply.Code.OK, new FileContent(request.uri()), action); } public void handle(SelectionKey sk) throws IOException { try { if (request == null) { if (!receive(sk)) return; rbb.flip(); if (parse()) build(); try { reply.prepare(); } catch (IOException x) { reply.release(); reply = new Reply(Reply.Code.NOT_FOUND, new StringContent(x)); reply.prepare(); } if (send()) { // More bytes remain to be written sk.interestOps(SelectionKey.OP_WRITE); } else { // Reply completely written; we're done if (cio.shutdown()) { cio.close(); reply.release(); } } } else { if (!send()) { // Should be rp.send() if (cio.shutdown()) { cio.close(); reply.release(); } } } } catch (IOException x) { String m = x.getMessage(); if (!m.equals("Broken pipe") && !m.equals("Connection reset by peer")) { System.err.println("RequestHandler: " + x.toString()); } try { /* * We had a failure here, so we'll try to be nice * before closing down and send off a close_notify, * but if we can't get the message off with one try, * we'll just shutdown. */ cio.shutdown(); } catch (IOException e) { // ignore } cio.close(); if (reply != null) { reply.release(); } } } private boolean send() throws IOException { try { return reply.send(cio); } catch (IOException x) { if (x.getMessage().startsWith("Resource temporarily")) { System.err.println("## RTA"); return true; } throw x; } } }
{ "content_hash": "12e1ef0902135fd43406565f94592871", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 79, "avg_line_length": 27.482233502538072, "alnum_prop": 0.657739194680458, "repo_name": "XClouded/t4f-core", "id": "09ead75383b450ebfad1516725ff3ccbc2479353", "size": "6602", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/io/src/main/java/io/aos/endpoint/socket/nio/fwk2/RequestHandler.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php /** * @author Łukasz Pior <pior.lukasz@gmail.com> */ namespace Seven\RpcBundle\Tests\Transport; class TransportCurlTest extends \PHPUnit_Framework_TestCase { /** * @expectedException \Seven\RpcBundle\Rpc\Exception\CurlTransportException * * @dataProvider providerMakeRequestWithCurlError */ public function testMakeRequestWithCurlError($errorCode, $errorMessage) { $transportMock = $this->getMock("Seven\\RpcBundle\\Rpc\\Transport\\TransportCurl", array( "getCurlRequest" )); $requestMock = $this->getMock("Symfony\\Component\\HttpFoundation\\Request"); $curlRequestMock = $this->getMock("Seven\\RpcBundle\\Rpc\\Transport\\Curl\\CurlRequest", array( "execute", "getErrorNumber", "getErrorMessage" )); $curlRequestMock->expects($this->once()) ->method('execute') ->will($this->returnValue(false)); $curlRequestMock->expects($this->once()) ->method('getErrorNumber') ->will($this->returnValue($errorCode)); $curlRequestMock->expects($this->once()) ->method('getErrorMessage') ->will($this->returnValue($errorMessage)); $transportMock->expects($this->once()) ->method('getCurlRequest') ->will($this->returnValue($curlRequestMock)); $transportMock->makeRequest($requestMock); } public function providerMakeRequestWithCurlError() { return array( array(CURLE_COULDNT_CONNECT, "Failed to connect() to host or proxy."), array(CURLE_OPERATION_TIMEOUTED, "Operation timeout. The specified time-out period was reached according to the conditions."), ); } }
{ "content_hash": "41dc7fdaa4eefabfe44e44453355ff73", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 138, "avg_line_length": 31.714285714285715, "alnum_prop": 0.6216216216216216, "repo_name": "skolodyazhnyy/symfony-rpc-bundle", "id": "4bb4c8a029e5e2a3e0ca2cac1af8c194a27dfcd7", "size": "1777", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tests/Rpc/Transport/TransportCurlTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "100070" } ], "symlink_target": "" }
package com.sap.belajar.domain; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="role") public class Role { @Id @GeneratedValue @Column(name="id") private Integer id; @Column(name="name",nullable=false) private String name; @Column(name="description",nullable=false) private String description; @Column(name="created_by",nullable=false) private String createdBy; @Column(name="created_at",nullable=false) private Date createdAt = new Date(); @Column(name="updated_by") private String updatedBy; @Column(name="updated_at") private Date updatedAt = new Date(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public String getUpdatedBy() { return updatedBy; } public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } }
{ "content_hash": "e0c0166c62d3303607ddedec4bb3d55c", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 49, "avg_line_length": 22.15068493150685, "alnum_prop": 0.7340754483611627, "repo_name": "adityapratama/spring-mvc-template", "id": "58431c8a3b2dd3eeea752107f2c64205a0eab635", "size": "1617", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "belajar/belajar-domain/src/main/java/com/sap/belajar/domain/Role.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "10317" } ], "symlink_target": "" }
'use strict'; const fs = require('fs'); const path = require('path'); const Readable = require('stream').Readable; // Parameters for safe file name parsing. const SAFE_FILE_NAME_REGEX = /[^\w-]/g; const MAX_EXTENSION_LENGTH = 3; // Parameters which used to generate unique temporary file names: const TEMP_COUNTER_MAX = 65536; const TEMP_PREFIX = 'tmp'; let tempCounter = 0; /** * Logs message to console if debug option set to true. * @param {Object} options - options object. * @param {String} msg - message to log. * @returns {Boolean} */ const debugLog = (options, msg) => { options = options || {}; if (!options.debug) return false; console.log(msg); // eslint-disable-line return true; }; /** * Generates unique temporary file name like: tmp-5000-156788789789. * @param prefix {String} - a prefix for generated unique file name. * @returns {String} */ const getTempFilename = (prefix) => { prefix = prefix || TEMP_PREFIX; tempCounter = tempCounter >= TEMP_COUNTER_MAX ? 1 : tempCounter + 1; return `${prefix}-${tempCounter}-${Date.now()}`; }; /** * Returns true if argument is a function. * @returns {Boolean} */ const isFunc = func => func && func.constructor && func.call && func.apply ? true: false; /** * Set errorFunc to the same value as successFunc for callback mode. * @returns {Function} */ const errorFunc = (resolve, reject) => isFunc(reject) ? reject : resolve; /** * Return a callback function for promise resole/reject args. * @returns {Function} */ const promiseCallback = (resolve, reject) => { return err => err ? errorFunc(resolve, reject)(err) : resolve(); }; /** * Builds instance options from arguments objects(can't be arrow function). * @returns {Object} - result options. */ const buildOptions = function(){ const result = {}; [...arguments].forEach(options => { if (!options || typeof options !== 'object') return; Object.keys(options).forEach(key => result[key] = options[key]); }); return result; }; /** * Builds request fields (using to build req.body and req.files) * @param {Object} instance - request object. * @param {String} field - field name. * @param value - field value. * @returns {Object} */ const buildFields = (instance, field, value) => { // Do nothing if value is not set. if (value === null || value === undefined) return instance; instance = instance || {}; // Non-array fields if (!instance[field]) { instance[field] = value; } else { // Array fields if (instance[field] instanceof Array) { instance[field].push(value); } else { instance[field] = [instance[field], value]; } } return instance; }; /** * Creates a folder for file specified in the path variable * @param {Object} fileUploadOptions * @param {String} filePath * @returns {Boolean} */ const checkAndMakeDir = (fileUploadOptions, filePath) => { // Check upload options were set. if (!fileUploadOptions) return false; if (!fileUploadOptions.createParentPath) return false; // Check whether folder for the file exists. if (!filePath) return false; const parentPath = path.dirname(filePath); // Create folder if it is not exists. if (!fs.existsSync(parentPath)) fs.mkdirSync(parentPath, { recursive: true }); // Checks folder again and return a results. return fs.existsSync(parentPath); }; /** * Delete file. * @param {String} file - Path to the file to delete. */ const deleteFile = (file, callback) => fs.unlink(file, err => err ? callback(err) : callback()); /** * Copy file via streams * @param {String} src - Path to the source file * @param {String} dst - Path to the destination file. */ const copyFile = (src, dst, callback) => { // cbCalled flag and runCb helps to run cb only once. let cbCalled = false; let runCb = (err) => { if (cbCalled) return; cbCalled = true; callback(err); }; // Create read stream let readable = fs.createReadStream(src); readable.on('error', runCb); // Create write stream let writable = fs.createWriteStream(dst); writable.on('error', (err)=>{ readable.destroy(); runCb(err); }); writable.on('close', () => runCb()); // Copy file via piping streams. readable.pipe(writable); }; /** * Move file via streams by copieng and the deleteing src. * @param {String} src - Path to the source file * @param {String} dst - Path to the destination file. * @param {Function} callback - A callback function. */ const moveFile = (src, dst, callback) => { fs.rename(src, dst, err => { if (err) { // Copy file to dst and delete src whether success. copyFile(src, dst, err => err ? callback(err) : deleteFile(src, callback)); return; } callback(); }); }; /** * Save buffer data to a file. * @param {Buffer} buffer - buffer to save to a file. * @param {String} filePath - path to a file. */ const saveBufferToFile = (buffer, filePath, callback) => { if (!Buffer.isBuffer(buffer)) { return callback(new Error('buffer variable should be type of Buffer!')); } // Setup readable stream from buffer. let streamData = buffer; let readStream = Readable(); readStream._read = () => { readStream.push(streamData); streamData = null; }; // Setup file system writable stream. let fstream = fs.createWriteStream(filePath); fstream.on('error', error => callback(error)); fstream.on('close', () => callback()); // Copy file via piping streams. readStream.pipe(fstream); }; /** * Decodes uriEncoded file names. * @param fileName {String} - file name to decode. * @returns {String} */ const uriDecodeFileName = (opts, fileName) => { return opts.uriDecodeFileNames ? decodeURIComponent(fileName) : fileName; }; /** * Parses filename and extension and returns object {name, extension}. * @param preserveExtension {Boolean, Integer} - true/false or number of characters for extension. * @param fileName {String} - file name to parse. * @returns {Object} - {name, extension}. */ const parseFileNameExtension = (preserveExtension, fileName) => { const preserveExtensionLengh = parseInt(preserveExtension); const result = {name: fileName, extension: ''}; if (!preserveExtension && preserveExtensionLengh !== 0) return result; // Define maximum extension length const maxExtLength = isNaN(preserveExtensionLengh) ? MAX_EXTENSION_LENGTH : Math.abs(preserveExtensionLengh); const nameParts = fileName.split('.'); if (nameParts.length < 2) return result; let extension = nameParts.pop(); if ( extension.length > maxExtLength && maxExtLength > 0 ) { nameParts[nameParts.length - 1] += '.' + extension.substr(0, extension.length - maxExtLength); extension = extension.substr(-maxExtLength); } result.extension = maxExtLength ? extension : ''; result.name = nameParts.join('.'); return result; }; /** * Parse file name and extension. * @param opts {Object} - middleware options. * @param fileName {String} - Uploaded file name. * @returns {String} */ const parseFileName = (opts, fileName) => { // Cut off file name if it's lenght more then 255. let parsedName = fileName.length <= 255 ? fileName : fileName.substr(0, 255); // Decode file name if uriDecodeFileNames option set true. parsedName = uriDecodeFileName(opts, parsedName); // Stop parsing file name if safeFileNames options hasn't been set. if (!opts.safeFileNames) return parsedName; // Set regular expression for the file name. const nameRegex = typeof opts.safeFileNames === 'object' && opts.safeFileNames instanceof RegExp ? opts.safeFileNames : SAFE_FILE_NAME_REGEX; // Parse file name extension. let {name, extension} = parseFileNameExtension(opts.preserveExtension, parsedName); if (extension.length) extension = '.' + extension.replace(nameRegex, ''); return name.replace(nameRegex, '').concat(extension); }; module.exports = { debugLog, isFunc, errorFunc, promiseCallback, buildOptions, buildFields, checkAndMakeDir, deleteFile, // For testing purpose. copyFile, // For testing purpose. moveFile, saveBufferToFile, parseFileName, getTempFilename, uriDecodeFileName };
{ "content_hash": "ecb20b71a48f78880a97061adf006275", "timestamp": "", "source": "github", "line_count": 273, "max_line_length": 98, "avg_line_length": 31.318681318681318, "alnum_prop": 0.643859649122807, "repo_name": "aguerny/LacquerTracker", "id": "9ff2d60783fd2a6caea156b92b6b095ac72cd586", "size": "8550", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/express-fileupload/lib/utilities.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "27571" }, { "name": "EJS", "bytes": "267971" }, { "name": "HTML", "bytes": "406" }, { "name": "JavaScript", "bytes": "491634" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebAPIs.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Title = "Home Page"; return View(); } } }
{ "content_hash": "e6fca634906e26d5faa1c2491fff6392", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 44, "avg_line_length": 18.055555555555557, "alnum_prop": 0.6184615384615385, "repo_name": "Everstar/HospitalManageSystem", "id": "13714e91c5d19e45cbcb28db13f2336322c43f09", "size": "327", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WebAPIs/WebAPIs/Controllers/HomeController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "101" }, { "name": "C#", "bytes": "330915" }, { "name": "CSS", "bytes": "3966" }, { "name": "HTML", "bytes": "15005" }, { "name": "JavaScript", "bytes": "21236" }, { "name": "Pascal", "bytes": "133111" }, { "name": "PowerShell", "bytes": "122441" }, { "name": "Puppet", "bytes": "972" } ], "symlink_target": "" }
Contributions are **welcome** and will be fully **credited**. I am accepting contributions via Pull Requests on [Github](https://github.com/adrianmejias/laravel-zipbomb). ## Pull Requests - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). - **Add tests!** - Your patch won't be accepted if it doesn't have tests. - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. - **Create feature branches** - Don't ask us to pull from your master branch. - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. ## Running Tests ``` bash $ phpunit ``` **Happy coding**!
{ "content_hash": "fccbb10b09e97fee650f3ae80d3270b4", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 302, "avg_line_length": 49, "alnum_prop": 0.7407407407407407, "repo_name": "adrianmejias/laravel-zipbomb", "id": "551103f11873760352899f1dad93f996b1f6c1e2", "size": "1339", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CONTRIBUTING.md", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "7831" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="refresh" content="0;URL=../../../libc/constant.POLLWRBAND.html"> </head> <body> <p>Redirecting to <a href="../../../libc/constant.POLLWRBAND.html">../../../libc/constant.POLLWRBAND.html</a>...</p> <script>location.replace("../../../libc/constant.POLLWRBAND.html" + location.search + location.hash);</script> </body> </html>
{ "content_hash": "d5c0bee600b976107debbfd31272e1b6", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 120, "avg_line_length": 39.3, "alnum_prop": 0.6361323155216285, "repo_name": "IllinoisRoboticsInSpace/Arduino_Control", "id": "4724c50916ba948c249e2d489c028e8f1ddab1ac", "size": "393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rust-serial/target/doc/libc/unix/bsd/constant.POLLWRBAND.html", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "81176" } ], "symlink_target": "" }
ACCEPTED #### According to Integrated Taxonomic Information System #### Published in null #### Original name null ### Remarks null
{ "content_hash": "afc6103f0fbec83d12fbde9f5beb14a5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.7238805970149254, "repo_name": "mdoering/backbone", "id": "5774c7c323614a1c571b98d6292604c914195511", "size": "178", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Anthocephalus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import logging import logging.config import pandas as pd import numpy as np from gmsdk import * class TurtleStrategy(StrategyBase): def __init__(self, *args, **kwargs): super(TurtleStrategy, self).__init__(*args, **kwargs) self.__get_param__() self.__init_data__() def __get_param__(self): self.csv_file = self.config.get('para', 'csv_file') self.period = self.config.getint('para', 'period') self.hop = self.config.get('para', 'hop') or 0.1 def __init_data__(self): ''' read stocks from csv file :return: ''' self.sec_ids = [] self.hist_data = dict() self.positions = dict() subscribe_symbols = [] stocks = pd.read_csv(self.csv_file, sep=',') for r in stocks.iterrows(): exchange = r[1][0] sec_id = r[1][1] buy_amount = r[1][2] t = "{0}.{1}".format(exchange, sec_id) hl = self.get_highest_lowest_price(t) #print (hl) self.hist_data[t] = hl + (buy_amount,) ## high, low, buy_amount self.sec_ids.append("{0}".format(sec_id)) subscribe_symbols.append(t + ".tick") self.subscribe(",".join(subscribe_symbols)) def get_highest_lowest_price(self, symbol): #print(symbol) ## get last N dailybars hd = self.get_last_n_dailybars(symbol, self.period) high_prices = [b.high for b in hd] #high_prices.reverse() low_prices = [b.low for b in hd] #low_prices.reverse() return np.max(high_prices), np.min(low_prices) def on_tick(self, tick): if not tick.sec_id in self.sec_ids: pass #self.logger.info( "received tick: %s %s %s %s" % (tick.exchange, tick.sec_id, round(tick.last_price,2), tick.last_volume)) else: #self.logger.info( "received tick: %s %s, A: %s B: %s" % (tick.sec_id, round(tick.last_price,2), round(tick.asks[0][0],2), round(tick.bids[0][0],2))) symbol = ".".join([tick.exchange, tick.sec_id]) data = self.hist_data.get(symbol) self.hop = float(self.hop) #print (data) pa = self.get_positions() #int pa if data and tick.last_price > data[0] : ## check high volume = int(data[2]/(tick.last_price+self.hop)/100)*100 ## get slots, then shares if bool(self.get_position(tick.exchange,tick.sec_id,1)) == 0: #print (to_dict(aaa[0])) self.open_long(tick.exchange, tick.sec_id, tick.last_price + self.hop, volume) #print (tick.exchange, tick.sec_id, tick.last_price + self.hop, volume) #print (tick.sec_id) elif data and tick.last_price < data[1]: ## check low #p = self.get_position(tick.exchange, tick.sec_id, OrderSide_Bid) ps = self.get_positions() for p in ps: sym = ".".join([p.exchange, p.sec_id]) self.positions[sym] = p #print (p) ## if not in stock list, close long position if p.sec_id in self.sec_ids: self.close_long(p.exchange, p.sec_id, 0, p.volume) if __name__ == '__main__': ini_file = sys.argv[1] if len(sys.argv) > 1 else 'turtle.ini' logging.config.fileConfig(ini_file) st = TurtleStrategy(config_file=ini_file) st.logger.info("Strategy turtle ready, waiting for data ...") ret = st.run() st.logger.info("Strategy turtle message %s" % st.get_strerror(ret))
{ "content_hash": "606030dbff985f1120bafb82be18fc40", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 161, "avg_line_length": 33.68807339449541, "alnum_prop": 0.5343137254901961, "repo_name": "wl41089496/strategy", "id": "a434711b4af002c51570fa6ccc686f91490bdcb4", "size": "3690", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Turtle/python/turtle.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GCC Machine Description", "bytes": "1389" }, { "name": "Matlab", "bytes": "3395" }, { "name": "Python", "bytes": "259661" } ], "symlink_target": "" }
>- How is it handled? >- How does it work? >- Garbage collection? >- Automatic reference counting? ## Python Python handles memory management internally through the "Python Memory Manager". This manager is a private heap that contains all python objects and data structures. Because Python is not a standardized language, and many different implementations exists, no guarantees can be made about garbage collections. In CPython, which is considered the main implementation, a combination of Reference Counting and Mark-And-Sweep are used. However, Jython and IronPython use a pure garbage collection system. ## C# C# itself does not handle memory, but instead the Common Language Runtime handles all memory management. C# uses garbage collection which, like Java, is unpredictable and can occur at any time. Garbage collection runs periodically to remove unreferenced objects, or when certain conditions are met, such as low physical memory or object allocation surpasses a threshold. [:rewind: Back to Table of Contents](../README.md) <!-- BackToC --> ## References - https://docs.python.org/3/c-api/memory.html - http://stackoverflow.com/questions/9062209/why-does-python-use-both-reference-counting-and-mark-and-sweep-for-gc - https://msdn.microsoft.com/en-us/library/ee787088(v=vs.110).aspx - https://msdn.microsoft.com/en-us/library/ms228629(v=vs.90).aspx
{ "content_hash": "974b866410031a530a039721d8d48a07", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 370, "avg_line_length": 68.35, "alnum_prop": 0.7856620336503292, "repo_name": "PercyODI/PythonCSharpOOComparison", "id": "803a01700c32a77adc3ecaebe250b6cf33aa8c23", "size": "1387", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MemoryManagement/Intro.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "2841" } ], "symlink_target": "" }
<!-- ~ Copyright 1998-2020 Linux.org.ru ~ 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. --> <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd"> <changeSet id="2019051201" author="Maxim Valyanskiy"> <addColumn tableName="topics"> <column name="allow_anonymous" defaultValue="true" type="boolean"> <constraints nullable="false"/> </column> </addColumn> </changeSet> </databaseChangeLog>
{ "content_hash": "923b3a0b26b949d025746e21d9968c1c", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 79, "avg_line_length": 44.107142857142854, "alnum_prop": 0.668825910931174, "repo_name": "maxcom/lorsource", "id": "6991f0b946c79ee36a844864bab5a9279003520b", "size": "1235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sql/updates/2020-01-02-no-anon.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12776" }, { "name": "Dockerfile", "bytes": "817" }, { "name": "HTML", "bytes": "58918" }, { "name": "Java", "bytes": "1511146" }, { "name": "JavaScript", "bytes": "51050" }, { "name": "SCSS", "bytes": "92783" }, { "name": "Scala", "bytes": "522179" }, { "name": "Shell", "bytes": "2329" } ], "symlink_target": "" }
require 'spec_helper' RSpec.describe Starling::Services::TransactionsService do let(:client) { Starling::Client.new(access_token: 'dummy_access_token') } subject(:service) { client.transactions } before { stub_user_agent } describe '#list' do subject(:transactions) { service.list } let(:status) { 200 } let(:body) { load_fixture('transactions.json') } let(:headers) { { 'Content-Type' => 'application/json' } } context 'with no filters' do before do stub_request(:get, 'https://api.starlingbank.com/api/v1/transactions') .with(headers: { 'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Authorization' => 'Bearer dummy_access_token', 'User-Agent' => user_agent }) .to_return(status: status, body: body, headers: headers) end its(:length) { is_expected.to eq(12) } it 'correctly constructs Transaction resources', :aggregate_failures do expect(transactions.first.created).to eq(Time.parse('2017-05-30T18:06:28.773Z')) expect(transactions.first.id).to eq('ed973200-037d-4f55-9c67-1b467a341203') expect(transactions.first.currency).to eq('GBP') expect(transactions.first.amount).to eq(-1.02) expect(transactions.first.direction).to eq(:outbound) expect(transactions.first.narrative).to eq('Aldi') expect(transactions.first.source).to eq(:master_card) end end context 'filtering by date' do let!(:stub) do stub_request(:get, 'https://api.starlingbank.com/api/v1/transactions?from=2017-05-30') .with(headers: { 'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Authorization' => 'Bearer dummy_access_token', 'User-Agent' => user_agent }) .to_return(status: status, body: body, headers: headers) end it 'adds the provided filter to the URL parameters' do service.list(params: { from: '2017-05-30' }) expect(stub).to have_been_requested end end end describe '#get' do subject(:transaction) { service.get(id) } let(:id) { '284ad156-cb66-465c-8757-f6440304a0f8' } before do stub_request(:get, "https://api.starlingbank.com/api/v1/transactions/#{id}") .with(headers: { 'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Authorization' => 'Bearer dummy_access_token', 'User-Agent' => user_agent }) .to_return(status: status, body: body, headers: headers) end context 'with a valid ID' do let(:status) { 200 } let(:body) { load_fixture('transaction.json') } let(:headers) { { 'Content-Type' => 'application/json' } } it { is_expected.to be_a(Starling::Resources::TransactionResource) } it 'correctly constructs a Transaction resource', :aggregate_failures do expect(transaction.created).to eq(Time.parse('2017-05-30T18:06:28.773Z')) expect(transaction.id).to eq('284ad156-cb66-465c-8757-f6440304a0f8') expect(transaction.currency).to eq('GBP') expect(transaction.amount).to eq(-1.02) expect(transaction.direction).to eq(:outbound) expect(transaction.narrative).to eq('Aldi') expect(transaction.source).to eq(:master_card) end end context 'with a non-existent ID' do let(:status) { 404 } let(:body) { nil } let(:headers) { {} } it 'raises an error' do expect { service.get(id) }.to raise_error(Starling::Errors::ApiError) end end end end
{ "content_hash": "3b716bca5cea80e87a01a0aeeac3d925", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 88, "avg_line_length": 35.972972972972975, "alnum_prop": 0.5780115201602805, "repo_name": "timrogers/starling-ruby", "id": "b4d9c256efe10c5e855d1f801406a276b930f1b4", "size": "3993", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/integration/transactions_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "153318" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
<? function GetCategories() { global $pdo; $Categories = []; foreach($pdo->query('SELECT * FROM tipos_productos') as $Category) { $Categories[$Category['tipo_producto_id']] = $Category; } return $Categories; } function GetActions() { global $pdo; $Categories = []; foreach($pdo->query('SELECT * FROM tipo_acciones') as $Category) { $Categories[$Category['tipo_acciones_id']] = $Category; } return $Categories; } function addCategory($CategoryName) { if ($CategoryName !="") { $pdo->exec('INSERT INTO `tipos_productos`(`tipo_producto_display`) VALUES ("'.$CategoryName.'")'); } } function GetProducts($criteria) { global $pdo; $Products = []; $sql = ""; if ($criteria != "") { $sql = 'SELECT * FROM producto WHERE titulo LIKE "%'.$criteria.'%" OR direccion = "'.$criteria.'"'; } else { $sql = 'SELECT * FROM producto'; } foreach($pdo->query($sql) as $Product) { foreach ($Product as $key => $value) { if (AssociateID($value, $key)) { $Product[$key."_Display"] = AssociateID($value, $key); } } $Products[$Product['id']] = $Product; } return $Products; } function GetProduct($id) { global $pdo; $UCompany = $_SESSION["User"]["company_id"]; $sql = 'SELECT * FROM productos WHERE id = "'.$id.'"'; foreach($pdo->query($sql) as $Product) { return $Product; } } function OutOfStock($pid, $q) { global $pdo; $UCompany = $_SESSION["User"]["company_id"]; $pdo->exec('UPDATE producto SET cantidad = cantidad -'.$q.' WHERE id = "'.$pid.'"'); } ?>
{ "content_hash": "0739774a77c6640898a8568f060839ec", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 103, "avg_line_length": 23.924242424242426, "alnum_prop": 0.5870804306523116, "repo_name": "DimasAriel/Inmobi-Itla", "id": "3d85a3d1fc02e9f2cde5bf7b0d40047a0a0c3e3e", "size": "1579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "inc/Repos/ProductsRepo.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "356" }, { "name": "CSS", "bytes": "667484" }, { "name": "HTML", "bytes": "2019861" }, { "name": "JavaScript", "bytes": "2970205" }, { "name": "PHP", "bytes": "75077" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- Just used while running in process while developing --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern> %d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n </pattern> </encoder> </appender> <!-- Used for application logging --> <appender name="APPLOGFILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logs/resourceRetriever.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>logs/resourceRetriever.%d{yyyy-MM-dd}.log </fileNamePattern> </rollingPolicy> <encoder> <pattern> %d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n </pattern> </encoder> </appender> <appender name="multiplex" class="de.huxhorn.lilith.logback.appender.ClassicMultiplexSocketAppender" > <Compressing>true</Compressing> <!-- will automatically use correct default port --> <!-- Default port for compressed is 10000 and uncompressed 10001 --> <ReconnectionDelay>10000</ReconnectionDelay> <IncludeCallerData>true</IncludeCallerData> <RemoteHosts>localhost</RemoteHosts> <!-- Alternatively: <RemoteHost>localhost</RemoteHost> <RemoteHost>10.200.55.13</RemoteHost> --> <!-- Optional: <CreatingUUID>false</CreatingUUID> --> </appender> <logger name="ca.uhn.fhir.rest" level="info" /> <logger name="org.apache.camel" level="info" /> <logger name="org.mitre" level="info" /> <logger name="org.springframework" level="info" /> <root level="warn"> <appender-ref ref="STDOUT" /> <appender-ref ref="multiplex" /> </root> </configuration>
{ "content_hash": "2bac0205b3feb26926e58192fdfd6973", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 86, "avg_line_length": 30.508474576271187, "alnum_prop": 0.6544444444444445, "repo_name": "mitre/ptmatchadapter", "id": "86ac1d294a217b0fbdad3286f3b72459cd3da13e", "size": "1800", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/resourceLoader/src/main/resources/logback.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "98476" } ], "symlink_target": "" }
#pragma once #if ENABLE(WEBGPU) #include "GPUDevice.h" #include <wtf/RefCounted.h> namespace WebCore { class WebGPURenderingContext; class WebGPUObject : public RefCounted<WebGPUObject> { public: virtual ~WebGPUObject(); void deleteObject(GPUDevice*); bool isDeleted() const { return m_deleted; } WebGPURenderingContext* context() { return m_context.get(); } protected: WebGPUObject(WebGPURenderingContext* = nullptr); bool hasContext() const { return m_context; } private: RefPtr<WebGPURenderingContext> m_context; bool m_deleted { false }; }; } // namespace WebCore #endif
{ "content_hash": "feb3544641457bbd0bab1ebeda26677f", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 65, "avg_line_length": 17.38888888888889, "alnum_prop": 0.7060702875399361, "repo_name": "gubaojian/trylearn", "id": "de2a73201be144af544048735dc97e52043736e7", "size": "1956", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WebLayoutCore/Source/WebCore/html/canvas/WebGPUObject.h", "mode": "33188", "license": "mit", "language": [ { "name": "AspectJ", "bytes": "623" }, { "name": "Assembly", "bytes": "1942" }, { "name": "Batchfile", "bytes": "6632" }, { "name": "C", "bytes": "6629351" }, { "name": "C++", "bytes": "57418677" }, { "name": "CMake", "bytes": "1269316" }, { "name": "CSS", "bytes": "99559" }, { "name": "HTML", "bytes": "283332" }, { "name": "Java", "bytes": "267448" }, { "name": "JavaScript", "bytes": "282026" }, { "name": "Makefile", "bytes": "164797" }, { "name": "Objective-C", "bytes": "956074" }, { "name": "Objective-C++", "bytes": "3645713" }, { "name": "Perl", "bytes": "192119" }, { "name": "Python", "bytes": "39191" }, { "name": "Ragel", "bytes": "128173" }, { "name": "Roff", "bytes": "26536" }, { "name": "Ruby", "bytes": "32784" }, { "name": "Shell", "bytes": "7177" }, { "name": "Vue", "bytes": "1776" }, { "name": "Yacc", "bytes": "11866" } ], "symlink_target": "" }
BASH_RC=~/.bashrc GODOT_BUILD_TOOLS_PATH=./godot-dev/build-tools mkdir -p $GODOT_BUILD_TOOLS_PATH cd $GODOT_BUILD_TOOLS_PATH ANDROID_BASE_URL=http://dl.google.com/android/repository ANDROID_SDK_RELEASE=4333796 ANDROID_SDK_DIR=android-sdk ANDROID_SDK_FILENAME=sdk-tools-linux-$ANDROID_SDK_RELEASE.zip ANDROID_SDK_URL=$ANDROID_BASE_URL/$ANDROID_SDK_FILENAME ANDROID_SDK_PATH=$GODOT_BUILD_TOOLS_PATH/$ANDROID_SDK_DIR ANDROID_SDK_SHA256=92ffee5a1d98d856634e8b71132e8a95d96c83a63fde1099be3d86df3106def9 ANDROID_NDK_RELEASE=r21 ANDROID_NDK_DIR=android-ndk ANDROID_NDK_FILENAME=android-ndk-$ANDROID_NDK_RELEASE-linux-x86_64.zip ANDROID_NDK_URL=$ANDROID_BASE_URL/$ANDROID_NDK_FILENAME ANDROID_NDK_PATH=$GODOT_BUILD_TOOLS_PATH/$ANDROID_NDK_DIR ANDROID_NDK_SHA1=afc9c0b9faad222898ac8168c78ad4ccac8a1b5c echo echo "Download and install Android development tools ..." echo if [ ! -e $ANDROID_SDK_FILENAME ]; then echo "Downloading: Android SDK ..." curl -L -O $ANDROID_SDK_URL else echo $ANDROID_SDK_SHA1 $ANDROID_SDK_FILENAME > $ANDROID_SDK_FILENAME.sha1 if [ $(shasum -a 256 < $ANDROID_SDK_FILENAME | awk '{print $1;}') != $ANDROID_SDK_SHA1 ]; then echo "Downloading: Android SDK ..." curl -L -O $ANDROID_SDK_URL fi fi if [ ! -d $ANDROID_SDK_DIR ]; then echo "Extracting: Android SDK ..." unzip -qq $ANDROID_SDK_FILENAME -d $ANDROID_SDK_DIR echo fi if [ ! -e $ANDROID_NDK_FILENAME ]; then echo "Downloading: Android NDK ..." curl -L -O $ANDROID_NDK_URL else echo $ANDROID_NDK_MD5 $ANDROID_NDK_FILENAME > $ANDROID_NDK_FILENAME.md5 if [ $(shasum -a 1 < $ANDROID_NDK_FILENAME | awk '{print $1;}') != $ANDROID_NDK_SHA1 ]; then echo "Downloading: Android NDK ..." curl -L -O $ANDROID_NDK_URL fi fi if [ ! -d $ANDROID_NDK_DIR ]; then echo "Extracting: Android NDK ..." unzip -qq $ANDROID_NDK_FILENAME mv android-ndk-$ANDROID_NDK_RELEASE $ANDROID_NDK_DIR echo fi mkdir -p ~/.android && echo "count=0" > ~/.android/repositories.cfg echo "Installing: Accepting Licenses ..." yes | $ANDROID_SDK_DIR/tools/bin/sdkmanager --licenses > /dev/null echo "Installing: Android Build and Platform Tools ..." yes | $ANDROID_SDK_DIR/tools/bin/sdkmanager 'tools' > /dev/null yes | $ANDROID_SDK_DIR/tools/bin/sdkmanager 'platform-tools' > /dev/null yes | $ANDROID_SDK_DIR/tools/bin/sdkmanager 'build-tools;29.0.3' > /dev/null echo EXPORT_VAL="export ANDROID_HOME=$ANDROID_SDK_PATH" if ! grep -q "^$EXPORT_VAL" $BASH_RC; then echo $EXPORT_VAL >> $BASH_RC fi #eval $EXPORT_VAL EXPORT_VAL="export ANDROID_NDK_ROOT=$ANDROID_NDK_PATH" if ! grep -q "^$EXPORT_VAL" $BASH_RC; then echo $EXPORT_VAL >> $BASH_RC fi #eval $EXPORT_VAL EXPORT_VAL="export PATH=$PATH:$ANDROID_SDK_PATH/tools" if ! grep -q "^export PATH=.*$ANDROID_SDK_PATH/tools.*" $BASH_RC; then echo $EXPORT_VAL >> $BASH_RC fi #eval $EXPORT_VAL EXPORT_VAL="export PATH=$PATH:$ANDROID_SDK_PATH/tools/bin" if ! grep -q "^export PATH=.*$ANDROID_SDK_PATH/tools/bin.*" $BASH_RC; then echo $EXPORT_VAL >> $BASH_RC fi #eval $EXPORT_VAL echo echo "Done!" echo
{ "content_hash": "15e7f0476ee49ebb4725297d83fef2f8", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 96, "avg_line_length": 31.96875, "alnum_prop": 0.7096774193548387, "repo_name": "Paulloz/godot", "id": "6114551861c17d8fbf255521dca6aa5cf640dc1f", "size": "3537", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "misc/ci/android-tools-linux.sh", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "50004" }, { "name": "C#", "bytes": "176259" }, { "name": "C++", "bytes": "18569070" }, { "name": "GLSL", "bytes": "1271" }, { "name": "Java", "bytes": "495377" }, { "name": "JavaScript", "bytes": "14680" }, { "name": "Makefile", "bytes": "451" }, { "name": "Objective-C", "bytes": "2645" }, { "name": "Objective-C++", "bytes": "173262" }, { "name": "Python", "bytes": "336142" }, { "name": "Shell", "bytes": "19610" } ], "symlink_target": "" }
package trivia; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
{ "content_hash": "37ff7c57b5d81e74dcd6e425ad9849d8", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 46, "avg_line_length": 16.68421052631579, "alnum_prop": 0.5694006309148265, "repo_name": "JoaGardiola/ProyectoTrivia", "id": "ef239acfec81e62cf8c132c4368a3f7b24e42623", "size": "634", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/test/java/trivia/AppTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18097" }, { "name": "HTML", "bytes": "17177" }, { "name": "Java", "bytes": "30057" }, { "name": "JavaScript", "bytes": "117000" }, { "name": "Shell", "bytes": "537" } ], "symlink_target": "" }
 #pragma once #include <aws/kinesisanalytics/KinesisAnalytics_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace KinesisAnalytics { namespace Model { /** * <p> For an application output, describes the Amazon Kinesis Firehose delivery * stream configured as its destination. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/KinesisFirehoseOutputDescription">AWS * API Reference</a></p> */ class AWS_KINESISANALYTICS_API KinesisFirehoseOutputDescription { public: KinesisFirehoseOutputDescription(); KinesisFirehoseOutputDescription(Aws::Utils::Json::JsonView jsonValue); KinesisFirehoseOutputDescription& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>Amazon Resource Name (ARN) of the Amazon Kinesis Firehose delivery * stream.</p> */ inline const Aws::String& GetResourceARN() const{ return m_resourceARN; } /** * <p>Amazon Resource Name (ARN) of the Amazon Kinesis Firehose delivery * stream.</p> */ inline void SetResourceARN(const Aws::String& value) { m_resourceARNHasBeenSet = true; m_resourceARN = value; } /** * <p>Amazon Resource Name (ARN) of the Amazon Kinesis Firehose delivery * stream.</p> */ inline void SetResourceARN(Aws::String&& value) { m_resourceARNHasBeenSet = true; m_resourceARN = std::move(value); } /** * <p>Amazon Resource Name (ARN) of the Amazon Kinesis Firehose delivery * stream.</p> */ inline void SetResourceARN(const char* value) { m_resourceARNHasBeenSet = true; m_resourceARN.assign(value); } /** * <p>Amazon Resource Name (ARN) of the Amazon Kinesis Firehose delivery * stream.</p> */ inline KinesisFirehoseOutputDescription& WithResourceARN(const Aws::String& value) { SetResourceARN(value); return *this;} /** * <p>Amazon Resource Name (ARN) of the Amazon Kinesis Firehose delivery * stream.</p> */ inline KinesisFirehoseOutputDescription& WithResourceARN(Aws::String&& value) { SetResourceARN(std::move(value)); return *this;} /** * <p>Amazon Resource Name (ARN) of the Amazon Kinesis Firehose delivery * stream.</p> */ inline KinesisFirehoseOutputDescription& WithResourceARN(const char* value) { SetResourceARN(value); return *this;} /** * <p>ARN of the IAM role that Amazon Kinesis Analytics can assume to access the * stream.</p> */ inline const Aws::String& GetRoleARN() const{ return m_roleARN; } /** * <p>ARN of the IAM role that Amazon Kinesis Analytics can assume to access the * stream.</p> */ inline void SetRoleARN(const Aws::String& value) { m_roleARNHasBeenSet = true; m_roleARN = value; } /** * <p>ARN of the IAM role that Amazon Kinesis Analytics can assume to access the * stream.</p> */ inline void SetRoleARN(Aws::String&& value) { m_roleARNHasBeenSet = true; m_roleARN = std::move(value); } /** * <p>ARN of the IAM role that Amazon Kinesis Analytics can assume to access the * stream.</p> */ inline void SetRoleARN(const char* value) { m_roleARNHasBeenSet = true; m_roleARN.assign(value); } /** * <p>ARN of the IAM role that Amazon Kinesis Analytics can assume to access the * stream.</p> */ inline KinesisFirehoseOutputDescription& WithRoleARN(const Aws::String& value) { SetRoleARN(value); return *this;} /** * <p>ARN of the IAM role that Amazon Kinesis Analytics can assume to access the * stream.</p> */ inline KinesisFirehoseOutputDescription& WithRoleARN(Aws::String&& value) { SetRoleARN(std::move(value)); return *this;} /** * <p>ARN of the IAM role that Amazon Kinesis Analytics can assume to access the * stream.</p> */ inline KinesisFirehoseOutputDescription& WithRoleARN(const char* value) { SetRoleARN(value); return *this;} private: Aws::String m_resourceARN; bool m_resourceARNHasBeenSet; Aws::String m_roleARN; bool m_roleARNHasBeenSet; }; } // namespace Model } // namespace KinesisAnalytics } // namespace Aws
{ "content_hash": "f17d100416adec259966da79c85701ca", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 132, "avg_line_length": 32.634328358208954, "alnum_prop": 0.6761948319231649, "repo_name": "JoyIfBam5/aws-sdk-cpp", "id": "d78ca1cdfb08f3b472767d973efb1ab4b3d3f778", "size": "4946", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-kinesisanalytics/include/aws/kinesisanalytics/model/KinesisFirehoseOutputDescription.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "11868" }, { "name": "C++", "bytes": "167818064" }, { "name": "CMake", "bytes": "591577" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "271801" }, { "name": "Python", "bytes": "85650" }, { "name": "Shell", "bytes": "5277" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_16) on Mon Jun 28 12:45:09 PDT 2010 --> <TITLE> Uses of Class org.apache.hadoop.contrib.index.lucene.ShardWriter (Hadoop 0.20.2+320 API) </TITLE> <META NAME="date" CONTENT="2010-06-28"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.contrib.index.lucene.ShardWriter (Hadoop 0.20.2+320 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/contrib/index/lucene/ShardWriter.html" title="class in org.apache.hadoop.contrib.index.lucene"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/contrib/index/lucene//class-useShardWriter.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ShardWriter.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.contrib.index.lucene.ShardWriter</B></H2> </CENTER> No usage of org.apache.hadoop.contrib.index.lucene.ShardWriter <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/contrib/index/lucene/ShardWriter.html" title="class in org.apache.hadoop.contrib.index.lucene"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/contrib/index/lucene//class-useShardWriter.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ShardWriter.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &copy; 2009 The Apache Software Foundation </BODY> </HTML>
{ "content_hash": "b4ea17ccb79e4199194d2df4b0b57187", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 251, "avg_line_length": 43.236111111111114, "alnum_prop": 0.6108255701895278, "repo_name": "ryanobjc/hadoop-cloudera", "id": "03f0ff29ea61e7171c2babffdd8d4210099ce857", "size": "6226", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/api/org/apache/hadoop/contrib/index/lucene/class-use/ShardWriter.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "309764" }, { "name": "C++", "bytes": "383846" }, { "name": "Java", "bytes": "12736305" }, { "name": "JavaScript", "bytes": "60544" }, { "name": "Objective-C", "bytes": "112020" }, { "name": "PHP", "bytes": "152555" }, { "name": "Perl", "bytes": "149888" }, { "name": "Python", "bytes": "1162926" }, { "name": "Ruby", "bytes": "28485" }, { "name": "Shell", "bytes": "1137904" }, { "name": "Smalltalk", "bytes": "56562" } ], "symlink_target": "" }
import { moduleFor, test } from 'ember-qunit'; moduleFor('service:browser', 'Unit | Service | browser', { // Specify the other units that are required for this test. // needs: ['service:foo'] }); // Replace this with your real tests. test('it exists', function(assert) { let service = this.subject(); assert.ok(service); });
{ "content_hash": "94c3508ba6276ed9629f38d0405655c7", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 61, "avg_line_length": 27.916666666666668, "alnum_prop": 0.6716417910447762, "repo_name": "cball/justa-table", "id": "7725c003e027a6f678b5e5ccf6e7f3cafc04606f", "size": "335", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/unit/services/browser-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3941" }, { "name": "HTML", "bytes": "15378" }, { "name": "JavaScript", "bytes": "76924" } ], "symlink_target": "" }
using System; using System.Linq.Expressions; using System.Reflection; namespace SimpleFixture { /// <summary> /// Interface for customizing how a Type gets created /// </summary> /// <typeparam name="T"></typeparam> public interface ICustomizeModel<T> { /// <summary> /// Provide a function for creating a new instance of T /// </summary> /// <param name="newFunc">function to create new T</param> /// <returns>customization instance</returns> ICustomizeModel<T> New(Func<T> newFunc); /// <summary> /// Provide a function for creating a new instance of T /// </summary> /// <param name="newFunc">delegate that accepts a data request and returns T</param> /// <returns>customization instance</returns> ICustomizeModel<T> New(Func<DataRequest, T> newFunc); /// <summary> /// Provide function for creating a new instance of T that depends on TIn /// </summary> /// <typeparam name="TIn">type for dependency</typeparam> /// <param name="factory">new factory that takes TIn</param> /// <returns>customization instance</returns> ICustomizeModel<T> NewFactory<TIn>(Func<TIn, T> factory); /// <summary> /// Provide function for creating a new instance of T that depends on TIn1 and TIn2 /// </summary> /// <typeparam name="TIn1">first dependency type</typeparam> /// <typeparam name="TIn2">second dependency type</typeparam> /// <param name="factory">new factory that takes TIn1 and TIn2</param> /// <returns>customization instance</returns> ICustomizeModel<T> NewFactory<TIn1, TIn2>(Func<TIn1, TIn2, T> factory); /// <summary> /// Provide function for creating a new instance of T that depends on TIn1, TIn2, and TIn3 /// </summary> /// <typeparam name="TIn1">first dependency type</typeparam> /// <typeparam name="TIn2">second dependency type</typeparam> /// <typeparam name="TIn3">third dependency type</typeparam> /// <param name="factory">new factory that takes TIn1, TIn2, and TIn3</param> /// <returns>customization instance</returns> ICustomizeModel<T> NewFactory<TIn1, TIn2, TIn3>(Func<TIn1, TIn2, TIn3, T> factory); /// <summary> /// Provide function for creating a new instance of T that depends on TIn1, TIn2, TIn3, and TIn4 /// </summary> /// <typeparam name="TIn1">first dependency type</typeparam> /// <typeparam name="TIn2">second dependency type</typeparam> /// <typeparam name="TIn3">third dependency type</typeparam> /// <typeparam name="TIn4">fourth dependency type</typeparam> /// <param name="factory">new factory that takes TIn1, TIn2, TIn3, and TIn4</param> /// <returns>customization instance</returns> ICustomizeModel<T> NewFactory<TIn1, TIn2, TIn3, TIn4>(Func<TIn1, TIn2, TIn3, TIn4, T> factory); /// <summary> /// Set a value for a particular property on T /// </summary> /// <typeparam name="TProp">type of property to set</typeparam> /// <param name="propertyFunc">method to specify property (x => x.PropertyName)</param> /// <param name="value">value to use when setting property</param> /// <returns>customization instance</returns> ICustomizeModel<T> Set<TProp>(Expression<Func<T, TProp>> propertyFunc, TProp value); /// <summary> /// Set a value for a particular property on T /// </summary> /// <typeparam name="TProp">type of property to set</typeparam> /// <param name="propertyFunc">method to specify property (x => x.PropertyName)</param> /// <param name="valueFunc">function to provide value</param> /// <returns>customization instance</returns> ICustomizeModel<T> Set<TProp>(Expression<Func<T, TProp>> propertyFunc, Func<TProp> valueFunc); /// <summary> /// Set a value for a particular property on T /// </summary> /// <typeparam name="TProp">type of property to set</typeparam> /// <param name="propertyFunc">method to specify property (x => x.PropertyName)</param> /// <param name="valueFunc">function to provide value</param> /// <returns>customization instance</returns> ICustomizeModel<T> Set<TProp>(Expression<Func<T, TProp>> propertyFunc, Func<DataRequest, TProp> valueFunc); /// <summary> /// Set a specific value into a set of Properties specified by the matching func /// </summary> /// <param name="matchingFunc">property matching func</param> /// <param name="value">property value</param> /// <returns>customization instance</returns> ICustomizeModel<T> SetProperties(Func<PropertyInfo, bool> matchingFunc, object value); /// <summary> /// Set a specific value into a set of Properties specified by the matching func /// </summary> /// <param name="matchingFunc">property matching func</param> /// <param name="value">func to be used to provide value</param> /// <returns>customization instance</returns> ICustomizeModel<T> SetProperties(Func<PropertyInfo, bool> matchingFunc, Func<object> value); /// <summary> /// Set a specific value into a set of Properties specified by the matching func /// </summary> /// <param name="matchingFunc">property matching func</param> /// <param name="value">func to be used to provide value</param> /// <returns>customization instance</returns> ICustomizeModel<T> SetProperties(Func<PropertyInfo, bool> matchingFunc, Func<DataRequest, PropertyInfo, object> value); /// <summary> /// Skip a particular property from being populated /// </summary> /// <typeparam name="TProp">property type</typeparam> /// <param name="propertyFunc">property expression</param> /// <returns>customization instance</returns> ICustomizeModel<T> Skip<TProp>(Expression<Func<T, TProp>> propertyFunc); /// <summary> /// Skip a particular set of properties /// </summary> /// <param name="matchingFunc">property matching function</param> /// <returns>customization instance</returns> ICustomizeModel<T> SkipProperties(Func<PropertyInfo, bool> matchingFunc = null); /// <summary> /// Skip a particular set of properties /// </summary> /// <param name="matchingFunc">property matching function</param> /// <returns>customization instance</returns> ICustomizeModel<T> SkipProperties(Func<DataRequest, PropertyInfo, bool> matchingFunc); /// <summary> /// Apply a piece of logic to each instance being created /// </summary> /// <param name="applyAction">apply function</param> /// <returns>customization instanc</returns> ICustomizeModel<T> Apply(Action<T> applyAction); } }
{ "content_hash": "22b5f7d8b454672f6bde34de79c79160", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 127, "avg_line_length": 48.97931034482759, "alnum_prop": 0.6302450014080541, "repo_name": "ipjohnson/SimpleFixture", "id": "bf9deaf1306a8a75640ea35f66c96d25e3c6df5a", "size": "7104", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/SimpleFixture/ICustomizeModel.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "900" }, { "name": "C#", "bytes": "414059" } ], "symlink_target": "" }
#include <thrift/lib/cpp2/fatal/flatten_getters.h> #include <thrift/test/gen-cpp2/reflection_fatal_types.h> #include <thrift/lib/cpp2/fatal/internal/test_helpers.h> #include <gtest/gtest.h> namespace test_cpp2 { namespace cpp_reflection { using namespace apache::thrift; TEST(flatten_getters, no_terminal_filter) { using sa = reflect_struct<structA>::member; using sb = reflect_struct<structB>::member; using sc = reflect_struct<structC>::member; using s1 = reflect_struct<struct1>::member; using s2 = reflect_struct<struct2>::member; using s3 = reflect_struct<struct3>::member; using s4 = reflect_struct<struct4>::member; using s5 = reflect_struct<struct5>::member; EXPECT_SAME< fatal::list< flat_getter<fatal::list<>, sa::a>, flat_getter<fatal::list<>, sa::b> >, flatten_getters<structA> >(); EXPECT_SAME< fatal::list< flat_getter<fatal::list<>, sb::c>, flat_getter<fatal::list<>, sb::d> >, flatten_getters<structB> >(); EXPECT_SAME< fatal::list< flat_getter<fatal::list<>, sc::a>, flat_getter<fatal::list<>, sc::b>, flat_getter<fatal::list<>, sc::c>, flat_getter<fatal::list<>, sc::d>, flat_getter<fatal::list<>, sc::e>, flat_getter<fatal::list<>, sc::f>, flat_getter<fatal::list<>, sc::g>, flat_getter<fatal::list<>, sc::h>, flat_getter<fatal::list<>, sc::i>, flat_getter<fatal::list<>, sc::j>, flat_getter<fatal::list<>, sc::j1>, flat_getter<fatal::list<>, sc::j2>, flat_getter<fatal::list<>, sc::j3>, flat_getter<fatal::list<>, sc::k>, flat_getter<fatal::list<>, sc::k1>, flat_getter<fatal::list<>, sc::k2>, flat_getter<fatal::list<>, sc::k3>, flat_getter<fatal::list<>, sc::l>, flat_getter<fatal::list<>, sc::l1>, flat_getter<fatal::list<>, sc::l2>, flat_getter<fatal::list<>, sc::l3>, flat_getter<fatal::list<>, sc::m1>, flat_getter<fatal::list<>, sc::m2>, flat_getter<fatal::list<>, sc::m3>, flat_getter<fatal::list<>, sc::n1>, flat_getter<fatal::list<>, sc::n2>, flat_getter<fatal::list<>, sc::n3>, flat_getter<fatal::list<>, sc::o1>, flat_getter<fatal::list<>, sc::o2>, flat_getter<fatal::list<>, sc::o3> >, flatten_getters<structC> >(); EXPECT_SAME< fatal::list< flat_getter<fatal::list<>, s1::field0>, flat_getter<fatal::list<>, s1::field1>, flat_getter<fatal::list<>, s1::field2>, flat_getter<fatal::list<>, s1::field3>, flat_getter<fatal::list<>, s1::field4>, flat_getter<fatal::list<>, s1::field5> >, flatten_getters<struct1> >(); EXPECT_SAME< fatal::list< flat_getter<fatal::list<>, s2::fieldA>, flat_getter<fatal::list<>, s2::fieldB>, flat_getter<fatal::list<>, s2::fieldC>, flat_getter<fatal::list<>, s2::fieldD>, flat_getter<fatal::list<>, s2::fieldE>, flat_getter<fatal::list<>, s2::fieldF>, flat_getter<fatal::list<s2::fieldG>, s1::field0>, flat_getter<fatal::list<s2::fieldG>, s1::field1>, flat_getter<fatal::list<s2::fieldG>, s1::field2>, flat_getter<fatal::list<s2::fieldG>, s1::field3>, flat_getter<fatal::list<s2::fieldG>, s1::field4>, flat_getter<fatal::list<s2::fieldG>, s1::field5> >, flatten_getters<struct2> >(); EXPECT_SAME< fatal::list< flat_getter<fatal::list<>, s3::fieldA>, flat_getter<fatal::list<>, s3::fieldB>, flat_getter<fatal::list<>, s3::fieldC>, flat_getter<fatal::list<>, s3::fieldD>, flat_getter<fatal::list<>, s3::fieldE>, flat_getter<fatal::list<>, s3::fieldF>, flat_getter<fatal::list<s3::fieldG>, s1::field0>, flat_getter<fatal::list<s3::fieldG>, s1::field1>, flat_getter<fatal::list<s3::fieldG>, s1::field2>, flat_getter<fatal::list<s3::fieldG>, s1::field3>, flat_getter<fatal::list<s3::fieldG>, s1::field4>, flat_getter<fatal::list<s3::fieldG>, s1::field5>, flat_getter<fatal::list<>, s3::fieldH>, flat_getter<fatal::list<>, s3::fieldI>, flat_getter<fatal::list<>, s3::fieldJ>, flat_getter<fatal::list<>, s3::fieldK>, flat_getter<fatal::list<>, s3::fieldL>, flat_getter<fatal::list<>, s3::fieldM>, flat_getter<fatal::list<>, s3::fieldN>, flat_getter<fatal::list<>, s3::fieldO>, flat_getter<fatal::list<>, s3::fieldP>, flat_getter<fatal::list<>, s3::fieldQ>, flat_getter<fatal::list<>, s3::fieldR>, flat_getter<fatal::list<>, s3::fieldS> >, flatten_getters<struct3> >(); EXPECT_SAME< fatal::list< flat_getter<fatal::list<>, s4::field0>, flat_getter<fatal::list<>, s4::field1>, flat_getter<fatal::list<>, s4::field2>, flat_getter<fatal::list<s4::field3>, sa::a>, flat_getter<fatal::list<s4::field3>, sa::b> >, flatten_getters<struct4> >(); EXPECT_SAME< fatal::list< flat_getter<fatal::list<>, s5::field0>, flat_getter<fatal::list<>, s5::field1>, flat_getter<fatal::list<>, s5::field2>, flat_getter<fatal::list<s5::field3>, sa::a>, flat_getter<fatal::list<s5::field3>, sa::b>, flat_getter<fatal::list<s5::field4>, sb::c>, flat_getter<fatal::list<s5::field4>, sb::d> >, flatten_getters<struct5> >(); } struct annotated_terminals_only_filter { template <typename Member> using apply = fatal::negate<fatal::empty<typename Member::annotations::map>>; }; TEST(flatten_getters, annotated_terminals_only) { using sa = reflect_struct<structA>::member; using sb = reflect_struct<structB>::member; using sc = reflect_struct<structC>::member; using s1 = reflect_struct<struct1>::member; using s2 = reflect_struct<struct2>::member; using s3 = reflect_struct<struct3>::member; using s4 = reflect_struct<struct4>::member; using s5 = reflect_struct<struct5>::member; EXPECT_SAME< fatal::list<>, flatten_getters<structA, annotated_terminals_only_filter> >(); EXPECT_SAME< fatal::list< flat_getter<fatal::list<>, sb::d> >, flatten_getters<structB, annotated_terminals_only_filter> >(); EXPECT_SAME< fatal::list<>, flatten_getters<structC, annotated_terminals_only_filter> >(); EXPECT_SAME< fatal::list<>, flatten_getters<struct1, annotated_terminals_only_filter> >(); EXPECT_SAME< fatal::list<>, flatten_getters<struct2, annotated_terminals_only_filter> >(); EXPECT_SAME< fatal::list<>, flatten_getters<struct3, annotated_terminals_only_filter> >(); EXPECT_SAME< fatal::list<>, flatten_getters<struct4, annotated_terminals_only_filter> >(); EXPECT_SAME< fatal::list< flat_getter<fatal::list<>, s5::field3>, flat_getter<fatal::list<s5::field4>, sb::d> >, flatten_getters<struct5, annotated_terminals_only_filter> >(); } struct runtime_checker { template <typename Member, std::size_t Index, typename T, typename Expected> void operator ()( fatal::indexed<Member, Index>, T const &actual, Expected const &expected ) const { EXPECT_EQ(std::get<Index>(expected), Member::getter::ref(actual)); } }; TEST(flatten_getters, runtime) { struct5 x; x.set_field0(10); x.set_field1("hello"); x.set_field2(enum1::field2); x.field3.set_a(56); x.field3.set_b("world"); x.field4.set_c(7.2); x.field4.set_d(true); fatal::foreach<flatten_getters<struct5>>( runtime_checker(), x, std::make_tuple(10, "hello", enum1::field2, 56, "world", 7.2, true) ); } } // namespace cpp_reflection { } // namespace test_cpp2 {
{ "content_hash": "826a9582bc307c1ae7ac687e6fffd2aa", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 79, "avg_line_length": 30.24206349206349, "alnum_prop": 0.6140926387613174, "repo_name": "SergeyMakarenko/fbthrift", "id": "4c6157a1eaa0546f0cc38134b7bf080c93d3408e", "size": "8216", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "thrift/test/fatal_flatten_getters_test.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "150086" }, { "name": "C#", "bytes": "28929" }, { "name": "C++", "bytes": "18204113" }, { "name": "CMake", "bytes": "9356" }, { "name": "D", "bytes": "669764" }, { "name": "Emacs Lisp", "bytes": "5154" }, { "name": "Erlang", "bytes": "23039" }, { "name": "Go", "bytes": "375667" }, { "name": "HTML", "bytes": "328615" }, { "name": "Hack", "bytes": "939114" }, { "name": "Haskell", "bytes": "297109" }, { "name": "Java", "bytes": "2386487" }, { "name": "JavaScript", "bytes": "6018" }, { "name": "Lex", "bytes": "11763" }, { "name": "M4", "bytes": "99564" }, { "name": "Makefile", "bytes": "51102" }, { "name": "OCaml", "bytes": "32043" }, { "name": "Objective-C", "bytes": "142982" }, { "name": "PHP", "bytes": "279643" }, { "name": "Perl", "bytes": "70682" }, { "name": "Protocol Buffer", "bytes": "585" }, { "name": "Python", "bytes": "1722870" }, { "name": "Ruby", "bytes": "323073" }, { "name": "Scala", "bytes": "1266" }, { "name": "Shell", "bytes": "23528" }, { "name": "Smalltalk", "bytes": "22812" }, { "name": "TeX", "bytes": "48707" }, { "name": "Thrift", "bytes": "232940" }, { "name": "Vim script", "bytes": "2837" }, { "name": "Yacc", "bytes": "33572" } ], "symlink_target": "" }
package io.yawp.servlet.child; import static org.junit.Assert.assertEquals; import io.yawp.repository.models.parents.Child; import java.util.List; import org.junit.Test; public class ChildCustomActionTest extends ChildServletTestCase { @Test public void testOverObject() { Child child = saveChild("xpto", parent); String json = put(uri("/parents/%s/children/%s/touched", parent, child)); Child retrievedChild = from(json, Child.class); assertEquals("touched xpto", retrievedChild.getName()); assertEquals(parent.getId(), retrievedChild.getParentId()); } @Test public void testOverCollection() { saveChild("xpto1", parent); saveChild("xpto2", parent); saveChild("xpto3", saveParent()); String json = put(uri("/parents/%s/children/touched", parent)); List<Child> children = fromList(json, Child.class); assertEquals(2, children.size()); assertEquals("touched xpto1", children.get(0).getName()); assertEquals("touched xpto2", children.get(1).getName()); assertEquals(parent.getId(), children.get(0).getParentId()); assertEquals(parent.getId(), children.get(1).getParentId()); } @Test public void overCollectionWithJsonAndParams() { saveParent(); String json = post(uri("/parents/%s/children/with-json-and-params", parent), "{ 'id': '/basic_objects/1', 'stringValue': 'basic object' }", params("x", "y")); assertEquals("basic object y - /basic_objects/1", from(json, String.class)); } }
{ "content_hash": "4dc371e590ece45d2a74dc3d78d8dd56", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 98, "avg_line_length": 32.53061224489796, "alnum_prop": 0.6461731493099122, "repo_name": "danilodeLuca/yawp", "id": "a578a309c502fbe803fe1387a38e04ed2fc510d0", "size": "1594", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "yawp-core/src/test/java/io/yawp/servlet/child/ChildCustomActionTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1854" }, { "name": "Java", "bytes": "815998" }, { "name": "JavaScript", "bytes": "107624" }, { "name": "Python", "bytes": "5168" }, { "name": "Shell", "bytes": "5549" } ], "symlink_target": "" }
// Returns all possible slot candidates, sorted by "quality" export function findAllSlotCandidates(particle, slotSpec, arcInfo) { const slotConn = particle.getSlandleConnectionByName(slotSpec.name); return { // Note: during manfiest parsing, target slot is only set in slot connection, if the slot exists in the recipe. // If this slot is internal to the recipe, it has the sourceConnection set to the providing connection // (and hence the consuming connection is considered connected already). Otherwise, this may only be a remote slot. local: !slotConn || !slotConn.targetSlot ? _findSlotCandidates(particle, slotSpec, particle.recipe.slots) : [], remote: _findSlotCandidates(particle, slotSpec, [...arcInfo.slotContainers, ...arcInfo.activeRecipe.slots]) }; } // Returns the given slot candidates, sorted by "quality". // TODO(sjmiles): `slots` is either Slot[] or ProvidedSlotContext[] ... these types do not obviously match, // seems like it's using only `[thing].spec` function _findSlotCandidates(particle, slotSpec, slots) { const possibleSlots = slots.filter(s => slotMatches(particle, slotSpec, s)); possibleSlots.sort((slot1, slot2) => { // TODO: implement. return slot1.name < slot2.name; }); return possibleSlots; } // Returns true, if the given slot is a viable candidate for the slotConnection. export function slotMatches(particle, slotSpec, slot) { if (!slotSpec || !slot.spec || slotSpec.isSet !== slot.spec.isSet) { return false; } const potentialSlotConn = particle.getSlandleConnectionBySpec(slotSpec); if (!tagsOrNameMatch(slotSpec, slot.spec, potentialSlotConn, slot)) { return false; } // Match handles of the provided slot with the slot-connection particle's handles. if (!handlesMatch(particle, slot)) { return false; } return true; } // Returns true, if the providing slot handle restrictions are satisfied by the consuming slot connection. // TODO: should we move some of this logic to the recipe? Or type matching? export function handlesMatch(particle, slot) { if (slot.handles.length === 0) { return true; // slot is not limited to specific handles } return !!Object.values(particle.connections).find(handleConn => { return slot.handles.includes(handleConn.handle) || (handleConn.handle && handleConn.handle.id && slot.handles.map(sh => sh.id).includes(handleConn.handle.id)); }); } export function tagsOrNameMatch(consumeSlotSpec, provideSlotSpec, consumeSlotConn, provideSlot) { const consumeTags = [].concat(consumeSlotSpec.tags || [], consumeSlotConn ? consumeSlotConn.tags : [], consumeSlotConn && consumeSlotConn.targetSlot ? consumeSlotConn.targetSlot.tags : []); const provideTags = [].concat(provideSlotSpec.tags || [], provideSlot ? provideSlot.tags : [], provideSlot ? provideSlot.name : (provideSlotSpec.name ? provideSlotSpec.name : [])); if (consumeTags.length > 0 && consumeTags.some(t => provideTags.includes(t))) { return true; } return consumeSlotSpec.name === (provideSlot ? provideSlot.name : provideSlotSpec.name); } //# sourceMappingURL=slot-utils.js.map
{ "content_hash": "71df808255ec19b6875d819ada7e1bba", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 193, "avg_line_length": 55.60344827586207, "alnum_prop": 0.7085271317829457, "repo_name": "PolymerLabs/arcs-live", "id": "77517bbe83b3bccecf17bc36f9cc341caf912ee0", "size": "3536", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/runtime/recipe/internal/slot-utils.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "42" }, { "name": "C++", "bytes": "2523" }, { "name": "CSS", "bytes": "91310" }, { "name": "CoffeeScript", "bytes": "3272" }, { "name": "HTML", "bytes": "1280188" }, { "name": "JavaScript", "bytes": "6704824" }, { "name": "Kotlin", "bytes": "55841" }, { "name": "Makefile", "bytes": "89" }, { "name": "PHP", "bytes": "3338" }, { "name": "Shell", "bytes": "2391" }, { "name": "Starlark", "bytes": "7650" }, { "name": "TypeScript", "bytes": "178144" } ], "symlink_target": "" }
#ifndef LIBXAOS_CORE_POINTERS_INTERNAL_CONTROLBLOCK_H #define LIBXAOS_CORE_POINTERS_INTERNAL_CONTROLBLOCK_H namespace libxaos { namespace pointers { namespace internal { // an extra namespace.. just to deter outside use //! An enum for differentiating between owners and observers enum ReferenceType { STRONG, WEAK }; //! An enum for differentiating between pointer types. enum PointerType { PLAIN, ARRAY }; /** * @brief A ControlBlock handles the lifetime of a shared pointer. * * THIS CLASS IS INTERNAL ONLY. YOU SHOULD NOT BE USING IT. * * A ControlBlock manages the lifetime of a shared pointer based on * registered Strong and Weak references. It deletes the held * pointer based on those referencing itself. Additionally, it * manages its own lifetime and will destroy itself when there are * no longer any shared pointers utilizing it. */ template<typename T, PointerType P> class ControlBlock { public: //! Create a ControlBlock* static inline ControlBlock<T, P>* create(T*); ~ControlBlock(); //! Should not be copy constructed ControlBlock(const ControlBlock<T, P>&) = delete; //! Should not be copy assigned ControlBlock<T, P>& operator=(const ControlBlock<T, P>&) = delete; //! Should not be move constructed ControlBlock(ControlBlock<T, P>&&) = delete; //! Should not be move assigned. ControlBlock<T, P>& operator=(ControlBlock<T, P>&&) = delete; //! Returns the pointer inline T* getPointer() const; //! Increment reference void incrementReference(ReferenceType); //! Decrement reference void decrementReference(ReferenceType); //! Validates the internal pointer to be non-null inline operator bool() const; private: //! Constructs a ControlBlock from a T* . This constructor //! is private since it shouldn't be stack allocated. ControlBlock(T*); //! Deletes the internal pointer inline void deletePointer(); //! The held pointer T* _pointer; //! The number of strong shared pointers using this block. int _strongReferences; //! The number of weak shared pointers using this block. int _weakReferences; }; } } } // Pull in implementations #include "ControlBlock-tpp.h" #endif // LIBXAOS_CORE_POINTERS_INTERNAL_CONTROLBLOCK_H
{ "content_hash": "40814e6cb84d2a9ac4ee30f272bc333b", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 80, "avg_line_length": 37.68235294117647, "alnum_prop": 0.5076490789884484, "repo_name": "CorneliaXaos/libxaos", "id": "faf0460e4d22e83dc245f5dac38578f8181e39e5", "size": "3203", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libxaos-core/interface/pointers/__internal__/ControlBlock.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2482" }, { "name": "C++", "bytes": "592594" } ], "symlink_target": "" }
.meanUser-example h1 { background-color: purple }
{ "content_hash": "388934ee4cdc9e32b20e139337c11955", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 25, "avg_line_length": 16.666666666666668, "alnum_prop": 0.76, "repo_name": "dianavermilya/rain", "id": "02006571487d3325357dc1dd566617f1f5c80511", "size": "50", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/users/public/assets/css/meanUser.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2147" }, { "name": "JavaScript", "bytes": "76336" }, { "name": "Perl", "bytes": "48" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('main', '0001_initial'), ] operations = [ migrations.CreateModel( name='Item', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('descriptor', models.SlugField(default='1')), ('notes', models.TextField(blank=True)), ], ), migrations.CreateModel( name='ItemRequest', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('accepted', models.BooleanField(default=False)), ('picked_up', models.BooleanField(default=False)), ('returned', models.BooleanField(default=False)), ('start_date', models.DateField()), ('end_date', models.DateField()), ('notes', models.TextField(blank=True)), ('was_checked', models.BooleanField(default=False, editable=False)), ('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='equipment.Item')), ('member', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='main.TeamMember')), ], ), migrations.CreateModel( name='ItemType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('descriptor', models.CharField(max_length=3)), ('location', models.CharField(max_length=100)), ('quantity', models.IntegerField()), ], ), migrations.AddField( model_name='item', name='item_type', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='equipment.ItemType'), ), ]
{ "content_hash": "7b17b5fab89d03ce5401cb49575547ee", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 116, "avg_line_length": 40.27777777777778, "alnum_prop": 0.5577011494252874, "repo_name": "rit-sailing/website", "id": "20d08b798e524fa383cf8a9be9a8011ffa4135eb", "size": "2247", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "equipment/migrations/0001_initial.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "29508" }, { "name": "HTML", "bytes": "103215" }, { "name": "JavaScript", "bytes": "81277" }, { "name": "Python", "bytes": "66948" } ], "symlink_target": "" }
// // OpenUpIntersitialWrapper.h // OpenUpSDK // // Created by steve on 2017/4/18. // Copyright © 2017年 liuguojun. All rights reserved. // #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> @protocol OpenUpIntersitialDelegate; @protocol OpenUpIntersitialLoadDelegate; @interface OpenUpIntersitialWrapper : NSObject - (instancetype)initPlacement:(NSString *)placement; - (NSString *)getPlacement; - (void)setDelegate:(id<OpenUpIntersitialDelegate>)delegate; - (BOOL)isReady; - (BOOL)show:(UIViewController *)viewController; - (void)load:(id<OpenUpIntersitialLoadDelegate>)loadDelegate; - (void)onlineReportDebug:(NSString *)eid placeId: placeid msg:(NSString *)msg; @end @protocol OpenUpIntersitialDelegate <NSObject> /** 插屏广告展示 @param interstitialAd 插屏广告 */ - (void)interstitialAdDidShow:(OpenUpIntersitialWrapper *)interstitialAd; /** 插屏广告关闭 @param interstitialAd 插屏广告 */ - (void)interstitialAdDidClose:(OpenUpIntersitialWrapper *)interstitialAd; /** 插屏广告点击 @param interstitialAd 插屏广告 */ - (void)interstitialAdDidClick:(OpenUpIntersitialWrapper *)interstitialAd; @end @protocol OpenUpIntersitialLoadDelegate <NSObject> /** 插屏广告加载成功 @param interstitialAd 插屏广告 */ - (void)interstitialAdDidLoad:(OpenUpIntersitialWrapper *)interstitialAd; /** 插屏广告加载失败 @param interstitialAd 插屏广告 */ - (void)interstitialAdDidLoadFail:(OpenUpIntersitialWrapper *)interstitialAd; @end
{ "content_hash": "ad8a3db951c869619e775839c37c2571", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 79, "avg_line_length": 19.397260273972602, "alnum_prop": 0.7690677966101694, "repo_name": "guojunliu/AvidlyAdsSDK", "id": "1938f8604129a08a20771f465b17cd7b00a7dfac", "size": "1527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Framework/OpenUpSDK/OpenUpSDK.framework/Headers/OpenUpIntersitialWrapper.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "45108" }, { "name": "Objective-C", "bytes": "1097930" }, { "name": "Ruby", "bytes": "2956" } ], "symlink_target": "" }
package org.opensaml.xml.signature.impl; import org.opensaml.xml.schema.impl.XSStringImpl; import org.opensaml.xml.signature.X509IssuerName; /** * Concrete implementation of {@link org.opensaml.xml.signature.X509IssuerName} */ public class X509IssuerNameImpl extends XSStringImpl implements X509IssuerName { /** * Constructor * * @param namespaceURI * @param elementLocalName * @param namespacePrefix */ protected X509IssuerNameImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { super(namespaceURI, elementLocalName, namespacePrefix); } }
{ "content_hash": "1c541df214fa603334f15e8bc42975a0", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 104, "avg_line_length": 26.958333333333332, "alnum_prop": 0.7125193199381762, "repo_name": "duck1123/java-xmltooling", "id": "9b85ca81fcad3c28c6c0f8da92e67a0a2b0b569e", "size": "1306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/opensaml/xml/signature/impl/X509IssuerNameImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2401232" } ], "symlink_target": "" }
<readable><title>3517362674_0f5296de19</title><content> A girl is blowing bubbles heavily . A little girl closes her eyes and blows through a bubble wand . A little girl with dark hair blowing bubbles . A small girl blows on an orange bubble stick . A young girl is blowing bubbles with an orange bubble wand . </content></readable>
{ "content_hash": "be7efa97ec0c53f51265075a027653b8", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 63, "avg_line_length": 47.42857142857143, "alnum_prop": 0.7801204819277109, "repo_name": "kevint2u/audio-collector", "id": "f4618627e94c47fac42887451e53ba1ec4403a36", "size": "332", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "captions/xml/3517362674_0f5296de19.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1015" }, { "name": "HTML", "bytes": "18349" }, { "name": "JavaScript", "bytes": "109819" }, { "name": "Python", "bytes": "3260" }, { "name": "Shell", "bytes": "4319" } ], "symlink_target": "" }
package com.android.settings.bluetooth; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothClass; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothUuid; import android.content.Context; import android.os.ParcelUuid; import android.util.Log; import com.android.settings.R; import java.util.ArrayList; import java.util.List; /** * HeadsetProfile handles Bluetooth HFP and Headset profiles. */ final class HeadsetProfile implements LocalBluetoothProfile { private static final String TAG = "HeadsetProfile"; private static boolean V = true; private BluetoothHeadset mService; private boolean mIsProfileReady; private final LocalBluetoothAdapter mLocalAdapter; private final CachedBluetoothDeviceManager mDeviceManager; private final LocalBluetoothProfileManager mProfileManager; static final ParcelUuid[] UUIDS = { BluetoothUuid.HSP, BluetoothUuid.Handsfree, }; static final String NAME = "HEADSET"; // Order of this profile in device profiles list private static final int ORDINAL = 0; // These callbacks run on the main thread. private final class HeadsetServiceListener implements BluetoothProfile.ServiceListener { public void onServiceConnected(int profile, BluetoothProfile proxy) { if (V) Log.d(TAG,"Bluetooth service connected"); mService = (BluetoothHeadset) proxy; // We just bound to the service, so refresh the UI for any connected HFP devices. List<BluetoothDevice> deviceList = mService.getConnectedDevices(); while (!deviceList.isEmpty()) { BluetoothDevice nextDevice = deviceList.remove(0); CachedBluetoothDevice device = mDeviceManager.findDevice(nextDevice); // we may add a new device here, but generally this should not happen if (device == null) { Log.w(TAG, "HeadsetProfile found new device: " + nextDevice); device = mDeviceManager.addDevice(mLocalAdapter, mProfileManager, nextDevice); } device.onProfileStateChanged(HeadsetProfile.this, BluetoothProfile.STATE_CONNECTED); device.refresh(); } mProfileManager.callServiceConnectedListeners(); mIsProfileReady=true; } public void onServiceDisconnected(int profile) { if (V) Log.d(TAG,"Bluetooth service disconnected"); mProfileManager.callServiceDisconnectedListeners(); mIsProfileReady=false; } } public boolean isProfileReady() { return mIsProfileReady; } HeadsetProfile(Context context, LocalBluetoothAdapter adapter, CachedBluetoothDeviceManager deviceManager, LocalBluetoothProfileManager profileManager) { mLocalAdapter = adapter; mDeviceManager = deviceManager; mProfileManager = profileManager; mLocalAdapter.getProfileProxy(context, new HeadsetServiceListener(), BluetoothProfile.HEADSET); } public boolean isConnectable() { return true; } public boolean isAutoConnectable() { return true; } public boolean connect(BluetoothDevice device) { if (mService == null) return false; List<BluetoothDevice> sinks = mService.getConnectedDevices(); if (sinks != null) { for (BluetoothDevice sink : sinks) { mService.disconnect(sink); } } return mService.connect(device); } public boolean disconnect(BluetoothDevice device) { if (mService == null) return false; List<BluetoothDevice> deviceList = mService.getConnectedDevices(); if (!deviceList.isEmpty() && deviceList.get(0).equals(device)) { // Downgrade priority as user is disconnecting the headset. if (mService.getPriority(device) > BluetoothProfile.PRIORITY_ON) { mService.setPriority(device, BluetoothProfile.PRIORITY_ON); } return mService.disconnect(device); } else { return false; } } public int getConnectionStatus(BluetoothDevice device) { if (mService == null) return BluetoothProfile.STATE_DISCONNECTED; List<BluetoothDevice> deviceList = mService.getConnectedDevices(); return !deviceList.isEmpty() && deviceList.get(0).equals(device) ? mService.getConnectionState(device) : BluetoothProfile.STATE_DISCONNECTED; } public boolean isPreferred(BluetoothDevice device) { if (mService == null) return false; return mService.getPriority(device) > BluetoothProfile.PRIORITY_OFF; } public int getPreferred(BluetoothDevice device) { if (mService == null) return BluetoothProfile.PRIORITY_OFF; return mService.getPriority(device); } public void setPreferred(BluetoothDevice device, boolean preferred) { if (mService == null) return; if (preferred) { if (mService.getPriority(device) < BluetoothProfile.PRIORITY_ON) { mService.setPriority(device, BluetoothProfile.PRIORITY_ON); } } else { mService.setPriority(device, BluetoothProfile.PRIORITY_OFF); } } public List<BluetoothDevice> getConnectedDevices() { if (mService == null) return new ArrayList<BluetoothDevice>(0); return mService.getDevicesMatchingConnectionStates( new int[] {BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTING}); } public String toString() { return NAME; } public int getOrdinal() { return ORDINAL; } public int getNameResource(BluetoothDevice device) { return R.string.bluetooth_profile_headset; } public int getSummaryResourceForDevice(BluetoothDevice device) { int state = getConnectionStatus(device); switch (state) { case BluetoothProfile.STATE_DISCONNECTED: return R.string.bluetooth_headset_profile_summary_use_for; case BluetoothProfile.STATE_CONNECTED: return R.string.bluetooth_headset_profile_summary_connected; default: return Utils.getConnectionStateSummary(state); } } public int getDrawableResource(BluetoothClass btClass) { return R.drawable.ic_bt_headset_hfp; } protected void finalize() { if (V) Log.d(TAG, "finalize()"); if (mService != null) { try { BluetoothAdapter.getDefaultAdapter().closeProfileProxy(BluetoothProfile.HEADSET, mService); mService = null; }catch (Throwable t) { Log.w(TAG, "Error cleaning up HID proxy", t); } } } }
{ "content_hash": "2f7648f53d6d96fb0a4565b1fa2593df", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 98, "avg_line_length": 35.34313725490196, "alnum_prop": 0.6425797503467406, "repo_name": "craigacgomez/flaming_monkey_packages_apps_Settings", "id": "1caeb65422c3ffe5395cfbb89c7fdcc698e7bcea", "size": "7829", "binary": false, "copies": "2", "ref": "refs/heads/android-4.3.1_r1", "path": "src/com/android/settings/bluetooth/HeadsetProfile.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2798404" } ], "symlink_target": "" }
package br.com.infowaypi.jheat.usage.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import br.com.infowaypi.jheat.usage.core.AppManager; public class AuthRedirectServlet extends HttpServlet { private static final long serialVersionUID = -553751587556822709L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("report_engine_id"); // AppManager.getInstance().registerReportEngine(reportEngineId, reportEngine); super.doGet(req, resp); } }
{ "content_hash": "4443201b9accd00a994313c47e2d27b0", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 110, "avg_line_length": 31.043478260869566, "alnum_prop": 0.8151260504201681, "repo_name": "infoway-ehealth-company/jheatbased-project-usage", "id": "85798db198c2e1431b960ac6e2afd19c95babf74", "size": "714", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jhbu-webapp/src/main/java/br/com/infowaypi/jheat/usage/servlet/AuthRedirectServlet.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "53706" }, { "name": "JavaScript", "bytes": "3540" } ], "symlink_target": "" }
require 'aws-sdk' module CSI module AWS # This module provides a client for making API requests to AWS OpsWorks. module OpsWorks @@logger = CSI::Plugins::CSILogger.create # Supported Method Parameters:: # CSI::AWS::OpsWorks.connect( # region: 'required - region name to connect (eu-west-1, ap-southeast-1, ap-southeast-2, eu-central-1, ap-northeast-2, ap-northeast-1, us-east-1, sa-east-1, us-west-1, us-west-2)', # access_key_id: 'required - Use AWS STS for best privacy (i.e. temporary access key id)', # secret_access_key: 'required - Use AWS STS for best privacy (i.e. temporary secret access key', # sts_session_token: 'optional - Temporary token returned by STS client for best privacy' # ) public_class_method def self.connect(opts = {}) region = opts[:region].to_s.scrub.chomp.strip access_key_id = opts[:access_key_id].to_s.scrub.chomp.strip secret_access_key = opts[:secret_access_key].to_s.scrub.chomp.strip sts_session_token = opts[:sts_session_token].to_s.scrub.chomp.strip @@logger.info('Connecting to AWS OpsWorks...') if sts_session_token == '' ops_works_obj = Aws::OpsWorks::Client.new( region: region, access_key_id: access_key_id, secret_access_key: secret_access_key ) else ops_works_obj = Aws::OpsWorks::Client.new( region: region, access_key_id: access_key_id, secret_access_key: secret_access_key, session_token: sts_session_token ) end @@logger.info("complete.\n") ops_works_obj rescue StandardError => e raise e end # Supported Method Parameters:: # CSI::AWS::OpsWorks.disconnect( # ops_works_obj: 'required - ops_works_obj returned from #connect method' # ) public_class_method def self.disconnect(opts = {}) ops_works_obj = opts[:ops_works_obj] @@logger.info('Disconnecting...') ops_works_obj = nil @@logger.info("complete.\n") ops_works_obj rescue StandardError => e raise e end # Author(s):: Jacob Hoopes <jake.hoopes@gmail.com> public_class_method def self.authors "AUTHOR(S): Jacob Hoopes <jake.hoopes@gmail.com> " end # Display Usage for this Module public_class_method def self.help puts "USAGE: ops_works_obj = #{self}.connect( region: 'required - region name to connect (eu-west-1, ap-southeast-1, ap-southeast-2, eu-central-1, ap-northeast-2, ap-northeast-1, us-east-1, sa-east-1, us-west-1, us-west-2)', access_key_id: 'required - Use AWS STS for best privacy (i.e. temporary access key id)', secret_access_key: 'required - Use AWS STS for best privacy (i.e. temporary secret access key', sts_session_token: 'optional - Temporary token returned by STS client for best privacy' ) puts ops_works_obj.public_methods #{self}.disconnect( ops_works_obj: 'required - ops_works_obj returned from #connect method' ) #{self}.authors " end end end end
{ "content_hash": "27fa651d7fcc77735c4b4604eec6cdc4", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 190, "avg_line_length": 36.48888888888889, "alnum_prop": 0.5992691839220463, "repo_name": "ninp0/csi", "id": "0aab5b3af64584223940dba432714bda7c378a36", "size": "3315", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/csi/aws/ops_works.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "1351941" }, { "name": "Shell", "bytes": "72652" } ], "symlink_target": "" }
cv::Mat img_uti::CropResize(cv::Mat& input_image, int image_size){ int org_row = input_image.rows; int org_col = input_image.cols; cv::Mat croped_image; cv::Mat resized_image; cv::Rect crop_reg; if (org_row <= org_col){ int start_col = (org_col - org_row)/2; int end_col = start_col + org_row; crop_reg = cv::Rect(start_col, 0, org_row, org_row); } else{ int start_row = (org_row - org_col)/2; int end_row = start_row + org_col; crop_reg = cv::Rect(0, start_row, org_col, org_col); } croped_image = input_image(crop_reg); cv::resize(croped_image, resized_image, cv::Size(image_size, image_size)); return resized_image; }
{ "content_hash": "230e1890bac71cb7f2f8dfd132d896eb", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 74, "avg_line_length": 26, "alnum_prop": 0.6476923076923077, "repo_name": "polltooh/FineGrainedAction", "id": "19bdc6ad600ff555486e1647d1b236d3063d8eb2", "size": "673", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/img_uti.cc", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "24672" }, { "name": "CMake", "bytes": "1119" }, { "name": "Python", "bytes": "188905" }, { "name": "Shell", "bytes": "54" } ], "symlink_target": "" }
import os from collections import defaultdict from hashlib import sha1 from pants.base.build_environment import get_buildroot from pants.base.hash_utils import CoercingEncoder, json_hash from pants.option.custom_types import UnsetBool, dict_with_files_option, dir_option, file_option class CoercingOptionEncoder(CoercingEncoder): def default(self, o): if o is UnsetBool: return "_UNSET_BOOL_ENCODING" return super().default(o) def stable_option_fingerprint(obj): return json_hash(obj, encoder=CoercingOptionEncoder) class OptionsFingerprinter: """Handles fingerprinting options under a given build_graph. :API: public """ @classmethod def combined_options_fingerprint_for_scope(cls, scope, options, **kwargs) -> str: """Given options and a scope, compute a combined fingerprint for the scope. :param string scope: The scope to fingerprint. :param Options options: The `Options` object to fingerprint. :param BuildGraph build_graph: A `BuildGraph` instance, only needed if fingerprinting target options. :param dict **kwargs: Keyword parameters passed on to `Options#get_fingerprintable_for_scope`. :return: Hexadecimal string representing the fingerprint for all `options` values in `scope`. """ fingerprinter = cls() hasher = sha1() pairs = options.get_fingerprintable_for_scope(scope, **kwargs) for (option_type, option_value) in pairs: fingerprint = fingerprinter.fingerprint(option_type, option_value) if fingerprint is None: # This isn't necessarily a good value to be using here, but it preserves behavior from # before the commit which added it. I suspect that using the empty string would be # reasonable too, but haven't done any archaeology to check. fingerprint = "None" hasher.update(fingerprint.encode()) return hasher.hexdigest() def fingerprint(self, option_type, option_val): """Returns a hash of the given option_val based on the option_type. :API: public Returns None if option_val is None. """ if option_val is None: return None # Wrapping all other values in a list here allows us to easily handle single-valued and # list-valued options uniformly. For non-list-valued options, this will be a singleton list # (with the exception of dict, which is not modified). This dict exception works because we do # not currently have any "list of dict" type, so there is no ambiguity. if not isinstance(option_val, (list, tuple, dict)): option_val = [option_val] if option_type == dir_option: return self._fingerprint_dirs(option_val) elif option_type == file_option: return self._fingerprint_files(option_val) elif option_type == dict_with_files_option: return self._fingerprint_dict_with_files(option_val) else: return self._fingerprint_primitives(option_val) def _assert_in_buildroot(self, filepath): """Raises an error if the given filepath isn't in the buildroot. Returns the normalized, absolute form of the path. """ filepath = os.path.normpath(filepath) root = get_buildroot() if not os.path.abspath(filepath) == filepath: # If not absolute, assume relative to the build root. return os.path.join(root, filepath) else: if ".." in os.path.relpath(filepath, root).split(os.path.sep): # The path wasn't in the buildroot. This is an error because it violates the pants being # hermetic. raise ValueError( "Received a file_option that was not inside the build root:\n" " file_option: {filepath}\n" " build_root: {buildroot}\n".format(filepath=filepath, buildroot=root) ) return filepath def _fingerprint_dirs(self, dirpaths, topdown=True, onerror=None, followlinks=False): """Returns a fingerprint of the given file directories and all their sub contents. This assumes that the file directories are of reasonable size to cause memory or performance issues. """ # Note that we don't sort the dirpaths, as their order may have meaning. filepaths = [] for dirpath in dirpaths: dirs = os.walk(dirpath, topdown=topdown, onerror=onerror, followlinks=followlinks) sorted_dirs = sorted(dirs, key=lambda d: d[0]) filepaths.extend( [ os.path.join(dirpath, filename) for dirpath, dirnames, filenames in sorted_dirs for filename in sorted(filenames) ] ) return self._fingerprint_files(filepaths) def _fingerprint_files(self, filepaths): """Returns a fingerprint of the given filepaths and their contents. This assumes the files are small enough to be read into memory. """ hasher = sha1() # Note that we don't sort the filepaths, as their order may have meaning. for filepath in filepaths: filepath = self._assert_in_buildroot(filepath) hasher.update(os.path.relpath(filepath, get_buildroot()).encode()) with open(filepath, "rb") as f: hasher.update(f.read()) return hasher.hexdigest() def _fingerprint_primitives(self, val): return stable_option_fingerprint(val) def _fingerprint_dict_with_files(self, option_val): """Returns a fingerprint of the given dictionary containing file paths. Any value which is a file path which exists on disk will be fingerprinted by that file's contents rather than by its path. This assumes the files are small enough to be read into memory. NB: The keys of the dict are assumed to be strings -- if they are not, the dict should be converted to encode its keys with `stable_option_fingerprint()`, as is done in the `fingerprint()` method. """ final = defaultdict(list) for k, v in option_val.items(): for sub_value in sorted(v.split(",")): if os.path.isfile(sub_value): with open(sub_value, "r") as f: final[k].append(f.read()) else: final[k].append(sub_value) fingerprint = stable_option_fingerprint(final) return fingerprint
{ "content_hash": "965f4dbae0d85bdd04dd40cdd1da7f94", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 106, "avg_line_length": 42.962025316455694, "alnum_prop": 0.6208014142604596, "repo_name": "jsirois/pants", "id": "3b577122190f3c3bb203e31e692f37201bea818f", "size": "6920", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/python/pants/option/options_fingerprinter.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "6008" }, { "name": "Mustache", "bytes": "1798" }, { "name": "Python", "bytes": "2837069" }, { "name": "Rust", "bytes": "1241058" }, { "name": "Shell", "bytes": "57720" }, { "name": "Starlark", "bytes": "27937" } ], "symlink_target": "" }
package LOL; import java.sql.*; import LOL.Champion.*; import LOL.Item.*; public class DB_Client { // DB variables private Connection conn; private Statement stmt; final int CHAMP_STAT_MAX = 21; final int ITEM_STAT_MAX = 21; public DB_Client(){ try{ Class.forName("com.mysql.jdbc.Driver"); } catch(Exception e) { System.out.println("JDBC Driver Error.");} try{ conn = DriverManager.getConnection( "jdbc:mysql://mysql.cnsp.iit.edu/hkim19", "hkim19", "hkim19lolteam"); stmt = conn.createStatement(); } catch (Exception sqle) { System.out.println("Exception : " + sqle);} } public String [] getChamp (int id){ String [] stat = new String [CHAMP_STAT_MAX]; try { ResultSet rset = stmt.executeQuery( "SELECT * " + "FROM Champ " + "WHERE id =" + id); int i = 0; rset.next(); while (i != CHAMP_STAT_MAX) { stat[i] = rset.getString(i+1); i++; } }catch (Exception sqle) {System.out.println("Exception: " + sqle);} return stat; } public String [] getItem (int id){ String [] stat = new String[ITEM_STAT_MAX]; try { ResultSet rset = stmt.executeQuery( "SELECT * " + "FROM Item " + "WHERE id =" + id); int i = 0; rset.next(); while (i != CHAMP_STAT_MAX) { stat[i] = rset.getString(i+1); i++; } }catch (Exception sqle) {System.out.println("Exception: " + sqle);} return stat; } public int getChampMax(){ return CHAMP_STAT_MAX; } public int getItemMax(){ return ITEM_STAT_MAX; } }
{ "content_hash": "158e80d8c38576b5a3a8166bb8ce0ff6", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 57, "avg_line_length": 18.410526315789475, "alnum_prop": 0.5288736420811893, "repo_name": "Sensimuse/LoL_Simulator", "id": "497214be41553bbd6724658fb13310f607306d3a", "size": "1749", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Java/LOL/DB_Client.java", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "229" }, { "name": "Java", "bytes": "27906" }, { "name": "JavaScript", "bytes": "641" }, { "name": "Ruby", "bytes": "105387" } ], "symlink_target": "" }