code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
<a href='https://github.com/angular/angular.js/edit//src/ng/log.js?message=docs($log)%3A%20describe%20your%20change...#L3' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a>
<a href='https://github.com/angular/angular.js/tree/v1.3.20/src/ng/log.js#L3' class='view-source pull-right btn btn-primary'>
<i class="glyphicon glyphicon-zoom-in"> </i>View Source
</a>
<header class="api-profile-header">
<h1 class="api-profile-header-heading">$log</h1>
<ol class="api-profile-header-structure naked-list step-list">
<li>
<a href="api/ng/provider/$logProvider">- $logProvider</a>
</li>
<li>
- service in module <a href="api/ng">ng</a>
</li>
</ol>
</header>
<div class="api-profile-description">
<p>Simple service for logging. Default implementation safely writes the message
into the browser's console (if present).</p>
<p>The main purpose of this service is to simplify debugging and troubleshooting.</p>
<p>The default is to log <code>debug</code> messages. You can use
<a href="api/ng/provider/$logProvider">ng.$logProvider#debugEnabled</a> to change this.</p>
</div>
<div>
<h2 id="dependencies">Dependencies</h2>
<ul>
<li><a href="api/ng/service/$window"><code>$window</code></a></li>
</ul>
<h2>Methods</h2>
<ul class="methods">
<li id="log">
<h3><p><code>log();</code></p>
</h3>
<div><p>Write a log message</p>
</div>
</li>
<li id="info">
<h3><p><code>info();</code></p>
</h3>
<div><p>Write an information message</p>
</div>
</li>
<li id="warn">
<h3><p><code>warn();</code></p>
</h3>
<div><p>Write a warning message</p>
</div>
</li>
<li id="error">
<h3><p><code>error();</code></p>
</h3>
<div><p>Write an error message</p>
</div>
</li>
<li id="debug">
<h3><p><code>debug();</code></p>
</h3>
<div><p>Write a debug message</p>
</div>
</li>
</ul>
<h2 id="example">Example</h2><p>
<div>
<a ng-click="openPlunkr('examples/example-example111', $event)" class="btn pull-right">
<i class="glyphicon glyphicon-edit"> </i>
Edit in Plunker</a>
<div class="runnable-example"
path="examples/example-example111"
module="logExample">
<div class="runnable-example-file"
name="script.js"
language="js"
type="js">
<pre><code>angular.module('logExample', []) .controller('LogController', ['$scope', '$log', function($scope, $log) { $scope.$log = $log; $scope.message = 'Hello World!'; }]);</code></pre>
</div>
<div class="runnable-example-file"
name="index.html"
language="html"
type="html">
<pre><code><div ng-controller="LogController"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" ng-model="message"/> <button ng-click="$log.log(message)">log</button> <button ng-click="$log.warn(message)">warn</button> <button ng-click="$log.info(message)">info</button> <button ng-click="$log.error(message)">error</button> <button ng-click="$log.debug(message)">debug</button> </div></code></pre>
</div>
<iframe class="runnable-example-frame" src="examples/example-example111/index.html" name="example-example111"></iframe>
</div>
</div>
</p>
</div>
|
dolymood/angular-packages
|
angular-1.3.20/docs/partials/api/ng/service/$log.html
|
HTML
|
mit
| 3,733
|
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using PixelCrushers.DialogueSystem.Examples;
namespace PixelCrushers.DialogueSystem.Editors {
/// <summary>
/// NPC setup wizard.
/// </summary>
public class NPCSetupWizard : EditorWindow {
[MenuItem("Window/Dialogue System/Tools/Wizards/NPC Setup Wizard", false, 1)]
public static void Init() {
(EditorWindow.GetWindow(typeof(NPCSetupWizard), false, "NPC Setup") as NPCSetupWizard).minSize = new Vector2(700, 500);
}
// Private fields for the window:
private enum Stage {
SelectNPC,
SelectDB,
Conversation,
Bark,
Targeting,
Persistence,
Review
};
private Stage stage = Stage.SelectNPC;
private string[] stageLabels = new string[] { "NPC", "Database", "Conversation", "Bark", "Targeting", "Persistence", "Review" };
private const float ToggleWidth = 16;
private GameObject npcObject = null;
private DialogueDatabase database = null;
private string[] conversationList = null;
/// <summary>
/// Draws the window.
/// </summary>
void OnGUI() {
DrawProgressIndicator();
DrawCurrentStage();
}
private void DrawProgressIndicator() {
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Toolbar((int) stage, stageLabels, GUILayout.Width(700));
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
EditorGUI.EndDisabledGroup();
EditorWindowTools.DrawHorizontalLine();
}
private void DrawNavigationButtons(bool backEnabled, bool nextEnabled, bool nextCloses) {
GUILayout.FlexibleSpace();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Cancel", GUILayout.Width(100))) {
this.Close();
} else if (backEnabled && GUILayout.Button("Back", GUILayout.Width(100))) {
stage--;
} else {
EditorGUI.BeginDisabledGroup(!nextEnabled);
if (GUILayout.Button(nextCloses ? "Finish" : "Next", GUILayout.Width(100))) {
if (nextCloses) {
Close();
} else {
stage++;
}
}
EditorGUI.EndDisabledGroup();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField(string.Empty, GUILayout.Height(2));
}
private void DrawCurrentStage() {
if (npcObject == null) stage = Stage.SelectNPC;
switch (stage) {
case Stage.SelectNPC: DrawSelectNPCStage(); break;
case Stage.SelectDB: DrawSelectDBStage(); break;
case Stage.Conversation: DrawConversationStage(); break;
case Stage.Bark: DrawBarkStage(); break;
case Stage.Targeting: DrawTargetingStage(); break;
case Stage.Persistence: DrawPersistenceStage(); break;
case Stage.Review: DrawReviewStage(); break;
}
}
private void DrawSelectNPCStage() {
EditorGUILayout.LabelField("Select NPC Object", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("This wizard will help you configure a Non Player Character (NPC) object to work with the Dialogue System. First, assign the NPC's GameObject below.", MessageType.Info);
npcObject = EditorGUILayout.ObjectField("NPC Object", npcObject, typeof(GameObject), true) as GameObject;
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(false, (npcObject != null), false);
}
private void DrawSelectDBStage() {
EditorGUILayout.LabelField("Select Dialogue Database", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("Assign the dialogue database that the NPC will use for conversations and barks.", MessageType.Info);
DialogueDatabase newDatabase = EditorGUILayout.ObjectField("Dialogue Database", database, typeof(DialogueDatabase), true) as DialogueDatabase;
if (newDatabase != database) {
database = newDatabase;
CreateConversationList(database);
}
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, (database != null), false);
}
private void CreateConversationList(DialogueDatabase database) {
List<string> list = new List<string>();
if (database != null) {
list.Add(string.Empty);
foreach (var conversation in database.conversations) {
list.Add(conversation.Title);
}
}
conversationList = list.ToArray();
}
private string DrawConversationPopup(string title) {
int index = GetConversationIndex(title);
index = EditorGUILayout.Popup("Conversation", index, conversationList);
return conversationList[index];
}
private int GetConversationIndex(string title) {
for (int i = 0; i < conversationList.Length; i++) {
if (string.Equals(title, conversationList[i])) return i;
}
return 0;
}
private void DrawConversationStage() {
EditorGUILayout.LabelField("Conversation", EditorStyles.boldLabel);
ConversationTrigger conversationTrigger = npcObject.GetComponentInChildren<ConversationTrigger>();
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("If the NPC has an interactive conversation (for example, with the player), tick the checkbox below.", MessageType.Info);
EditorGUILayout.BeginHorizontal();
bool hasConversation = EditorGUILayout.Toggle((conversationTrigger != null), GUILayout.Width(ToggleWidth));
EditorGUILayout.LabelField("NPC has an interactive conversation", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
if (hasConversation) {
EditorWindowTools.StartIndentedSection();
if (conversationTrigger == null) conversationTrigger = npcObject.AddComponent<ConversationTrigger>();
EditorGUILayout.HelpBox("Select the NPC's conversation and what event will trigger it. If the NPC will only engage in this conversation once, tick Once Only. Click Select NPC to further customize the Conversation Trigger in the inspector, such as setting conditions on when the conversation can occur.",
string.IsNullOrEmpty(conversationTrigger.conversation) ? MessageType.Info : MessageType.None);
conversationTrigger.conversation = DrawConversationPopup(conversationTrigger.conversation);
conversationTrigger.once = EditorGUILayout.Toggle("Once Only", conversationTrigger.once);
conversationTrigger.trigger = DrawTriggerPopup(conversationTrigger.trigger);
if (GUILayout.Button("Select NPC", GUILayout.Width(100))) Selection.activeGameObject = npcObject;
EditorWindowTools.EndIndentedSection();
} else {
DestroyImmediate(conversationTrigger);
}
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, true, false);
}
private DialogueTriggerEvent DrawTriggerPopup(DialogueTriggerEvent trigger) {
DialogueTriggerEvent result = (DialogueTriggerEvent) EditorGUILayout.EnumPopup("Trigger", trigger);
EditorGUILayout.HelpBox(GetDialogueTriggerDescription(trigger), MessageType.None);
return result;
}
private string GetDialogueTriggerDescription(DialogueTriggerEvent trigger) {
switch (trigger) {
case DialogueTriggerEvent.OnBarkEnd: return "Will occur when the NPC receives an 'OnBarkEnd' message.";
case DialogueTriggerEvent.OnConversationEnd: return "Will occur when the NPC receives an 'OnConversationEnd' message.";
case DialogueTriggerEvent.OnEnable: return "Will occur when the NPC's components are enabled (or re-enabled).";
case DialogueTriggerEvent.OnSequenceEnd: return "Will occur when the NPC receives an 'OnSequenceEnd' message.";
case DialogueTriggerEvent.OnStart: return "Will occur when the NPC object is instantiated.";
case DialogueTriggerEvent.OnTriggerEnter: return "Will occur when a valid actor (usually the player) enters the NPC's trigger collider.";
case DialogueTriggerEvent.OnUse: return "Will occur when the NPC receives an 'OnUse' event. If the player has a Selector component, it can send OnUse. You can also send OnUse from scripts, cutscene sequences, etc.";
default: return string.Empty;
}
}
private void DrawBarkStage() {
EditorGUILayout.LabelField("Bark", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("If the NPC barks (says one-off lines during gameplay), tick either or both of the checkboxs below.", MessageType.Info);
bool hasBarkTrigger = DrawBarkTriggerSection();
EditorWindowTools.DrawHorizontalLine();
bool hasBarkOnIdle = DrawBarkOnIdleSection();
bool hasBarkComponent = hasBarkTrigger || hasBarkOnIdle;
bool hasBarkUI = false;
if (hasBarkComponent) hasBarkUI = DrawBarkUISection();
if (hasBarkComponent && GUILayout.Button("Select NPC", GUILayout.Width(100))) Selection.activeGameObject = npcObject;
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, (hasBarkUI || !hasBarkComponent), false);
}
private bool DrawBarkTriggerSection() {
EditorGUILayout.BeginHorizontal();
BarkTrigger barkTrigger = npcObject.GetComponentInChildren<BarkTrigger>();
bool hasBarkTrigger = EditorGUILayout.Toggle((barkTrigger != null), GUILayout.Width(ToggleWidth));
EditorGUILayout.LabelField("NPC barks when triggered", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
if (hasBarkTrigger) {
EditorWindowTools.StartIndentedSection();
if (barkTrigger == null) barkTrigger = npcObject.AddComponent<BarkTrigger>();
EditorGUILayout.HelpBox("Select the conversation containing the NPC's bark lines, the order in which to display them, and when barks should be triggered.", string.IsNullOrEmpty(barkTrigger.conversation) ? MessageType.Info : MessageType.None);
barkTrigger.conversation = DrawConversationPopup(barkTrigger.conversation);
barkTrigger.barkOrder = (BarkOrder) EditorGUILayout.EnumPopup("Order of Lines", barkTrigger.barkOrder);
barkTrigger.trigger = DrawTriggerPopup(barkTrigger.trigger);
EditorWindowTools.EndIndentedSection();
} else {
DestroyImmediate(barkTrigger);
}
return hasBarkTrigger;
}
private bool DrawBarkOnIdleSection() {
EditorGUILayout.BeginHorizontal();
BarkOnIdle barkOnIdle = npcObject.GetComponentInChildren<BarkOnIdle>();
bool hasBarkOnIdle = EditorGUILayout.Toggle((barkOnIdle != null), GUILayout.Width(ToggleWidth));
EditorGUILayout.LabelField("NPC barks on a timed basis", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
if (hasBarkOnIdle) {
EditorWindowTools.StartIndentedSection();
if (barkOnIdle == null) barkOnIdle = npcObject.AddComponent<BarkOnIdle>();
EditorGUILayout.HelpBox("Select the conversation containing the NPC's bark lines, the order in which to display them, and the time that should pass between barks.",
string.IsNullOrEmpty(barkOnIdle.conversation) ? MessageType.Info : MessageType.None);
barkOnIdle.conversation = DrawConversationPopup(barkOnIdle.conversation);
barkOnIdle.barkOrder = (BarkOrder) EditorGUILayout.EnumPopup("Order of Lines", barkOnIdle.barkOrder);
barkOnIdle.minSeconds = EditorGUILayout.FloatField("Min Seconds", barkOnIdle.minSeconds);
barkOnIdle.maxSeconds = EditorGUILayout.FloatField("Max Seconds", barkOnIdle.maxSeconds);
EditorWindowTools.EndIndentedSection();
} else {
DestroyImmediate(barkOnIdle);
}
return hasBarkOnIdle;
}
private bool DrawBarkUISection() {
EditorWindowTools.DrawHorizontalLine();
EditorGUILayout.BeginHorizontal();
IBarkUI barkUI = npcObject.GetComponentInChildren(typeof(IBarkUI)) as IBarkUI;
bool hasBarkUI = (barkUI != null);
EditorGUILayout.LabelField("Bark UI", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
EditorWindowTools.StartIndentedSection();
if (hasBarkUI) {
EditorGUILayout.HelpBox("The NPC has a bark UI, so it will be able to display barks.", MessageType.None);
} else {
EditorGUILayout.HelpBox("The NPC needs a bark UI to be able to display barks. Click Default Bark UI to add a default Unity GUI bark UI, or assign one manually from Window > Dialogue System > Component > UI.", MessageType.Info);
if (GUILayout.Button("Default Bark UI", GUILayout.Width(160))) {
npcObject.AddComponent<PixelCrushers.DialogueSystem.UnityGUI.UnityBarkUI>();
hasBarkUI = true;
}
}
EditorWindowTools.EndIndentedSection();
return hasBarkUI;
}
private void DrawTargetingStage() {
DrawOverrideNameSubsection(npcObject);
EditorGUILayout.LabelField("Targeting", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
ConversationTrigger conversationTrigger = npcObject.GetComponentInChildren<ConversationTrigger>();
BarkTrigger barkTrigger = npcObject.GetComponentInChildren<BarkTrigger>();
bool hasOnTriggerEnter = ((conversationTrigger != null) && (conversationTrigger.trigger == DialogueTriggerEvent.OnTriggerEnter)) ||
((barkTrigger != null) && (barkTrigger.trigger == DialogueTriggerEvent.OnTriggerEnter));
bool hasOnUse = ((conversationTrigger != null) && (conversationTrigger.trigger == DialogueTriggerEvent.OnUse)) ||
((barkTrigger != null) && (barkTrigger.trigger == DialogueTriggerEvent.OnUse));
bool needsColliders = hasOnTriggerEnter || hasOnUse;
bool hasAppropriateColliders = false;
if (hasOnTriggerEnter) hasAppropriateColliders = DrawTargetingOnTriggerEnter();
if (hasOnUse) hasAppropriateColliders = DrawTargetingOnUse() || hasAppropriateColliders;
if (!needsColliders) EditorGUILayout.HelpBox("The NPC doesn't need any targeting components. Click Next to proceed.", MessageType.Info);
if (GUILayout.Button("Select NPC", GUILayout.Width(100))) Selection.activeGameObject = npcObject;
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, (hasAppropriateColliders || !needsColliders) , false);
}
private bool DrawTargetingOnTriggerEnter() {
EditorWindowTools.DrawHorizontalLine();
EditorGUILayout.LabelField("Trigger Collider", EditorStyles.boldLabel);
Collider triggerCollider = null;
foreach (var collider in npcObject.GetComponentsInChildren<Collider>()) {
if (collider.isTrigger) triggerCollider = collider;
}
if (triggerCollider != null) {
if (triggerCollider is SphereCollider) {
EditorGUILayout.HelpBox("The NPC has a trigger collider, so it's ready for OnTriggerEnter events. You can adjust its radius below. Make sure its layer collision properties are configured to detect when the intended colliders enter its area.", MessageType.None);
SphereCollider sphereCollider = triggerCollider as SphereCollider;
sphereCollider.radius = EditorGUILayout.FloatField("Radius", sphereCollider.radius);
return true;
} else {
EditorGUILayout.HelpBox("The NPC has a trigger collider, so it's ready for OnTriggerEnter events.", MessageType.None);
}
return true;
} else {
EditorGUILayout.HelpBox("The NPC needs a trigger collider. Add Trigger to add a sphere trigger, or add one manually.", MessageType.Info);
if (GUILayout.Button("Add Trigger", GUILayout.Width(160))) {
SphereCollider sphereCollider = npcObject.AddComponent<SphereCollider>();
sphereCollider.isTrigger = true;
sphereCollider.radius = 1.5f;
return true;
}
}
return false;
}
private bool DrawTargetingOnUse() {
EditorWindowTools.DrawHorizontalLine();
EditorGUILayout.LabelField("Collider", EditorStyles.boldLabel);
Collider nontriggerCollider = null;
foreach (var collider in npcObject.GetComponentsInChildren<Collider>()) {
if (!collider.isTrigger) nontriggerCollider = collider;
}
Usable usable = npcObject.GetComponent<Usable>();
if ((nontriggerCollider != null) && (usable != null)) {
EditorGUILayout.HelpBox("The NPC has a collider and a Usable component. The player's Selector component will be able to target it to send OnUse messages.", MessageType.None);
EditorGUILayout.LabelField("'Usable' Customization", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
usable.maxUseDistance = EditorGUILayout.FloatField("Max Usable Distance", usable.maxUseDistance);
usable.overrideName = EditorGUILayout.TextField("Override Actor Name (leave blank to use main override)", usable.overrideName);
usable.overrideUseMessage = EditorGUILayout.TextField("Override Use Message", usable.overrideUseMessage);
EditorWindowTools.EndIndentedSection();
} else {
if (nontriggerCollider == null) {
EditorGUILayout.HelpBox("The NPC is configured to listen for OnUse messages. If these messages will be coming from the player's Selector component, the NPC needs a collider that the Selector can target. Click Add Collider to add a CharacterController. If OnUse will come from another source, you don't necessarily need a collider.", MessageType.Info);
if (GUILayout.Button("Add Collider", GUILayout.Width(160))) {
npcObject.AddComponent<CharacterController>();
}
}
if (usable == null) {
EditorGUILayout.HelpBox("The NPC is configured to listen for OnUse messages. If these messages will be coming from the player's Selector component, the NPC needs a Usable component to tell the Selector that it's usable. Click Add Usable to add one.", MessageType.Info);
if (GUILayout.Button("Add Usable", GUILayout.Width(160))) {
npcObject.AddComponent<Usable>();
}
}
}
return true;
}
public static void DrawOverrideNameSubsection(GameObject character) {
EditorGUILayout.LabelField("Override Actor Name", EditorStyles.boldLabel);
OverrideActorName overrideActorName = character.GetComponent<OverrideActorName>();
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox(string.Format("By default, the dialogue UI will use the name of the GameObject ({0}). You can override it below.", character.name), MessageType.Info);
EditorGUILayout.BeginHorizontal();
bool hasOverrideActorName = EditorGUILayout.Toggle((overrideActorName != null), GUILayout.Width(ToggleWidth));
EditorGUILayout.LabelField("Override actor name", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
if (hasOverrideActorName) {
if (overrideActorName == null) overrideActorName = character.AddComponent<OverrideActorName>();
overrideActorName.overrideName = EditorGUILayout.TextField("Actor Name", overrideActorName.overrideName);
} else {
DestroyImmediate(overrideActorName);
}
EditorWindowTools.EndIndentedSection();
EditorWindowTools.DrawHorizontalLine();
}
private void DrawPersistenceStage() {
EditorGUILayout.LabelField("Persistence", EditorStyles.boldLabel);
PersistentPositionData persistentPositionData = npcObject.GetComponent<PersistentPositionData>();
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("The NPC can be configured to record its position in the Dialogue System's Lua environment so it will be preserved when saving and loading games.", MessageType.Info);
EditorGUILayout.BeginHorizontal();
bool hasPersistentPosition = EditorGUILayout.Toggle((persistentPositionData != null), GUILayout.Width(ToggleWidth));
EditorGUILayout.LabelField("NPC records position for saved games", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
if (hasPersistentPosition) {
if (persistentPositionData == null) persistentPositionData = npcObject.AddComponent<PersistentPositionData>();
if (string.IsNullOrEmpty(persistentPositionData.overrideActorName)) {
EditorGUILayout.HelpBox(string.Format("Position data will be saved to the Actor['{0}'] (the name of the NPC GameObject) or the Override Actor Name if defined. You can override the name below.", npcObject.name), MessageType.None);
} else {
EditorGUILayout.HelpBox(string.Format("Position data will be saved to the Actor['{0}']. To use the name of the NPC GameObject instead, clear the field below.", persistentPositionData.overrideActorName), MessageType.None);
}
persistentPositionData.overrideActorName = EditorGUILayout.TextField("Actor Name", persistentPositionData.overrideActorName);
} else {
DestroyImmediate(persistentPositionData);
}
if (GUILayout.Button("Select NPC", GUILayout.Width(100))) Selection.activeGameObject = npcObject;
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, true, false);
}
private void DrawReviewStage() {
EditorGUILayout.LabelField("Review", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("Your NPC is ready! Below is a summary of your NPC's configuration.", MessageType.Info);
ConversationTrigger conversationTrigger = npcObject.GetComponentInChildren<ConversationTrigger>();
if (conversationTrigger != null) {
EditorGUILayout.LabelField(string.Format("Conversation: '{0}'{1} {2}", conversationTrigger.conversation, conversationTrigger.once ? " (once)" : string.Empty, conversationTrigger.trigger));
} else {
EditorGUILayout.LabelField("Conversation: None");
}
BarkTrigger barkTrigger = npcObject.GetComponentInChildren<BarkTrigger>();
if (barkTrigger != null) {
EditorGUILayout.LabelField(string.Format("Triggered Bark: '{0}' ({1}) {2}", barkTrigger.conversation, barkTrigger.barkOrder, barkTrigger.trigger));
} else {
EditorGUILayout.LabelField("Triggered Bark: None");
}
BarkOnIdle barkOnIdle = npcObject.GetComponentInChildren<BarkOnIdle>();
if (barkOnIdle != null) {
EditorGUILayout.LabelField(string.Format("Timed Bark: '{0}' ({1}) every {2}-{3} seconds", barkOnIdle.conversation, barkOnIdle.barkOrder, barkOnIdle.minSeconds, barkOnIdle.maxSeconds));
} else {
EditorGUILayout.LabelField("Timed Bark: No");
}
PersistentPositionData persistentPositionData = npcObject.GetComponentInChildren<PersistentPositionData>();
EditorGUILayout.LabelField(string.Format("Save Position: {0}", (persistentPositionData != null) ? "Yes" : "No"));
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, true, true);
}
}
}
|
phelow/FallOfTheTzar
|
FallOfTheTzar/Assets/Dialogue System/Scripts/Editor/Wizards/NPCSetupWizard.cs
|
C#
|
mit
| 21,891
|
import React, { memo, useMemo } from 'react';
import PropTypes from 'prop-types';
import { useIntl } from 'react-intl';
import get from 'lodash/get';
import omit from 'lodash/omit';
import take from 'lodash/take';
import isEqual from 'react-fast-compare';
import { GenericInput, NotAllowedInput, useLibrary } from '@strapi/helper-plugin';
import { useContentTypeLayout } from '../../hooks';
import { getFieldName } from '../../utils';
import Wysiwyg from '../Wysiwyg';
import InputJSON from '../InputJSON';
import InputUID from '../InputUID';
import SelectWrapper from '../SelectWrapper';
import {
connect,
generateOptions,
getInputType,
getStep,
select,
VALIDATIONS_TO_OMIT,
} from './utils';
function Inputs({
allowedFields,
fieldSchema,
formErrors,
isCreatingEntry,
keys,
labelAction,
metadatas,
onChange,
readableFields,
shouldNotRunValidations,
queryInfos,
value,
}) {
const { fields } = useLibrary();
const { formatMessage } = useIntl();
const { contentType: currentContentTypeLayout } = useContentTypeLayout();
const disabled = useMemo(() => !get(metadatas, 'editable', true), [metadatas]);
const type = fieldSchema.type;
const errorId = useMemo(() => {
return get(formErrors, [keys, 'id'], null);
}, [formErrors, keys]);
const fieldName = useMemo(() => {
return getFieldName(keys);
}, [keys]);
const validations = useMemo(() => {
const inputValidations = omit(
fieldSchema,
shouldNotRunValidations
? [...VALIDATIONS_TO_OMIT, 'required', 'minLength']
: VALIDATIONS_TO_OMIT
);
const regexpString = fieldSchema.regex || null;
if (regexpString) {
const regexp = new RegExp(regexpString);
if (regexp) {
inputValidations.regex = regexp;
}
}
return inputValidations;
}, [fieldSchema, shouldNotRunValidations]);
const isRequired = useMemo(() => get(validations, ['required'], false), [validations]);
const isChildOfDynamicZone = useMemo(() => {
const attributes = get(currentContentTypeLayout, ['attributes'], {});
const foundAttributeType = get(attributes, [fieldName[0], 'type'], null);
return foundAttributeType === 'dynamiczone';
}, [currentContentTypeLayout, fieldName]);
const inputType = useMemo(() => {
return getInputType(type);
}, [type]);
const inputValue = useMemo(() => {
// Fix for input file multipe
if (type === 'media' && !value) {
return [];
}
return value;
}, [type, value]);
const step = useMemo(() => {
return getStep(type);
}, [type]);
const isUserAllowedToEditField = useMemo(() => {
const joinedName = fieldName.join('.');
if (allowedFields.includes(joinedName)) {
return true;
}
if (isChildOfDynamicZone) {
return allowedFields.includes(fieldName[0]);
}
const isChildOfComponent = fieldName.length > 1;
if (isChildOfComponent) {
const parentFieldName = take(fieldName, fieldName.length - 1).join('.');
return allowedFields.includes(parentFieldName);
}
return false;
}, [allowedFields, fieldName, isChildOfDynamicZone]);
const isUserAllowedToReadField = useMemo(() => {
const joinedName = fieldName.join('.');
if (readableFields.includes(joinedName)) {
return true;
}
if (isChildOfDynamicZone) {
return readableFields.includes(fieldName[0]);
}
const isChildOfComponent = fieldName.length > 1;
if (isChildOfComponent) {
const parentFieldName = take(fieldName, fieldName.length - 1).join('.');
return readableFields.includes(parentFieldName);
}
return false;
}, [readableFields, fieldName, isChildOfDynamicZone]);
const shouldDisplayNotAllowedInput = useMemo(() => {
return isUserAllowedToReadField || isUserAllowedToEditField;
}, [isUserAllowedToEditField, isUserAllowedToReadField]);
const shouldDisableField = useMemo(() => {
if (!isCreatingEntry) {
const doesNotHaveRight = isUserAllowedToReadField && !isUserAllowedToEditField;
if (doesNotHaveRight) {
return true;
}
return disabled;
}
return disabled;
}, [disabled, isCreatingEntry, isUserAllowedToEditField, isUserAllowedToReadField]);
const options = useMemo(() => generateOptions(fieldSchema.enum || [], isRequired), [
fieldSchema,
isRequired,
]);
const { label, description, placeholder, visible } = metadatas;
if (visible === false) {
return null;
}
if (!shouldDisplayNotAllowedInput) {
return (
<NotAllowedInput
description={description ? { id: description, defaultMessage: description } : null}
intlLabel={{ id: label, defaultMessage: label }}
labelAction={labelAction}
error={errorId}
name={keys}
required={isRequired}
/>
);
}
if (type === 'relation') {
return (
<SelectWrapper
{...metadatas}
{...fieldSchema}
description={
metadatas.description
? formatMessage({
id: metadatas.description,
defaultMessage: metadatas.description,
})
: undefined
}
intlLabel={{
id: metadatas.label,
defaultMessage: metadatas.label,
}}
labelAction={labelAction}
isUserAllowedToEditField={isUserAllowedToEditField}
isUserAllowedToReadField={isUserAllowedToReadField}
name={keys}
placeholder={
metadatas.placeholder
? {
id: metadatas.placeholder,
defaultMessage: metadatas.placeholder,
}
: null
}
queryInfos={queryInfos}
value={value}
/>
);
}
return (
<GenericInput
attribute={fieldSchema}
autoComplete="new-password"
intlLabel={{ id: label, defaultMessage: label }}
description={description ? { id: description, defaultMessage: description } : null}
disabled={shouldDisableField}
error={errorId}
labelAction={labelAction}
contentTypeUID={currentContentTypeLayout.uid}
customInputs={{
json: InputJSON,
uid: InputUID,
media: fields.media,
wysiwyg: Wysiwyg,
...fields,
}}
multiple={fieldSchema.multiple || false}
name={keys}
onChange={onChange}
options={options}
placeholder={placeholder ? { id: placeholder, defaultMessage: placeholder } : null}
required={fieldSchema.required || false}
step={step}
type={inputType}
// validations={validations}
value={inputValue}
withDefaultValue={false}
/>
);
}
Inputs.defaultProps = {
formErrors: {},
labelAction: undefined,
queryInfos: {},
value: null,
};
Inputs.propTypes = {
allowedFields: PropTypes.array.isRequired,
fieldSchema: PropTypes.object.isRequired,
formErrors: PropTypes.object,
keys: PropTypes.string.isRequired,
isCreatingEntry: PropTypes.bool.isRequired,
labelAction: PropTypes.element,
metadatas: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
readableFields: PropTypes.array.isRequired,
shouldNotRunValidations: PropTypes.bool.isRequired,
queryInfos: PropTypes.shape({
containsKey: PropTypes.string,
defaultParams: PropTypes.object,
endPoint: PropTypes.string,
}),
value: PropTypes.any,
};
const Memoized = memo(Inputs, isEqual);
export default connect(
Memoized,
select
);
|
wistityhq/strapi
|
packages/core/admin/admin/src/content-manager/components/Inputs/index.js
|
JavaScript
|
mit
| 7,484
|
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { addUserRequest, getUserRequest, updateUserRequest } from 'App/actions/users'
import { USER_TYPE_USER } from 'Server/constants'
import EditView from '../components/EditView'
class EditContainer extends Component {
static propTypes = {
addUserRequest: PropTypes.func.isRequired,
updateUserRequest: PropTypes.func.isRequired,
getUserRequest: PropTypes.func.isRequired,
user: PropTypes.object.isRequired,
params: PropTypes.object.isRequired,
}
constructor(props) {
super(props)
this.isAdding = props.params.id === undefined
this.handleSubmit = this.handleSubmit.bind(this)
}
componentDidMount() {
if (!this.isAdding) {
this.props.getUserRequest(this.props.params.id)
}
}
handleSubmit(user) {
if (this.isAdding) {
this.props.addUserRequest(user)
} else {
this.props.updateUserRequest(this.props.params.id, user)
}
}
render() {
const { user } = this.props
return (
<div>
<div className="page-header">
<h2>
{this.isAdding ? 'Add New User' : `Edit User - ${user.username}`}
</h2>
</div>
<EditView
isAdding={this.isAdding}
user={user}
onSubmit={this.handleSubmit}
/>
</div>
)
}
}
const mapStateToProps = (state, ownProps) => {
let user
if (ownProps.params.id === undefined) {
user = {
username: '',
password: '',
type: USER_TYPE_USER,
}
} else {
user = state.users.find(_user => _user._id === ownProps.params.id)
user.password = ''
}
return {
user,
}
}
const mapDispatchToProps = {
addUserRequest,
updateUserRequest,
getUserRequest,
}
export default connect(mapStateToProps, mapDispatchToProps)(EditContainer)
|
nabil-jazoul/react-starter
|
app/routes/User/containers/EditContainer.js
|
JavaScript
|
mit
| 1,876
|
package com.aspose.cells.cloud.examples.cells;
import android.content.Context;
import com.aspose.cells.api.CellsApi;
import com.aspose.cells.cloud.examples.Configuration;
import com.aspose.cells.cloud.examples.R;
import com.aspose.cells.cloud.examples.Utils;
import com.aspose.storage.api.StorageApi;
import java.io.File;
import java.io.IOException;
public class GetFirstCellWorksheet {
public static void execute(Context context) throws IOException {
//ExStart: get-first-cell-excel-worksheet
try {
// Instantiate Aspose Storage API SDK
StorageApi storageApi = new StorageApi(Configuration.apiKey, Configuration.appSID, true);
// Instantiate Aspose Words API SDK
CellsApi cellsApi = new CellsApi(Configuration.apiKey, Configuration.appSID, true);
String input = "sample1.xlsx";
File inputFile = Utils.stream2file("sample1","xlsx", context.getResources().openRawResource(R.raw.sample1));
String sheetName = "Sheet1";
String cellOrMethodName = "firstcell";
storageApi.PutCreate(input, null, Utils.STORAGE, inputFile);
com.aspose.cells.model.CellResponse apiResponse = cellsApi.GetWorksheetCell(input, sheetName,
cellOrMethodName, Utils.STORAGE, Utils.FOLDER);
com.aspose.cells.model.Cell cell = apiResponse.getCell();
System.out.println("Cell Name :: " + cell.getName());
System.out.println("Cell Value :: " + cell.getValue());
}
catch (Exception e) {
e.printStackTrace();
}
//ExEnd: get-first-cell-excel-worksheet
}
}
|
aspose-cells/Aspose.Cells-for-Cloud
|
Examples/Android/app/src/main/java/com/aspose/cells/cloud/examples/cells/GetFirstCellWorksheet.java
|
Java
|
mit
| 1,492
|
import { Universal } from '../../../src/types';
const { Set } = Universal;
const emptySet = new Set();
export default emptySet;
|
ComplyCloud/asn1
|
test/resources/asn1/empty-set_null-children.js
|
JavaScript
|
mit
| 131
|
// Copyright (c) 2015 Elements of Programming Interviews. All rights reserved.
#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <iostream>
#include <queue>
#include <random>
#include <sstream>
#include <string>
#include <vector>
using std::array;
using std::cout;
using std::default_random_engine;
using std::endl;
using std::istringstream;
using std::max;
using std::min;
using std::priority_queue;
using std::random_device;
using std::stoi;
using std::string;
using std::stringstream;
using std::swap;
using std::uniform_int_distribution;
using std::uniform_real_distribution;
using std::vector;
// @include
struct Star {
bool operator<(const Star& that) const {
return Distance() < that.Distance();
}
double Distance() const { return sqrt(x * x + y * y + z * z); }
double x, y, z;
};
vector<Star> FindClosestKStars(int k, istringstream* stars) {
// max_heap to store the closest k stars seen so far.
priority_queue<Star, vector<Star>> max_heap;
string line;
while (getline(*stars, line)) {
stringstream line_stream(line);
array<double, 3> data; // stores x, y, and z.
for (int i = 0; i < 3; ++i) {
string buf;
getline(line_stream, buf, ',');
data[i] = stod(buf);
}
// Add each star to the max-heap. If the max-heap size exceeds k,
// remove the maximum element from the max-heap.
max_heap.emplace(Star{data[0], data[1], data[2]});
if (max_heap.size() == k + 1) {
max_heap.pop();
}
}
// Iteratively extract from the max-heap, which yields the stars
// sorted according from furthest to closest.
vector<Star> closest_stars;
while (!max_heap.empty()) {
closest_stars.emplace_back(max_heap.top());
max_heap.pop();
}
return {closest_stars.rbegin(), closest_stars.rend()};
}
// @exclude
string CreateStreamingString(const vector<Star>& stars) {
string s;
for (int i = 0; i < stars.size(); ++i) {
stringstream ss;
ss << stars[i].x << ',' << stars[i].y << ',' << stars[i].z << endl;
s += ss.str();
}
return s;
}
void SimpleTest() {
vector<Star> stars;
stars.emplace_back((Star{1, 2, 3}));
stars.emplace_back((Star{5, 5, 5}));
stars.emplace_back((Star{0, 2, 1}));
stars.emplace_back((Star{9, 2, 1}));
stars.emplace_back((Star{1, 2, 1}));
stars.emplace_back((Star{2, 2, 1}));
istringstream sin(CreateStreamingString(stars));
vector<Star> closest_stars = FindClosestKStars(3, &sin);
assert(3 == closest_stars.size());
assert(closest_stars[0].Distance() == (Star{0, 2, 1}.Distance()));
assert(closest_stars[0].Distance() == (Star{2, 0, 1}.Distance()));
assert(closest_stars[1].Distance() == (Star{1, 2, 1}.Distance()));
assert(closest_stars[1].Distance() == (Star{1, 1, 2}.Distance()));
stars.clear();
stars.emplace_back((Star{1, 2, 3}));
stars.emplace_back((Star{5, 5, 5}));
stars.emplace_back((Star{4, 4, 4}));
stars.emplace_back((Star{3, 2, 1}));
stars.emplace_back((Star{5, 5, 5}));
stars.emplace_back((Star{3, 2, 3}));
stars.emplace_back((Star{3, 2, 3}));
stars.emplace_back((Star{3, 2, 1}));
istringstream sin2(CreateStreamingString(stars));
closest_stars = FindClosestKStars(2, &sin2);
assert(2 == closest_stars.size());
assert(closest_stars[0].Distance() == (Star{1, 2, 3}.Distance()));
assert(closest_stars[1].Distance() == (Star{3, 2, 1}.Distance()));
}
int main(int argc, char* argv[]) {
SimpleTest();
default_random_engine gen((random_device())());
for (int times = 0; times < 1000; ++times) {
int num, k;
if (argc == 2) {
num = stoi(argv[1]);
uniform_int_distribution<int> dis(1, num);
k = dis(gen);
} else if (argc == 3) {
num = stoi(argv[1]);
k = stoi(argv[2]);
} else {
uniform_int_distribution<int> num_dis(1, 10000);
num = num_dis(gen);
uniform_int_distribution<int> k_dis(1, num);
k = k_dis(gen);
}
vector<Star> stars;
// Randomly generate num of stars.
uniform_real_distribution<double> dis(0, 10000);
for (int i = 0; i < num; ++i) {
stars.emplace_back(Star{dis(gen), dis(gen), dis(gen)});
}
istringstream sin(CreateStreamingString(stars));
vector<Star> closest_stars(FindClosestKStars(k, &sin));
sort(closest_stars.begin(), closest_stars.end());
sort(stars.begin(), stars.end());
cout << "k = " << k << endl;
cout << stars[k - 1].x << " " << stars[k - 1].y << " " << stars[k - 1].z
<< " " << stars[k - 1].Distance() << endl;
cout << closest_stars.back().x << " " << closest_stars.back().y << " "
<< closest_stars.back().z << " " << closest_stars.back().Distance()
<< endl;
assert(fabs(stars[k - 1].Distance() - closest_stars.back().Distance()) <
1.0e-2);
}
return 0;
}
|
adnanaziz/epicode
|
cpp/Closest_stars.cc
|
C++
|
mit
| 4,787
|
$(document).ready(function () {
/*
$('.sign-up-submit').click(function(e) {
var $button = $(e.target);
var $input = $button.closest(".sign-up-form").find(".mdl-textfield__input");
var $warning = $button.closest(".sign-up-form").find(".warning-message");
buttonAnimate($button, $input, $warning);
});
$('.sign-up-form .mdl-textfield__input').keypress(function(e) {
if (e.which === 13) {
var $input = $(e.target);
var $button = $input.closest(".sign-up-form").find(".mdl-button");
var $warning = $button.closest(".sign-up-form").find(".warning-message");
buttonAnimate($button, $input, $warning);
}
});
*/
var envSlug = getEnvironmentSlug();
intercomLauncher(envSlug, true, '#intercom-launcher');
initializeGoogleAnalytics(envSlug);
});
// returns true if email contains an @ that is not at either end of the string
function simpleEmailCheck(email) {
var atSignLocation = email.indexOf("@");
return (atSignLocation > 0) && (atSignLocation < (email.length - 1));
}
function buttonAnimate($button, $input, $warning) {
var email = $input.val();
var $area = $input.closest(".sign-up-area");
if (simpleEmailCheck(email)) {
$warning.css("visibility", "hidden");
$area.removeClass("warning");
$button.animate({
opacity: 0.7,
});
$button.attr("disabled", "disabled");
$input.animate({
opacity: 0.5,
});
$input.attr("disabled", "disabled");
setTimeout(function() {
$button.text("Email Sent!");
}, 200);
} else {
$warning.css("visibility", "visible");
$area.addClass("warning");
}
}
|
Neil-Ni/v2
|
www/assets/js/common.js
|
JavaScript
|
mit
| 1,625
|
<?php
namespace Chamilo\Core\Repository\ContentObject\Survey\Page\Question\Choice\Storage\DataClass;
use Chamilo\Core\Repository\Storage\DataClass\ContentObject;
use Chamilo\Libraries\Architecture\ClassnameUtilities;
use Chamilo\Libraries\Architecture\Interfaces\Versionable;
use Chamilo\Libraries\Platform\Translation;
/**
*
* @package repository.content_object.survey_open_question
* @author Eduard Vossen
* @author Magali Gillard
*/
/**
* A Open
*/
class Choice extends ContentObject implements Versionable
{
const PROPERTY_QUESTION = 'question';
const PROPERTY_INSTRUCTION = 'instruction';
const PROPERTY_QUESTION_TYPE = 'question_type';
const PROPERTY_FIRST_CHOICE = 'first_choice';
const PROPERTY_SECOND_CHOICE = 'second_choice';
const TYPE_YES_NO = 0;
const TYPE_OTHER = 1;
static function get_type_name()
{
return ClassnameUtilities::getInstance()->getClassNameFromNamespace(self::class_name(), true);
}
public function get_question()
{
return $this->get_additional_property(self::PROPERTY_QUESTION);
}
public function set_question($question)
{
return $this->set_additional_property(self::PROPERTY_QUESTION, $question);
}
public function get_instruction()
{
return $this->get_additional_property(self::PROPERTY_INSTRUCTION);
}
public function set_instruction($instruction)
{
return $this->set_additional_property(self::PROPERTY_INSTRUCTION, $instruction);
}
public function has_instruction()
{
$instruction = $this->get_instruction();
return ($instruction != '<p> </p>' && count($instruction) > 0);
}
public function get_question_type()
{
return $this->get_additional_property(self::PROPERTY_QUESTION_TYPE);
}
public function set_question_type($question_type)
{
return $this->set_additional_property(self::PROPERTY_QUESTION_TYPE, $question_type);
}
public function get_first_choice()
{
return $this->get_additional_property(self::PROPERTY_FIRST_CHOICE);
}
public function set_first_choice($first_choice)
{
return $this->set_additional_property(self::PROPERTY_FIRST_CHOICE, $first_choice);
}
public function get_second_choice()
{
return $this->get_additional_property(self::PROPERTY_SECOND_CHOICE);
}
public function set_second_choice($second_choice)
{
return $this->set_additional_property(self::PROPERTY_SECOND_CHOICE, $second_choice);
}
public function choices()
{
if (self::PROPERTY_FIRST_CHOICE && self::PROPERTY_SECOND_CHOICE)
{
return true;
}
else
{
return false;
}
}
public function getOptions()
{
$options = array();
if ($this->get_question_type() == self::TYPE_YES_NO)
{
$options[1] = Translation::get('AnswerYes');
$options[2] = Translation::get('AnswerNo');
}
else
{
$options[1] = $this->get_first_choice();
$options[2] = $this->get_second_choice();
}
return $options;
}
static function get_additional_property_names()
{
return array(
self::PROPERTY_QUESTION,
self::PROPERTY_INSTRUCTION,
self::PROPERTY_QUESTION_TYPE,
self::PROPERTY_FIRST_CHOICE,
self::PROPERTY_SECOND_CHOICE);
}
}
?>
|
cosnicsTHLU/cosnics
|
src/Chamilo/Core/Repository/ContentObject/Survey/Page/Question/Choice/Storage/DataClass/Choice.php
|
PHP
|
mit
| 3,519
|
import styled from 'styled-components';
export const Wrapper = styled.section`
margin: 0 auto;
width: 100%;
max-width: 1170px;
`;
export const VerticalListView = styled.ul`
margin: var(--topbar-height) 0;
padding: 0;
list-style-type: none;
`;
export const VerticalListSection = styled.li`
margin-bottom: var(--padding);
&:last-child {
position: relative;
padding-bottom: calc(var(--topbar-height) * 1.5);
}
h4, ul:not(.slider-list) {
padding-left: var(--padding);
}
`;
export const HorizontalListView = styled.ul`
margin: 0;
padding: var(--padding);
padding-left: 0;
display: flex;
flex-flow: row no-wrap;
list-style-type: none;
overflow-x: auto;
align-items: center;
`;
export const HorizontalListItem = styled.li`
margin-right: var(--padding);
&:last-child {
position: relative;
padding-right: calc(var(--topbar-height) * 0.5);
}
`;
export const TagButton = styled.button`
padding: calc(var(--padding) * 0.5) calc(var(--padding) * 2);
background: var(--primary-accent-color);
color: var(--background-color);
border-radius: 50px;
white-space: nowrap;
`;
export const FacilityButton = styled.button`
background: var(--foreground-color);
color: var(--background-color);
padding: var(--padding);
border-radius: 4px;
white-space: nowrap;
`;
export const FacilityIcon = styled.img`
display: block;
margin: 0 auto;
height: 24px;
margin-bottom: calc(var(--padding) / 2);
`;
export const SearchContainer = styled.section`
position: relative;
margin: auto;
width: 100%;
max-width: 1170px;
display: flex;
align-items: center;
`;
export const SearchLabel = styled.label`
// padding: calc(var(--padding) / 1);
padding-left: calc(var(--padding) / 2);
border-radius: 4px 0 0 4px;
`;
export const SearchBox = styled.input`
display: block;
flex: 2;
// padding: calc(var(--padding) / 1);
font-size: 16px;
&:focus {
outline: 0;
}
`;
export const List = styled.ul`
margin: var(--topbar-height) 0 calc(var(--topbar-height) * 1.5) 0;
padding: 0;
list-style-type: 0;
`;
export const Item = styled.li`
border-bottom: 1px solid var(--light-gray);
`;
export const SlideList = styled.section`
padding: var(--padding);
`;
|
TeamVenu/venu
|
app/containers/Search/styles.js
|
JavaScript
|
mit
| 2,254
|
<?php
/**
* HTML_QuickForm_tinymce.
*
* @author guillaule l. <guillaume@geelweb.org>
* @license PHP License http://www.php.net/license/3_0.txt
* $Id: tinymce.php,v 1.1.1.1 2007-06-06 11:14:50 david Exp $
*/
/**
* include parent class.
*/
require_once 'HTML/QuickForm/textarea.php';
/**
* Register QuickForm element type
*/
HTML_QuickForm::registerElementType('tinymce', 'HTML/QuickForm/tinymce.php', 'HTML_QuickForm_tinymce');
/**
* HTML_QuickForm_tinymce
*
* Add a web based Javascript HTML WYSIWYG editor control based on
* {@link http://tinymce.moxiecode.com TinyMCE}.
*
* Example:
* <code>
* ...
* require_once 'HTML/QuickForm/tinymce.php';
*
* $options = array(
* 'baseURL' => 'js/tinymce/jscript/tiny_mce/',
* 'configFile' => 'js/tinymce/tinymce.inc.js');
* $attributes = array(
* 'class' => 'mceEditor');
*
* $element = HTML_QuickForm::createElement('tinymce', 'tinymceEditor',
* 'TinyMCE Editor', $options, $attributes);
* $form->addElement($element);
* ...
* </code>
* @author guillaume l. <guillaume@geelweb.org>
* @version 1.0
* @license PHP License http://www.php.net/license/3_0.txt
*/
class HTML_QuickForm_tinymce extends HTML_QuickForm_textarea {
var $_options = array();
/**
* Constructor
*
* @param string $elementName Input field name attribute
* @param string $elementLabel Label for field
* @param array $options array for TinyMCE options (needed keys are 'baseURL' and
* 'configFile')
* @param mixed $attributes Either a typical HTML attribute string or an
* associative array
* @since 1.0
* @access public
* @return void
*/
function HTML_QuickForm_tinymce($elementName=null, $elementLabel=null,
$options=array(), $attributes=null) {
$this->HTML_QuickForm_textarea($elementName, $elementLabel, $attributes);
$this->_type = 'tinymce';
if(is_array($options)) {
$this->_options = $options;
}
}
/**
* Returns the element in HTML
*
* @since 1.0
* @access public
* @return string
*/
function toHtml() {
if($this->_flagFrozen) {
return $this->getFrozenHtml();
}
$html = '';
if(!defined('HTML_QUICKFORM_TINYMCE_LOADED')) {
$html = sprintf(
'<script type="text/javascript" src="%stiny_mce.js"></script>' .
'<script type="text/javascript" src="%s"></script>',
$this->_options['baseURL'], $this->_options['configFile']);
define('HTML_QUICKFORM_TINYMCE_LOADED', true);
}
$html .= $this->_getTabs() .
'<textarea' . $this->_getAttrString($this->_attributes) . '>' .
// because we wrap the form later we don't want the text indented
preg_replace("/(\r\n|\n|\r)/", '
', htmlspecialchars($this->_value)) .
'</textarea>';
return $html;
}
}
?>
|
arhe/pwak
|
vendor/HTML/QuickForm/tinymce.php
|
PHP
|
mit
| 2,969
|
package cases
import (
"io/ioutil"
"path/filepath"
"regexp"
"strings"
"testing"
)
func testFilesFor(t testing.TB, dirname string, includes, ignores []string) []string {
files, err := ioutil.ReadDir(dirname)
if err != nil {
t.Fatal(err)
}
testFiles := make([]string, 0)
for _, file := range files {
if file.IsDir() {
continue
}
if !strings.HasSuffix(file.Name(), ".json") {
continue
}
if !isIncludedTestCase(file.Name(), includes, ignores) {
continue
}
if !isTestCaseAllowed(file.Name()) {
continue
}
if !file.IsDir() {
testFiles = append(testFiles, filepath.Join(dirname, file.Name()))
}
}
return testFiles
}
func isIncludedTestCase(s string, includes, ignores []string) bool {
for _, ignore := range ignores {
rgx := rgxForMatcher(ignore)
if rgx.MatchString(s) {
return false
}
}
for _, include := range includes {
rgx := rgxForMatcher(include)
if !rgx.MatchString(s) {
return false
}
}
return true
}
func rgxForMatcher(s string) *regexp.Regexp {
return regexp.MustCompile("(?i)" + regexp.QuoteMeta(s))
}
|
adamluzsi/escher-go
|
testing/cases/test_file_for.go
|
GO
|
mit
| 1,099
|
var hub = require('..')
, cluster = require('cluster')
, assert = require('assert')
, WORKERS = 2
if (cluster.isMaster) {
var workers = [];
for (var i = 0; i < WORKERS; i++) {
workers.push(cluster.fork());
}
var n = WORKERS;
hub.on('imready', function() {
if (--n === 0) hub.emit('allready');
});
describe('Master', function() {
it('Waits for workers to exit', function(done) {
var n = WORKERS;
function exit() {
if (--n === 0) done();
}
cluster.on('exit', exit);
});
});
} else {
describe('Worker', function() {
describe('Emit message to other worker', function() {
it('Respond when all workers are listening', function(done) {
hub.on('fromworker', done);
hub.on('allready', function() {
hub.emitRemote('fromworker');
});
hub.emit('imready');
});
});
describe('Calls hub method', function() {
it('Data should be shared amongst workers', function(done) {
var n = 0;
hub.on('incr work', function() {
if (++n === WORKERS) {
done();
}
});
hub.ready(function() {
setTimeout(function() {
hub.incr('work');
}, 100);
});
});
});
});
}
|
undertuga/nyxeye
|
node_modules/look/node_modules/clusterhub/test/workerworker-test.js
|
JavaScript
|
mit
| 1,308
|
import addOptionsToOrdinalScale from 'ember-d3-helpers/utils/add-options-to-ordinal-scale';
import { module, test } from 'qunit';
module('Unit | Utility | add options to ordinal scale');
// Replace this with your real tests.
test('works supporting paddingInner/Outer', function(assert) {
let callCounts = {};
let lastArgs = {};
let scale = ['align', 'padding', 'paddingInner', 'paddingOuter'].reduce((hash, prop) => {
callCounts[prop] = 0;
lastArgs[prop] = [];
hash[prop] = (...args) => {
lastArgs[prop] = args;
callCounts[prop]++;
};
return hash;
}, {
domain() {},
range() {},
rangeRound() {}
});
addOptionsToOrdinalScale(scale, [], [], {});
assert.deepEqual(callCounts, {
align: 0,
padding: 0,
paddingInner: 0,
paddingOuter: 0
});
assert.deepEqual(lastArgs, {
align: [],
padding: [],
paddingInner: [],
paddingOuter: []
});
addOptionsToOrdinalScale(scale, [], [], {
padding: 10
});
assert.deepEqual(callCounts, {
align: 0,
padding: 1,
paddingInner: 0,
paddingOuter: 0
});
assert.deepEqual(lastArgs, {
align: [],
padding: [10],
paddingInner: [],
paddingOuter: []
});
addOptionsToOrdinalScale(scale, [], [], {
'padding-inner': 10
});
assert.deepEqual(callCounts, {
align: 0,
padding: 1,
paddingInner: 1,
paddingOuter: 0
});
assert.deepEqual(lastArgs, {
align: [],
padding: [10],
paddingInner: [10],
paddingOuter: []
});
addOptionsToOrdinalScale(scale, [], [], {
'padding-outer': 10
});
assert.deepEqual(callCounts, {
align: 0,
padding: 1,
paddingInner: 1,
paddingOuter: 1
});
assert.deepEqual(lastArgs, {
align: [],
padding: [10],
paddingInner: [10],
paddingOuter: [10]
});
addOptionsToOrdinalScale(scale, [], [], {
align: 0
});
assert.deepEqual(callCounts, {
align: 1,
padding: 1,
paddingInner: 1,
paddingOuter: 1
});
assert.deepEqual(lastArgs, {
align: [0],
padding: [10],
paddingInner: [10],
paddingOuter: [10]
});
});
test('works without supporting paddingInner/Outer', function(assert) {
let callCounts = {};
let lastArgs = {};
let scale = ['align', 'padding'].reduce((hash, prop) => {
callCounts[prop] = 0;
lastArgs[prop] = [];
hash[prop] = (...args) => {
lastArgs[prop] = args;
callCounts[prop]++;
};
return hash;
}, {});
assert.throws(() => {
addOptionsToOrdinalScale(scale, {
'padding-inner': 10
});
}, 'padding inner without support throws');
assert.deepEqual(callCounts, {
align: 0,
padding: 0
});
assert.deepEqual(lastArgs, {
align: [],
padding: []
});
assert.throws(() => {
addOptionsToOrdinalScale(scale, {
'padding-outer': 10
});
}, 'padding outer without support throws');
assert.deepEqual(callCounts, {
align: 0,
padding: 0
});
assert.deepEqual(lastArgs, {
align: [],
padding: []
});
});
|
LocusEnergy/ember-d3-helpers
|
tests/unit/utils/add-options-to-ordinal-scale-test.js
|
JavaScript
|
mit
| 3,029
|
require 'tempfile'
require_relative '../../spec_helper'
require_lib 'reek/examiner'
require_lib 'reek/report/report'
RSpec.describe Reek::Report::HTMLReport do
let(:instance) { Reek::Report::HTMLReport.new }
context 'with an empty source' do
let(:examiner) { Reek::Examiner.new('') }
before do
instance.add_examiner examiner
end
it 'has the text 0 total warnings' do
tempfile = Tempfile.new(['Reek::Report::HTMLReport.', '.html'])
response = "HTML file saved\n"
expect { instance.show(target_path: tempfile.path) }.
to output(response).to_stdout
expect(tempfile.read).to include('0 total warnings')
end
end
end
|
andyw8/reek
|
spec/reek/report/html_report_spec.rb
|
Ruby
|
mit
| 679
|
package testutil
import (
"testing"
ci "gx/ipfs/QmP1DfoUjiWH2ZBo1PBH6FupdBucbDepx3HpWmEY6JMUpY/go-libp2p-crypto"
ma "gx/ipfs/QmcyqRMCAXVtYPS4DiBrA7sezL9rRGfW8Ctx7cywL4TXJj/go-multiaddr"
peer "gx/ipfs/QmdS9KpbDyPrieswibZhkod1oXqRwZJrUPzxCofAMWpFGq/go-libp2p-peer"
)
type Identity interface {
Address() ma.Multiaddr
ID() peer.ID
PrivateKey() ci.PrivKey
PublicKey() ci.PubKey
}
// TODO add a cheaper way to generate identities
func RandIdentity() (Identity, error) {
p, err := RandPeerNetParams()
if err != nil {
return nil, err
}
return &identity{*p}, nil
}
func RandIdentityOrFatal(t *testing.T) Identity {
p, err := RandPeerNetParams()
if err != nil {
t.Fatal(err)
}
return &identity{*p}
}
// identity is a temporary shim to delay binding of PeerNetParams.
type identity struct {
PeerNetParams
}
func (p *identity) ID() peer.ID {
return p.PeerNetParams.ID
}
func (p *identity) Address() ma.Multiaddr {
return p.Addr
}
func (p *identity) PrivateKey() ci.PrivKey {
return p.PrivKey
}
func (p *identity) PublicKey() ci.PubKey {
return p.PubKey
}
|
duomarket/openbazaar-test-nodes
|
vendor/gx/ipfs/QmdVnYKahrvndXhyreWhY8YT3a5chJoWv8b4wVyH9JG2KB/go-testutil/identity.go
|
GO
|
mit
| 1,079
|
/**
* UserController
*
* @description :: Server-side logic for managing users
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
notes: function(req, res) {
EvernoteService.listNotes(function(err, notes) {
if(err){
console.log(err);
return res.serverError(err);
}
return res.json({
notes: notes
});
});
},
notebooks: function (req, res) {
EvernoteService.listNotebooks(function(err, notes) {
if(err){
console.log(err);
return res.serverError(err);
}
return res.json({
notebooks: notes
});
});
}
};
|
Boffee/YARN
|
api/controllers/UserController.js
|
JavaScript
|
mit
| 661
|
'''Support module for translating strings.
This module provides several functions
for definitions, keys, and transforms.'''
__version__ = 1.3
################################################################################
import random
def definition(name=None):
'Returns a valid definition.'
random.seed(name)
definition, list_one, list_two = str(), range(256), range(256)
for index in range(256):
index_one, index_two = random.randrange(256 - index), random.randrange(256 - index)
definition += chr(list_one[index_one]) + chr(list_two[index_two])
del list_one[index_one], list_two[index_two]
return definition
def key(definition, select):
'Returns a valid key.'
key = range(256)
for index in range(256):
key[ord(definition[index * 2 + int(bool(select))])] = definition[index * 2 + int(not bool(select))]
return ''.join(key)
def transform(key, string):
'Returns a valid transformation.'
return string.translate(key)
################################################################################
if __name__ == '__main__':
import sys
print 'Content-Type: text/plain'
print
print file(sys.argv[0]).read()
|
ActiveState/code
|
recipes/Python/496858_zcryptpy/recipe-496858.py
|
Python
|
mit
| 1,213
|
<?php
namespace Doctrine\Tests\ORM\Mapping;
use Doctrine\Tests\Mocks\MetadataDriverMock;
use Doctrine\Tests\Mocks\EntityManagerMock;
use Doctrine\Tests\Mocks\ConnectionMock;
use Doctrine\Tests\Mocks\DriverMock;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\Common\EventManager;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
require_once __DIR__ . '/../../TestInit.php';
class ClassMetadataFactoryTest extends \Doctrine\Tests\OrmTestCase
{
public function testGetMetadataForSingleClass()
{
$mockDriver = new MetadataDriverMock();
$entityManager = $this->_createEntityManager($mockDriver);
$conn = $entityManager->getConnection();
$mockPlatform = $conn->getDatabasePlatform();
$mockPlatform->setPrefersSequences(true);
$mockPlatform->setPrefersIdentityColumns(false);
$cm1 = $this->_createValidClassMetadata();
// SUT
$cmf = new \Doctrine\ORM\Mapping\ClassMetadataFactory();
$cmf->setEntityManager($entityManager);
$cmf->setMetadataFor($cm1->name, $cm1);
// Prechecks
$this->assertEquals(array(), $cm1->parentClasses);
$this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $cm1->inheritanceType);
$this->assertTrue($cm1->hasField('name'));
$this->assertEquals(2, count($cm1->associationMappings));
$this->assertEquals(ClassMetadata::GENERATOR_TYPE_AUTO, $cm1->generatorType);
$this->assertEquals('group', $cm1->table['name']);
// Go
$cmMap1 = $cmf->getMetadataFor($cm1->name);
$this->assertSame($cm1, $cmMap1);
$this->assertEquals('group', $cmMap1->table['name']);
$this->assertTrue($cmMap1->table['quoted']);
$this->assertEquals(array(), $cmMap1->parentClasses);
$this->assertTrue($cmMap1->hasField('name'));
}
public function testGetMetadataFor_ReturnsLoadedCustomIdGenerator()
{
$cm1 = $this->_createValidClassMetadata();
$cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_CUSTOM);
$cm1->customGeneratorDefinition = array(
"class" => "Doctrine\Tests\ORM\Mapping\CustomIdGenerator");
$cmf = $this->_createTestFactory();
$cmf->setMetadataForClass($cm1->name, $cm1);
$actual = $cmf->getMetadataFor($cm1->name);
$this->assertEquals(ClassMetadata::GENERATOR_TYPE_CUSTOM,
$actual->generatorType);
$this->assertInstanceOf("Doctrine\Tests\ORM\Mapping\CustomIdGenerator",
$actual->idGenerator);
}
public function testGetMetadataFor_ThrowsExceptionOnUnknownCustomGeneratorClass()
{
$cm1 = $this->_createValidClassMetadata();
$cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_CUSTOM);
$cm1->customGeneratorDefinition = array("class" => "NotExistingGenerator");
$cmf = $this->_createTestFactory();
$cmf->setMetadataForClass($cm1->name, $cm1);
$this->setExpectedException("Doctrine\ORM\ORMException");
$actual = $cmf->getMetadataFor($cm1->name);
}
public function testGetMetadataFor_ThrowsExceptionOnMissingCustomGeneratorDefinition()
{
$cm1 = $this->_createValidClassMetadata();
$cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_CUSTOM);
$cmf = $this->_createTestFactory();
$cmf->setMetadataForClass($cm1->name, $cm1);
$this->setExpectedException("Doctrine\ORM\ORMException");
$actual = $cmf->getMetadataFor($cm1->name);
}
public function testHasGetMetadata_NamespaceSeperatorIsNotNormalized()
{
require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php";
$metadataDriver = $this->createAnnotationDriver(array(__DIR__ . '/../../Models/Global/'));
$entityManager = $this->_createEntityManager($metadataDriver);
$mf = $entityManager->getMetadataFactory();
$m1 = $mf->getMetadataFor("DoctrineGlobal_Article");
$h1 = $mf->hasMetadataFor("DoctrineGlobal_Article");
$h2 = $mf->hasMetadataFor("\DoctrineGlobal_Article");
$m2 = $mf->getMetadataFor("\DoctrineGlobal_Article");
$this->assertNotSame($m1, $m2);
$this->assertFalse($h2);
$this->assertTrue($h1);
}
/**
* @group DDC-1512
*/
public function testIsTransient()
{
$cmf = new ClassMetadataFactory();
$driver = $this->getMock('Doctrine\ORM\Mapping\Driver\Driver');
$driver->expects($this->at(0))
->method('isTransient')
->with($this->equalTo('Doctrine\Tests\Models\CMS\CmsUser'))
->will($this->returnValue(true));
$driver->expects($this->at(1))
->method('isTransient')
->with($this->equalTo('Doctrine\Tests\Models\CMS\CmsArticle'))
->will($this->returnValue(false));
$em = $this->_createEntityManager($driver);
$this->assertTrue($em->getMetadataFactory()->isTransient('Doctrine\Tests\Models\CMS\CmsUser'));
$this->assertFalse($em->getMetadataFactory()->isTransient('Doctrine\Tests\Models\CMS\CmsArticle'));
}
/**
* @group DDC-1512
*/
public function testIsTransientEntityNamespace()
{
$cmf = new ClassMetadataFactory();
$driver = $this->getMock('Doctrine\ORM\Mapping\Driver\Driver');
$driver->expects($this->at(0))
->method('isTransient')
->with($this->equalTo('Doctrine\Tests\Models\CMS\CmsUser'))
->will($this->returnValue(true));
$driver->expects($this->at(1))
->method('isTransient')
->with($this->equalTo('Doctrine\Tests\Models\CMS\CmsArticle'))
->will($this->returnValue(false));
$em = $this->_createEntityManager($driver);
$em->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS');
$this->assertTrue($em->getMetadataFactory()->isTransient('CMS:CmsUser'));
$this->assertFalse($em->getMetadataFactory()->isTransient('CMS:CmsArticle'));
}
public function testAddDefaultDiscriminatorMap()
{
$cmf = new ClassMetadataFactory();
$driver = $this->createAnnotationDriver(array(__DIR__ . '/../../Models/JoinedInheritanceType/'));
$em = $this->_createEntityManager($driver);
$cmf->setEntityManager($em);
$rootMetadata = $cmf->getMetadataFor('Doctrine\Tests\Models\JoinedInheritanceType\RootClass');
$childMetadata = $cmf->getMetadataFor('Doctrine\Tests\Models\JoinedInheritanceType\ChildClass');
$anotherChildMetadata = $cmf->getMetadataFor('Doctrine\Tests\Models\JoinedInheritanceType\AnotherChildClass');
$rootDiscriminatorMap = $rootMetadata->discriminatorMap;
$childDiscriminatorMap = $childMetadata->discriminatorMap;
$anotherChildDiscriminatorMap = $anotherChildMetadata->discriminatorMap;
$rootClass = 'Doctrine\Tests\Models\JoinedInheritanceType\RootClass';
$childClass = 'Doctrine\Tests\Models\JoinedInheritanceType\ChildClass';
$anotherChildClass = 'Doctrine\Tests\Models\JoinedInheritanceType\AnotherChildClass';
$rootClassKey = array_search($rootClass, $rootDiscriminatorMap);
$childClassKey = array_search($childClass, $rootDiscriminatorMap);
$anotherChildClassKey = array_search($anotherChildClass, $rootDiscriminatorMap);
$this->assertEquals('rootclass', $rootClassKey);
$this->assertEquals('childclass', $childClassKey);
$this->assertEquals('anotherchildclass', $anotherChildClassKey);
$this->assertEquals($childDiscriminatorMap, $rootDiscriminatorMap);
$this->assertEquals($anotherChildDiscriminatorMap, $rootDiscriminatorMap);
// ClassMetadataFactory::addDefaultDiscriminatorMap shouldn't be called again, because the
// discriminator map is already cached
$cmf = $this->getMock('Doctrine\ORM\Mapping\ClassMetadataFactory', array('addDefaultDiscriminatorMap'));
$cmf->setEntityManager($em);
$cmf->expects($this->never())
->method('addDefaultDiscriminatorMap');
$rootMetadata = $cmf->getMetadataFor('Doctrine\Tests\Models\JoinedInheritanceType\RootClass');
}
protected function _createEntityManager($metadataDriver)
{
$driverMock = new DriverMock();
$config = new \Doctrine\ORM\Configuration();
$config->setProxyDir(__DIR__ . '/../../Proxies');
$config->setProxyNamespace('Doctrine\Tests\Proxies');
$eventManager = new EventManager();
$conn = new ConnectionMock(array(), $driverMock, $config, $eventManager);
$mockDriver = new MetadataDriverMock();
$config->setMetadataDriverImpl($metadataDriver);
return EntityManagerMock::create($conn, $config, $eventManager);
}
/**
* @return ClassMetadataFactoryTestSubject
*/
protected function _createTestFactory()
{
$mockDriver = new MetadataDriverMock();
$entityManager = $this->_createEntityManager($mockDriver);
$cmf = new ClassMetadataFactoryTestSubject();
$cmf->setEntityManager($entityManager);
return $cmf;
}
/**
* @param string $class
* @return ClassMetadata
*/
protected function _createValidClassMetadata()
{
// Self-made metadata
$cm1 = new ClassMetadata('Doctrine\Tests\ORM\Mapping\TestEntity1');
$cm1->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
$cm1->setPrimaryTable(array('name' => '`group`'));
// Add a mapped field
$cm1->mapField(array('fieldName' => 'name', 'type' => 'varchar'));
// Add a mapped field
$cm1->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true));
// and a mapped association
$cm1->mapOneToOne(array('fieldName' => 'other', 'targetEntity' => 'TestEntity1', 'mappedBy' => 'this'));
// and an association on the owning side
$joinColumns = array(
array('name' => 'other_id', 'referencedColumnName' => 'id')
);
$cm1->mapOneToOne(array('fieldName' => 'association', 'targetEntity' => 'TestEntity1', 'joinColumns' => $joinColumns));
// and an id generator type
$cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO);
return $cm1;
}
}
/* Test subject class with overriden factory method for mocking purposes */
class ClassMetadataFactoryTestSubject extends \Doctrine\ORM\Mapping\ClassMetadataFactory
{
private $mockMetadata = array();
private $requestedClasses = array();
/** @override */
protected function newClassMetadataInstance($className)
{
$this->requestedClasses[] = $className;
if ( ! isset($this->mockMetadata[$className])) {
throw new InvalidArgumentException("No mock metadata found for class $className.");
}
return $this->mockMetadata[$className];
}
public function setMetadataForClass($className, $metadata)
{
$this->mockMetadata[$className] = $metadata;
}
public function getRequestedClasses()
{
return $this->requestedClasses;
}
}
class TestEntity1
{
private $id;
private $name;
private $other;
private $association;
}
class CustomIdGenerator extends \Doctrine\ORM\Id\AbstractIdGenerator
{
public function generate(\Doctrine\ORM\EntityManager $em, $entity)
{
}
}
|
greg0ire/doctrine2
|
tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php
|
PHP
|
mit
| 11,477
|
# NB! This project is deprecated
All users of this project are urged to find an alternative as it is not maintained anymore. Read more [here](https://blog.nodemailer.com/2018/03/11/spring-cleaning/)

Send e-mails from Node.js – easy as cake! 🍰✉️
<a href="http://badge.fury.io/js/nodemailer"><img src="https://badge.fury.io/js/nodemailer.svg" alt="NPM version" height="18"></a> <a href="https://www.npmjs.com/package/nodemailer"><img src="https://img.shields.io/npm/dt/nodemailer.svg" alt="NPM downloads" height="18"></a>
See [Nodemailer](https://nodemailer.com/) homepage for details.
--------------------------------------------------------------------------------
The Nodemailer logo was designed by [Sven Kristjansen](https://www.behance.net/kristjansen).
|
andris9/mailcomposer
|
README.md
|
Markdown
|
mit
| 881
|
# frozen_string_literal: true
class System::Admin::CoursesController < System::Admin::Controller
around_action :unscope_resources
add_breadcrumb :index, :admin_courses_path
def index
@courses = Course.includes(:instance).search(search_param).calculated(:active_user_count, :user_count)
@courses = @courses.active_in_past_7_days.order('active_user_count DESC, user_count') if params[:active]
@courses = @courses.ordered_by_title.page(page_param)
@owner_preload_service = Course::CourseOwnerPreloadService.new(@courses.map(&:id))
end
def destroy
@course ||= Course.find(params[:id])
if @course.destroy
redirect_to admin_courses_path, success: t('.success', course: @course.title)
else
redirect_to admin_courses_path,
danger: t('.failure', error: @course.errors.full_messages.to_sentence)
end
end
private
def search_param
params.permit(:search)[:search]
end
def unscope_resources
Course.unscoped do
yield
end
end
end
|
cysjonathan/coursemology2
|
app/controllers/system/admin/courses_controller.rb
|
Ruby
|
mit
| 1,023
|
/**
* @todo same issue as in movement.js - which profile takes precedence?
*/
on("change:repeating_profiles:attacks", async (e) => {
console.log("change:repeating_profiles:attacks", e);
const movementIds = await getSectionIDsAsync("movement");
const attrNames = movementIds.map(
(id) => `repeating_movement_${id}_ft_melee`
);
const attrs = {};
const a = await getAttrsAsync(attrNames.concat(["run_ft_melee"]));
attrs.run_ft_attack = Math.round(a.run_ft_melee / e.newValue);
movementIds.forEach((id) => {
const row = `repeating_movement_${id}`;
const feetPerMelee = a[`${row}_ft_melee`] || 0;
if (feetPerMelee) {
attrs[`${row}_ft_attack`] = Math.round(feetPerMelee / e.newValue);
}
});
await setAttrsAsync(attrs);
});
async function addStrikeRangeToCombinedAsync(rowPrefix) {
console.log("addStrikeRangeToCombinedAsync", rowPrefix);
const a = await getAttrsAsync([
`${rowPrefix}_strike_range`,
`${rowPrefix}_strike_range_single`,
`${rowPrefix}_strike_range_burst`,
`${rowPrefix}_strike_range_aimed`,
`${rowPrefix}_strike_range_called`,
]);
const strikeRangeSingle =
+a[`${rowPrefix}_strike_range`] + +a[`${rowPrefix}_strike_range_single`];
const strikeRangeBurst =
+a[`${rowPrefix}_strike_range`] + +a[`${rowPrefix}_strike_range_burst`];
const strikeRangeAimedSingle =
strikeRangeSingle + +a[`${rowPrefix}_strike_range_aimed`] + 2;
const strikeRangeAimedPulse = Math.floor(strikeRangeAimedSingle / 2);
const strikeRangeCalledSingle =
strikeRangeSingle + a[`${rowPrefix}_strike_range_called`];
const strikeRangeCalledPulse = Math.floor(strikeRangeCalledSingle / 2);
const strikeRangeAimedCalledSingle =
strikeRangeAimedSingle + +a[`${rowPrefix}_strike_range_called`];
const strikeRangeAimedCalledPulse = Math.floor(
strikeRangeAimedCalledSingle / 2
);
const attrs = {
[`${rowPrefix}_strike_range_single`]: strikeRangeSingle,
[`${rowPrefix}_strike_range_burst`]: strikeRangeBurst,
[`${rowPrefix}_strike_range_aimed_single`]: strikeRangeAimedSingle,
[`${rowPrefix}_strike_range_aimed_pulse`]: strikeRangeAimedPulse,
[`${rowPrefix}_strike_range_called_single`]: strikeRangeCalledSingle,
[`${rowPrefix}_strike_range_called_pulse`]: strikeRangeCalledPulse,
[`${rowPrefix}_strike_range_aimed_called_single`]:
strikeRangeAimedCalledSingle,
[`${rowPrefix}_strike_range_aimed_called_pulse`]:
strikeRangeAimedCalledPulse,
};
console.log(attrs);
await setAttrsAsync(attrs);
}
async function repeatingAbsoluteAttributes(rowIds, destinationPrefix) {
console.log("repeatingAbsoluteAttributes", rowIds, destinationPrefix);
const fields = [
"iq",
"me",
"ma",
"ps",
"pp",
"pe",
"pb",
"spd",
"spdfly",
"hf",
"spellstrength",
"trust",
"intimidate",
"charmimpress",
];
const fieldNames = rowIds.reduce((acc, rowId) => {
const absFieldNames = fields.map(
(f) => `repeating_bonuses_${rowId}_${f}_abs`
);
const attFieldNames = fields.map(
(f) => `repeating_bonuses_${rowId}_mod_${f}`
);
return acc.concat(absFieldNames, attFieldNames);
}, []);
const a = await getAttrsAsync(fieldNames);
fields.forEach(async (field) => {
let fieldAbsValue = null;
rowIds.forEach((rowId) => {
const rowFieldAbs = a[`repeating_bonuses_${rowId}_${field}_abs`];
if (Boolean(Number(rowFieldAbs)) == true) {
rowFieldValue = a[`repeating_bonuses_${rowId}_mod_${field}`];
fieldAbsValue =
fieldAbsValue > rowFieldValue ? fieldAbsValue : rowFieldValue;
}
});
if (fieldAbsValue) {
// compare the modified absolute value against the original attribute
const coreValue = (await getAttrsAsync([field]))[field];
const newValue = coreValue > fieldAbsValue ? coreValue : fieldAbsValue;
const attr = {
[`${destinationPrefix}_mod_${field}`]: newValue,
};
await setAttrsAsync(attr);
} else {
// repeatingSum
const rsaDestinations = [`${destinationPrefix}_mod_${field}`];
const rsaFields = [`mod_${field}`];
let base = field;
if (field == "trust" || field == "intimidate") {
base = `${destinationPrefix}_mod_ma_bonus`;
} else if (field == "charmimpress") {
base = `${destinationPrefix}_mod_pb_bonus`;
}
await repeatingSumAsync(
rsaDestinations,
"bonuses",
rsaFields,
`filter:${rowIds.toString()}`,
base
);
}
});
}
async function combineBonuses(rowIds, destinationPrefix) {
// we need to combine the values of each repeated attribute within
// each of the sectionIds and aggregate them in the combined combat section
// +PP +PS, and add a saving throws section with +ME +PE
console.log("combineBonuses", rowIds, destinationPrefix);
const options = await getAttrsAsync(["opt_pp_extras"]);
const optPpExtras = Boolean(+options["opt_pp_extras"]);
await repeatingAbsoluteAttributes(rowIds, destinationPrefix);
await repeatingStringConcatAsync({
destinations: [
`${destinationPrefix}_damage`,
`${destinationPrefix}_damage_paired`,
`${destinationPrefix}_damage_mainhand`,
`${destinationPrefix}_damage_offhand`,
`${destinationPrefix}_damage_range`,
`${destinationPrefix}_damage_range_single`,
`${destinationPrefix}_damage_range_burst`,
],
section: "bonuses",
fields: [
"damage",
"damage_paired",
"damage_mainhand",
"damage_offhand",
"damage_range",
"damage_range_single",
"damage_range_burst",
],
filter: rowIds,
});
const pickBestFieldsBase = [
"ar",
"critical",
"knockout",
"deathblow",
"mod_character_ps_type",
"mod_liftcarry_weight_multiplier",
"mod_liftcarry_duration_multiplier",
];
const pickBestDestinations = pickBestFieldsBase.map(
(field) => `${destinationPrefix}_${field}`
);
const pickBestFields = pickBestFieldsBase;
const core = await getAttrsAsync(["character_ps_type"]);
await repeatingPickBestAsync({
destinations: pickBestDestinations,
section: "bonuses",
fields: pickBestFields,
defaultValues: [0, 20, 0, 0, core.character_ps_type, 1, 1],
ranks: ["high", "low", "low", "low", "high", "high", "high", "high"],
filter: rowIds,
});
let noAttributeBonusFields = [
"attacks",
"initiative",
"pull",
"roll",
"strike_range",
"strike_range_single",
"strike_range_burst",
"strike_range_aimed",
"strike_range_called",
"disarm_range",
];
let ppBonusFields = [
"strike",
"parry",
"dodge",
"throw",
"dodge_flight",
"dodge_auto",
"dodge_teleport",
"dodge_motion",
"dodge_underwater",
"flipthrow",
];
const ppExtras = ["disarm", "entangle"];
if (optPpExtras) {
ppBonusFields = ppBonusFields.concat(ppExtras);
} else {
noAttributeBonusFields = noAttributeBonusFields.concat(ppExtras);
}
// No attribute bonuses.
await repeatingSumAsync(
noAttributeBonusFields.map((field) => `${destinationPrefix}_${field}`),
"bonuses",
noAttributeBonusFields,
`filter:${rowIds.toString()}`
);
await addStrikeRangeToCombinedAsync(destinationPrefix);
await repeatingSumAsync(
[`${destinationPrefix}_hp`],
"bonuses",
["hp"],
`filter:${rowIds.toString()}`,
"character_hp"
);
await repeatingSumAsync(
[`${destinationPrefix}_sdc`],
"bonuses",
["sdc"],
`filter:${rowIds.toString()}`,
"character_sdc"
);
await repeatingSumAsync(
[`${destinationPrefix}_mdc`],
"bonuses",
["mdc"],
`filter:${rowIds.toString()}`,
"character_mdc"
);
await repeatingSumAsync(
[`${destinationPrefix}_ppe`],
"bonuses",
["ppe"],
`filter:${rowIds.toString()}`,
"character_ppe"
);
await repeatingSumAsync(
[`${destinationPrefix}_isp`],
"bonuses",
["isp"],
`filter:${rowIds.toString()}`,
"character_isp"
);
await repeatingSumAsync(
[`${destinationPrefix}_mod_skillbonus`],
"bonuses",
["mod_skillbonus"],
`filter:${rowIds.toString()}`
);
await repeatingSumAsync(
ppBonusFields.map((field) => `${destinationPrefix}_${field}`),
"bonuses",
ppBonusFields,
`filter:${rowIds.toString()}`,
`${destinationPrefix}_mod_pp_bonus`
);
// Saving Throws
Object.entries(SAVE_KEYS_ATTRIBUTE_BONUSES).forEach(
async ([attributeBonus, saves]) => {
const destinations = saves.map((save) => `${destinationPrefix}_${save}`);
const section = "bonuses";
const fields = saves;
await repeatingSumAsync(
destinations,
section,
fields,
`filter:${rowIds.toString()}`,
`${destinationPrefix}_mod_${attributeBonus}`
);
}
);
}
async function removeBonusSelectionsRowAsync(bonusRowId) {
const a = await getAttrsAsync([
`repeating_bonuses_${bonusRowId}_selection_id`,
]);
removeRepeatingRow(
`repeating_bonusselections_${
a[`repeating_bonuses_${bonusRowId}_selection_id`]
}`
);
}
async function removeBonusRowsAsync(bonusRowId) {
await removeBonusSelectionsRowAsync(bonusRowId);
removeRepeatingRow(`repeating_bonuses_${bonusRowId}`);
}
on("remove:repeating_wp remove:repeating_wpmodern", async (e) => {
console.log("remove wp", e);
// const [r, section, rowId] = e.sourceAttribute.split('_');
const bonusRowId = e.removedInfo[`${e.sourceAttribute}_bonus_id`];
await removeBonusRowsAsync(bonusRowId);
});
async function outputSelectedBonusIds() {
const bonusselectionsIds = await getSectionIDsAsync("bonusselections");
const checkboxNames = bonusselectionsIds.map(
(id) => `repeating_bonusselections_${id}_enabled`
);
const bonusIdNames = bonusselectionsIds.map(
(id) => `repeating_bonusselections_${id}_bonus_id`
);
const attrNames = checkboxNames.concat(bonusIdNames);
const a = await getAttrsAsync(attrNames);
const bonusRowIds = bonusselectionsIds.reduce((acc, id) => {
const prefix = `repeating_bonusselections_${id}`;
if (Boolean(Number(a[`${prefix}_enabled`])) == true) {
acc.push(a[`${prefix}_bonus_id`]);
}
return acc;
}, []);
await setAttrsAsync({ bonus_ids_output: bonusRowIds.toString() });
}
on("change:repeating_bonusselections:enabled", async (e) => {
console.log("change:repeating_bonusselections:enabled", e);
await outputSelectedBonusIds();
});
async function insertSelection(name, bonusRowId) {
console.log("insertSelection", name, bonusRowId);
const selectionRowId = generateRowID();
const attrs = {};
attrs[`repeating_bonusselections_${selectionRowId}_bonus_id`] = bonusRowId;
attrs[`repeating_bonusselections_${selectionRowId}_name`] = name;
attrs[`repeating_bonuses_${bonusRowId}_selection_id`] = selectionRowId;
console.log(attrs);
await setAttrsAsync(attrs);
}
async function updateSelection(name, selectionRowId) {
console.log("updateSelection", name, selectionRowId);
const attrs = {};
attrs[`repeating_bonusselections_${selectionRowId}_name`] = name;
await setAttrsAsync(attrs);
}
on("change:repeating_bonuses:name", async (e) => {
console.log("change:repeating_bonuses:name", e);
const [r, section, rowId] = e.sourceAttribute.split("_");
const selectionIdKey = `repeating_bonuses_${rowId}_selection_id`;
const a = await getAttrsAsync([selectionIdKey]);
console.log(a);
if (a[selectionIdKey]) {
await updateSelection(e.newValue, a[selectionIdKey]);
} else {
await insertSelection(e.newValue, rowId);
}
});
on("change:repeating_profiles:name", async (e) => {
console.log("change:repeating_profiles:name", e);
const [r, section, rowId] = e.sourceAttribute.split("_");
await setAttrsAsync({
repeating_profiles_rowid: `${r}_${section}_${rowId}_`,
});
await setDefaultRepeatingRow(section, null, "is_default", "default_profile");
});
on("change:repeating_profiles:mod_iq", async (e) => {
console.log("change:repeating_profiles:mod_iq", e);
const [r, section, rowId] = e.sourceAttribute.split("_");
await iqBonus(e.newValue, `${r}_${section}_${rowId}_mod_`);
});
on(
"change:repeating_profiles:mod_me \
change:repeating_profiles:mod_pp \
change:repeating_profiles:mod_pe",
async (e) => {
await mePpPeBonus(e.sourceAttribute, e.newValue);
}
);
on("change:repeating_profiles:mod_ma", async (e) => {
console.log("change:repeating_profiles:mod_ma", e);
const [r, section, rowId] = e.sourceAttribute.split("_");
await maBonus(e.newValue, `${r}_${section}_${rowId}_mod_`);
});
on(
"change:repeating_profiles:mod_ps \
change:repeating_profiles:mod_character_ps_type \
change:repeating_profiles:mod_liftcarry_weight_multiplier \
change:repeating_profiles:mod_liftcarry_duration_multiplier",
async (e) => {
console.log("change:repeating_profiles:mod_ps", e);
const [r, section, rowId] = e.sourceAttribute.split("_");
await psBonusComplete(`${r}_${section}_${rowId}_mod_`);
}
);
on("change:repeating_profiles:mod_pb", async (e) => {
console.log("change:repeating_profiles:mod_pb", e);
const [r, section, rowId] = e.sourceAttribute.split("_");
await pbBonus(e.newValue, `${r}_${section}_${rowId}_mod_`);
});
|
Zakarik/roll20-character-sheets
|
Palladium Rifts by Grinning Gecko/src/js/bonuses.js
|
JavaScript
|
mit
| 13,275
|
/* @group Base */
.chzn-container {
position: relative;
display: inline-block;
vertical-align: middle;
font-size: 13px;
zoom: 1;
*display: inline;
}
.chzn-container .chzn-drop {
position: absolute;
top: 100%;
left: -9999px;
z-index: 1010;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
width: 100%;
border: 1px solid #aaa;
border-top: 0;
background: #fff;
box-shadow: 0 4px 5px rgba(0, 0, 0, 0.15);
}
.chzn-container.chzn-with-drop .chzn-drop {
left: 0;
}
/* @end */
/* @group Single Chosen */
.chzn-container-single .chzn-single {
position: relative;
display: block;
overflow: hidden;
padding: 0 0 0 8px;
height: 23px;
border: 1px solid #aaa;
border-radius: 5px;
background-color: #fff;
background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #ffffff), color-stop(50%, #f6f6f6), color-stop(52%, #eeeeee), color-stop(100%, #f4f4f4));
background: -webkit-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
background: -moz-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
background: -o-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
background: linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%);
background-clip: padding-box;
box-shadow: 0 0 3px white inset, 0 1px 1px rgba(0, 0, 0, 0.1);
color: #444;
text-decoration: none;
white-space: nowrap;
line-height: 24px;
}
.chzn-container-single .chzn-default {
color: #999;
}
.chzn-container-single .chzn-single span {
display: block;
overflow: hidden;
margin-right: 26px;
text-overflow: ellipsis;
white-space: nowrap;
}
.chzn-container-single .chzn-single-with-deselect span {
margin-right: 38px;
}
.chzn-container-single .chzn-single abbr {
position: absolute;
top: 6px;
right: 26px;
display: block;
width: 12px;
height: 12px;
background: url('chosen-sprite.png') -42px 1px no-repeat;
font-size: 1px;
}
.chzn-container-single .chzn-single abbr:hover {
background-position: -42px -10px;
}
.chzn-container-single.chzn-disabled .chzn-single abbr:hover {
background-position: -42px -10px;
}
.chzn-container-single .chzn-single div {
position: absolute;
top: 0;
right: 0;
display: block;
width: 18px;
height: 100%;
}
.chzn-container-single .chzn-single div b {
display: block;
width: 100%;
height: 100%;
background: url('chosen-sprite.png') no-repeat 0px 2px;
}
.chzn-container-single .chzn-search {
position: relative;
z-index: 1010;
margin: 0;
padding: 3px 4px;
white-space: nowrap;
}
.chzn-container-single .chzn-search input {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
margin: 1px 0;
padding: 4px 20px 4px 5px;
width: 100%;
outline: 0;
border: 1px solid #aaa;
background: white url('chosen-sprite.png') no-repeat 100% -20px;
background: url('chosen-sprite.png') no-repeat 100% -20px, -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(1%, #eeeeee), color-stop(15%, #ffffff));
background: url('chosen-sprite.png') no-repeat 100% -20px, -webkit-linear-gradient(#eeeeee 1%, #ffffff 15%);
background: url('chosen-sprite.png') no-repeat 100% -20px, -moz-linear-gradient(#eeeeee 1%, #ffffff 15%);
background: url('chosen-sprite.png') no-repeat 100% -20px, -o-linear-gradient(#eeeeee 1%, #ffffff 15%);
background: url('chosen-sprite.png') no-repeat 100% -20px, linear-gradient(#eeeeee 1%, #ffffff 15%);
font-size: 1em;
font-family: sans-serif;
}
.chzn-container-single .chzn-drop {
margin-top: -1px;
border-radius: 0 0 4px 4px;
background-clip: padding-box;
}
.chzn-container-single.chzn-container-single-nosearch .chzn-search {
position: absolute;
left: -9999px;
}
/* @end */
/* @group Results */
.chzn-container .chzn-results {
position: relative;
overflow-x: hidden;
overflow-y: auto;
margin: 0 4px 4px 0;
padding: 0 0 0 4px;
max-height: 240px;
-webkit-overflow-scrolling: touch;
}
.chzn-container .chzn-results li {
display: none;
margin: 0;
padding: 5px 6px;
list-style: none;
line-height: 15px;
}
.chzn-container .chzn-results li.active-result {
display: list-item;
cursor: pointer;
}
.chzn-container .chzn-results li.disabled-result {
display: list-item;
color: #ccc;
cursor: default;
}
.chzn-container .chzn-results li.highlighted {
background-color: #3875d7;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #3875d7), color-stop(90%, #2a62bc));
background-image: -webkit-linear-gradient(#3875d7 20%, #2a62bc 90%);
background-image: -moz-linear-gradient(#3875d7 20%, #2a62bc 90%);
background-image: -o-linear-gradient(#3875d7 20%, #2a62bc 90%);
background-image: linear-gradient(#3875d7 20%, #2a62bc 90%);
color: #fff;
}
.chzn-container .chzn-results li.no-results {
display: list-item;
background: #f4f4f4;
}
.chzn-container .chzn-results li.group-result {
display: list-item;
color: #999;
font-weight: bold;
cursor: default;
}
.chzn-container .chzn-results li.group-option {
padding-left: 15px;
}
.chzn-container .chzn-results li em {
font-style: normal;
text-decoration: underline;
}
/* @end */
/* @group Multi Chosen */
.chzn-container-multi .chzn-choices {
position: relative;
overflow: hidden;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
margin: 0;
padding: 0;
width: 100%;
height: auto !important;
height: 1%;
border: 1px solid #aaa;
background-color: #fff;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(1%, #eeeeee), color-stop(15%, #ffffff));
background-image: -webkit-linear-gradient(#eeeeee 1%, #ffffff 15%);
background-image: -moz-linear-gradient(#eeeeee 1%, #ffffff 15%);
background-image: -o-linear-gradient(#eeeeee 1%, #ffffff 15%);
background-image: linear-gradient(#eeeeee 1%, #ffffff 15%);
cursor: text;
}
.chzn-container-multi .chzn-choices li {
float: left;
list-style: none;
}
.chzn-container-multi .chzn-choices li.search-field {
margin: 0;
padding: 0;
white-space: nowrap;
}
.chzn-container-multi .chzn-choices li.search-field input {
margin: 1px 0;
padding: 5px;
height: 15px;
outline: 0;
border: 0 !important;
background: transparent !important;
box-shadow: none;
color: #666;
font-size: 100%;
font-family: sans-serif;
}
.chzn-container-multi .chzn-choices li.search-field .default {
color: #999;
}
.chzn-container-multi .chzn-choices li.search-choice {
position: relative;
margin: 3px 0 3px 5px;
padding: 3px 20px 3px 5px;
border: 1px solid #aaa;
border-radius: 3px;
background-color: #e4e4e4;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eeeeee));
background-image: -webkit-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: -moz-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: -o-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-clip: padding-box;
box-shadow: 0 0 2px white inset, 0 1px 0 rgba(0, 0, 0, 0.05);
color: #333;
line-height: 13px;
cursor: default;
}
.chzn-container-multi .chzn-choices li.search-choice .search-choice-close {
position: absolute;
top: 4px;
right: 3px;
display: block;
width: 12px;
height: 12px;
background: url('../../images/chosen-sprite.png') -42px 1px no-repeat;
font-size: 1px;
}
.chzn-container-multi .chzn-choices li.search-choice .search-choice-close:hover {
background-position: -42px -10px;
}
.chzn-container-multi .chzn-choices li.search-choice-disabled {
padding-right: 5px;
border: 1px solid #ccc;
background-color: #e4e4e4;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eeeeee));
background-image: -webkit-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: -moz-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: -o-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
background-image: linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%);
color: #666;
}
.chzn-container-multi .chzn-choices li.search-choice-focus {
background: #d4d4d4;
}
.chzn-container-multi .chzn-choices li.search-choice-focus .search-choice-close {
background-position: -42px -10px;
}
.chzn-container-multi .chzn-results {
margin: 0;
padding: 0;
}
.chzn-container-multi .chzn-drop .result-selected {
display: list-item;
color: #ccc;
cursor: default;
}
/* @end */
/* @group Active */
.chzn-container-active .chzn-single {
border: 1px solid #5897fb;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.chzn-container-active.chzn-with-drop .chzn-single {
border: 1px solid #aaa;
-moz-border-radius-bottomright: 0;
border-bottom-right-radius: 0;
-moz-border-radius-bottomleft: 0;
border-bottom-left-radius: 0;
background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #eeeeee), color-stop(80%, #ffffff));
background-image: -webkit-linear-gradient(#eeeeee 20%, #ffffff 80%);
background-image: -moz-linear-gradient(#eeeeee 20%, #ffffff 80%);
background-image: -o-linear-gradient(#eeeeee 20%, #ffffff 80%);
background-image: linear-gradient(#eeeeee 20%, #ffffff 80%);
box-shadow: 0 1px 0 #fff inset;
}
.chzn-container-active.chzn-with-drop .chzn-single div {
border-left: none;
background: transparent;
}
.chzn-container-active.chzn-with-drop .chzn-single div b {
background-position: -18px 2px;
}
.chzn-container-active .chzn-choices {
border: 1px solid #5897fb;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.chzn-container-active .chzn-choices li.search-field input {
color: #111 !important;
}
/* @end */
/* @group Disabled Support */
.chzn-disabled {
opacity: 0.5 !important;
cursor: default;
}
.chzn-disabled .chzn-single {
cursor: default;
}
.chzn-disabled .chzn-choices .search-choice .search-choice-close {
cursor: default;
}
/* @end */
/* @group Right to Left */
.chzn-rtl {
text-align: right;
}
.chzn-rtl .chzn-single {
overflow: visible;
padding: 0 8px 0 0;
}
.chzn-rtl .chzn-single span {
margin-right: 0;
margin-left: 26px;
direction: rtl;
}
.chzn-rtl .chzn-single-with-deselect span {
margin-left: 38px;
}
.chzn-rtl .chzn-single div {
right: auto;
left: 3px;
}
.chzn-rtl .chzn-single abbr {
right: auto;
left: 26px;
}
.chzn-rtl .chzn-choices li {
float: right;
}
.chzn-rtl .chzn-choices li.search-field input {
direction: rtl;
}
.chzn-rtl .chzn-choices li.search-choice {
margin: 3px 5px 3px 0;
padding: 3px 5px 3px 19px;
}
.chzn-rtl .chzn-choices li.search-choice .search-choice-close {
right: auto;
left: 4px;
}
.chzn-rtl.chzn-container-single-nosearch .chzn-search,
.chzn-rtl .chzn-drop {
left: 9999px;
}
.chzn-rtl.chzn-container-single .chzn-results {
margin: 0 0 4px 4px;
padding: 0 4px 0 0;
}
.chzn-rtl .chzn-results li.group-option {
padding-right: 15px;
padding-left: 0;
}
.chzn-rtl.chzn-container-active.chzn-with-drop .chzn-single div {
border-right: none;
}
.chzn-rtl .chzn-search input {
padding: 4px 5px 4px 20px;
background: white url('chosen-sprite.png') no-repeat -30px -20px;
background: url('chosen-sprite.png') no-repeat -30px -20px, -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(1%, #eeeeee), color-stop(15%, #ffffff));
background: url('chosen-sprite.png') no-repeat -30px -20px, -webkit-linear-gradient(#eeeeee 1%, #ffffff 15%);
background: url('chosen-sprite.png') no-repeat -30px -20px, -moz-linear-gradient(#eeeeee 1%, #ffffff 15%);
background: url('chosen-sprite.png') no-repeat -30px -20px, -o-linear-gradient(#eeeeee 1%, #ffffff 15%);
background: url('chosen-sprite.png') no-repeat -30px -20px, linear-gradient(#eeeeee 1%, #ffffff 15%);
direction: rtl;
}
.chzn-rtl.chzn-container-single .chzn-single div b {
background-position: 6px 2px;
}
.chzn-rtl.chzn-container-single.chzn-with-drop .chzn-single div b {
background-position: -12px 2px;
}
/* @end */
/* @group Retina compatibility */
@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-resolution: 144dpi) {
.chzn-rtl .chzn-search input,
.chzn-container-single .chzn-single abbr,
.chzn-container-single .chzn-single div b,
.chzn-container-single .chzn-search input,
.chzn-container-multi .chzn-choices .search-choice .search-choice-close,
.chzn-container .chzn-results-scroll-down span,
.chzn-container .chzn-results-scroll-up span {
background-image: url('chosen-sprite@2x.png') !important;
background-size: 52px 37px !important;
background-repeat: no-repeat !important;
}
}
/* @end */
|
devmars/openHPMIS
|
style/extra/css/docsupport/chosen.css
|
CSS
|
mit
| 13,414
|
<!DOCTYPE html >
<html>
<head>
<link rel="stylesheet" href="demos.css" type="text/css" media="screen" />
<script src="../libraries/RGraph.common.core.js" ></script>
<script src="../libraries/RGraph.common.effects.js" ></script>
<script src="../libraries/RGraph.pie.js" ></script>
<!--[if lt IE 9]><script src="../excanvas/excanvas.js"></script><![endif]-->
<title>An animated Donut chart (RoundRobin effect)</title>
<meta name="keywords" content="demo donut roundrobin" />
<meta name="description" content="An example of the Donut chart variant of the Pie chart which uses the RoundRobin animation effec" />
<meta name="robots" content="noindex,nofollow" />
</head>
<body>
<h1>An animated Donut chart (RoundRobin effect)</h1>
<canvas id="cvs" width="350" height="300">[No canvas support]</canvas>
<script>
window.onload = function ()
{
var donut = new RGraph.Pie('cvs', [4,6,3,5,8,6,5])
.Set('variant', 'donut')
.Set('labels', ['John','Luis','Olga','Beverly','Jack','Kevin','Jill'])
.Set('strokestyle', 'transparent')
.Set('exploded', 3)
RGraph.Effects.Pie.RoundRobin(donut, {'radius': false,'frames':60});
}
</script>
<p>
<a href="./">« Back</a>
</p>
</body>
</html>
|
ControlSystemStudio/diirt
|
pods/web-pods/src/main/webapp/js/widgets/lib/RGraph/demos/donut-roundrobin.html
|
HTML
|
mit
| 1,361
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.0-rc.5-master-7f01138
*/
/* Only used with Theme processes */
html.md-THEME_NAME-theme, body.md-THEME_NAME-theme {
color: '{{foreground-1}}';
background-color: '{{background-color}}'; }
md-content {
display: block;
position: relative;
overflow: auto;
-webkit-overflow-scrolling: touch; }
md-content[md-scroll-y] {
overflow-y: auto;
overflow-x: hidden; }
md-content[md-scroll-x] {
overflow-x: auto;
overflow-y: hidden; }
@media print {
md-content {
overflow: visible !important; } }
|
maximeBuguel/mirror
|
bower_components/angular-material/modules/js/content/content.css
|
CSS
|
mit
| 623
|
import React from 'react';
import PropTypes from 'prop-types';
import { FetchedData, Param } from '../fetched';
import * as globals from '../globals';
import { ObjectPicker } from '../inputs';
const ItemBlockView = (props) => {
const ViewComponent = globals.contentViews.lookup(props.context);
return <ViewComponent {...props} />;
};
ItemBlockView.propTypes = {
context: PropTypes.object,
};
ItemBlockView.defaultProps = {
context: null,
};
export default ItemBlockView;
class FetchedItemBlockView extends React.Component {
shouldComponentUpdate(nextProps) {
return (nextProps.value.item !== this.props.value.item);
}
render() {
const context = this.props.value.item;
if (typeof context === 'object') {
return <ItemBlockView context={context} />;
}
if (typeof context === 'string') {
return (
<FetchedData>
<Param name="context" url={context} />
<ItemBlockView />
</FetchedData>
);
}
return null;
}
}
FetchedItemBlockView.propTypes = {
value: PropTypes.object,
};
FetchedItemBlockView.defaultProps = {
value: null,
};
globals.blocks.register({
label: 'item block',
icon: 'icon icon-paperclip',
schema: {
type: 'object',
properties: {
item: {
title: 'Item',
type: 'string',
formInput: <ObjectPicker />,
},
className: {
title: 'CSS Class',
type: 'string',
},
},
},
view: FetchedItemBlockView,
}, 'itemblock');
|
T2DREAM/t2dream-portal
|
src/encoded/static/components/blocks/item.js
|
JavaScript
|
mit
| 1,696
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML
><HEAD
><TITLE
>bmat_width_max</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REL="HOME"
TITLE="LIBIT Documentation"
HREF="index.html"><LINK
REL="UP"
HREF="refmanual.html"><LINK
REL="PREVIOUS"
TITLE="imat_width_max"
HREF="man.imat-width-max.html"><LINK
REL="NEXT"
TITLE="cmat_width_max"
HREF="man.cmat-width-max.html"></HEAD
><BODY
CLASS="REFENTRY"
BGCOLOR="#FFFFFF"
TEXT="#000000"
LINK="#0000FF"
VLINK="#840084"
ALINK="#0000FF"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="3"
ALIGN="center"
>LIBIT Documentation</TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="bottom"
><A
HREF="man.imat-width-max.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="80%"
ALIGN="center"
VALIGN="bottom"
></TD
><TD
WIDTH="10%"
ALIGN="right"
VALIGN="bottom"
><A
HREF="man.cmat-width-max.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><H1
><A
NAME="MAN.BMAT-WIDTH-MAX"
></A
>bmat_width_max</H1
><DIV
CLASS="REFNAMEDIV"
><A
NAME="AEN9181"
></A
><H2
>Name</H2
>bmat_width_max -- Maximum width of a matrix</DIV
><DIV
CLASS="REFSYNOPSISDIV"
><A
NAME="AEN9184"
></A
><H2
>Synopsis</H2
><DIV
CLASS="FUNCSYNOPSIS"
><P
></P
><A
NAME="AEN9185"
></A
><PRE
CLASS="FUNCSYNOPSISINFO"
>#include <it/mat.h>
</PRE
><P
><CODE
><CODE
CLASS="FUNCDEF"
>int bmat_width_max</CODE
>( bmat m
);</CODE
></P
><P
></P
></DIV
></DIV
><H2
>DESCRIPTION</H2
><P
> This function returns the maximum width of the matrix <CODE
CLASS="PARAMETER"
>m</CODE
> </P
><H2
>RETURN VALUE</H2
><P
> The maximum width
</P
><H2
>EXAMPLE</H2
><PRE
CLASS="PROGRAMLISTING"
> #include <mat.h>
...
bmat m = bmat_new_ones(5,3);
int width = bmat_width_max(m); /* width=3 */</PRE
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="man.imat-width-max.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="man.cmat-width-max.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>imat_width_max</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="refmanual.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>cmat_width_max</TD
></TR
></TABLE
></DIV
></BODY
></HTML
>
|
xiao00li/Undergraduate_Dissertation
|
libit-0.2.3/doc/html/man.bmat-width-max.html
|
HTML
|
mit
| 2,690
|
// This example compiles using the new STL<ToolKit> from ObjectSpace, Inc.
// STL<ToolKit> is the EASIEST to use STL that works on most platform/compiler
// combinations, including cfront, Borland, Visual C++, C Set++, ObjectCenter,
// and the latest Sun & HP compilers. Read the README.STL file in this
// directory for more information, or send email to info@objectspace.com.
// For an overview of STL, read the OVERVIEW.STL file in this directory.
#include <iostream.h>
#include <stl.h>
int input1 [4] = { 6, 8, 10, 2 };
int input2 [4] = { 4, 2, 11, 3 };
int main ()
{
int output [4];
transform (input1, input1 + 4, input2, output, modulus<int> ());
for (int i = 0; i < 4; i++)
cout << output[i] << endl;
return 0;
}
|
ombt/ombt
|
lts08.lcstools/tools/src/ihgp/src/stl/examples/modulus.cpp
|
C++
|
mit
| 738
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2013-2014 Igor Zinken - http://www.igorski.nl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "drumevent.h"
#include "../audioengine.h"
#include "../global.h"
#include "../utilities/samplemanager.h"
#include <cstdlib>
/* constructor / destructor */
/**
* initializes an DrumEvent with very definitive properties to be pre-cached
* for use in a sequencer context
*
* @param aPosition {int} the step position in the sequencer
* @param aDrumType {int} the PercussionType to synthesize
* @param aDrumTimbre {int} the drum machine's timbre
* @param aInstrument {BaseInstrument*} the DrumInstrument the event corresponds to
*/
DrumEvent::DrumEvent( int aPosition, int aDrumType, int aDrumTimbre, BaseInstrument* aInstrument )
{
init( aInstrument );
position = aPosition;
_sampleStart = position * AudioEngine::bytes_per_tick;
setType ( aDrumType );
setTimbre( aDrumTimbre );
updateSample();
}
DrumEvent::~DrumEvent()
{
}
/* public methods */
int DrumEvent::getTimbre()
{
return _timbre;
}
void DrumEvent::setTimbre( int aTimbre )
{
_timbre = aTimbre;
if ( !_locked )
updateSample();
else
_updateAfterUnlock = true;
}
int DrumEvent::getType()
{
return _type;
}
void DrumEvent::setType( int aType )
{
_type = aType;
if ( !_locked )
updateSample();
else
_updateAfterUnlock = true;
}
void DrumEvent::unlock()
{
_locked = false;
if ( _updateAfterUnlock )
updateSample();
_updateAfterUnlock = false;
}
/* private methods */
void DrumEvent::updateSample()
{
std::string smp;
switch ( _type )
{
case PercussionTypes::KICK_808:
if ( _timbre == DrumTimbres::GRAVEL )
smp = "kdg";
else
smp = "kd";
break;
case PercussionTypes::STICK:
if ( _timbre == DrumTimbres::GRAVEL )
smp = "stg";
else
smp = "st";
break;
case PercussionTypes::SNARE:
if ( _timbre == DrumTimbres::GRAVEL )
smp = "sng";
else
smp = "sn";
break;
case PercussionTypes::HI_HAT:
if ( _timbre == DrumTimbres::GRAVEL )
smp = "hhg";
else
smp = "hh";
break;
}
setSample( SampleManager::getSample( smp ));
}
|
hicks0074/MWEngine
|
jni/events/drumevent.cpp
|
C++
|
mit
| 3,516
|
package main
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
"testing"
app "github.com/luistm/banksaurus/cmd/bscli/application"
"github.com/luistm/testkit"
)
func deleteTestFiles(t *testing.T) {
if err := os.RemoveAll(app.Path()); err != nil {
t.Error(err)
}
}
func TestMain(t *testing.M) {
os.Setenv("BANKSAURUS_ENV", "dev")
defer os.Setenv("BANKSAURUS_ENV", "")
os.Exit(t.Run())
}
func TestAcceptanceUsage(t *testing.T) {
defer deleteTestFiles(t)
testCases := []struct {
name string
command []string
expected string
errorExpected bool
}{
{
name: "Shows usage if no option is defined",
command: []string{""},
expected: usage + "\n",
errorExpected: true,
},
}
for _, tc := range testCases {
t.Log(tc.name)
t.Log(fmt.Sprintf("$ bscli %s", strings.Join(tc.command, " ")))
cmd := exec.Command("../../bscli", tc.command...)
var outBuffer, errBuffer bytes.Buffer
cmd.Stdout = &outBuffer
cmd.Stderr = &errBuffer
err := cmd.Run()
if !tc.errorExpected && err != nil {
t.Log(outBuffer.String())
t.Log(errBuffer.String())
t.Fatalf("Test failed due to command error: %s", err.Error())
}
testkit.AssertEqual(t, tc.expected, errBuffer.String())
testkit.AssertEqual(t, "", outBuffer.String())
}
}
func TestAcceptance(t *testing.T) {
defer deleteTestFiles(t)
fixture := "./data/fixtures/sample_records_load.csv"
testCases := []struct {
name string
command []string
expected string
errorExpected bool
}{
{
name: "Shows usage if option is '-h'",
command: []string{"-h"},
expected: intro + usage + options + "\n",
errorExpected: false,
},
{
name: "Shows version if option is '--version'",
command: []string{"--version"},
expected: app.Version + "\n",
errorExpected: false,
},
{
name: "No seller should be available here",
command: []string{"seller", "show"},
expected: "",
},
{
name: "Load records from file",
command: []string{"load", "--input", fixture},
expected: "",
},
{
name: "Shows seller loaded by the load records from file",
command: []string{"seller", "show"},
expected: "COMPRA CONTINENTE MAI\nTRF CREDIT\nCOMPRA FARMACIA SAO J\n",
},
{
name: "Shows report with all available transactions",
command: []string{"report"},
expected: "-0,52€ COMPRA CONTINENTE MAI\n593,48€ TRF CREDIT\n-95,09€ COMPRA FARMACIA SAO J\n-95,09€ COMPRA FARMACIA SAO J\n",
errorExpected: false,
},
{
name: "Shows report from bank records file",
command: []string{"report", "--input", fixture},
expected: "-0,52€ COMPRA CONTINENTE MAI\n593,48€ TRF CREDIT\n-95,09€ COMPRA FARMACIA SAO J\n-95,09€ COMPRA FARMACIA SAO J\n",
errorExpected: false,
},
{
name: "Shows report from bank records file, returns error if path does not exist",
command: []string{"report", "--input", "./thispathdoesnotexist/sample_records_load.csv"},
expected: errGeneric.Error() + "\n",
errorExpected: true,
},
{
name: "Shows report from bank records file, grouped by seller",
command: []string{
"report",
"--input", fixture,
"--grouped",
},
expected: "-0,52€ COMPRA CONTINENTE MAI\n593,48€ TRF CREDIT\n-190,18€ COMPRA FARMACIA SAO J\n",
errorExpected: false,
},
{
name: "Adds pretty name to seller",
command: []string{"seller", "change", "COMPRA CONTINENTE MAI", "--pretty", "Continente"},
expected: "",
},
{
name: "Show seller changed",
command: []string{"seller", "show"},
expected: "Continente\nTRF CREDIT\nCOMPRA FARMACIA SAO J\n",
},
{
name: "Shows report, with seller name instead of slug",
command: []string{"report"},
expected: "-0,52€ Continente\n593,48€ TRF CREDIT\n-95,09€ COMPRA FARMACIA SAO J\n-95,09€ COMPRA FARMACIA SAO J\n",
errorExpected: false,
},
}
for _, tc := range testCases {
t.Log(tc.name)
t.Log(fmt.Sprintf("$ bscli %s", strings.Join(tc.command, " ")))
cmd := exec.Command("../../bscli", tc.command...)
var outBuffer, errBuffer bytes.Buffer
cmd.Stdout = &outBuffer
cmd.Stderr = &errBuffer
err := cmd.Run()
if !tc.errorExpected && err != nil {
t.Log(outBuffer.String())
t.Log(errBuffer.String())
t.Fatalf("Test failed due to command error: %s", err.Error())
} else {
if tc.errorExpected {
testkit.AssertEqual(t, tc.expected, errBuffer.String())
testkit.AssertEqual(t, "", outBuffer.String())
} else {
testkit.AssertEqual(t, "", errBuffer.String())
testkit.AssertEqual(t, tc.expected, outBuffer.String())
}
}
}
}
|
luistm/go-bank-cli
|
cmd/bscli/main_test.go
|
GO
|
mit
| 4,775
|
---
author: ZSM
comments: true
date: 2014-12-02 16:17:26
layout: post
slug: tanzania3
title: Tanzania
categories: [tanzania]
tags:
- Photo
---

|
Photographerzsm/Photographerzsm.github.io
|
_posts/2014-12-02-ts3.md
|
Markdown
|
mit
| 178
|
var assert = require('assert');
var createTestConfig = require('./test-util').createTestConfig;
var createTestServicesWithStubs = require('./test-util').createTestServicesWithStubs;
var FileServer = require('../braid-file-server').FileServer;
var request = require('request');
var fs = require('fs');
var path = require('path');
var config1;
var config2;
var services1;
var services2;
var fileServer1;
var fileServer2;
describe('file-server:', function() {
before(function(done) {
config1 = createTestConfig('test.26111', 'test1', 26101, 26111);
createTestServicesWithStubs(config1, function(err, svcs) {
assert(!err, err);
services1 = svcs;
fileServer1 = new FileServer();
fileServer1.initialize(config1, services1);
config2 = createTestConfig('test.26211', 'test2', 26201, 26211);
createTestServicesWithStubs(config2, function(err, svcs) {
assert(!err, err);
services2 = svcs;
fileServer2 = new FileServer();
fileServer2.initialize(config2, services2);
done();
});
});
});
after(function(done) {
fileServer1.close();
fileServer2.close();
services1.braidDb.close(done);
services2.braidDb.close(done);
});
it('put and retrieve file', function(done) {
fs.createReadStream(path.join(__dirname, 'braid.png')).pipe(request.put({
uri : 'http://localhost:26121',
headers : [ {
name : 'Content-Type',
value : 'image/png'
} ]
}, function(error, response, body) {
assert.equal(response.statusCode, 200);
var details = JSON.parse(body);
assert.equal(details.domain, 'test.26111');
assert.equal(details.contentType, 'image/png');
request.get({
uri : 'http://localhost:26121/' + details.domain + "/" + details.fileId,
encoding : null
}, function(error, response, body) {
assert.equal(response.body.length, 65048)
assert.equal(response.headers['content-type'], 'image/png');
assert.equal(response.statusCode, 200);
done();
});
}).on('error', function(err) {
throw err;
}));
});
it('using encryption', function(done) {
fs.createReadStream(path.join(__dirname, 'braid.png')).pipe(request.put({
uri : 'http://localhost:26121?encrypt=true',
headers : [ {
name : 'Content-Type',
value : 'image/png'
} ]
}, function(error, response, body) {
assert.equal(response.statusCode, 200);
var details = JSON.parse(body);
assert.equal(details.domain, 'test.26111');
assert.equal(details.contentType, 'image/png');
assert(details.encryptionKey !== null);
request.get({
uri : 'http://localhost:26121/' + details.domain + "/" + details.fileId + "?decrypt=true&key=" + details.encryptionKey,
encoding : null
}, function(error, response, body) {
assert.equal(response.body.length, 65048)
assert.equal(response.headers['content-type'], 'image/png');
assert.equal(response.statusCode, 200);
done();
});
}).on('error', function(err) {
throw err;
}));
});
it('files on remote domains', function(done) {
fs.createReadStream(path.join(__dirname, 'braid.png')).pipe(request.put({
uri : 'http://localhost:26221',
headers : [ {
name : 'Content-Type',
value : 'image/png'
} ]
}, function(error, response, body) {
assert.equal(response.statusCode, 200);
var details = JSON.parse(body);
assert.equal(details.domain, 'test.26211');
assert.equal(details.contentType, 'image/png');
request.get({
uri : 'http://localhost:26121/' + details.domain + "/" + details.fileId,
encoding : null
}, function(error, response, body) {
assert.equal(response.statusCode, 200);
assert.equal(response.headers['content-type'], 'image/png');
assert.equal(response.body.length, 65048)
done();
});
}).on('error', function(err) {
throw err;
}));
});
});
|
kduffie/braid-server
|
test/test-file-server.js
|
JavaScript
|
mit
| 3,779
|
<?php
/**
* An example Morph_Object derived class
*
* @property string $userName
* @property string $firstName
* @property string $lastName
* @property int $dateOfBirth
*/
class User extends Morph_Object
{
public function __construct($id = null) {
parent::__construct($id);
$this->addProperty(new Morph_Property_String('userName'))
->addProperty(new Morph_Property_String('firstName'))
->addProperty(new Morph_Property_String('lastName'))
->addProperty(new Morph_Property_Date('dateOfBirth'))
->addProperty(new Morph_Property_Integer('numberOfPosts', 0));
}
}
|
a-musing-moose/morph
|
src/tutorials/Morph/examples/MinimalObject.php
|
PHP
|
mit
| 622
|
package controllers5;
import play.mvc.Controller;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Hello1111111111111111111111111111111111 extends Controller {
public static void hello() {
// System.out.println("tere");
render("Application/hello.html", debug());
}
private static Object debug() {return util.Util.get();}
private static void sort(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort2(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort3(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort4(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort5(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort6(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort7(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort8(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort9(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort10(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort11(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort12(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort13(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort14(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort15(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort16(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort17(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort18(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort19(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
private static void sort20(List<Object> list) {
Collections.sort(list, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
return o2.hashCode() - o2.hashCode();
}
});
}
}
|
asolntsev/big-app.play
|
app/controllers5/Hello1111111111111111111111111111111111.java
|
Java
|
mit
| 4,765
|
version https://git-lfs.github.com/spec/v1
oid sha256:7f9cbfb4555e04b948aae3356d710f479a41b7a1c0b5a605beeefce843edd9e6
size 2675
|
yogeshsaroya/new-cdnjs
|
ajax/libs/yui/3.15.0/arraylist-add/arraylist-add.js
|
JavaScript
|
mit
| 129
|
define([
'angular',
'../module',
'../service',
'common/services/bootstrap',
], function(angular, lazyModule, service, bootstrapService) {
'use strict';
/**
* [homeController description]
* @param {[type]} $scope [description]
* @param {[type]} homeService [description]
* @return {[type]} [description]
*/
lazyModule.controller('ContentController', ['$scope', '$modal', '$rootScope', 'HomeService', 'ModalService',
function($scope, $modal, $rootScope, homeService, modalService) {
var self = this;
$rootScope.pageTitle = 'home';
/**
* [pageLoad description]
* @return {[type]} [description]
*/
self.pageLoad = function() {
homeService.getData().success(function(response) {
$scope.awesomeThings = response.data;
});
};
self.pageLoad();
}
]);
});
|
pradeepbhati/angularjs-requirejs-optimiser
|
public/scripts/home/content/controller.js
|
JavaScript
|
mit
| 1,004
|
module ShadowsocksRuby
module Connections
# A ServerConnection is a connection whose peer is a downstream peer, like a Client or a LocalBackend.
class ServerConnection < Connection
# Packet Protocol
#
# A Strategy Pattern for replacing protocol algorithm
#
# the first read from {ServerConnection}'s {packet_protocol} is an address_bin,
# other read from {packet_protocol} is just data
#
# all send to {packet_protocol} should be just data
#
# @return [ShadowsocksRuby::Protocols::SomePacketProtocol]
# @see ShadowsocksRuby::Protocols
attr_accessor :packet_protocol
# Params
# @return [Hash]
attr_reader :params
# If clild class override initialize, make sure to call super
#
# @param [Protocols::ProtocolStack] protocol_stack
# @param [Hash] params
# @option params [Integer] :timeout set +comm_inactivity_timeout+
# @param [Protocols::ProtocolStack] backend_protocol_stack
# @param [Hash] backend_params
# @option backend_params [Integer] :timeout set +comm_inactivity_timeout+
# @return [Connection_Object]
def initialize protocol_stack, params, backend_protocol_stack, backend_params
super()
@packet_protocol = protocol_stack.build!(self)
@params = params
@backend_protocol_stack = backend_protocol_stack
@backend_params = backend_params
self.comm_inactivity_timeout = @params[:timeout] if @params[:timeout] && @params[:timeout] != 0
end
def post_init
App.instance.incr
super()
end
# Create a plexer -- a backend connection
# @param [String] host
# @param [Integer] port
# @param [Class] backend_klass
# @return [Connection_Object]
def create_plexer(host, port, backend_klass)
@plexer = EventMachine.connect host, port, backend_klass, @backend_protocol_stack, @backend_params
@plexer.plexer = self
@plexer
rescue EventMachine::ConnectionError => e
raise ConnectionError, e.message + " when connect to #{host}:#{port}"
end
def unbind
App.instance.decr
super()
end
end
end
end
|
zhenkyle/shadowsocks_ruby
|
lib/shadowsocks_ruby/connections/server_connection.rb
|
Ruby
|
mit
| 2,252
|
(function() {
var Sherpa;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.__super__ = parent.prototype;
return child;
};
root.Sherpa = Sherpa = (function() {
var Glob, Lookup, Node, Path, PathRequest, RegexMatcher, RegexPath, Request, RequestMatcher, Response, Route, SpanningRegexMatcher, Variable;
function Sherpa(callback) {
this.callback = callback;
this.root = new Node();
this.routes = {};
}
Sherpa.prototype.match = function(httpRequest, httpResponse) {
var request;
request = (httpRequest.url != null) ? new Request(httpRequest) : new PathRequest(httpRequest);
this.root.match(request);
if (request.destinations.length > 0) {
return new Response(request, httpResponse).invoke();
} else if (this.callback != null) {
return this.callback(request.underlyingRequest);
}
};
Sherpa.prototype.findSubparts = function(part) {
var match, subparts;
subparts = [];
while (match = part.match(/\\.|[:*][a-z0-9_]+|[^:*\\]+/)) {
part = part.slice(match.index, part.length);
subparts.push(part.slice(0, match[0].length));
part = part.slice(match[0].length, part.length);
}
return subparts;
};
Sherpa.prototype.generatePaths = function(path) {
var add, c, charIndex, chars, endIndex, pathIndex, paths, startIndex, _ref, _ref2;
_ref = [[''], path.split(''), 0, 1], paths = _ref[0], chars = _ref[1], startIndex = _ref[2], endIndex = _ref[3];
for (charIndex = 0, _ref2 = chars.length; 0 <= _ref2 ? charIndex < _ref2 : charIndex > _ref2; 0 <= _ref2 ? charIndex++ : charIndex--) {
c = chars[charIndex];
switch (c) {
case '\\':
charIndex++;
add = chars[charIndex] === ')' || chars[charIndex] === '(' ? chars[charIndex] : "\\" + chars[charIndex];
for (pathIndex = startIndex; startIndex <= endIndex ? pathIndex < endIndex : pathIndex > endIndex; startIndex <= endIndex ? pathIndex++ : pathIndex--) {
paths[pathIndex] += add;
}
break;
case '(':
for (pathIndex = startIndex; startIndex <= endIndex ? pathIndex < endIndex : pathIndex > endIndex; startIndex <= endIndex ? pathIndex++ : pathIndex--) {
paths.push(paths[pathIndex]);
}
startIndex = endIndex;
endIndex = paths.length;
break;
case ')':
startIndex -= endIndex - startIndex;
break;
default:
for (pathIndex = startIndex; startIndex <= endIndex ? pathIndex < endIndex : pathIndex > endIndex; startIndex <= endIndex ? pathIndex++ : pathIndex--) {
paths[pathIndex] += c;
}
}
}
paths.reverse();
return paths;
};
Sherpa.prototype.url = function(name, params) {
var _ref;
return (_ref = this.routes[name]) != null ? _ref.url(params) : void 0;
};
Sherpa.prototype.addComplexPart = function(subparts, compiledPath, matchesWith, variableNames) {
var captures, capturingIndicies, escapeRegexp, name, part, regexSubparts, regexp, spans, splittingIndicies, _ref;
escapeRegexp = function(str) {
return str.replace(/([\.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
_ref = [[], [], 0, false], capturingIndicies = _ref[0], splittingIndicies = _ref[1], captures = _ref[2], spans = _ref[3];
regexSubparts = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = subparts.length; _i < _len; _i++) {
part = subparts[_i];
_results.push((function() {
var _ref2;
switch (part[0]) {
case '\\':
compiledPath.push("'" + part[1] + "'");
return escapeRegexp(part[1]);
case ':':
case '*':
if (part[0] === '*') {
spans = true;
}
captures += 1;
name = part.slice(1, part.length);
variableNames.push(name);
if (part[0] === '*') {
splittingIndicies.push(captures);
compiledPath.push("params['" + name + "'].join('/')");
} else {
capturingIndicies.push(captures);
compiledPath.push("params['" + name + "']");
}
if (spans) {
if (matchesWith[name] != null) {
return "((?:" + matchesWith[name].source + "\\/?)+)";
} else {
return '(.*?)';
}
} else {
return "(" + (((_ref2 = matchesWith[name]) != null ? _ref2.source : void 0) || '[^/]*?') + ")";
}
break;
default:
compiledPath.push("'" + part + "'");
return escapeRegexp(part);
}
})());
}
return _results;
})();
regexp = new RegExp("" + (regexSubparts.join('')) + "$");
if (spans) {
return new SpanningRegexMatcher(regexp, capturingIndicies, splittingIndicies);
} else {
return new RegexMatcher(regexp, capturingIndicies, splittingIndicies);
}
};
Sherpa.prototype.addSimplePart = function(subparts, compiledPath, matchesWith, variableNames) {
var part, variableName;
part = subparts[0];
switch (part[0]) {
case ':':
variableName = part.slice(1, part.length);
compiledPath.push("params['" + variableName + "']");
variableNames.push(variableName);
if (matchesWith[variableName] != null) {
return new SpanningRegexMatcher(matchesWith[variableName], [0], []);
} else {
return new Variable();
}
break;
case '*':
compiledPath.push("params['" + variableName + "'].join('/')");
variableName = part.slice(1, part.length);
variableNames.push(variableName);
return new Glob(matchesWith[variableName]);
default:
compiledPath.push("'" + part + "'");
return new Lookup(part);
}
};
Sherpa.prototype.add = function(rawPath, opts) {
var compiledPath, defaults, matchesWith, nextNodeFn, node, part, partiallyMatch, parts, path, pathSet, route, routeName, subparts, variableNames;
matchesWith = (opts != null ? opts.matchesWith : void 0) || {};
defaults = (opts != null ? opts["default"] : void 0) || {};
routeName = opts != null ? opts.name : void 0;
partiallyMatch = false;
route = rawPath.exec != null ? new Route([this.root.add(new RegexPath(this.root, rawPath))]) : (rawPath.substring(rawPath.length - 1) === '*' ? (rawPath = rawPath.substring(0, rawPath.length - 1), partiallyMatch = true) : void 0, pathSet = (function() {
var _i, _j, _len, _len2, _ref, _results;
_ref = this.generatePaths(rawPath);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
path = _ref[_i];
node = this.root;
variableNames = [];
parts = path.split('/');
compiledPath = [];
for (_j = 0, _len2 = parts.length; _j < _len2; _j++) {
part = parts[_j];
if (part !== '') {
compiledPath.push("'/'");
subparts = this.findSubparts(part);
nextNodeFn = subparts.length === 1 ? this.addSimplePart : this.addComplexPart;
node = node.add(nextNodeFn(subparts, compiledPath, matchesWith, variableNames));
}
}
if ((opts != null ? opts.conditions : void 0) != null) {
node = node.add(new RequestMatcher(opts.conditions));
}
path = new Path(node, variableNames);
path.partial = partiallyMatch;
path.compiled = compiledPath.length === 0 ? "'/'" : compiledPath.join('+');
_results.push(path);
}
return _results;
}).call(this), new Route(pathSet, matchesWith));
route["default"] = defaults;
route.name = routeName;
if (routeName != null) {
this.routes[routeName] = route;
}
return route;
};
Response = (function() {
function Response(request, httpResponse, position) {
this.request = request;
this.httpResponse = httpResponse;
this.position = position;
this.position || (this.position = 0);
}
Response.prototype.next = function() {
if (this.position === this.destinations.length - 1) {
return false;
} else {
return new Response(this.request, this.httpResponse, this.position + 1).invoke();
}
};
Response.prototype.invoke = function() {
var req;
req = typeof this.request.underlyingRequest === 'string' ? {} : this.request.underlyingRequest;
req.params = this.request.destinations[this.position].params;
req.route = this.request.destinations[this.position].route;
req.pathInfo = this.request.destinations[this.position].pathInfo;
return this.request.destinations[this.position].route.destination(req, this.httpResponse);
};
return Response;
})();
Node = (function() {
function Node() {
this.type || (this.type = 'node');
this.matchers = [];
}
Node.prototype.add = function(n) {
var _ref;
if (!((_ref = this.matchers[this.matchers.length - 1]) != null ? _ref.usable(n) : void 0)) {
this.matchers.push(n);
}
return this.matchers[this.matchers.length - 1].use(n);
};
Node.prototype.usable = function(n) {
return n.type === this.type;
};
Node.prototype.match = function(request) {
var m, _i, _len, _ref, _results;
_ref = this.matchers;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
m = _ref[_i];
_results.push(m.match(request));
}
return _results;
};
Node.prototype.superMatch = Node.prototype.match;
Node.prototype.use = function(n) {
return this;
};
return Node;
})();
Lookup = (function() {
__extends(Lookup, Node);
function Lookup(part) {
this.part = part;
this.type = 'lookup';
this.map = {};
Lookup.__super__.constructor.apply(this, arguments);
}
Lookup.prototype.match = function(request) {
var part;
if (this.map[request.path[0]] != null) {
request = request.clone();
part = request.path.shift();
return this.map[part].match(request);
}
};
Lookup.prototype.use = function(n) {
var _base, _name;
(_base = this.map)[_name = n.part] || (_base[_name] = new Node());
return this.map[n.part];
};
return Lookup;
})();
Variable = (function() {
__extends(Variable, Node);
function Variable() {
this.type || (this.type = 'variable');
Variable.__super__.constructor.apply(this, arguments);
}
Variable.prototype.match = function(request) {
if (request.path.length > 0) {
request = request.clone();
request.variables.push(request.path.shift());
return Variable.__super__.match.call(this, request);
}
};
return Variable;
})();
Glob = (function() {
__extends(Glob, Variable);
function Glob(regexp) {
this.regexp = regexp;
this.type = 'glob';
Glob.__super__.constructor.apply(this, arguments);
}
Glob.prototype.match = function(request) {
var cloned_path, i, match, original_request, _ref, _results;
if (request.path.length > 0) {
original_request = request;
cloned_path = request.path.slice(0, request.path);
_results = [];
for (i = 1, _ref = original_request.path.length; 1 <= _ref ? i <= _ref : i >= _ref; 1 <= _ref ? i++ : i--) {
request = original_request.clone();
if (this.regexp != null) {
match = request.path[i - 1].match(this.regexp);
}
if ((this.regexp != null) && (!(match != null) || match[0].length !== request.path[i - 1].length)) {
return;
}
request.variables.push(request.path.slice(0, i));
request.path = request.path.slice(i, request.path.length);
_results.push(this.superMatch(request));
}
return _results;
}
};
return Glob;
})();
RegexMatcher = (function() {
__extends(RegexMatcher, Node);
function RegexMatcher(regexp, capturingIndicies, splittingIndicies) {
var i, _i, _j, _len, _len2, _ref, _ref2;
this.regexp = regexp;
this.capturingIndicies = capturingIndicies;
this.splittingIndicies = splittingIndicies;
this.type || (this.type = 'regex');
this.varIndicies = [];
_ref = this.splittingIndicies;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
i = _ref[_i];
this.varIndicies[i] = [i, 'split'];
}
_ref2 = this.capturingIndicies;
for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) {
i = _ref2[_j];
this.varIndicies[i] = [i, 'capture'];
}
this.varIndicies.sort(function(a, b) {
return a[0] - b[0];
});
RegexMatcher.__super__.constructor.apply(this, arguments);
}
RegexMatcher.prototype.match = function(request) {
var match;
if ((request.path[0] != null) && (match = request.path[0].match(this.regexp))) {
if (match[0].length !== request.path[0].length) {
return;
}
request = request.clone();
this.addVariables(request, match);
request.path.shift();
return RegexMatcher.__super__.match.call(this, request);
}
};
RegexMatcher.prototype.addVariables = function(request, match) {
var idx, type, v, _i, _len, _ref, _results;
_ref = this.varIndicies;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
v = _ref[_i];
if (v != null) {
idx = v[0];
type = v[1];
_results.push((function() {
switch (type) {
case 'split':
return request.variables.push(match[idx].split('/'));
case 'capture':
return request.variables.push(match[idx]);
}
})());
}
}
return _results;
};
RegexMatcher.prototype.usable = function(n) {
return n.type === this.type && n.regexp === this.regexp && n.capturingIndicies === this.capturingIndicies && n.splittingIndicies === this.splittingIndicies;
};
return RegexMatcher;
})();
SpanningRegexMatcher = (function() {
__extends(SpanningRegexMatcher, RegexMatcher);
function SpanningRegexMatcher(regexp, capturingIndicies, splittingIndicies) {
this.regexp = regexp;
this.capturingIndicies = capturingIndicies;
this.splittingIndicies = splittingIndicies;
this.type = 'spanning';
SpanningRegexMatcher.__super__.constructor.apply(this, arguments);
}
SpanningRegexMatcher.prototype.match = function(request) {
var match, wholePath;
if (request.path.length > 0) {
wholePath = request.wholePath();
if (match = wholePath.match(this.regexp)) {
if (match.index !== 0) {
return;
}
request = request.clone();
this.addVariables(request, match);
request.path = request.splitPath(wholePath.slice(match.index + match[0].length, wholePath.length));
return this.superMatch(request);
}
}
};
return SpanningRegexMatcher;
})();
RequestMatcher = (function() {
__extends(RequestMatcher, Node);
function RequestMatcher(conditions) {
this.conditions = conditions;
this.type = 'request';
RequestMatcher.__super__.constructor.apply(this, arguments);
}
RequestMatcher.prototype.match = function(request) {
var conditionCount, matcher, matching, satisfiedConditionCount, type, v, val, _ref;
conditionCount = 0;
satisfiedConditionCount = 0;
_ref = this.conditions;
for (type in _ref) {
matcher = _ref[type];
val = request.underlyingRequest[type];
conditionCount++;
v = matcher instanceof Array ? (matching = function() {
var cond, _i, _len;
for (_i = 0, _len = matcher.length; _i < _len; _i++) {
cond = matcher[_i];
if (cond.exec != null) {
if (matcher.exec(val)) {
return true;
}
} else {
if (cond === val) {
return true;
}
}
}
return false;
}, matching()) : matcher.exec != null ? matcher.exec(val) : matcher === val;
if (v) {
satisfiedConditionCount++;
}
}
if (conditionCount === satisfiedConditionCount) {
return RequestMatcher.__super__.match.call(this, request);
}
};
RequestMatcher.prototype.usable = function(n) {
return n.type === this.type && n.conditions === this.conditions;
};
return RequestMatcher;
})();
Path = (function() {
__extends(Path, Node);
function Path(parent, variableNames) {
this.parent = parent;
this.variableNames = variableNames;
this.type = 'path';
this.partial = false;
}
Path.prototype.addDestination = function(request) {
return request.destinations.push({
route: this.route,
request: request,
params: this.constructParams(request)
});
};
Path.prototype.match = function(request) {
if (this.partial || request.path.length === 0) {
this.addDestination(request);
if (this.partial) {
return request.destinations[request.destinations.length - 1].pathInfo = "/" + (request.wholePath());
}
}
};
Path.prototype.constructParams = function(request) {
var i, params, _ref;
params = {};
for (i = 0, _ref = this.variableNames.length; 0 <= _ref ? i < _ref : i > _ref; 0 <= _ref ? i++ : i--) {
params[this.variableNames[i]] = request.variables[i];
}
return params;
};
Path.prototype.url = function(rawParams) {
var key, match, name, params, path, _i, _j, _k, _len, _len2, _len3, _ref, _ref2, _ref3;
if (rawParams == null) {
rawParams = {};
}
params = {};
_ref = this.variableNames;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
params[key] = this.route["default"] != null ? rawParams[key] || this.route["default"][key] : rawParams[key];
if (!(params[key] != null)) {
return;
}
}
_ref2 = this.variableNames;
for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) {
name = _ref2[_j];
if (this.route.matchesWith[name] != null) {
match = params[name].match(this.route.matchesWith[name]);
if (!((match != null) && match[0].length === params[name].length)) {
return;
}
}
}
path = this.compiled === '' ? '' : eval(this.compiled);
if (path != null) {
_ref3 = this.variableNames;
for (_k = 0, _len3 = _ref3.length; _k < _len3; _k++) {
name = _ref3[_k];
delete rawParams[name];
}
return path;
}
};
return Path;
})();
RegexPath = (function() {
__extends(RegexPath, Path);
function RegexPath(parent, regexp) {
this.parent = parent;
this.regexp = regexp;
this.type = 'regexp_route';
RegexPath.__super__.constructor.apply(this, arguments);
}
RegexPath.prototype.match = function(request) {
request.regexpRouteMatch = this.regexp.exec(request.decodedPath());
if ((request.regexpRouteMatch != null) && request.regexpRouteMatch[0].length === request.decodedPath().length) {
request = request.clone();
request.path = [];
return RegexPath.__super__.match.call(this, request);
}
};
RegexPath.prototype.constructParams = function(request) {
return request.regexpRouteMatch;
};
RegexPath.prototype.url = function(rawParams) {
throw "This route cannot be generated";
};
return RegexPath;
})();
Route = (function() {
function Route(pathSet, matchesWith) {
var path, _i, _len, _ref;
this.pathSet = pathSet;
this.matchesWith = matchesWith;
_ref = this.pathSet;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
path = _ref[_i];
path.route = this;
}
}
Route.prototype.to = function(destination) {
var path, _i, _len, _ref, _results;
this.destination = destination;
_ref = this.pathSet;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
path = _ref[_i];
_results.push(path.parent.add(path));
}
return _results;
};
Route.prototype.generateQuery = function(params, base, query) {
var idx, k, v, _ref;
query = "";
base || (base = "");
if (params != null) {
if (params instanceof Array) {
for (idx = 0, _ref = params.length; 0 <= _ref ? idx < _ref : idx > _ref; 0 <= _ref ? idx++ : idx--) {
query += this.generateQuery(params[idx], "" + base + "[]");
}
} else if (params instanceof Object) {
for (k in params) {
v = params[k];
query += this.generateQuery(v, base === '' ? k : "" + base + "[" + k + "]");
}
} else {
query += encodeURIComponent(base).replace(/%20/g, '+');
query += '=';
query += encodeURIComponent(params).replace(/%20/g, '+');
query += '&';
}
}
return query;
};
Route.prototype.url = function(params) {
var joiner, path, pathObj, query, _i, _len, _ref;
path = void 0;
_ref = this.pathSet;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
pathObj = _ref[_i];
path = pathObj.url(params);
if (path != null) {
break;
}
}
if (path != null) {
query = this.generateQuery(params);
joiner = query !== '' ? '?' : '';
return "" + (encodeURI(path)) + joiner + (query.substr(0, query.length - 1));
} else {
return;
}
};
return Route;
})();
Request = (function() {
function Request(underlyingRequest, callback) {
this.underlyingRequest = underlyingRequest;
this.callback = callback;
this.variables = [];
this.destinations = [];
if (this.underlyingRequest != null) {
this.path = this.splitPath();
}
}
Request.prototype.toString = function() {
return "<Request path: /" + (this.path.join('/')) + " " + this.path.length + ">";
};
Request.prototype.wholePath = function() {
return this.path.join('/');
};
Request.prototype.decodedPath = function(path) {
if (path == null) {
path = require('url').parse(this.underlyingRequest.url).pathname;
}
return decodeURI(path);
};
Request.prototype.splitPath = function(path) {
var decodedPath, splitPath;
decodedPath = this.decodedPath(path);
splitPath = decodedPath === '/' ? [] : decodedPath.split('/');
if (splitPath[0] === '') {
splitPath.shift();
}
return splitPath;
};
Request.prototype.clone = function() {
var c;
c = new Request();
c.path = this.path.slice(0, this.path.length);
c.variables = this.variables.slice(0, this.variables.length);
c.underlyingRequest = this.underlyingRequest;
c.callback = this.callback;
c.destinations = this.destinations;
return c;
};
return Request;
})();
PathRequest = (function() {
__extends(PathRequest, Request);
function PathRequest() {
PathRequest.__super__.constructor.apply(this, arguments);
}
PathRequest.prototype.decodedPath = function(path) {
if (path == null) {
path = this.underlyingRequest;
}
return decodeURI(path);
};
return PathRequest;
})();
return Sherpa;
})();
}).call(this);
|
joshbuddy/http_router
|
js/lib/http_router.js
|
JavaScript
|
mit
| 25,532
|
require 'rails_helper'
RSpec.describe FeedbacksController, type: :controller do
end
|
xzlstc415/yujihomo
|
spec/controllers/feedbacks_controller_spec.rb
|
Ruby
|
mit
| 86
|
import {flags} from '@heroku-cli/command'
import {cli} from 'cli-ux'
import BaseCommand from '../../../base'
export default class EventsIndex extends BaseCommand {
static description = 'list webhook events on an app'
static examples = [
'$ heroku webhooks:events',
]
static flags = {
app: flags.app(),
remote: flags.remote(),
pipeline: flags.pipeline({char: 'p', description: 'pipeline on which to list', hidden: true}),
}
async run() {
const {flags} = this.parse(EventsIndex)
const {path, display} = this.webhookType(flags)
cli.warn('heroku webhooks:event is deprecated, please use heroku webhooks:deliveries')
const {body: events} = await this.webhooksClient.get(`${path}/webhook-events`)
if (events.length === 0) {
this.log(`${display} has no events`)
} else {
events.sort((a: any, b: any) => Date.parse(a.created_at) - Date.parse(b.created_at))
cli.table(events, {
id: {
header: 'Event ID',
},
resource: {
get: (w: any) => w.payload.resource,
},
action: {
get: (w: any) => w.payload.action,
},
published_at: {
header: 'Published At', get: (w: any) => w.payload.published_at,
},
}, {
printLine: this.log,
})
}
}
}
|
heroku/heroku-cli
|
packages/webhooks/src/commands/webhooks/events/index.ts
|
TypeScript
|
mit
| 1,326
|
#ifdef DEBUG_X11
extern int _Xdebug; /* part of Xlib */
#endif
#include <sys/time.h>
#include "allegro5/allegro.h"
#include "allegro5/internal/aintern_bitmap.h"
#include "allegro5/internal/aintern_x.h"
#include "allegro5/internal/aintern_xcursor.h"
#include "allegro5/internal/aintern_xembed.h"
#include "allegro5/internal/aintern_xevents.h"
#include "allegro5/internal/aintern_xfullscreen.h"
#include "allegro5/internal/aintern_xkeyboard.h"
#include "allegro5/internal/aintern_xmouse.h"
#include "allegro5/internal/aintern_xsystem.h"
#include "allegro5/platform/aintunix.h"
#include "allegro5/platform/aintxglx.h"
ALLEGRO_DEBUG_CHANNEL("system")
static ALLEGRO_SYSTEM_INTERFACE *xglx_vt;
static ALLEGRO_SYSTEM *xglx_initialize(int flags)
{
Display *x11display;
Display *gfxdisplay;
ALLEGRO_SYSTEM_XGLX *s;
(void)flags;
#ifdef DEBUG_X11
_Xdebug = 1;
#endif
XInitThreads();
/* Get an X11 display handle. */
x11display = XOpenDisplay(0);
if (x11display) {
/* Never ask. */
gfxdisplay = XOpenDisplay(0);
if (!gfxdisplay) {
ALLEGRO_ERROR("XOpenDisplay failed second time.\n");
XCloseDisplay(x11display);
return NULL;
}
}
else {
ALLEGRO_INFO("XOpenDisplay failed; assuming headless mode.\n");
gfxdisplay = NULL;
}
_al_unix_init_time();
s = al_calloc(1, sizeof *s);
_al_mutex_init_recursive(&s->lock);
_al_cond_init(&s->resized);
s->inhibit_screensaver = false;
_al_vector_init(&s->system.displays, sizeof (ALLEGRO_DISPLAY_XGLX *));
s->system.vt = xglx_vt;
s->gfxdisplay = gfxdisplay;
s->x11display = x11display;
if (s->x11display) {
ALLEGRO_INFO("XGLX driver connected to X11 (%s %d).\n",
ServerVendor(s->x11display), VendorRelease(s->x11display));
ALLEGRO_INFO("X11 protocol version %d.%d.\n",
ProtocolVersion(s->x11display), ProtocolRevision(s->x11display));
/* We need to put *some* atom into the ClientMessage we send for
* faking mouse movements with al_set_mouse_xy - so let's ask X11
* for one here.
*/
s->AllegroAtom = XInternAtom(x11display, "AllegroAtom", False);
/* Message type for XEmbed protocol. */
s->XEmbedAtom = XInternAtom(x11display, "_XEMBED", False);
_al_thread_create(&s->xevents_thread, _al_xwin_background_thread, s);
s->have_xevents_thread = true;
ALLEGRO_INFO("events thread spawned.\n");
}
return &s->system;
}
static void xglx_shutdown_system(void)
{
ALLEGRO_SYSTEM *s = al_get_system_driver();
ALLEGRO_SYSTEM_XGLX *sx = (void *)s;
ALLEGRO_INFO("shutting down.\n");
if (sx->have_xevents_thread) {
_al_thread_join(&sx->xevents_thread);
sx->have_xevents_thread = false;
}
/* Close all open displays. */
while (_al_vector_size(&s->displays) > 0) {
ALLEGRO_DISPLAY **dptr = _al_vector_ref(&s->displays, 0);
ALLEGRO_DISPLAY *d = *dptr;
al_destroy_display(d);
}
_al_vector_free(&s->displays);
// Makes sure we wait for any commands sent to the X server when destroying the displays.
// Should make sure we don't shutdown before modes are restored.
if (sx->x11display) {
XSync(sx->x11display, False);
}
_al_xsys_mmon_exit(sx);
if (sx->x11display) {
XCloseDisplay(sx->x11display);
sx->x11display = None;
ALLEGRO_DEBUG("xsys: close x11display.\n");
}
if (sx->gfxdisplay) {
XCloseDisplay(sx->gfxdisplay);
sx->gfxdisplay = None;
}
al_free(sx);
}
static ALLEGRO_DISPLAY_INTERFACE *xglx_get_display_driver(void)
{
ALLEGRO_SYSTEM_XGLX *system = (ALLEGRO_SYSTEM_XGLX *)al_get_system_driver();
/* Look up the toggle_mouse_grab_key binding. This isn't such a great place
* to do it, but the config file is not available until after the system driver
* is initialised.
*/
if (!system->toggle_mouse_grab_keycode) {
const char *binding = al_get_config_value(al_get_system_config(),
"keyboard", "toggle_mouse_grab_key");
if (binding) {
system->toggle_mouse_grab_keycode = _al_parse_key_binding(binding,
&system->toggle_mouse_grab_modifiers);
if (system->toggle_mouse_grab_keycode) {
ALLEGRO_DEBUG("Toggle mouse grab key: '%s'\n", binding);
}
else {
ALLEGRO_WARN("Cannot parse key binding '%s'\n", binding);
}
}
}
return _al_display_xglx_driver();
}
static ALLEGRO_KEYBOARD_DRIVER *xglx_get_keyboard_driver(void)
{
return _al_xwin_keyboard_driver();
}
static ALLEGRO_MOUSE_DRIVER *xglx_get_mouse_driver(void)
{
return _al_xwin_mouse_driver();
}
static ALLEGRO_JOYSTICK_DRIVER *xglx_get_joystick_driver(void)
{
return _al_joystick_driver_list[0].driver;
}
static ALLEGRO_HAPTIC_DRIVER *xglx_get_haptic_driver(void)
{
return _al_haptic_driver_list[0].driver;
}
static ALLEGRO_TOUCH_INPUT_DRIVER *xglx_get_touch_driver(void)
{
return _al_touch_input_driver_list[0].driver;
}
static int xglx_get_num_video_adapters(void)
{
ALLEGRO_SYSTEM_XGLX *system = (void *)al_get_system_driver();
return _al_xglx_get_num_video_adapters(system);
}
static bool xglx_get_monitor_info(int adapter, ALLEGRO_MONITOR_INFO *info)
{
ALLEGRO_SYSTEM_XGLX *system = (void *)al_get_system_driver();
return _al_xglx_get_monitor_info(system, adapter, info);
}
static bool xglx_get_cursor_position(int *ret_x, int *ret_y)
{
ALLEGRO_SYSTEM_XGLX *system = (void *)al_get_system_driver();
Window root = RootWindow(system->x11display, 0);
Window child;
int wx, wy;
unsigned int mask;
_al_mutex_lock(&system->lock);
XQueryPointer(system->x11display, root, &root, &child, ret_x, ret_y,
&wx, &wy, &mask);
_al_mutex_unlock(&system->lock);
return true;
}
static bool xglx_inhibit_screensaver(bool inhibit)
{
ALLEGRO_SYSTEM_XGLX *system = (void *)al_get_system_driver();
system->inhibit_screensaver = inhibit;
return true;
}
static int xglx_get_num_display_modes(void)
{
int adapter = al_get_new_display_adapter();
ALLEGRO_SYSTEM_XGLX *s = (ALLEGRO_SYSTEM_XGLX *)al_get_system_driver();
return _al_xglx_get_num_display_modes(s, adapter);
}
static ALLEGRO_DISPLAY_MODE *xglx_get_display_mode(int mode, ALLEGRO_DISPLAY_MODE *dm)
{
int adapter = al_get_new_display_adapter();
ALLEGRO_SYSTEM_XGLX *s = (ALLEGRO_SYSTEM_XGLX *)al_get_system_driver();
return _al_xglx_get_display_mode(s, adapter, mode, dm);
}
/* Internal function to get a reference to this driver. */
ALLEGRO_SYSTEM_INTERFACE *_al_system_xglx_driver(void)
{
if (xglx_vt)
return xglx_vt;
xglx_vt = al_calloc(1, sizeof *xglx_vt);
xglx_vt->initialize = xglx_initialize;
xglx_vt->get_display_driver = xglx_get_display_driver;
xglx_vt->get_keyboard_driver = xglx_get_keyboard_driver;
xglx_vt->get_mouse_driver = xglx_get_mouse_driver;
xglx_vt->get_joystick_driver = xglx_get_joystick_driver;
xglx_vt->get_haptic_driver = xglx_get_haptic_driver;
xglx_vt->get_touch_input_driver = xglx_get_touch_driver;
xglx_vt->get_num_display_modes = xglx_get_num_display_modes;
xglx_vt->get_display_mode = xglx_get_display_mode;
xglx_vt->shutdown_system = xglx_shutdown_system;
xglx_vt->get_num_video_adapters = xglx_get_num_video_adapters;
xglx_vt->get_monitor_info = xglx_get_monitor_info;
xglx_vt->create_mouse_cursor = _al_xwin_create_mouse_cursor;
xglx_vt->destroy_mouse_cursor = _al_xwin_destroy_mouse_cursor;
xglx_vt->get_cursor_position = xglx_get_cursor_position;
xglx_vt->grab_mouse = _al_xwin_grab_mouse;
xglx_vt->ungrab_mouse = _al_xwin_ungrab_mouse;
xglx_vt->get_path = _al_unix_get_path;
xglx_vt->inhibit_screensaver = xglx_inhibit_screensaver;
return xglx_vt;
}
/* vim: set sts=3 sw=3 et: */
|
tsteinholz/SR-Gaming
|
Libraries/allegro5-5.1/src/x/xsystem.c
|
C
|
mit
| 7,812
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2018_07_01.implementation;
import java.util.List;
import com.microsoft.azure.management.network.v2018_07_01.ConnectivityHop;
import com.microsoft.azure.management.network.v2018_07_01.ConnectionStatus;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Information on the connectivity status.
*/
public class ConnectivityInformationInner {
/**
* List of hops between the source and the destination.
*/
@JsonProperty(value = "hops", access = JsonProperty.Access.WRITE_ONLY)
private List<ConnectivityHop> hops;
/**
* The connection status. Possible values include: 'Unknown', 'Connected',
* 'Disconnected', 'Degraded'.
*/
@JsonProperty(value = "connectionStatus", access = JsonProperty.Access.WRITE_ONLY)
private ConnectionStatus connectionStatus;
/**
* Average latency in milliseconds.
*/
@JsonProperty(value = "avgLatencyInMs", access = JsonProperty.Access.WRITE_ONLY)
private Integer avgLatencyInMs;
/**
* Minimum latency in milliseconds.
*/
@JsonProperty(value = "minLatencyInMs", access = JsonProperty.Access.WRITE_ONLY)
private Integer minLatencyInMs;
/**
* Maximum latency in milliseconds.
*/
@JsonProperty(value = "maxLatencyInMs", access = JsonProperty.Access.WRITE_ONLY)
private Integer maxLatencyInMs;
/**
* Total number of probes sent.
*/
@JsonProperty(value = "probesSent", access = JsonProperty.Access.WRITE_ONLY)
private Integer probesSent;
/**
* Number of failed probes.
*/
@JsonProperty(value = "probesFailed", access = JsonProperty.Access.WRITE_ONLY)
private Integer probesFailed;
/**
* Get list of hops between the source and the destination.
*
* @return the hops value
*/
public List<ConnectivityHop> hops() {
return this.hops;
}
/**
* Get the connection status. Possible values include: 'Unknown', 'Connected', 'Disconnected', 'Degraded'.
*
* @return the connectionStatus value
*/
public ConnectionStatus connectionStatus() {
return this.connectionStatus;
}
/**
* Get average latency in milliseconds.
*
* @return the avgLatencyInMs value
*/
public Integer avgLatencyInMs() {
return this.avgLatencyInMs;
}
/**
* Get minimum latency in milliseconds.
*
* @return the minLatencyInMs value
*/
public Integer minLatencyInMs() {
return this.minLatencyInMs;
}
/**
* Get maximum latency in milliseconds.
*
* @return the maxLatencyInMs value
*/
public Integer maxLatencyInMs() {
return this.maxLatencyInMs;
}
/**
* Get total number of probes sent.
*
* @return the probesSent value
*/
public Integer probesSent() {
return this.probesSent;
}
/**
* Get number of failed probes.
*
* @return the probesFailed value
*/
public Integer probesFailed() {
return this.probesFailed;
}
}
|
selvasingh/azure-sdk-for-java
|
sdk/network/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/ConnectivityInformationInner.java
|
Java
|
mit
| 3,329
|
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {HeaderComponent} from './header.component';
describe('HeaderComponent', () => {
let component: HeaderComponent;
let fixture: ComponentFixture<HeaderComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [HeaderComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HeaderComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
|
GDG-Lille/twall-front
|
src/app/layout/header/component/header.component.spec.ts
|
TypeScript
|
mit
| 628
|
#!/usr/bin/env python
from __future__ import print_function
import argparse
import glob
import os
import platform
import shutil
import subprocess
import sys
from lib.util import get_electron_branding, rm_rf, scoped_cwd
PROJECT_NAME = get_electron_branding()['project_name']
PRODUCT_NAME = get_electron_branding()['product_name']
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
SNAPSHOT_SOURCE = os.path.join(SOURCE_ROOT, 'spec', 'fixtures', 'testsnap.js')
def main():
args = parse_args()
source_root = os.path.abspath(args.source_root)
initial_app_path = os.path.join(source_root, args.build_dir)
app_path = create_app_copy(initial_app_path)
returncode = 0
try:
with scoped_cwd(app_path):
if args.snapshot_files_dir is None:
with open(os.path.join(app_path, 'mksnapshot_args')) as f:
mkargs = f.read().splitlines()
subprocess.check_call(mkargs + [ SNAPSHOT_SOURCE ], cwd=app_path)
print('ok mksnapshot successfully created snapshot_blob.bin.')
context_snapshot = 'v8_context_snapshot.bin'
if platform.system() == 'Darwin':
if os.environ.get('TARGET_ARCH') == 'arm64':
context_snapshot = 'v8_context_snapshot.arm64.bin'
else:
context_snapshot = 'v8_context_snapshot.x86_64.bin'
context_snapshot_path = os.path.join(app_path, context_snapshot)
gen_binary = get_binary_path('v8_context_snapshot_generator', \
app_path)
genargs = [ gen_binary, \
'--output_file={0}'.format(context_snapshot_path) ]
subprocess.check_call(genargs)
print('ok v8_context_snapshot_generator successfully created ' \
+ context_snapshot)
if args.create_snapshot_only:
return 0
else:
gen_bin_path = os.path.join(args.snapshot_files_dir, '*.bin')
generated_bin_files = glob.glob(gen_bin_path)
for bin_file in generated_bin_files:
shutil.copy2(bin_file, app_path)
test_path = os.path.join(SOURCE_ROOT, 'spec', 'fixtures', \
'snapshot-items-available')
if sys.platform == 'darwin':
bin_files = glob.glob(os.path.join(app_path, '*.bin'))
app_dir = os.path.join(app_path, '{0}.app'.format(PRODUCT_NAME))
electron = os.path.join(app_dir, 'Contents', 'MacOS', PRODUCT_NAME)
bin_out_path = os.path.join(app_dir, 'Contents', 'Frameworks',
'{0} Framework.framework'.format(PROJECT_NAME),
'Resources')
for bin_file in bin_files:
shutil.copy2(bin_file, bin_out_path)
elif sys.platform == 'win32':
electron = os.path.join(app_path, '{0}.exe'.format(PROJECT_NAME))
else:
electron = os.path.join(app_path, PROJECT_NAME)
subprocess.check_call([electron, test_path])
print('ok successfully used custom snapshot.')
except subprocess.CalledProcessError as e:
print('not ok an error was encountered while testing mksnapshot.')
print(e)
returncode = e.returncode
except KeyboardInterrupt:
print('Other error')
returncode = 0
print('Returning with error code: {0}'.format(returncode))
return returncode
# Create copy of app to install custom snapshot
def create_app_copy(initial_app_path):
print('Creating copy of app for testing')
app_path = os.path.join(os.path.dirname(initial_app_path),
os.path.basename(initial_app_path)
+ '-mksnapshot-test')
rm_rf(app_path)
shutil.copytree(initial_app_path, app_path, symlinks=True)
return app_path
def get_binary_path(binary_name, root_path):
if sys.platform == 'win32':
binary_path = os.path.join(root_path, '{0}.exe'.format(binary_name))
else:
binary_path = os.path.join(root_path, binary_name)
return binary_path
def parse_args():
parser = argparse.ArgumentParser(description='Test mksnapshot')
parser.add_argument('-b', '--build-dir',
help='Path to an Electron build folder. \
Relative to the --source-root.',
default=None,
required=True)
parser.add_argument('--create-snapshot-only',
help='Just create snapshot files, but do not run test',
action='store_true')
parser.add_argument('--snapshot-files-dir',
help='Directory containing snapshot files to use \
for testing',
default=None,
required=False)
parser.add_argument('--source-root',
default=SOURCE_ROOT,
required=False)
return parser.parse_args()
if __name__ == '__main__':
sys.exit(main())
|
electron/electron
|
script/verify-mksnapshot.py
|
Python
|
mit
| 4,821
|
//
// Copyright (c) 2008-2015 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "../Precompiled.h"
#include "../Resource/Localization.h"
#include "../Resource/ResourceCache.h"
#include "../Resource/JSONFile.h"
#include "../Resource/ResourceEvents.h"
#include "../IO/Log.h"
#include "../DebugNew.h"
namespace Atomic
{
Localization::Localization(Context* context) :
Object(context),
languageIndex_(-1)
{
}
Localization::~Localization()
{
}
int Localization::GetLanguageIndex(const String& language)
{
if (language.Empty())
{
LOGWARNING("Localization::GetLanguageIndex(language): language name is empty");
return -1;
}
if (GetNumLanguages() == 0)
{
LOGWARNING("Localization::GetLanguageIndex(language): no loaded languages");
return -1;
}
for (int i = 0; i < GetNumLanguages(); i++)
{
if (languages_[i] == language)
return i;
}
return -1;
}
String Localization::GetLanguage()
{
if (languageIndex_ == -1)
{
LOGWARNING("Localization::GetLanguage(): no loaded languages");
return String::EMPTY;
}
return languages_[languageIndex_];
}
String Localization::GetLanguage(int index)
{
if (GetNumLanguages() == 0)
{
LOGWARNING("Localization::GetLanguage(index): no loaded languages");
return String::EMPTY;
}
if (index < 0 || index >= GetNumLanguages())
{
LOGWARNING("Localization::GetLanguage(index): index out of range");
return String::EMPTY;
}
return languages_[index];
}
void Localization::SetLanguage(int index)
{
if (GetNumLanguages() == 0)
{
LOGWARNING("Localization::SetLanguage(index): no loaded languages");
return;
}
if (index < 0 || index >= GetNumLanguages())
{
LOGWARNING("Localization::SetLanguage(index): index out of range");
return;
}
if (index != languageIndex_)
{
languageIndex_ = index;
VariantMap& eventData = GetEventDataMap();
SendEvent(E_CHANGELANGUAGE, eventData);
}
}
void Localization::SetLanguage(const String& language)
{
if (language.Empty())
{
LOGWARNING("Localization::SetLanguage(language): language name is empty");
return;
}
if (GetNumLanguages() == 0)
{
LOGWARNING("Localization::SetLanguage(language): no loaded languages");
return;
}
int index = GetLanguageIndex(language);
if (index == -1)
{
LOGWARNING("Localization::SetLanguage(language): language not found");
return;
}
SetLanguage(index);
}
String Localization::Get(const String& id)
{
if (id.Empty())
return String::EMPTY;
if (GetNumLanguages() == 0)
{
LOGWARNING("Localization::Get(id): no loaded languages");
return id;
}
String result = strings_[StringHash(GetLanguage())][StringHash(id)];
if (result.Empty())
{
LOGWARNING("Localization::Get(\"" + id + "\") not found translation, language=\"" + GetLanguage() + "\"");
return id;
}
return result;
}
void Localization::Reset()
{
languages_.Clear();
languageIndex_ = -1;
strings_.Clear();
}
void Localization::LoadJSON(const JSONValue& source)
{
for (JSONObject::ConstIterator i = source.Begin(); i != source.End(); ++i)
{
String id = i->first_;
if (id.Empty())
{
LOGWARNING("Localization::LoadJSON(source): string ID is empty");
continue;
}
const JSONValue& langs = i->second_;
for (JSONObject::ConstIterator j = langs.Begin(); j != langs.End(); ++j)
{
const String& lang = j->first_;
if (lang.Empty())
{
LOGWARNING("Localization::LoadJSON(source): language name is empty, string ID=\"" + id + "\"");
continue;
}
const String& string = j->second_.GetString();
if (string.Empty())
{
LOGWARNING(
"Localization::LoadJSON(source): translation is empty, string ID=\"" + id + "\", language=\"" + lang + "\"");
continue;
}
if (strings_[StringHash(lang)][StringHash(id)] != String::EMPTY)
{
LOGWARNING(
"Localization::LoadJSON(source): override translation, string ID=\"" + id + "\", language=\"" + lang + "\"");
}
strings_[StringHash(lang)][StringHash(id)] = string;
if (!languages_.Contains(lang))
languages_.Push(lang);
if (languageIndex_ == -1)
languageIndex_ = 0;
}
}
}
void Localization::LoadJSONFile(const String& name)
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
JSONFile* jsonFile = cache->GetResource<JSONFile>(name);
if (jsonFile)
LoadJSON(jsonFile->GetRoot());
}
}
|
rsredsq/AtomicGameEngine
|
Source/Atomic/Resource/Localization.cpp
|
C++
|
mit
| 5,994
|
#include <a.hpp>
int main()
{
a_lib_func();
return 0;
}
|
crafn/clbs
|
tests/proxyproject/b/main.cpp
|
C++
|
mit
| 59
|
---
title: 'Znak Saveza'
date: 25/05/2021
---
**“Stoga neka Izraelci drže subotu — svetkujući je od naraštaja do naraštaja — kao vječni savez. Neka je ona znak, zauvijek, između mene i Izraelaca. Ta Jahve je za šest dana sazdao nebo i zemlju, a sedmoga je dana prestao raditi i odahnuo.” (Izlazak 31,16.17)**
Četiri puta u Svetom pismu subota je označena kao “znak” (Izlazak 31,13.17; Ezekiel 20,12.20). “Znak” nije “simbol” u smislu da nešto prikazuje, da upućuje na nešto ili da podsjeća na nešto zato što posjeduje slične osobine (na primjer šaka kao simbol često označava moć ili silu). U Bibliji je subota bila vanjski znak, predmet ili stanje čija je svrha bila da prenese prepoznatljivu poruku. U samom tom znaku nije bilo ničega što bi ga posebno vezivalo za Savez. Subota je bila znak Saveza “između mene i vas od naraštaja do naraštaja” (Izlazak 31,13) samo zato što je Bog tako rekao.
`Zašto bi Bog upotrijebio subotu kao znak Saveza? Po čemu je subota tako prikladan simbol spasonosnog odnosa s Bogom? S obzirom na to da je ključni aspekt Saveza spasenje milošću i da nas djela ne mogu spasiti, kako je subota dobar simbol tog odnosa? (Vidi Postanak 2,3; Hebrejima 4,1-4)`
U vezi sa subotom kao znakom Saveza milosti, zadivljuje činjenica da su Izraelci stoljećima shvaćali subotu kao znak mesijanskog otkupljenja. Oni su u suboti vidjeli sliku spasenja preko Mesije. S obzirom na to da mi spasenje razumijemo kao nešto što se dobiva samo na osnovi milosti koja je srž Saveza, povezanost između subote, otkupljenja i Saveza postaje jasna (vidi Ponovljeni zakon 5,13-15). Prema tome, subota je znak Božje spasonosne milosti, a ne znak spasenja djelima.
`Kako vi razumijete što znači subotnji “odmor”? Kako se vi odmarate u subotu? Što radite drugačije tog dana zbog čega on postaje “znak”? Bi li netko tko vas poznaje mogao na osnovi vašeg života zapaziti da je subota za vas poseban dan?`
|
imasaru/sabbath-school-lessons
|
src/hr/2021-02/09/04.md
|
Markdown
|
mit
| 1,984
|
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** @author John Miller, Khalid Jahangeer
* @version 1.3
* @date Thu Jan 17 13:12:42 EST 2013
* @see LICENSE (MIT style license file).
*
* @see http://web.mit.edu/be.400/www/SVD/Singular_Value_Decomposition.htm
* @see http://www.cs.utexas.edu/users/inderjit/public_papers/HLA_SVD.pdf
*/
// U N D E R D E V E L O P M E N T
package scalation.linalgebra
import scala.math.sqrt
import MatrixD.eye
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `SVD2` class performs Single Value Decomposition 'SVD' using the `Eigen`
* class. For a direct, more robust algorithm that is less sensitive to round-off errors,
* @see the `SVD` class.
* @param a the matrix to be factored/decomposed
*/
class SVD2 (a: MatrixD)
extends SVDecomp
{
private val DEBUG = true // debug flag
private val (m, n) = (a.dim1, a.dim2) // number of rows, columns in matrix a
private val s_vec = true // provide option for s to be a vector (true) or a matrix (false)
// private var s: VectorD = null // vector of singular values (main diagonal)
private var notflat = true // whether matrix a is already factored/deflated
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Factor matrix 'a' forming a diagonal matrix consisting of singular values
* and return the singular values in vector 's' along with left and right
* singular matrices, 'u' and 'v'.
*/
override def factor (): FactorType =
{
if (notflat) deflate () else (eye(m), a.getDiag (), eye(n)) // (u, s, v)
} // factor
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Deflate matrix 'a' and decompose it into 'u * s * v.t', where 'u's columns
* are the eigenvectors of 'a * a.t' and 'v's columns are the eigenvectors
* of 'a.t * a'.
*/
def deflate (): FactorType =
{
val aat = a * a.t // a times a transpose
if (DEBUG) println ("aat = " + aat)
val u_e = (new Eigenvalue (aat)).getE () // aat's eigenvalues
val u = (new Eigenvector (aat, u_e)).getV.normalizeU // u matrix
val ata = a.t * a // a transpose times a
if (DEBUG) println ("ata = " + ata)
val v_e = (new Eigenvalue (ata)).getE () // ata's eigenvalues
val v = (new Eigenvector (ata, v_e)).getV.normalizeU // v matrix
val s = if (m < n) VectorD (for (j <- 0 until m) yield sqrt (u_e(j)))
else VectorD (for (j <- 0 until n) yield sqrt (v_e(j)))
flip (u, s)
if (DEBUG) {
println ("u_e = " + u_e)
println ("u = " + u)
println ("v_e = " + v_e)
println ("v = " + v)
println ("s = " + s)
} // if
notflat = false
(u, s, v)
} // deflate
} // SVD2 class
import SVDecomp._
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `SVD2Test` object is used to test the `SVD2` class.
* @see www.ling.ohio-state.edu/~kbaker/pubs/Singular_Value_Decomposition_Tutorial.pdf
* > run-main scalation.linalgebra.SVD2Test
*/
object SVD2Test extends App
{
val (u2, s2, v2) = (new SVD2 (a1)).factor ()
test (a1, (u2, s2, v2), "SVD2Test")
} // SVD2Test object
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `SVD2Test2` object is used to test the `SVD2` class.
* @see www.ling.ohio-state.edu/~kbaker/pubs/Singular_Value_Decomposition_Tutorial.pdf
* > run-main scalation.linalgebra.SVD2Test2
*/
object SVD2Test2 extends App
{
val (u2, s2, v2) = (new SVD2 (a2)).factor ()
test (a2, (u2, s2, v2), "SVD2Test2")
} // SVD2Test2 object
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `SVD2Test3` object is used to test the `SVD2` class.
* > run-main scalation.linalgebra.SVD2Test3
*/
object SVD2Test3 extends App
{
val (u2, s2, v2) = (new SVD2 (a3)).factor ()
test (a3, (u2, s2, v2), "SVD2Test3")
} // SVD2Test3 object
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `SVD2Test4` object is used to test the `SVD2` class.
* > run-main scalation.linalgebra.SVD2Test4
*/
object SVD2Test4 extends App
{
val (u2, s2, v2) = (new SVD2 (a4)).factor ()
test (a4, (u2, s2, v2), "SVD2Test4")
} // SVD2Test4 object
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `SVD2Test5` object is used to test the `SVD2` class.
* > run-main scalation.linalgebra.SVD2Test5
*/
object SVD2Test5 extends App
{
val (u2, s2, v2) = (new SVD2 (a5)).factor ()
test (a5, (u2, s2, v2), "SVD2Test5")
} // SVD2Test5 object
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `SVD2Test6` object is used to test the `SVD2` class.
* > run-main scalation.linalgebra.SVD2Test6
*/
object SVD2Test6 extends App
{
val (u2, s2, v2) = (new SVD2 (a6)).factor ()
test (a6, (u2, s2, v2), "SVD2Test6")
} // SVD2Test6 object
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `SVD2Test7` object is used to test the `SVD2` class.
* > run-main scalation.linalgebra.SVD2Test7
*/
object SVD2Test7 extends App
{
val (u2, s2, v2) = (new SVD2 (a7)).factor ()
test (a7, (u2, s2, v2), "SVD2Test7")
} // SVD2Test7 object
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `SVD2Test8` object is used to test the `SVD2` class.
* > run-main scalation.linalgebra.SVD2Test8
*/
object SVD2Test8 extends App
{
val (u2, s2, v2) = (new SVD2 (a8)).factor ()
test (a8, (u2, s2, v2), "SVD2Test8")
} // SVD2Test8 object
|
scalation/fda
|
scalation_1.3/scalation_mathstat/src/main/scala/scalation/linalgebra/SVD2.scala
|
Scala
|
mit
| 6,042
|
// if97_xps stub - Interfaces CoolProp IF97 function to Mathcad
//
// this code executes the user function if97_xps(p,s), which is a wrapper for
// the CoolProp-IF97 function, Q_psmass(p,s).
LRESULT if97_XPS(
LPCOMPLEXSCALAR x, // pointer to the result
LPCCOMPLEXSCALAR p,
LPCCOMPLEXSCALAR s) // pointer to the parameter received from Mathcad
{
// first check to make sure "p" and "s" have no imaginary component
if ( p->imag != 0.0 )
return MAKELRESULT(MUST_BE_REAL,1);
if ( s->imag != 0.0 )
return MAKELRESULT(MUST_BE_REAL,2);
//otherwise, all is well, evaluate function
try {
x->real = IF97::Q_psmass(p->real,s->real);
}
catch (const std::out_of_range& e) {
if (e.what()[0] == 'P')
return MAKELRESULT(P_OUT_OF_RANGE,1);
else if ((e.what()[0] == 'E') && (e.what()[3] == 'r'))
return MAKELRESULT(S_OUT_OF_RANGE,2);
else
return MAKELRESULT(UNKNOWN,1);
}
// normal return
return 0;
}
FUNCTIONINFO if97_xps =
{
"if97_xps", // name by which Mathcad will recognize the function
"p,s", // if97_xps will be called as if97_xps(p,s)
// description of if97_xps(p,s)
"Obtains the steam quality, x, as a function of pressure, p [Pa], and mass entropy [J/kg-K].",
(LPCFUNCTION)if97_XPS, // pointer to executable code
COMPLEX_SCALAR, // the return type is a complex scalar
2, // there are two input parameters
{ COMPLEX_SCALAR, COMPLEX_SCALAR } // that are both complex scalars
};
|
CoolProp/IF97
|
wrapper/Mathcad/includes/xps.h
|
C
|
mit
| 1,670
|
require 'test_helper'
class ArticlesControllerTest < ActionController::TestCase
setup do
@article = articles(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:articles)
end
test "should get new" do
get :new
assert_response :success
end
test "should create article" do
assert_difference('Article.count') do
post :create, article: { body: @article.body }
end
assert_redirected_to article_path(assigns(:article))
end
test "should show article" do
get :show, id: @article
assert_response :success
end
test "should get edit" do
get :edit, id: @article
assert_response :success
end
test "should update article" do
put :update, id: @article, article: { body: @article.body }
assert_redirected_to article_path(assigns(:article))
end
test "should destroy article" do
assert_difference('Article.count', -1) do
delete :destroy, id: @article
end
assert_redirected_to articles_path
end
end
|
jeyavel-velankani/Jel_Apps
|
kaminari-bootstrap-demo/test/functional/articles_controller_test.rb
|
Ruby
|
mit
| 1,050
|
package trace
import (
"context"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stripe/veneur/ssf"
)
func benchmarkPlainCombination(backend ClientBackend, span *ssf.SSFSpan) func(*testing.B) {
ctx := context.TODO()
return func(b *testing.B) {
for i := 0; i < b.N; i++ {
assert.NoError(b, backend.SendSync(ctx, span))
}
}
}
func benchmarkFlushingCombination(backend FlushableClientBackend, span *ssf.SSFSpan, every time.Duration) func(*testing.B) {
return func(b *testing.B) {
ctx := context.TODO()
tick := time.NewTicker(every)
defer tick.Stop()
for i := 0; i < b.N; i++ {
select {
case <-tick.C:
assert.NoError(b, backend.FlushSync(ctx))
default:
assert.NoError(b, backend.SendSync(ctx, span))
}
}
assert.NoError(b, backend.FlushSync(ctx))
}
}
func serveUNIX(t testing.TB, laddr *net.UnixAddr, onconnect func(conn net.Conn)) (cleanup func() error) {
srv, err := net.ListenUnix(laddr.Network(), laddr)
require.NoError(t, err)
cleanup = srv.Close
go func() {
for {
in, err := srv.Accept()
if err != nil {
return
}
go onconnect(in)
}
}()
return
}
// BenchmarkSerialization tests how long the serialization of a span
// over each kind of network link can take: UNIX with no buffer, UNIX
// with a buffer, UDP (only unbuffered); combined with the kinds of
// spans we send: spans with metrics attached, spans with no metrics
// attached, and empty spans with only metrics.
//
// The counterpart is either a fresh UDP port with nothing reading
// packets, or a network reader that discards every byte read.
func BenchmarkSerialization(b *testing.B) {
dir, err := ioutil.TempDir("", "test_unix")
require.NoError(b, err)
defer os.RemoveAll(dir)
sockName := filepath.Join(dir, "sock")
laddr, err := net.ResolveUnixAddr("unix", sockName)
require.NoError(b, err)
cleanup := serveUNIX(b, laddr, func(conn net.Conn) {
io.Copy(ioutil.Discard, conn)
})
defer cleanup()
udpConn, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 0})
require.NoError(b, err)
defer udpConn.Close()
unixBackend := &streamBackend{
backendParams: backendParams{
addr: laddr,
},
}
flushyUnixBackend := &streamBackend{
backendParams: backendParams{
addr: laddr,
bufferSize: uint(BufferSize),
},
}
udpBackend := &packetBackend{
backendParams: backendParams{
addr: udpConn.LocalAddr(),
},
}
spanWithMetrics := &ssf.SSFSpan{
Name: "realistic_span",
Service: "hi-there-srv",
Id: 1,
ParentId: 2,
TraceId: 3,
Error: false,
Tags: map[string]string{
"span_purpose": "testing",
},
Metrics: []*ssf.SSFSample{
ssf.Count("oh.hai", 1, map[string]string{"purpose": "testing"}),
ssf.Histogram("hello.there", 1, map[string]string{"purpose": "testing"}, ssf.Unit("absolute")),
},
}
spanNoMetrics := &ssf.SSFSpan{
Name: "realistic_span",
Service: "hi-there-srv",
Id: 1,
ParentId: 2,
TraceId: 3,
Error: false,
Tags: map[string]string{
"span_purpose": "testing",
},
}
emptySpanWithMetrics := &ssf.SSFSpan{
Metrics: []*ssf.SSFSample{
ssf.Count("oh.hai", 1, map[string]string{"purpose": "testing"}),
ssf.Histogram("hello.there", 1, map[string]string{"purpose": "testing"}, ssf.Unit("lad")),
},
}
// Warm up things:
connect(context.TODO(), unixBackend)
_ = flushyUnixBackend.FlushSync(context.TODO())
connect(context.TODO(), udpBackend)
b.ResetTimer()
// Start benchmarking:
for _, every := range []int{10, 50, 100} {
b.Run(fmt.Sprintf("UNIX_flush_span_with_metrics_%dms", every),
benchmarkFlushingCombination(flushyUnixBackend, spanWithMetrics, time.Duration(every)*time.Millisecond))
b.Run(fmt.Sprintf("UNIX_flush_span_no_metrics_%dms", every),
benchmarkFlushingCombination(flushyUnixBackend, spanNoMetrics, time.Duration(every)*time.Millisecond))
b.Run(fmt.Sprintf("UNIX_flush_empty_span_with_metrics_%dms", every),
benchmarkFlushingCombination(flushyUnixBackend, emptySpanWithMetrics, time.Duration(every)*time.Millisecond))
}
b.Run("UNIX_plain_span_with_metrics", benchmarkPlainCombination(unixBackend, spanWithMetrics))
b.Run("UNIX_plain_span_no_metrics", benchmarkPlainCombination(unixBackend, spanNoMetrics))
b.Run("UNIX_plain_empty_span_with_metrics", benchmarkPlainCombination(unixBackend, emptySpanWithMetrics))
b.Run("UDP_plain_span_with_metrics", benchmarkPlainCombination(udpBackend, spanWithMetrics))
b.Run("UDP_plain_span_no_metrics", benchmarkPlainCombination(udpBackend, spanNoMetrics))
b.Run("UDP_plain_empty_span_with_metrics", benchmarkPlainCombination(udpBackend, emptySpanWithMetrics))
}
|
gphat/veneur
|
trace/backend_test.go
|
GO
|
mit
| 4,756
|
#ifndef UTIL_TOKEN_H
#define UTIL_TOKEN_H
#include <stdbool.h>
#define TOKEN_STRLEN 33
bool generate_token(char out[static TOKEN_STRLEN]);
#endif
|
swaywm/wlroots
|
include/util/token.h
|
C
|
mit
| 149
|
#!/bin/sh
./ss.sh &
sleep 10
python gipt.py config.json
|
lehui99/gipt
|
gipt.sh
|
Shell
|
mit
| 56
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using NSAPConnector.CustomExceptions;
namespace NSAPConnector.Utils
{
/// <summary>
/// This class is used for extracting
/// SAP destination configuration from the
/// application configuration file.
/// This class is was designed only for the internal use.
/// </summary>
internal class ConfigParser
{
/// <summary>
/// Name of the current application configuration file.
/// </summary>
private static readonly string _configFile;
static ConfigParser()
{
//get current app/web config file
_configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
}
/// <summary>
/// Parses current application config file
/// and searches for the sap configuration sections.
/// </summary>
/// <param name="destinationName">If this parameter is provided then a destination configuration with the same name will be searched,
/// otherwise first destionation configuration section will be returned.</param>
/// <returns>All the parameters specified for the found destination.</returns>
internal static Dictionary<string, string> GetDestinationParameters(string destinationName = null)
{
var destParams = new Dictionary<string, string>();
IEnumerable<XElement> resultElements;
XElement xDoc;
try
{
//open cofiguration file
xDoc = XElement.Load(_configFile);
}
catch (Exception ex)
{
throw new NSAPConnectorException(string.Format("An error occurred when trying to open/read application configuration file '{0}'",_configFile), ex);
}
//if no name was provided then take data from first destination configuration section
if (string.IsNullOrEmpty(destinationName))
{
resultElements =
xDoc.XPathSelectElements("/SAP.Middleware.Connector/ClientSettings/DestinationConfiguration/destinations/add");
if (!resultElements.Any())
{
throw new NSAPConnectorException("There is no destination configuration in the config file.");
}
}
else
{
resultElements =
xDoc.XPathSelectElements(string.Format("/SAP.Middleware.Connector/ClientSettings/DestinationConfiguration/destinations/add[@NAME='{0}']", destinationName));
if (!resultElements.Any())
{
throw new NSAPConnectorException(string.Format("There is no destination configuration with the name '{0}' in the config file.",destinationName));
}
}
foreach (var attr in resultElements.First().Attributes())
{
destParams[attr.Name.LocalName] = attr.Value;
}
return destParams;
}
}
}
|
ion-sapoval/NSAPConnector
|
NSAPConnector.Core/Utils/ConfigParser.cs
|
C#
|
mit
| 3,147
|
<?php
Library::import('recess.database.sql.SqlBuilder');
Library::import('recess.database.sql.ISqlSelectOptions');
Library::import('recess.database.sql.ISqlConditions');
/**
* PdoDataSet is used as a proxy to query results that is realized once the results are
* iterated over or accessed using array notation. Queries can thus be built incrementally
* and an SQL request will only be issued once needed.
*
* Example usage:
*
* $results = new PdoDataSet(Databases::getDefault());
* $results->from('tableName')->equal('someColumn', 'Hi')->limit(10)->offset(50);
* foreach($results as $result) { // This is when the query is run!
* print_r($result);
* }
*
* @author Kris Jordan <krisjordan@gmail.com>
* @copyright 2008, 2009 Kris Jordan
* @package Recess PHP Framework
* @license MIT
* @link http://www.recessframework.org/
*/
class PdoDataSet implements Iterator, Countable, ArrayAccess, ISqlSelectOptions, ISqlConditions {
/**
* The SqlBuilder instance we use to build up the query string.
*
* @var SqlBuilder
*/
protected $sqlBuilder;
/**
* Whether this instance has fetched results or not.
*
* @var boolean
*/
protected $hasResults = false;
/**
* Array of results that is filled once a query is realized.
*
* @var array of type $this->rowClass
*/
protected $results = array();
/**
* The PdoDataSource which this PdoDataSet is extracted from.
*
* @var PdoDataSource
*/
protected $source;
/**
* The Class which PDO will fetch rows into.
*
* @var string Classname
*/
public $rowClass = 'stdClass';
/**
* Index counter for our location in the result set.
*
* @var integer
*/
protected $index = 0;
/**
* @param PdoDataSource $source
*/
public function __construct(PdoDataSource $source) {
$this->sqlBuilder = new SqlBuilder();
$this->source = $source;
}
public function __clone() {
$this->sqlBuilder = clone $this->sqlBuilder;
$this->hasResults = false;
$this->results = array();
$this->index = 0;
}
protected function reset() {
$this->hasResults = false;
$this->index = 0;
}
/**
* Once results are needed this method executes the accumulated query
* on the data source.
*/
protected function realize() {
if(!$this->hasResults) {
unset($this->results);
$this->results = $this->source->queryForClass($this->sqlBuilder, $this->rowClass);
$this->hasResults = true;
}
}
/**
* Return the SQL representation of this PdoDataSet
*
* @return string
*/
public function toSql() {
return $this->sqlBuilder->select();
}
/**
* Return the results as an array.
*
* @return array of type $this->rowClass
*/
public function toArray() {
$this->realize();
return $this->results;
}
public function count() {
return iterator_count($this);
}
/*
* The following methods are in accordance with the Iterator interface
*/
public function rewind() {
if(!$this->hasResults) {$this->realize();}
$this->index = 0;
}
public function current() {
if(!$this->hasResults) {$this->realize();}
return $this->results[$this->index];
}
public function key() {
if(!$this->hasResults) {$this->realize();}
return $this->index;
}
public function next() {
if(!$this->hasResults) {$this->realize();}
$this->index++;
}
public function valid() {
if(!$this->hasResults) {$this->realize();}
return isset($this->results[$this->index]);
}
/*
* The following methods are in accordance with the ArrayAccess interface
*/
function offsetExists($index) {
if(!$this->hasResults) {$this->realize();}
return isset($this->results[$index]);
}
function offsetGet($index) {
if(!$this->hasResults) {$this->realize();}
if(isset($this->results[$index])) {
return $this->results[$index];
} else {
throw new OutOfBoundsException();
}
}
function offsetSet($index, $value) {
if(!$this->hasResults) {$this->realize();}
$this->results[$index] = $value;
}
function offsetUnset($index) {
if(!$this->hasResults) {$this->realize();}
if(isset($this->results[$index])) {
unset($this->results[$index]);
}
}
function isEmpty() {
return !(isset($this[0]) && $this[0] != null);
// return !isset($this[0]);
}
/**
* Return the first item in the PdoDataSet or Null if none exist
*
* @return object or false
*/
function first() {
if(!$this->hasResults) {
$results = $this->range(0,1);
if(!$results->isEmpty()) {
return $results[0];
}
} else {
if(!$this->isEmpty()) {
return $this[0];
}
}
return false;
}
/**
* @see SqlBuilder::assign
* @return PdoDataSet
*/
function assign($column, $value) { $copy = clone $this; $copy->sqlBuilder->assign($column, $value); return $copy; }
/**
* @see SqlBuilder::useAssignmentsAsConditions
* @return PdoDataSet
*/
function useAssignmentsAsConditions($bool) { $copy = clone $this; $copy->sqlBuilder->useAssignmentsAsConditions($bool); return $copy; }
/**
* @see SqlBuilder::from
* @return PdoDataSet
*/
function from($table) { $copy = clone $this; $copy->sqlBuilder->from($table); return $copy; }
/**
* @see SqlBuilder::leftOuterJoin
* @return PdoDataSet
*/
function leftOuterJoin($table, $tablePrimaryKey, $fromTableForeignKey) { $copy = clone $this; $copy->sqlBuilder->leftOuterJoin($table, $tablePrimaryKey, $fromTableForeignKey); return $copy; }
/**
* @see SqlBuilder::innerJoin
* @return PdoDataSet
*/
function innerJoin($table, $tablePrimaryKey, $fromTableForeignKey) { $copy = clone $this; $copy->sqlBuilder->innerJoin($table, $tablePrimaryKey, $fromTableForeignKey); return $copy; }
/**
* @see SqlBuilder::selectAs
* @return PdoDataSet
*/
function selectAs($select, $as) { $copy = clone $this; $copy->sqlBuilder->selectAs($select, $as); return $copy; }
/**
* @see SqlBuilder::distinct
* @return PdoDataSet
*/
function distinct() { $copy = clone $this; $copy->sqlBuilder->distinct(); return $copy; }
/**
* @see SqlBuilder::equal
* @return PdoDataSet
*/
function equal($lhs, $rhs){ $copy = clone $this; $copy->sqlBuilder->equal($lhs,$rhs); return $copy; }
/**
* @see SqlBuilder::notEqual
* @return PdoDataSet
*/
function notEqual($lhs, $rhs) { $copy = clone $this; $copy->sqlBuilder->notEqual($lhs,$rhs); return $copy; }
/**
* @see SqlBuilder::between
* @return PdoDataSet
*/
function between ($column, $lhs, $rhs) { $copy = clone $this; $copy->sqlBuilder->between($column, $lhs, $rhs); return $copy; }
/**
* @see SqlBuilder::greaterThan
* @return PdoDataSet
*/
function greaterThan($lhs, $rhs) { $copy = clone $this; $copy->sqlBuilder->greaterThan($lhs,$rhs); return $copy; }
/**
* @see SqlBuilder::greaterThanOrEqualTo
* @return PdoDataSet
*/
function greaterThanOrEqualTo($lhs, $rhs) { $copy = clone $this; $copy->sqlBuilder->greaterThanOrEqualTo($lhs,$rhs); return $copy; }
/**
* @see SqlBuilder::lessThan
* @return PdoDataSet
*/
function lessThan($lhs, $rhs) { $copy = clone $this; $copy->sqlBuilder->lessThan($lhs,$rhs); return $copy; }
/**
* @see SqlBuilder::lessThanOrEqualTo
* @return PdoDataSet
*/
function lessThanOrEqualTo($lhs, $rhs) { $copy = clone $this; $copy->sqlBuilder->lessThanOrEqualTo($lhs,$rhs); return $copy; }
/**
* @see SqlBuilder::like
* @return PdoDataSet
*/
function like($lhs, $rhs) { $copy = clone $this; $copy->sqlBuilder->like($lhs,$rhs); return $copy; }
/**
* @see SqlBuilder::like
* @return PdoDataSet
*/
function notLike($lhs, $rhs) { $copy = clone $this; $copy->sqlBuilder->notLike($lhs,$rhs); return $copy; }
/**
* @see SqlBuilder::isNull
* @return PdoDataSet
*/
function isNull($lhs) { $copy = clone $this; $copy->sqlBuilder->isNull($lhs); return $copy; }
/**
* @see SqlBuilder::like
* @return PdoDataSet
*/
function isNotNull($lhs) { $copy = clone $this; $copy->sqlBuilder->isNotNull($lhs); return $copy; }
/**
* @see SqlBuilder::where
* @return PdoDataSet
*/
function where($lhs, $rhs, $operator) { $copy = clone $this; $copy->sqlBuilder->where($lhs,$rhs,$operator); return $copy; }
/**
* @see SqlBuilder::limit
* @return PdoDataSet
*/
function limit($size) { $copy = clone $this; $copy->sqlBuilder->limit($size); return $copy; }
/**
* @see SqlBuilder::offset
* @return PdoDataSet
*/
function offset($offset) { $copy = clone $this; $copy->sqlBuilder->offset($offset); return $copy; }
/**
* @see SqlBuilder::range
* @return PdoDataSet
*/
function range($start, $finish) { $copy = clone $this; $copy->sqlBuilder->range($start,$finish); return $copy; }
/**
* @see SqlBuilder::orderBy
* @return PdoDataSet
*/
function orderBy($clause) { $copy = clone $this; $copy->sqlBuilder->orderBy($clause); return $copy; }
}
?>
|
aabhushan/RESTful-TTS
|
recess/recess/database/pdo/PdoDataSet.class.php
|
PHP
|
mit
| 9,120
|
var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')(); // Load all gulp plugins
// automatically and attach
// them to the `plugins` object
var runSequence = require('run-sequence'); // Temporary solution until gulp 4
// https://github.com/gulpjs/gulp/issues/355
var pkg = require('./package.json');
var dirs = pkg['h5bp-configs'].directories;
// ---------------------------------------------------------------------
// | Helper tasks |
// ---------------------------------------------------------------------
gulp.task('archive:create_archive_dir', function () {
fs.mkdirSync(path.resolve(dirs.archive), '0755');
});
gulp.task('archive:zip', function (done) {
var archiveName = path.resolve(dirs.archive, pkg.name + '_v' + pkg.version + '.zip');
var archiver = require('archiver')('zip');
var files = require('glob').sync('**/*.*', {
'cwd': dirs.dist,
'dot': true // include hidden files
});
var output = fs.createWriteStream(archiveName);
archiver.on('error', function (error) {
done();
throw error;
});
output.on('close', done);
files.forEach(function (file) {
var filePath = path.resolve(dirs.dist, file);
// `archiver.bulk` does not maintain the file
// permissions, so we need to add files individually
archiver.append(fs.createReadStream(filePath), {
'name': file,
'mode': fs.statSync(filePath)
});
});
archiver.pipe(output);
archiver.finalize();
});
gulp.task('clean', function (done) {
require('del')([
dirs.archive,
dirs.dist
], done);
});
gulp.task('copy', [
'copy:.htaccess',
'copy:index.html',
'copy:jquery',
'copy:license',
'copy:main.css',
'copy:misc',
'copy:normalize'
]);
gulp.task('copy:.htaccess', function () {
return gulp.src('node_modules/apache-server-configs/dist/.htaccess')
.pipe(plugins.replace(/# ErrorDocument/g, 'ErrorDocument'))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:index.html', function () {
return gulp.src(dirs.src + '/index.html')
.pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:jquery', function () {
return gulp.src(['node_modules/jquery/dist/jquery.min.js'])
.pipe(plugins.rename('jquery-' + pkg.devDependencies.jquery + '.min.js'))
.pipe(gulp.dest(dirs.dist + '/js/vendor'));
});
gulp.task('copy:license', function () {
return gulp.src('LICENSE.txt')
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:main.css', function () {
var banner = '/*! HTML5 Boilerplate v' + pkg.version +
' | ' + pkg.license.type + ' License' +
' | ' + pkg.homepage + ' */\n\n';
return gulp.src(dirs.src + '/css/main.css')
.pipe(plugins.header(banner))
.pipe(plugins.autoprefixer({
browsers: ['last 2 versions', 'ie >= 8', '> 1%'],
cascade: false
}))
.pipe(gulp.dest(dirs.dist + '/css'));
});
gulp.task('copy:misc', function () {
return gulp.src([
// Copy all files
dirs.src + '/**/*',
// Exclude the following files
// (other tasks will handle the copying of these files)
'!' + dirs.src + '/css/main.css',
'!' + dirs.src + '/index.html'
], {
// Include hidden files by default
dot: true
}).pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:normalize', function () {
return gulp.src('node_modules/normalize.css/normalize.css')
.pipe(gulp.dest(dirs.dist + '/css'));
});
gulp.task('lint:js', function () {
return gulp.src([
'gulpfile.js',
dirs.src + '/js/*.js',
dirs.test + '/*.js'
]).pipe(plugins.jscs())
.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter('jshint-stylish'))
.pipe(plugins.jshint.reporter('fail'));
});
// ---------------------------------------------------------------------
// | Main tasks |
// ---------------------------------------------------------------------
gulp.task('archive', function (done) {
runSequence(
'build',
'archive:create_archive_dir',
'archive:zip',
done);
});
gulp.task('build', function (done) {
runSequence(
['clean', 'lint:js'],
'copy',
done);
});
gulp.task('default', ['build']);
gulp.task('autoprefixer', function () {
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
return gulp.src('./src/css/*.css')
.pipe(postcss([ autoprefixer({ browsers: ['last 2 versions'] }) ]))
.pipe(gulp.dest('./dest'));
});
|
ardentum/tumbleweed
|
gulpfile.js
|
JavaScript
|
mit
| 5,147
|
class AddEnableStudentTestsToAssignments < ActiveRecord::Migration[4.2]
def change
add_column :assignments, :enable_student_tests, :boolean, null: false, default: false
end
end
|
MarkUsProject/Markus
|
db/migrate/20160902214959_add_enable_student_tests_to_assignments.rb
|
Ruby
|
mit
| 185
|
<?php
namespace Chamilo\Core\User\Table\Admin;
use Chamilo\Core\User\Storage\DataClass\User;
use Chamilo\Core\User\Storage\DataManager;
use Chamilo\Libraries\Format\Table\Extension\DataClassTable\DataClassTableDataProvider;
use Chamilo\Libraries\Storage\Parameters\DataClassCountParameters;
use Chamilo\Libraries\Storage\Parameters\DataClassRetrievesParameters;
/**
*
* @package user.lib.user_manager.component.admin_user_browser
*/
/**
* Data provider for a user browser table.
* This class implements some functions to allow user browser tables to retrieve
* information about the users to display.
*/
class AdminUserTableDataProvider extends DataClassTableDataProvider
{
/**
* Gets the users
*
* @param $user String
* @param $category String
* @param $offset int
* @param $count int
* @param $order_property string
* @return ResultSet A set of matching learning objects.
*/
public function retrieve_data($condition, $offset, $count, $order_property = null)
{
return DataManager::retrieves(
User::class_name(),
new DataClassRetrievesParameters($condition, $count, $offset, $order_property));
}
/**
* Gets the number of users in the table
*
* @return int
*/
public function count_data($condition)
{
return DataManager::count(User::class_name(), new DataClassCountParameters($condition));
}
}
|
forelo/cosnics
|
src/Chamilo/Core/User/Table/Admin/AdminUserTableDataProvider.php
|
PHP
|
mit
| 1,441
|
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace Tests.Execution.ProvidedPorts.Methods
{
using Shouldly;
using Utilities;
internal class X1 : TestComponent
{
private int M(int i)
{
return i * 2;
}
protected override void Check()
{
M(2).ShouldBe(4);
M(10).ShouldBe(20);
}
}
}
|
maul-esel/ssharp
|
SafetySharpTests/Execution/ProvidedPorts/Methods/non-inherited.cs
|
C#
|
mit
| 1,447
|
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Adxstudio.Xrm.Web.Mvc;
using Microsoft.Xrm.Sdk;
namespace Adxstudio.Xrm.Cms
{
internal class WebLinkSet : IWebLinkSet
{
public WebLinkSet(Entity entity, IPortalViewEntity viewEntity, IEnumerable<IWebLink> webLinks)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
if (viewEntity == null)
{
throw new ArgumentNullException("viewEntity");
}
if (webLinks == null)
{
throw new ArgumentNullException("webLinks");
}
Entity = entity;
ViewEntity = viewEntity;
WebLinks = webLinks.ToArray();
Copy = viewEntity.GetAttribute("adx_copy");
Name = entity.GetAttributeValue<string>("adx_name");
Title = viewEntity.GetAttribute("adx_title");
DisplayName = entity.GetAttributeValue<string>("adx_display_name");
}
/// <summary>
/// Gets the DisplayName attribute of the entity record
/// </summary>
public string DisplayName { get; private set; }
public string Description
{
get { return Name; }
}
public bool Editable
{
get { return ViewEntity.Editable; }
}
public EntityReference EntityReference
{
get { return ViewEntity.EntityReference; }
}
public IPortalViewAttribute Copy { get; private set; }
public Entity Entity { get; private set; }
public string Name { get; private set; }
public IPortalViewAttribute Title { get; private set; }
public string Url
{
get { return null; }
}
public IEnumerable<IWebLink> WebLinks { get; private set; }
protected IPortalViewEntity ViewEntity { get; private set; }
public IPortalViewAttribute GetAttribute(string attributeLogicalName)
{
return ViewEntity.GetAttribute(attributeLogicalName);
}
}
}
|
Adoxio/xRM-Portals-Community-Edition
|
Framework/Adxstudio.Xrm/Cms/WebLinkSet.cs
|
C#
|
mit
| 1,927
|
package collectors
import (
"bytes"
"encoding/base64"
"encoding/gob"
"fmt"
"net/http"
"strconv"
"time"
analytics "google.golang.org/api/analytics/v3"
"bosun.org/cmd/scollector/conf"
"bosun.org/metadata"
"bosun.org/opentsdb"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
const descActiveUsers = "Number of unique users actively visiting the site."
type multiError []error
func (m multiError) Error() string {
var fullErr string
for _, err := range m {
fullErr = fmt.Sprintf("%s\n%s", fullErr, err)
}
return fullErr
}
func init() {
registerInit(func(c *conf.Conf) {
for _, g := range c.GoogleAnalytics {
collectors = append(collectors, &IntervalCollector{
F: func() (opentsdb.MultiDataPoint, error) {
return c_google_analytics(g.ClientID, g.Secret, g.Token, g.Sites)
},
name: "c_google_analytics",
Interval: time.Minute * 1,
})
}
})
}
func c_google_analytics(clientid string, secret string, tokenstr string, sites []conf.GoogleAnalyticsSite) (opentsdb.MultiDataPoint, error) {
var md opentsdb.MultiDataPoint
var mErr multiError
c, err := analyticsClient(clientid, secret, tokenstr)
if err != nil {
return nil, err
}
svc, err := analytics.New(c)
if err != nil {
return nil, err
}
dimensions := []string{"browser", "trafficType", "deviceCategory", "operatingSystem"}
for _, site := range sites {
getPageviews(&md, svc, site)
if site.Detailed {
if err = getActiveUsers(&md, svc, site); err != nil {
mErr = append(mErr, err)
}
for _, dimension := range dimensions {
if err = getActiveUsersByDimension(&md, svc, site, dimension); err != nil {
mErr = append(mErr, err)
}
}
}
}
if len(mErr) == 0 {
return md, nil
} else {
return md, mErr
}
}
func getActiveUsersByDimension(md *opentsdb.MultiDataPoint, svc *analytics.Service, site conf.GoogleAnalyticsSite, dimension string) error {
call := svc.Data.Realtime.Get("ga:"+site.Profile, "rt:activeusers").Dimensions("rt:" + dimension)
data, err := call.Do()
if err != nil {
return err
}
tags := opentsdb.TagSet{"site": site.Name}
for _, row := range data.Rows {
// key will always be an string of the dimension we care about.
// For example, 'Chrome' would be a key for the 'browser' dimension.
key, _ := opentsdb.Clean(row[0])
if key == "" {
key = "__blank__"
}
value, err := strconv.Atoi(row[1])
if err != nil {
return fmt.Errorf("Error parsing GA data: %s", err)
}
Add(md, "google.analytics.realtime.activeusers.by_"+dimension, value, opentsdb.TagSet{dimension: key}.Merge(tags), metadata.Gauge, metadata.ActiveUsers, descActiveUsers)
}
return nil
}
func getActiveUsers(md *opentsdb.MultiDataPoint, svc *analytics.Service, site conf.GoogleAnalyticsSite) error {
call := svc.Data.Realtime.Get("ga:"+site.Profile, "rt:activeusers")
data, err := call.Do()
if err != nil {
return err
}
tags := opentsdb.TagSet{"site": site.Name}
value, err := strconv.Atoi(data.Rows[0][0])
if err != nil {
return fmt.Errorf("Error parsing GA data: %s", err)
}
Add(md, "google.analytics.realtime.activeusers", value, tags, metadata.Gauge, metadata.ActiveUsers, descActiveUsers)
return nil
}
func getPageviews(md *opentsdb.MultiDataPoint, svc *analytics.Service, site conf.GoogleAnalyticsSite) error {
call := svc.Data.Realtime.Get("ga:"+site.Profile, "rt:pageviews").Dimensions("rt:minutesAgo")
data, err := call.Do()
if err != nil {
return err
}
// If no offset was specified, the minute we care about is '1', or the most
// recently gathered, completed datapoint. Minute '0' is the current minute,
// and as such is incomplete.
offset := site.Offset
if offset == 0 {
offset = 1
}
time := time.Now().Add(time.Duration(-1*offset) * time.Minute).Unix()
pageviews := 0
// Iterates through the response data and returns the time slice we
// actually care about when we find it.
for _, row := range data.Rows {
// row == [2]string{"0", "123"}
// First item is the minute, second is the data (pageviews in this case)
minute, err := strconv.Atoi(row[0])
if err != nil {
return fmt.Errorf("Error parsing GA data: %s", err)
}
if minute == offset {
if pageviews, err = strconv.Atoi(row[1]); err != nil {
return fmt.Errorf("Error parsing GA data: %s", err)
}
break
}
}
AddTS(md, "google.analytics.realtime.pageviews", time, pageviews, opentsdb.TagSet{"site": site.Name}, metadata.Gauge, metadata.Count, "Number of pageviews tracked by GA in one minute")
return nil
}
// analyticsClient() takes in a clientid, secret, and a base64'd gob representing the cached oauth token.
// Generating the token is left as an exercise to the reader. (TODO)
func analyticsClient(clientid string, secret string, tokenstr string) (*http.Client, error) {
ctx := context.Background()
config := &oauth2.Config{
ClientID: clientid,
ClientSecret: secret,
Endpoint: google.Endpoint,
Scopes: []string{analytics.AnalyticsScope},
}
token := new(oauth2.Token)
// Decode the base64'd gob
by, err := base64.StdEncoding.DecodeString(tokenstr)
if err != nil {
return nil, err
}
b := bytes.Buffer{}
b.Write(by)
d := gob.NewDecoder(&b)
err = d.Decode(&token)
return config.Client(ctx, token), nil
}
|
CheRuisiBesares/bosun
|
cmd/scollector/collectors/google_analytics.go
|
GO
|
mit
| 5,280
|
/// <reference path="../../definitions/vsts-task-lib.d.ts" />
import path = require('path');
import os = require('os');
import tl = require('vsts-task-lib/task');
function getCommonLocalPath(files: string[]): string {
if (!files || files.length === 0) {
return "";
}
else if (files.length === 1) {
return path.dirname(files[0]);
}
else {
var root: string = files[0];
for (var index = 1; index < files.length; index++) {
root = _getCommonLocalPath(root, files[index]);
if (!root) {
break;
}
}
return root;
}
}
function _getCommonLocalPath(path1: string, path2: string): string {
var path1Depth = getFolderDepth(path1);
var path2Depth = getFolderDepth(path2);
var shortPath: string;
var longPath: string;
if (path1Depth >= path2Depth) {
shortPath = path2;
longPath = path1;
}
else {
shortPath = path1;
longPath = path2;
}
while (!isSubItem(longPath, shortPath)) {
var parentPath = path.dirname(shortPath);
if (path.normalize(parentPath) === path.normalize(shortPath)) {
break;
}
shortPath = parentPath;
}
return shortPath;
}
function isSubItem(item: string, parent: string): boolean {
item = path.normalize(item);
parent = path.normalize(parent);
return item.substring(0, parent.length) == parent
&& (item.length == parent.length || (parent.length > 0 && parent[parent.length - 1] === path.sep) || (item[parent.length] === path.sep));
}
function getFolderDepth(fullPath: string): number {
if (!fullPath) {
return 0;
}
var current = path.normalize(fullPath);
var parentPath = path.dirname(current);
var count = 0;
while (parentPath !== current) {
++count;
current = parentPath;
parentPath = path.dirname(current);
}
return count;
}
tl.setResourcePath(path.join( __dirname, 'task.json'));
// contents is a multiline input containing glob patterns
var contents: string[] = tl.getDelimitedInput('Contents', '\n', true);
var sourceFolder: string = tl.getPathInput('SourceFolder', true, true);
var targetFolder: string = tl.getPathInput('TargetFolder', true);
var cleanTargetFolder: boolean = tl.getBoolInput('CleanTargetFolder', false);
var overWrite: boolean = tl.getBoolInput('OverWrite', false);
// not use common root for now.
//var useCommonRoot: boolean = tl.getBoolInput('UseCommonRoot', false);
var useCommonRoot: boolean = false;
// include filter
var includeContents: string[] = [];
// exclude filter
var excludeContents: string[] = [];
for (var i: number = 0; i < contents.length; i++){
var pattern = contents[i].trim();
var negate: Boolean = false;
var negateOffset: number = 0;
for (var j = 0; j < pattern.length && pattern[j] === '!'; j++){
negate = !negate;
negateOffset++;
}
if(negate){
tl.debug('exclude content pattern: ' + pattern);
var realPattern = pattern.substring(0, negateOffset) + path.join(sourceFolder, pattern.substring(negateOffset));
excludeContents.push(realPattern);
}
else{
tl.debug('include content pattern: ' + pattern);
var realPattern = path.join(sourceFolder, pattern);
includeContents.push(realPattern);
}
}
// enumerate all files
var files: string[] = [];
var allPaths: string[] = tl.find(sourceFolder, { followSymbolicLinks: true } as tl.FindOptions);
var allFiles: string[] = [];
// remove folder path
for (var i: number = 0; i < allPaths.length; i++) {
if (!tl.stats(allPaths[i]).isDirectory()) {
allFiles.push(allPaths[i]);
}
}
// if we only have exclude filters, we need add a include all filter, so we can have something to exclude.
if(includeContents.length == 0 && excludeContents.length > 0) {
includeContents.push('**');
}
if (includeContents.length > 0 && allFiles.length > 0) {
tl.debug("allFiles contains " + allFiles.length + " files");
// a map to eliminate duplicates
var map = {};
// minimatch options
var matchOptions = { matchBase: true };
if(os.type().match(/^Win/))
{
matchOptions["nocase"] = true;
}
// apply include filter
for (var i: number = 0; i < includeContents.length; i++) {
var pattern = includeContents[i];
tl.debug('Include matching ' + pattern);
// let minimatch do the actual filtering
var matches: string[] = tl.match(allFiles, pattern, matchOptions);
tl.debug('Include matched ' + matches.length + ' files');
for (var j: number = 0; j < matches.length; j++) {
var matchPath = matches[j];
if (!map.hasOwnProperty(matchPath)) {
map[matchPath] = true;
files.push(matchPath);
}
}
}
// apply exclude filter
for (var i: number = 0; i < excludeContents.length; i++) {
var pattern = excludeContents[i];
tl.debug('Exclude matching ' + pattern);
// let minimatch do the actual filtering
var matches: string[] = tl.match(files, pattern, matchOptions);
tl.debug('Exclude matched ' + matches.length + ' files');
files = [];
for (var j: number = 0; j < matches.length; j++) {
var matchPath = matches[j];
files.push(matchPath);
}
}
}
else {
tl.debug("Either includeContents or allFiles is empty");
}
// copy the files to the target folder
console.log(tl.loc('FoundNFiles', files.length));
if (files.length > 0) {
// dump all files to debug trace.
files.forEach((file: string) => {
tl.debug('file:' + file + ' will be copied.');
})
// clean target folder if required
if (cleanTargetFolder) {
console.log(tl.loc('CleaningTargetFolder', targetFolder));
tl.rmRF(targetFolder);
}
// make sure the target folder exists
tl.mkdirP(targetFolder);
var commonRoot: string = "";
if (useCommonRoot) {
var computeCommonRoot = getCommonLocalPath(files);
if (!!computeCommonRoot) {
commonRoot = computeCommonRoot;
}
else {
commonRoot = sourceFolder;
}
tl.debug("There is a common root (" + commonRoot + ") for the files. Using the remaining path elements in target folder.");
}
try {
var createdFolders = {};
files.forEach((file: string) => {
var relativePath = file.substring(sourceFolder.length)
.replace(/^\\/g, "")
.replace(/^\//g, "");
if (useCommonRoot) {
relativePath = file.substring(commonRoot.length)
.replace(/^\\/g, "")
.replace(/^\//g, "");
}
var targetPath = path.join(targetFolder, relativePath);
var targetDir = path.dirname(targetPath);
if (!createdFolders[targetDir]) {
tl.debug("Creating folder " + targetDir);
tl.mkdirP(targetDir);
createdFolders[targetDir] = true;
}
if (tl.exist(targetPath) && tl.stats(targetPath).isFile() && !overWrite) {
console.log(tl.loc('FileAlreadyExistAt', file, targetPath));
}
else {
console.log(tl.loc('CopyingTo', file, targetPath));
tl.cp(file, targetPath, "-f");
}
});
}
catch (err) {
tl.setResult(tl.TaskResult.Failed, err);
}
}
|
AArnott/vso-agent-tasks
|
Tasks/CopyFiles/copyfiles.ts
|
TypeScript
|
mit
| 7,711
|
<?php
namespace TransformCore\PHE\LocalHealthAuthorityBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class TransformCorePHELocalHealthAuthorityBundle extends Bundle
{
}
|
TransformCore/HayPersistenceApi
|
src/TransformCore/PHE/LocalHealthAuthorityBundle/TransformCorePHELocalHealthAuthorityBundle.php
|
PHP
|
mit
| 181
|
/*
* Usage:
*
* <div class="sk-spinner sk-spinner-cube-grid">
* <div class="sk-cube"></div>
* <div class="sk-cube"></div>
* <div class="sk-cube"></div>
* <div class="sk-cube"></div>
* <div class="sk-cube"></div>
* <div class="sk-cube"></div>
* <div class="sk-cube"></div>
* <div class="sk-cube"></div>
* <div class="sk-cube"></div>
* </div>
*
*/
.sk-spinner-cube-grid {
/*
* Spinner positions
* 1 2 3
* 4 5 6
* 7 8 9
*/ }
.sk-spinner-cube-grid.sk-spinner {
width: 30px;
height: 30px;
margin: 0 auto; }
.sk-spinner-cube-grid .sk-cube {
width: 33%;
height: 33%;
background: #333;
float: left;
-webkit-animation: sk-cubeGridScaleDelay 1.3s infinite ease-in-out;
animation: sk-cubeGridScaleDelay 1.3s infinite ease-in-out; }
.sk-spinner-cube-grid .sk-cube:nth-child(1) {
-webkit-animation-delay: 0.2s;
animation-delay: 0.2s; }
.sk-spinner-cube-grid .sk-cube:nth-child(2) {
-webkit-animation-delay: 0.3s;
animation-delay: 0.3s; }
.sk-spinner-cube-grid .sk-cube:nth-child(3) {
-webkit-animation-delay: 0.4s;
animation-delay: 0.4s; }
.sk-spinner-cube-grid .sk-cube:nth-child(4) {
-webkit-animation-delay: 0.1s;
animation-delay: 0.1s; }
.sk-spinner-cube-grid .sk-cube:nth-child(5) {
-webkit-animation-delay: 0.2s;
animation-delay: 0.2s; }
.sk-spinner-cube-grid .sk-cube:nth-child(6) {
-webkit-animation-delay: 0.3s;
animation-delay: 0.3s; }
.sk-spinner-cube-grid .sk-cube:nth-child(7) {
-webkit-animation-delay: 0s;
animation-delay: 0s; }
.sk-spinner-cube-grid .sk-cube:nth-child(8) {
-webkit-animation-delay: 0.1s;
animation-delay: 0.1s; }
.sk-spinner-cube-grid .sk-cube:nth-child(9) {
-webkit-animation-delay: 0.2s;
animation-delay: 0.2s; }
@-webkit-keyframes sk-cubeGridScaleDelay {
0%, 70%, 100% {
-webkit-transform: scale3D(1, 1, 1);
transform: scale3D(1, 1, 1); }
35% {
-webkit-transform: scale3D(0, 0, 1);
transform: scale3D(0, 0, 1); } }
@keyframes sk-cubeGridScaleDelay {
0%, 70%, 100% {
-webkit-transform: scale3D(1, 1, 1);
transform: scale3D(1, 1, 1); }
35% {
-webkit-transform: scale3D(0, 0, 1);
transform: scale3D(0, 0, 1); } }
|
nbagonet/AlphaAdminTemplate
|
dist/vendor/SpinKit/css/spinners/9-cube-grid.css
|
CSS
|
mit
| 2,403
|
(function () {
ko.bindingHandlers = {};
ko.bindingContext = function(dataItem, parentBindingContext, dataItemAlias) {
if (parentBindingContext) {
ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties
this['$parentContext'] = parentBindingContext;
this['$parent'] = parentBindingContext['$data'];
this['$parents'] = (parentBindingContext['$parents'] || []).slice(0);
this['$parents'].unshift(this['$parent']);
} else {
this['$parents'] = [];
this['$root'] = dataItem;
// Export 'ko' in the binding context so it will be available in bindings and templates
// even if 'ko' isn't exported as a global, such as when using an AMD loader.
// See https://github.com/SteveSanderson/knockout/issues/490
this['ko'] = ko;
}
this['$data'] = dataItem;
if (dataItemAlias)
this[dataItemAlias] = dataItem;
}
ko.bindingContext.prototype['createChildContext'] = function (dataItem, dataItemAlias) {
return new ko.bindingContext(dataItem, this, dataItemAlias);
};
ko.bindingContext.prototype['extend'] = function(properties) {
var clone = ko.utils.extend(new ko.bindingContext(), this);
return ko.utils.extend(clone, properties);
};
function validateThatBindingIsAllowedForVirtualElements(bindingName) {
var validator = ko.virtualElements.allowedBindings[bindingName];
if (!validator)
throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
}
function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
while (currentChild = nextInQueue) {
// Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
nextInQueue = ko.virtualElements.nextSibling(currentChild);
applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement);
}
}
function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) {
var shouldBindDescendants = true;
// Perf optimisation: Apply bindings only if...
// (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
// Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
// (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
var isElement = (nodeVerified.nodeType === 1);
if (isElement) // Workaround IE <= 8 HTML parsing weirdness
ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
|| ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
if (shouldApplyBindings)
shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants;
if (shouldBindDescendants) {
// We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
// * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
// hence bindingContextsMayDifferFromDomParentElement is false
// * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
// skip over any number of intermediate virtual elements, any of which might define a custom binding context,
// hence bindingContextsMayDifferFromDomParentElement is true
applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
}
}
var boundElementDomDataKey = '__ko_boundElement';
function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) {
// Need to be sure that inits are only run once, and updates never run until all the inits have been run
var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits
// Each time the dependentObservable is evaluated (after data changes),
// the binding attribute is reparsed so that it can pick out the correct
// model properties in the context of the changed data.
// DOM event callbacks need to be able to access this changed data,
// so we need a single parsedBindings variable (shared by all callbacks
// associated with this node's bindings) that all the closures can access.
var parsedBindings;
function makeValueAccessor(bindingKey) {
return function () { return parsedBindings[bindingKey] }
}
function parsedBindingsAccessor() {
return parsedBindings;
}
var bindingHandlerThatControlsDescendantBindings;
// Prevent multiple applyBindings calls for the same node, except when a binding value is specified
var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
if (!bindings) {
if (alreadyBound) {
throw Error("You cannot apply bindings multiple times to the same element.");
}
ko.utils.domData.set(node, boundElementDomDataKey, true);
}
ko.dependentObservable(
function () {
// Ensure we have a nonnull binding context to work with
var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
? viewModelOrBindingContext
: new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext));
var viewModel = bindingContextInstance['$data'];
// Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
// we can easily recover it just by scanning up the node's ancestors in the DOM
// (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
if (!alreadyBound && bindingContextMayDifferFromDomParentElement)
ko.storedBindingContextForNode(node, bindingContextInstance);
// Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings
var evaluatedBindings = (typeof bindings == "function") ? bindings(bindingContextInstance, node) : bindings;
parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance);
if (parsedBindings) {
// First run all the inits, so bindings can register for notification on changes
if (initPhase === 0) {
initPhase = 1;
ko.utils.objectForEach(parsedBindings, function(bindingKey) {
var binding = ko.bindingHandlers[bindingKey];
if (binding && node.nodeType === 8)
validateThatBindingIsAllowedForVirtualElements(bindingKey);
if (binding && typeof binding["init"] == "function") {
var handlerInitFn = binding["init"];
var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
// If this binding handler claims to control descendant bindings, make a note of this
if (initResult && initResult['controlsDescendantBindings']) {
if (bindingHandlerThatControlsDescendantBindings !== undefined)
throw new Error("Multiple bindings (" + bindingHandlerThatControlsDescendantBindings + " and " + bindingKey + ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");
bindingHandlerThatControlsDescendantBindings = bindingKey;
}
}
});
initPhase = 2;
}
// ... then run all the updates, which might trigger changes even on the first evaluation
if (initPhase === 2) {
ko.utils.objectForEach(parsedBindings, function(bindingKey) {
var binding = ko.bindingHandlers[bindingKey];
if (binding && typeof binding["update"] == "function") {
var handlerUpdateFn = binding["update"];
handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance);
}
});
}
}
},
null,
{ disposeWhenNodeIsRemoved : node }
);
return {
shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined
};
};
var storedBindingContextDomDataKey = "__ko_bindingContext__";
ko.storedBindingContextForNode = function (node, bindingContext) {
if (arguments.length == 2)
ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
else
return ko.utils.domData.get(node, storedBindingContextDomDataKey);
}
ko.applyBindingsToNode = function (node, bindings, viewModel) {
if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
ko.virtualElements.normaliseVirtualElementDomStructure(node);
return applyBindingsToNodeInternal(node, bindings, viewModel, true);
};
ko.applyBindingsToDescendants = function(viewModel, rootNode) {
if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
applyBindingsToDescendantsInternal(viewModel, rootNode, true);
};
ko.applyBindings = function (viewModel, rootNode) {
if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true);
};
// Retrieving binding context from arbitrary nodes
ko.contextFor = function(node) {
// We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
switch (node.nodeType) {
case 1:
case 8:
var context = ko.storedBindingContextForNode(node);
if (context) return context;
if (node.parentNode) return ko.contextFor(node.parentNode);
break;
}
return undefined;
};
ko.dataFor = function(node) {
var context = ko.contextFor(node);
return context ? context['$data'] : undefined;
};
ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
ko.exportSymbol('applyBindings', ko.applyBindings);
ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
ko.exportSymbol('contextFor', ko.contextFor);
ko.exportSymbol('dataFor', ko.dataFor);
})();
|
chrismaul/knockout-render-server
|
public/components/knockoutjs/src/binding/bindingAttributeSyntax.js
|
JavaScript
|
mit
| 12,421
|
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: 'src/main/javascript/app',
frameworks: ['jasmine'],
files: [
'lib/lodash/dist/lodash.js',
'lib/angular/angular.js',
'lib/angular-resource/angular-resource.js',
'lib/restangular/dist/restangular.js'
],
// list of files / patterns to exclude
exclude: [],
plugins: [
'karma-jasmine',
'karma-coverage',
'karma-chrome-launcher',
'karma-phantomjs-launcher'
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress', 'coverage'],
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
// Coverage reporter generates the coverage
coverageReporter: {
reporters: [
{ type: 'lcov', dir: 'build/coverage/' },
{ type: 'text-summary', dir: 'build/coverage/' }
]
}
});
};
|
fundacionjala/sevenwonders
|
ui/karma.conf.js
|
JavaScript
|
mit
| 1,761
|
class AddOnlyChildren < ActiveRecord::Migration
def up
create_table :only_children, :force => true do |t|
t.string :name
t.references :parent
t.references :draft, :foreign_key => true
t.datetime :trashed_at
t.datetime :published_at
t.timestamps
end
end
def down
drop_table :only_children
end
end
|
npezza93/draftsman
|
spec/dummy/db/migrate/20150408234937_add_only_children.rb
|
Ruby
|
mit
| 361
|
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Calendar.slug'
db.add_column('schedule_calendar', 'slug',
self.gf('django.db.models.fields.SlugField')(max_length=255, null=True, blank=True),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Calendar.slug'
db.delete_column('schedule_calendar', 'slug')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'schedule.calendar': {
'Meta': {'ordering': "('-modified', '-created')", 'object_name': 'Calendar'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'data': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
}
}
complete_apps = ['schedule']
|
Bionetbook/bionetbook
|
bnbapp/schedule/migrations/0003_auto__add_field_calendar_slug.py
|
Python
|
mit
| 4,571
|
#ifndef JQ_PARSER_H
#define JQ_PARSER_H
int jq_parse(struct locfile* source, block* answer);
int jq_parse_library(struct locfile* locations, block* answer);
#endif
|
fleitz/jq-objc
|
src/jq_parser.h
|
C
|
mit
| 166
|
/*
pO\
6 /\
/OO\
/OOOO\
/OOOOOOOO\
((OOOOOOOO))
\:~=++=~:/
ChocolateChip-UI
ChUI.js
Copyright 2014 Sourcebits www.sourcebits.com
License: MIT
Version: 3.5.2
*/
(function($) {
'use strict';
$.extend({
///////////////
// Create Uuid:
///////////////
Uuid : function() {
return Date.now().toString(36);
},
///////////////////////////
// Concat array of strings:
///////////////////////////
concat : function ( args ) {
return (args instanceof Array) ? args.join('') : [].slice.apply(arguments).join('');
},
////////////////////////////
// Version of each that uses
// regular paramater order:
////////////////////////////
forEach : function ( obj, callback, args ) {
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], obj[ i ], i );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], obj[ i ], i );
if ( value === false ) {
break;
}
}
}
}
}
});
$.fn.extend({
//////////////////////
// Return element that
// matches selector:
//////////////////////
iz : function ( selector ) {
var ret = $();
this.forEach(function(ctx) {
if ($(ctx).is(selector)) {
ret.push(ctx);
}
});
return ret;
},
//////////////////////////////
// Return element that doesn't
// match selector:
//////////////////////////////
iznt : function ( selector ) {
return this.not(selector);
},
///////////////////////////////////
// Return element whose descendants
// match selector:
///////////////////////////////////
haz : function ( selector ) {
return this.has(selector);
},
///////////////////////////////////
// Return element whose descendants
// don't match selector:
///////////////////////////////////
haznt : function ( selector ) {
var ret = $();
this.forEach(function(ctx) {
if (!$(ctx).has(selector)[0]) {
ret.push(ctx);
}
});
return ret;
},
//////////////////////////////////////
// Return element that has class name:
//////////////////////////////////////
hazClass : function ( className ) {
var ret = $();
this.forEach(function(ctx) {
if ($(ctx).hasClass(className)) {
ret.push(ctx);
}
});
return ret;
},
//////////////////////////////
// Return element that doesn't
// have class name:
//////////////////////////////
hazntClass : function ( className ) {
var ret = $();
this.forEach(function(ctx) {
if (!$(ctx).hasClass(className)) {
ret.push(ctx);
}
});
return ret;
},
/////////////////////////////////////
// Return element that has attribute:
/////////////////////////////////////
hazAttr : function ( property ) {
var ret = $();
this.forEach(function(ctx){
if ($(ctx).attr(property)) {
ret.push(ctx);
}
});
return ret;
},
//////////////////////////
// Return element that
// doesn't have attribute:
//////////////////////////
hazntAttr : function ( property ) {
var ret = $();
this.forEach(function(ctx){
if (!$(ctx).attr(property)) {
ret.push(ctx);
}
});
return ret;
},
////////////////////////////
// Version of each that uses
// regular paramater order:
////////////////////////////
forEach : function ( callback, args ) {
return $.forEach( this, callback, args );
}
});
$.extend({
eventStart : null,
eventEnd : null,
eventMove : null,
eventCancel : null,
// Define min-length for gesture detection:
gestureLength : 30
});
$(function() {
//////////////////////////
// Setup Event Variables:
//////////////////////////
// Pointer events for IE10 and WP8:
if (window.navigator.pointerEnabled) {
$.eventStart = 'pointerdown';
$.eventEnd = 'pointerup';
$.eventMove = 'pointermove';
$.eventCancel = 'pointercancel';
// Pointer events for IE10 and WP8:
} else if (window.navigator.msPointerEnabled) {
$.eventStart = 'MSPointerDown';
$.eventEnd = 'MSPointerUp';
$.eventMove = 'MSPointerMove';
$.eventCancel = 'MSPointerCancel';
// Touch events for iOS & Android:
} else if ('ontouchstart' in window) {
$.eventStart = 'touchstart';
$.eventEnd = 'touchend';
$.eventMove = 'touchmove';
$.eventCancel = 'touchcancel';
// Mouse events for desktop:
} else {
$.eventStart = 'mousedown';
$.eventEnd = 'click';
$.eventMove = 'mousemove';
$.eventCancel = 'mouseout';
}
});
$.extend({
isiPhone : /iphone/img.test(navigator.userAgent),
isiPad : /ipad/img.test(navigator.userAgent),
isiPod : /ipod/img.test(navigator.userAgent),
isiOS : /ip(hone|od|ad)/img.test(navigator.userAgent),
isAndroid : (/android/img.test(navigator.userAgent) && !/trident/img.test(navigator.userAgent)),
isWebOS : /webos/img.test(navigator.userAgent),
isBlackberry : /blackberry/img.test(navigator.userAgent),
isTouchEnabled : ('createTouch' in document),
isOnline : navigator.onLine,
isStandalone : navigator.standalone,
isiOS6 : navigator.userAgent.match(/OS 6/i),
isiOS7 : navigator.userAgent.match(/OS 7/i),
isWin : /trident/img.test(navigator.userAgent),
isWinPhone : (/trident/img.test(navigator.userAgent) && /mobile/img.test(navigator.userAgent)),
isIE10 : navigator.userAgent.match(/msie 10/i),
isIE11 : navigator.userAgent.match(/msie 11/i),
isWebkit : navigator.userAgent.match(/webkit/),
isMobile : /mobile/img.test(navigator.userAgent),
isDesktop : !(/mobile/img.test(navigator.userAgent)),
isSafari : (!/Chrome/img.test(navigator.userAgent) && /Safari/img.test(navigator.userAgent) && !/android/img.test(navigator.userAgent)),
isChrome : /Chrome/img.test(navigator.userAgent),
isNativeAndroid : (/android/i.test(navigator.userAgent) && /webkit/i.test(navigator.userAgent) && !/chrome/i.test(navigator.userAgent))
});
//////////////////////////////////////////////////////
// Swipe Gestures for ChocolateChip-UI.
// Includes mouse gestures for desktop compatibility.
//////////////////////////////////////////////////////
var touch = {};
var touchTimeout;
var swipeTimeout;
var tapTimeout;
var longTapDelay = 750;
var singleTapDelay = 150;
var longTapTimeout;
function parentIfText(node) {
return 'tagName' in node ? node : node.parentNode;
}
function swipeDirection(x1, x2, y1, y2) {
return Math.abs(x1 - x2) >=
Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'left' : 'right') : (y1 - y2 > 0 ? 'up' : 'down');
}
function longTap() {
longTapTimeout = null;
if (touch.last) {
try {
if (touch && touch.el) {
touch.el.trigger('longtap');
touch = {};
}
} catch(err) { }
}
}
function cancelLongTap() {
if (longTapTimeout) clearTimeout(longTapTimeout);
longTapTimeout = null;
}
function cancelAll() {
if (touchTimeout) clearTimeout(touchTimeout);
if (tapTimeout) clearTimeout(tapTimeout);
if (swipeTimeout) clearTimeout(swipeTimeout);
if (longTapTimeout) clearTimeout(longTapTimeout);
touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null;
touch = {};
}
$(function(){
var now;
var delta;
var body = $(document.body);
var twoTouches = false;
body.on($.eventStart, function(e) {
now = Date.now();
delta = now - (touch.last || now);
if (e.originalEvent) e = e.originalEvent;
// Handle MSPointer Events:
if (window.navigator.msPointerEnabled || window.navigator.pointerEnabled) {
if (window && window.jQuery && $ === window.jQuery) {
if (e.originalEvent && !e.originalEvent.isPrimary) return;
} else {
if (!e.isPrimary) return;
}
e = e.originalEvent ? e.originalEvent : e;
body.on('MSHoldVisual', function (e) {
e.preventDefault();
});
touch.el = $(parentIfText(e.target));
touchTimeout && clearTimeout(touchTimeout);
touch.x1 = e.pageX;
touch.y1 = e.pageY;
twoTouches = false;
} else {
if ($.eventStart === 'mousedown') {
touch.el = $(parentIfText(e.target));
touchTimeout && clearTimeout(touchTimeout);
touch.x1 = e.pageX;
touch.y1 = e.pageY;
twoTouches = false;
} else {
// User to detect two or more finger gestures:
if (e.touches.length === 1) {
touch.el = $(parentIfText(e.touches[0].target));
touchTimeout && clearTimeout(touchTimeout);
touch.x1 = e.touches[0].pageX;
touch.y1 = e.touches[0].pageY;
if (e.targetTouches.length === 2) {
twoTouches = true;
} else {
twoTouches = false;
}
}
}
}
if (delta > 0 && delta <= 250) {
touch.isDoubleTap = true;
}
touch.last = now;
longTapTimeout = setTimeout(longTap, longTapDelay);
});
body.on($.eventMove, function(e) {
if (e.originalEvent) e = e.originalEvent;
if (window.navigator.msPointerEnabled) {
if (window && window.jQuery && $ === window.jQuery) {
if (e.originalEvent && !e.originalEvent.isPrimary) return;
} else {
if (!e.isPrimary) return;
}
e = e.originalEvent ? e.originalEvent : e;
cancelLongTap();
touch.x2 = e.pageX;
touch.y2 = e.pageY;
} else {
cancelLongTap();
if ($.eventMove === 'mousemove') {
touch.x2 = e.pageX;
touch.y2 = e.pageY;
} else {
// One finger gesture:
if (e.touches.length === 1) {
touch.x2 = e.touches[0].pageX;
touch.y2 = e.touches[0].pageY;
}
}
}
if ($.isAndroid) {
$.gestureLength = 10;
if (!!touch.el) {
// Swipe detection:
if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > $.gestureLength) ||
(touch.y2 && Math.abs(touch.y1 - touch.y2) > $.gestureLength)) {
swipeTimeout = setTimeout(function() {
e.preventDefault();
if (touch && touch.el) {
touch.el.trigger('swipe');
touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)));
touch = {};
}
}, 0);
// Normal tap:
} else if ('last' in touch) {
// Delay by one tick so we can cancel the 'tap' event if 'scroll' fires:
tapTimeout = setTimeout(function() {
// Trigger universal 'tap' with the option to cancelTouch():
if (touch && touch.el) {
touch.el.trigger('tap');
}
// Trigger double tap immediately:
if (touch && touch.isDoubleTap) {
if (touch && touch.el) {
touch.el.trigger('doubletap');
touch = {};
}
} else {
// Trigger single tap after singleTapDelay:
touchTimeout = setTimeout(function(){
touchTimeout = null;
if (touch && touch.el) {
touch.el.trigger('singletap');
touch = {};
return false;
}
}, singleTapDelay);
}
}, 0);
}
} else { return; }
}
});
body.on($.eventEnd, function(e) {
if (window.navigator.msPointerEnabled) {
if (window && window.jQuery && $ === window.jQuery) {
if (e.originalEvent && !e.originalEvent.isPrimary) return;
} else {
if (!e.isPrimary) return;
}
}
cancelLongTap();
if (!!touch.el) {
// Swipe detection:
if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > $.gestureLength) ||
(touch.y2 && Math.abs(touch.y1 - touch.y2) > $.gestureLength)) {
swipeTimeout = setTimeout(function() {
if (touch && touch.el) {
touch.el.trigger('swipe');
touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)));
touch = {};
}
}, 0);
// Normal tap:
} else if ('last' in touch) {
// Delay by one tick so we can cancel the 'tap' event if 'scroll' fires:
tapTimeout = setTimeout(function() {
// Trigger universal 'tap' with the option to cancelTouch():
if (touch && touch.el) {
touch.el.trigger('tap');
}
// Trigger double tap immediately:
if (touch && touch.isDoubleTap) {
if (touch && touch.el) {
touch.el.trigger('doubletap');
touch = {};
}
} else {
// Trigger single tap after singleTapDelay:
touchTimeout = setTimeout(function(){
touchTimeout = null;
if (touch && touch.el) {
touch.el.trigger('singletap');
touch = {};
return false;
}
}, singleTapDelay);
}
}, 0);
}
} else { return; }
});
body.on('touchcancel', cancelAll);
});
['swipe', 'swipeleft', 'swiperight', 'swipeup', 'swipedown', 'doubletap', 'tap', 'singletap', 'longtap'].forEach(function(method){
// Add gesture events to ChocolateChipJS:
$.fn.extend({
method : function(callback){
return this.on(method, callback);
}
});
});
/////////////////////////////////////////
// Set classes for desktop compatibility:
/////////////////////////////////////////
$.extend({
UIDesktopCompat : function ( ) {
if ($.isDesktop && $.isSafari) {
$('body').addClass('isiOS').addClass('isDesktopSafari');
} else if ($.isDesktop && $.isChrome) {
$('body').addClass('isAndroid').addClass('isDesktopChrome');
}
}
});
////////////////////////////////
// Determine browser version:
////////////////////////////////
$.extend({
browserVersion : function ( ) {
var n = navigator.appName;
var ua = navigator.userAgent;
var temp;
var m = ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
if (m && (temp = ua.match(/version\/([\.\d]+)/i))!== null) m[2]= temp[1];
m = m ? [m[1], m[2]]: [n, navigator.appVersion, '-?'];
return m[1];
}
});
$(function() {
////////////////////////////////
// Added classes for client side
// os-specific styles:
////////////////////////////////
$.body = $('body');
if ($.isWin) {
$.body.addClass('isWindows');
} else if ($.isiOS) {
$.body.addClass('isiOS');
} else if ($.isAndroid) {
$.body.addClass('isAndroid');
}
if ($.isSafari && parseInt($.browserVersion(), 10) === 6) {
$.body.addClass('isSafari6');
}
$.UIDesktopCompat();
});
$(function() {
$.body = $('body');
//////////////////////
// Add the global nav:
//////////////////////
if (!$.body[0].classList.contains('splitlayout')) {
$('body').prepend("<nav id='global-nav'></nav>");
}
/////////////////////////////////////////////////
// Fix Split Layout to display properly on phone:
/////////////////////////////////////////////////
if ($.body[0].classList.contains('splitlayout')) {
if (window.innerWidth < 768) {
$('meta[name=viewport]').attr('content','width=device-width, initial-scale=0.45, maximum-scale=2, user-scalable=yes');
}
}
/////////////////////////////////////////////////////////
// Add class to nav when button on right.
// This allows us to adjust the nav h1 for small screens.
/////////////////////////////////////////////////////////
$('h1').each(function(idx, ctx) {
if (ctx.nextElementSibling && ctx.nextElementSibling.nodeName === 'A') {
ctx.classList.add('buttonOnRight');
}
});
//////////////////////////////////////////
// Get any toolbars and adjust the bottom
// of their corresponding articles:
//////////////////////////////////////////
$('.toolbar').prev('article').addClass('has-toolbar');
});
$.extend({
subscriptions : {},
// Topic: string defining topic: /some/topic
// Data: a string, number, array or object.
subscribe : function (topic, callback) {
if (!$.subscriptions[topic]) {
$.subscriptions[topic] = [];
}
var token = ($.Uuid());
$.subscriptions[topic].push({
token: token,
callback: callback
});
return token;
},
unsubscribe : function ( token ) {
setTimeout(function() {
for (var m in $.subscriptions) {
if ($.subscriptions[m]) {
for (var i = 0, len = $.subscriptions[m].length; i < len; i++) {
if ($.subscriptions[m][i].token === token) {
$.subscriptions[m].splice(i, 1);
return token;
}
}
}
}
return false;
});
},
publish : function ( topic, args ) {
if (!$.subscriptions[topic]) {
return false;
}
setTimeout(function () {
var len = $.subscriptions[topic] ? $.subscriptions[topic].length : 0;
while (len--) {
$.subscriptions[topic][len].callback(topic, args);
}
return true;
});
return true;
}
});
////////////////////////////////////
// Create custom navigationend event
////////////////////////////////////
function triggerNavigationEvent(target) {
var transition;
var tansitionDuration;
if ('transition' in document.body.style) {
transition = 'transition-duration';
} else if ('-webkit-transition' in document.body.style){
transition = '-webkit-transition-duration';
}
function determineDurationType (duration) {
if (/m/.test(duration)) {
return parseFloat(duration);
} else if (/s/.test(duration)) {
return parseFloat(duration) * 100;
}
}
tansitionDuration = determineDurationType($('article').eq(0).css(transition));
setTimeout(function() {
$(target).trigger({type: 'navigationend'});
}, tansitionDuration);
}
$.extend({
////////////////////////////////////////////////
// Manage location.hash for client side routing:
////////////////////////////////////////////////
UITrackHashNavigation : function ( url, delimeter ) {
url = url || true;
$.UISetHashOnUrl($.UINavigationHistory[$.UINavigationHistory.length-1], delimeter);
},
/////////////////////////////////////////////////////
// Set the hash according to where the user is going:
/////////////////////////////////////////////////////
UISetHashOnUrl : function ( url, delimiter ) {
delimiter = delimiter || '#/';
var hash;
if (/^#/.test(url)) {
hash = delimiter + (url.split('#')[1]);
} else {
hash = delimiter + url;
}
if ($.isAndroid) {
if (/#/.test(url)) {
url = url.split('#')[1];
}
if (/\//.test(url)) {
url = url.split('/')[1];
}
window.location.hash = '#/' + url;
} else {
window.history.replaceState('Object', 'Title', hash);
}
},
//////////////////////////////////////
// Navigate Back to Non-linear Article
//////////////////////////////////////
UIGoBackToArticle : function ( articleID ) {
var historyIndex = $.UINavigationHistory.indexOf(articleID);
var currentArticle = $('article.current');
var destination = $(articleID);
var currentToolbar;
var destinationToolbar;
if ($.UINavigationHistory.length === 0) {
destination = $('article:first-of-type');
$.UINavigationHistory.push('#' + destination[0].id);
}
var prevArticles;
if ($.UINavigationHistory.length > 1) {
prevArticles = $.UINavigationHistory.splice(historyIndex+1);
} else {
prevArticles = $('article.previous');
}
$.publish('chui/navigateBack/leave', currentArticle[0].id);
$.publish('chui/navigateBack/enter', destination[0].id);
currentArticle[0].scrollTop = 0;
destination[0].scrollTop = 0;
if (prevArticles.length) {
$.each(prevArticles, function(_, ctx) {
$(ctx).removeClass('previous').addClass('next');
$(ctx).prev().removeClass('previous').addClass('next');
});
}
currentToolbar = currentArticle.next().hazClass('toolbar');
destinationToolbar = destination.next().hazClass('toolbar');
destination.removeClass('previous next').addClass('current');
destination.prev().removeClass('previous next').addClass('current');
destinationToolbar.removeClass('previous next').addClass('current');
currentArticle.removeClass('current').addClass('next');
currentArticle.prev().removeClass('current').addClass('next');
currentToolbar.removeClass('current').addClass('next');
$('.toolbar.previous').removeClass('previous').addClass('next');
$.UISetHashOnUrl($.UINavigationHistory[$.UINavigationHistory.length-1]);
triggerNavigationEvent(destination);
},
////////////////////////////////////
// Navigate Back to Previous Article
////////////////////////////////////
UIGoBack : function () {
var histLen = $.UINavigationHistory.length;
var currentArticle = $('article.current');
var destination = $($.UINavigationHistory[histLen-2]);
var currentToolbar;
var destinationToolbar;
if (histLen === 0) {
destination = $('article:first-of-type');
$.UINavigationHistory.push('#' + destination[0].id);
}
$.publish('chui/navigateBack/leave', currentArticle[0].id);
$.publish('chui/navigateBack/enter', destination[0].id);
currentArticle[0].scrollTop = 0;
destination[0].scrollTop = 0;
currentToolbar = currentArticle.next().hazClass('toolbar');
destinationToolbar = destination.next().hazClass('toolbar');
destination.removeClass('previous').addClass('current');
destination.prev().removeClass('previous').addClass('current');
destinationToolbar.removeClass('previous').addClass('current');
currentArticle.removeClass('current').addClass('next');
currentArticle.prev().removeClass('current').addClass('next');
currentToolbar.removeClass('current').addClass('next');
$.UISetHashOnUrl($.UINavigationHistory[histLen-2]);
if ($.UINavigationHistory.length === 1) return;
$.UINavigationHistory.pop();
},
isNavigating : false,
///////////////////////////////
// Navigate to Specific Article
///////////////////////////////
UIGoToArticle : function ( destination ) {
if ($.isNavigating) return;
$.isNavigating = true;
var current = $('article.current');
var currentNav = current.prev();
destination = $(destination);
var destinationID = '#' + destination[0].id;
var destinationNav = destination.prev();
var currentToolbar;
var destinationToolbar;
var navigationClass = 'next previous';
$.publish('chui/navigate/leave', current[0].id);
$.UINavigationHistory.push(destinationID);
$.publish('chui/navigate/enter', destination[0].id);
current[0].scrollTop = 0;
destination[0].scrollTop = 0;
currentToolbar = current.next().hazClass('toolbar');
destinationToolbar = destination.next().hazClass('toolbar');
current.removeClass('current').addClass('previous');
currentNav.removeClass('current').addClass('previous');
currentToolbar.removeClass('current').addClass('previous');
destination.removeClass(navigationClass).addClass('current');
destinationNav.removeClass(navigationClass).addClass('current');
destinationToolbar.removeClass(navigationClass).addClass('current');
$.UISetHashOnUrl(destination[0].id);
setTimeout(function() {
$.isNavigating = false;
}, 500);
triggerNavigationEvent(destination);
}
});
///////////////////
// Init navigation:
///////////////////
$(function() {
//////////////////////////////////////////
// Set first value for navigation history:
//////////////////////////////////////////
$.extend({
UINavigationHistory : ["#" + $('article').eq(0).attr('id')]
});
///////////////////////////////////////////////////////////
// Make sure that navs and articles have navigation states:
///////////////////////////////////////////////////////////
$('nav:not(#global-nav)').each(function(idx, ctx) {
// Prevent if splitlayout for tablets:
if ($('body')[0].classList.contains('splitlayout')) return;
if (idx === 0) {
ctx.classList.add('current');
} else {
ctx.classList.add('next');
}
});
$('article').each(function(idx, ctx) {
// Prevent if splitlayout for tablets:
if ($('body')[0].classList.contains('splitlayout')) return;
if ($('body')[0].classList.contains('slide-out-app')) return;
if (idx === 0) {
ctx.classList.add('current');
} else {
ctx.classList.add('next');
}
});
///////////////////////////
// Initialize Back Buttons:
///////////////////////////
$('body').on('singletap', 'a.back', function() {
if (this.classList.contains('back')) {
$.UIGoBack();
}
});
////////////////////////////////
// Handle navigation list items:
////////////////////////////////
$('body').on('singletap doubletap', 'li', function() {
if ($.isNavigating) return;
if (!this.hasAttribute('data-goto')) return;
if (!this.getAttribute('data-goto')) return;
if (!document.getElementById(this.getAttribute('data-goto'))) return;
if ($(this).parent()[0].classList.contains('deletable')) return;
var destinationHref = '#' + this.getAttribute('data-goto');
$(destinationHref).addClass('navigable');
var destination = $(destinationHref);
$.UIGoToArticle(destination);
});
$('li[data-goto]').each(function(idx, ctx) {
$(ctx).closest('article').addClass('navigable');
var navigable = '#' + ctx.getAttribute('data-goto');
$(navigable).addClass('navigable');
});
/////////////////////////////////////
// Init navigation url hash tracking:
/////////////////////////////////////
// If there's more than one article:
if ($('article').eq(1)[0]) {
$.UISetHashOnUrl($('article').eq(0)[0].id);
}
/////////////////////////////////////////////////////////
// Stop rubber banding when dragging down on nav:
/////////////////////////////////////////////////////////
$('nav').on($.eventStart, function(e) {
e.preventDefault();
});
});
$(function() {
///////////////////////////////////
// Initialize singletap on buttons:
///////////////////////////////////
$('body').on('singletap', '.button', function() {
var $this = $(this);
if ($this.parent('.segmented')[0]) return;
if ($this.parent('.tabbar')[0]) return;
$this.addClass('selected');
setTimeout(function() {
$this.removeClass('selected');
}, 500);
});
});
$.fn.extend({
/////////////////////////
// Block Screen with Mask
/////////////////////////
UIBlock : function ( opacity ) {
opacity = opacity ? " style='opacity:" + opacity + "'" : " style='opacity: .5;'";
$(this).before("<div class='mask'" + opacity + "></div>");
$('article.current').attr('aria-hidden',true);
return this;
},
//////////////////////////
// Remove Mask from Screen
//////////////////////////
UIUnblock : function ( ) {
$('.mask').remove();
$('article.current').removeAttr('aria-hidden');
return this;
}
});
$.fn.extend({
//////////////////////////////
// Center an Element on Screen
//////////////////////////////
UICenter : function ( ) {
if (!this[0]) return;
var $this = $(this);
var parent = $this.parent();
var position;
if ($this.css('position') !== 'absolute') position = 'relative';
else position = 'absolute';
var height, width, parentHeight, parentWidth;
if (position === 'absolute') {
height = $this[0].clientHeight;
width = $this[0].clientWidth;
parentHeight = parent[0].clientHeight;
parentWidth = parent[0].clientWidth;
} else {
height = parseInt($this.css('height'),10);
width = parseInt($this.css('width'),10);
parentHeight = parseInt(parent.css('height'),10);
parentWidth = parseInt(parent.css('width'),10);
}
var tmpTop, tmpLeft;
if (parent[0].nodeName === 'body') {
tmpTop = ((window.innerHeight /2) + window.pageYOffset) - height /2 + 'px';
tmpLeft = ((window.innerWidth / 2) - (width / 2) + 'px');
} else {
tmpTop = (parentHeight /2) - (height /2) + 'px';
tmpLeft = (parentWidth / 2) - (width / 2) + 'px';
}
if (position !== 'absolute') tmpLeft = 0;
// if (parseInt(tmpLeft,10) <= 0) tmpLeft = '10px';
$this.css({left: tmpLeft, top: tmpTop});
}
});
$.fn.extend({
////////////////////////
// Create Busy indicator
////////////////////////
/*
var options = {
color: 'red',
size: '80px',
position: 'right'
}
*/
UIBusy : function ( options ) {
options = options || {};
var $this = this;
var color = options.color || '#000';
var size = options.size || '80px';
var position = (options && options.position === 'right') ? 'align-flush' : null;
var duration = options.duration || '2s';
var spinner;
// For iOS:
var iOSBusy = function() {
var webkitAnim = {'-webkit-animation-duration': duration};
spinner = $('<span class="busy"></span>');
$(spinner).css({'background-color': color, 'height': size, 'width': size});
$(spinner).css(webkitAnim);
$(spinner).attr('role','progressbar');
if (position) $(spinner).addClass(position);
$this.append(spinner);
return this;
};
// For Android:
var androidBusy = function() {
var webkitAnim = {'-webkit-animation-duration': duration};
spinner = $('<div class="busy"><div></div><div></div></div>');
$(spinner).css({'height': size, 'width': size, "background-image": 'url(' + '"data:image/svg+xml;utf8,<svg xmlns:svg=' + "'http://www.w3.org/2000/svg' xmlns='http://www.w3.org/2000/svg' version='1.1' x='0px' y='0px' width='400px' height='400px' viewBox='0 0 400 400' enable-background='new 0 0 400 400' xml:space='preserve'><circle fill='none' stroke='" + color + "' stroke-width='20' stroke-miterlimit='10' cx='199' cy='199' r='174'/>" + '</svg>"' + ')'});
$(spinner).css(webkitAnim);
$(spinner).attr('role','progressbar');
$(spinner).innerHTML = "<div></div><div></div>";
if (position) $(spinner).addClass('align-' + position);
$this.append(spinner);
return this;
};
// For Windows 8/WP8:
var winBusy = function() {
spinner = $('<progress class="busy"></progress>');
$(spinner).css({ 'color': color });
$(spinner).attr('role','progressbar');
$(spinner).addClass('win-ring');
if (position) $(spinner).addClass('align-' + position);
$this.append(spinner);
return this;
};
// Create Busy control for appropriate OS:
if ($.isWin) {
winBusy(options);
} else if ($.isAndroid || $.isChrome) {
androidBusy(options);
} else if ($.isiOS || $.isSafari) {
iOSBusy(options);
}
}
});
$.extend({
///////////////
// Create Popup
///////////////
UIPopup : function( options ) {
/*
options {
id: 'alertID',
title: 'Alert',
message: 'This is a message from me to you.',
cancelButton: 'Cancel',
continueButton: 'Go Ahead',
callback: function() { // do nothing }
}
*/
if (!options) return;
var id = options.id || $.Uuid();
var title = options.title ? '<header><h1>' + options.title + '</h1></header>' : '';
var message = options.message ? '<p role="note">' + options.message + '</p>' : '';
var cancelButton = options.cancelButton ? '<a href="javascript:void(null)" class="button cancel" role="button">' + options.cancelButton + '</a>' : '';
var continueButton = options.continueButton ? '<a href="javascript:void(null)" class="button continue" role="button">' + options.continueButton + '</a>' : '';
var callback = options.callback || $.noop;
var padding = options.empty ? ' style="padding: 40px 0;" ' : '';
var panelOpen, panelClose;
if (options.empty) {
panelOpen = '';
panelClose = '';
} else {
panelOpen = '<div class="panel">';
panelClose = '</div>';
}
var popup = '<div class="popup closed" role="alertdialog" id="' + id + '"' + padding + '>' + panelOpen + title + message + '<footer>' + cancelButton + continueButton + '</footer>' + panelClose + '</div>';
$('body').append(popup);
if (callback && continueButton) {
$('.popup').find('.continue').on($.eventStart, function() {
$('.popup').UIPopupClose();
callback.call(callback);
});
}
$.UICenterPopup();
setTimeout(function() {
$('body').find('.popup').removeClass('closed');
}, 200);
$('body').find('.popup').UIBlock('0.5');
var events = $.eventStart + ' singletap ' + $.eventEnd;
$('.mask').on(events, function(e) {
e.stopPropagation();
});
},
//////////////////////////////////////////
// Center Popups When Orientation Changes:
//////////////////////////////////////////
UICenterPopup : function ( ) {
var popup = $('.popup');
if (!popup[0]) return;
var tmpTop = ((window.innerHeight /2) + window.pageYOffset) - (popup[0].clientHeight /2) + 'px';
var tmpLeft;
if (window.innerWidth === 320) {
tmpLeft = '10px';
} else {
tmpLeft = Math.floor((window.innerWidth - 318) /2) + 'px';
}
if ($.isWin) {
popup.css({top: tmpTop});
} else {
popup.css({left: tmpLeft, top: tmpTop});
}
}
});
$.fn.extend({
//////////////
// Close Popup
//////////////
UIPopupClose : function ( ) {
if (!this && !this.classList.contains('popup')) return;
$(this).UIUnblock();
$(this).remove();
}
});
$(function() {
//////////////////////////
// Handle Closing Popups:
//////////////////////////
$('body').on($.eventStart, '.cancel', function() {
if ($(this).closest('.popup')[0]) {
$(this).closest('.popup').UIPopupClose();
}
});
/////////////////////////////////////////////////
// Reposition popups on window resize:
/////////////////////////////////////////////////
window.onresize = function() {
$.UICenterPopup();
};
});
$.fn.extend({
/////////////////
// Create Popover
/////////////////
/*
id: myUniqueID,
title: 'Great',
callback: myCallback
*/
UIPopover : function ( options ) {
if (!options) return [];
var triggerEl = $(this);
var triggerID;
if (this[0].id) {
triggerID = this[0].id;
} else {
triggerID = $.Uuid();
triggerEl.attr('id', triggerID);
}
var id = options.id ? options.id : $.Uuid();
var header = options.title ? ('<header><h1>' + options.title + '</h1></header>') : '';
var callback = options.callback ? options.callback : $.noop;
var popover = '<div class="popover" id="' + id + '">' + header + '<section></section></div>';
// Calculate position of popover relative to the button that opened it:
var _calcPopPos = function (element) {
var offset = $(element).offset();
var left = offset.left;
var calcLeft;
var calcTop;
var popover = $('.popover');
var popoverOffset = popover.offset();
calcLeft = popoverOffset.left;
calcTop = offset.top + $(element)[0].clientHeight;
if ((popover.width() + offset.left) > window.innerWidth) {
popover.css({
'left': ((window.innerWidth - popover.width())-20) + 'px',
'top': (calcTop + 20) + 'px'
});
} else {
popover.css({'left': left + 'px', 'top': (calcTop + 20) + 'px'});
}
};
$(this).on($.eventStart, function() {
var $this = this;
$(this).addClass('selected');
setTimeout(function() {
$($this).removeClass('selected');
}, 1000);
$('body').append(popover);
$('.popover').UIBlock('.5');
var event = 'singletap';
if ($.isWin && $.isDesktop) {
event = $.eventStart + ' singletap ' + $.eventEnd;
}
$('.mask').on(event, function(e) {
e.preventDefault();
e.stopPropagation();
});
$('.popover').data('triggerEl', triggerID);
if ($.isWin) {
_calcPopPos($this);
$('.popover').addClass('open');
} else {
$('.popover').addClass('open');
setTimeout(function () {
_calcPopPos($this);
});
}
callback.call(callback, $this);
});
}
});
$.extend({
///////////////////////////////////////
// Align the Popover Before Showing it:
///////////////////////////////////////
UIAlignPopover : function () {
var popover = $('.popover');
if (!popover.length) return;
var triggerID = popover.data('triggerEl');
var offset = $('#'+triggerID).offset();
var left = offset.left;
if (($(popover).width() + offset.left) > window.innerWidth) {
popover.css({
'left': ((window.innerWidth - $(popover).width())-20) + 'px'
});
} else {
popover.css({'left': left + 'px'});
}
}
});
$.extend({
UIPopoverClose : function ( ) {
$('body').UIUnblock();
$('.popover').css('visibility','hidden');
setTimeout(function() {
$('.popover').remove();
},10);
}
});
$(function() {
/////////////////////////////////////////////////
// Reposition popovers on window resize:
/////////////////////////////////////////////////
window.onresize = function() {
$.UIAlignPopover();
};
var events = $.eventStart + ' singletap ' + $.eventEnd;
$('body').on(events, '.mask', function(e) {
if (!$('.popover')[0]) {
if (e && e.nodeType === 1) return;
e.stopPropogation();
} else {
$.UIPopoverClose();
}
});
});
$.fn.extend({
///////////////////////////////
// Initialize Segmented Control
///////////////////////////////
UISegmented : function ( options ) {
if (this.hasClass('paging')) return;
var callback = (options && options.callback) ? options.callback : $.noop;
var selected;
if (options && options.selected) selected = options.selected;
if (options && options.callback) {
callback = options.callback;
}
this.find('a').each(function(idx, ctx) {
$(ctx).find('a').attr('role','radio');
if (selected === 0 && idx === 0) {
ctx.setAttribute('aria-checked', 'true');
ctx.classList.add('selected');
}
if (idx === selected) {
ctx.setAttribute('aria-checked', 'true');
ctx.classList.add('selected');
}
});
if (!selected) {
if (!this.find('.selected')[0]) {
this.children().eq(0).addClass('selected');
}
}
this.on('singletap', '.button', function(e) {
var $this = $(this);
if (this.parentNode.classList.contains('paging')) return;
$this.siblings('a').removeClass('selected');
$this.siblings('a').removeAttr('aria-checked');
$this.addClass('selected');
$this.attr('aria-checked', true);
callback.call(this, e);
});
}
});
$.extend({
///////////////////////////
// Create Segmented Control
///////////////////////////
UICreateSegmented : function ( options ) {
/*
options = {
id : '#myId',
className : 'special' || '',
labels : ['first','second','third'],
selected : 0 based number of selected button
}
*/
var className = (options && options.className) ? options.className : '';
var labels = (options && options.labels) ? options.labels : [];
var selected = (options && options.selected) ? options.selected : 0;
var _segmented = ['<div class="segmented'];
if (className) _segmented.push(' ' + className);
_segmented.push('">');
labels.forEach(function(ctx, idx) {
_segmented.push('<a role="radio" class="button');
if (selected === idx) {
_segmented.push(' selected" aria-checked="true"');
} else {
_segmented.push('"');
}
_segmented.push('>');
_segmented.push(ctx);
_segmented.push('</a>');
});
_segmented.push('</div>');
return _segmented.join('');
}
});
$(function() {
/////////////////////////////////////
// Handle Existing Segmented Buttons:
/////////////////////////////////////
$('.segmented').UISegmented();
});
$.fn.extend({
////////////////////////////////////////////
// Allow Segmented Control to toggle panels
////////////////////////////////////////////
UIPanelToggle : function ( panel, callback ) {
var panels;
var selected = 0;
selected = this.children().hazClass('selected').index() || 0;
if (panel instanceof Array) {
panels = panel.children('div');
} else if (typeof panel === 'string') {
panels = $(panel).children('div');
}
panels.eq(selected).siblings().css({display: 'none'});
if (callback) callback.apply(this, arguments);
this.on($.eventEnd, 'a', function() {
panels.eq($(this).index()).css({display:'block'})
.siblings().css('display','none');
});
this.on('singletap', '.button', function() {
var $this = $(this);
if (this.parentNode.classList.contains('paging')) return;
$this.siblings('a').removeClass('selected');
$this.siblings('a').removeAttr('aria-checked');
$this.addClass('selected');
$this.attr('aria-checked', true);
});
}
});
$.extend({
///////////////////////
// Setup Paging Control
///////////////////////
UIPaging : function ( ) {
var currentArticle = $('.segmented.paging').closest('nav').next();
if (window && window.jQuery && $ === window.jQuery) {
if ($('.segmented.paging').hasClass('horizontal')) {
currentArticle.addClass('horizontal');
} else if ($('.segmented.paging').hasClass('vertical')) {
currentArticle.addClass('vertical');
}
} else {
if ($('.segmented.paging').hasClass('horizontal')[0]) {
currentArticle.addClass('horizontal');
} else if ($('.segmented.paging').hasClass('vertical')[0]) {
currentArticle.addClass('vertical');
}
}
currentArticle.children().eq(0).addClass('current');
currentArticle.children().eq(0).siblings().addClass('next');
var sections = function() {
return currentArticle.children().length;
};
$('.segmented.paging').on($.eventStart, '.button:first-of-type', function() {
if (sections() === 1) return;
var $this = $(this);
$this.next().removeClass('selected');
$this.addClass('selected');
var currentSection;
currentSection = $('section.current');
if (currentSection.index() === 0) {
currentSection.removeClass('current');
currentArticle.children().eq(sections() - 1).addClass('current').removeClass('next');
currentArticle.children().eq(sections() - 1).siblings().removeClass('next').addClass('previous');
} else {
currentSection.removeClass('current').addClass('next');
currentSection.prev().removeClass('previous').addClass('current');
}
setTimeout(function() {
$this.removeClass('selected');
}, 250);
});
$('.segmented.paging').on($.eventStart, '.button:last-of-type', function() {
if (sections() === 1) return;
var $this = $(this);
$this.prev().removeClass('selected');
$this.addClass('selected');
var currentSection;
if (this.classList.contains('disabled')) return;
currentSection = $('section.current');
if (currentSection.index() === sections() - 1) {
// start again!
currentSection.removeClass('current');
currentArticle.children().eq(0).addClass('current').removeClass('previous');
currentArticle.children().eq(0).siblings().removeClass('previous').addClass('next');
} else {
currentSection.removeClass('current').addClass('previous');
currentSection.next().removeClass('next').addClass('current');
}
setTimeout(function() {
$this.removeClass('selected');
}, 250);
});
}
});
$.extend({
////////////////////////////
// Initialize Deletable List
////////////////////////////
UIDeletable : function ( options ) {
/*
options = {
list: selector,
editLabel : labelName || Edit,
doneLabel : labelName || Done,
deleteLabel : labelName || Delete,
placement: left || right,
callback : callback
}
*/
if (!options || !options.list || !options instanceof Array) {
return;
}
var list = $(options.list);
var editLabel = options.editLabel || 'Edit';
var doneLabel = options.doneLabel || 'Done';
var deleteLabel = options.deleteLabel || 'Delete';
var placement = options.placement || 'right';
var callback = options.callback || $.noop;
var deleteButton;
var editButton;
var deletionIndicator;
var button;
var swipe = 'swiperight';
if ($('html').attr('dir') === 'rtl') swipe = 'swipeleft';
// Windows uses an icon for the delete button:
if ($.isWin) deleteLabel = '';
if (list[0].classList.contains('deletable')) return;
var height = $('li').eq(1)[0].clientHeight;
deleteButton = $.concat('<a href="javascript:void(null)" class="button delete">', deleteLabel, '</a>');
editButton = $.concat('<a href="javascript:void(null)" class="button edit">', editLabel, '</a>');
deletionIndicator = '<span class="deletion-indicator"></span>';
if (placement === 'left') {
list.closest('article').prev().prepend(editButton);
} else {
list.closest('article').prev().append(editButton);
list.closest('article').prev().find('h1').addClass('buttonOnRight');
list.closest('article').prev().find('.edit').addClass('align-flush');
button = list.closest('article').prev().find('.edit');
}
list.find('li').prepend(deletionIndicator);
list.find('li').append(deleteButton);
var setupDeletability = function(callback, list, button) {
var deleteSlide;
if ($.isiOS) {
deleteSlide = '100px';
} else if ($.isAndroid) {
deleteSlide = '140px';
}
$(function() {
button.on('singletap', function() {
var $this = this;
if (this.classList.contains('edit')) {
list.addClass('deletable');
setTimeout(function() {
$this.classList.remove('edit');
$this.classList.add('done');
$($this).text(doneLabel);
$(list).addClass('showIndicators');
});
} else if (this.classList.contains('done')) {
list.removeClass('deletable');
setTimeout(function() {
$this.classList.remove('done');
$this.classList.add('edit');
$($this).text(editLabel);
$(list).removeClass('showIndicators');
$(list).find('li').removeClass('selected');
});
}
});
$(list).on('singletap', '.deletion-indicator', function() {
if ($(this).parent('li').hasClass('selected')) {
$(this).parent('li').removeClass('selected');
return;
} else {
$(this).parent('li').addClass('selected');
}
});
if ($.isiOS || $.isSafari) {
$(list).on(swipe, 'li', function() {
$(this).removeClass('selected');
});
}
$(list).on('singletap', '.delete', function() {
var $this = this;
var direction = '-1000%';
if ($('html').attr('dir') === 'rtl') direction = '1000%';
$(this).siblings().css({'-webkit-transform': 'translate3d(' + direction + ',0,0)', '-webkit-transition': 'all 1s ease-out'});
setTimeout(function() {
callback.call(callback, $this);
$($this).parent().remove();
}, 500);
});
});
};
return setupDeletability(callback, list, button);
//return list;
}
});
$.fn.extend({
/////////////////////////
// Initialize Select List
/////////////////////////
/*
// For default selection use zero-based integer:
options = {
name : name // used on radio buttons as group name, defaults to uuid.
selected : integer,
callback : callback
// callback example:
function () {
// this is the selected list item:
console.log($(this).text());
}
}
*/
UISelectList : function (options) {
var name = (options && options.name) ? options.name : $.Uuid();
var list = this[0];
if (list && !$(list).hasClass('select')) {
this.addClass('select');
}
if (!list) return [];
list.classList.add('select');
$(list).find('li').forEach(function(ctx, idx) {
ctx.setAttribute('role', 'radio');
if (options && options.selected === idx) {
ctx.setAttribute('aria-checked', 'true');
ctx.classList.add('selected');
if (!$(ctx).find('input')[0]) {
$(ctx).append('<input type="radio" checked="checked" name="' + name + '">');
} else {
$(ctx).find('input').attr('checked','checked');
}
} else {
if (!$(ctx).find('input')[0]) {
$(ctx).append('<input type="radio" name="' + name + '">');
}
}
});
$(list).on('singletap', 'li', function() {
var item = this;
$(item).siblings('li').removeClass('selected');
$(item).siblings('li').removeAttr('aria-checked');
$(item).siblings('li').find('input').removeAttr('checked');
$(item).addClass('selected');
item.setAttribute('aria-checked', true);
$(item).find('input').attr('checked','checked');
if (options && options.callback) {
options.callback.apply(this, arguments);
}
});
}
});
$.extend({
///////////////////////////////////////////////
// UISheet: Create an Overlay for Buttons, etc.
///////////////////////////////////////////////
/*
var options {
id : 'starTrek',
listClass :'enterprise',
background: 'transparent',
}
*/
UISheet : function ( options ) {
var id = $.Uuid();
var listClass = '';
var background = '';
if (options) {
id = options.id ? options.id : id;
listClass = options.listClass ? ' ' + options.listClass : '';
background = ' style="background-color:' + options.background + ';" ' || '';
}
var sheet = '<div id="' + id + '" class="sheet' + listClass + '"><div class="handle"></div><section class="scroller-vertical"></section></div>';
$('body').append(sheet);
$('.sheet .handle').on($.eventStart, function() {
$.UIHideSheet();
});
},
UIShowSheet : function ( ) {
$('article.current').addClass('blurred');
if ($.isAndroid || $.isChrome) {
$('.sheet').css('display','block');
setTimeout(function() {
$('.sheet').addClass('opened');
}, 20);
} else {
$('.sheet').addClass('opened');
}
},
UIHideSheet : function ( ) {
$('.sheet').removeClass('opened');
$('article.current').addClass('removeBlurSlow');
setTimeout(function() {
$('article').removeClass('blurred');
$('article').removeClass('removeBlurSlow');
},500);
}
});
$.extend({
////////////////////////////////////////////////
// Create Slideout with toggle button.
// Use $.UISlideout.populate to polate slideout.
// See widget-factor.js for details.
////////////////////////////////////////////////
UISlideout : function ( position ) {
var slideoutButton = $("<a class='button slide-out-button' href='javascript:void(null)'></a>");
var slideOut = '<div class="slide-out"><section></section></div>';
$('article').removeClass('next');
$('article').removeClass('current');
$('article').prev().removeClass('next');
$('article').prev().removeClass('current');
position = position || 'left';
$('body').append(slideOut);
$('body').addClass('slide-out-app');
$('article:first-of-type').addClass('show');
$('article:first-of-type').prev().addClass('show');
$('#global-nav').append(slideoutButton);
$('.slide-out-button').on($.eventStart, function() {
$('.slide-out').toggleClass('open');
});
$('.slide-out').on('singletap', 'li', function() {
var whichArticle = '#' + $(this).attr('data-show-article');
$.UINavigationHistory[0] = whichArticle;
$.UISetHashOnUrl(whichArticle);
$.publish('chui/navigate/leave', $('article.show')[0].id);
$.publish('chui/navigate/enter', whichArticle);
$('.slide-out').removeClass('open');
$('article').removeClass('show');
$('article').prev().removeClass('show');
$(whichArticle).addClass('show');
$(whichArticle).prev().addClass('show');
});
}
});
$.extend($.UISlideout, {
/////////////////////////////////////////////////////////////////
// Method to populate a slideout with actionable items.
// The argument is an array of objects consisting of a key/value.
// The key will be the id of the article to be shown.
// The value is the title for the list item.
// [{music:'Music'},{docs:'Documents'},{recipes:'Recipes'}]
/////////////////////////////////////////////////////////////////
populate: function( args ) {
var slideout = $('.slide-out');
if (!slideout[0]) return;
if (!$.isArray(args)) {
return;
} else {
slideout.find('section').append('<ul class="list"></ul>');
var list = slideout.find('ul');
args.forEach(function(ctx) {
for (var key in ctx) {
if (key === 'header') {
list.append('<li class="slideout-header"><h2>'+ctx[key]+'</h2></li>');
} else {
list.append('<li data-show-article="' + key + '"><h3>' + ctx[key] + '</h3></li>');
}
}
});
}
}
});
$.fn.extend({
/////////////////
// Create stepper
/////////////////
/*
var options = {
start: 0,
end: 10,
defaultValue: 3
}
*/
UIStepper : function (options) {
if (!options) return [];
if (!options.start) return [];
if (!options.end) return [];
var stepper = $(this);
var start = options.start;
var end = options.end;
var defaultValue = options.defaultValue ? options.defaultValue : options.start;
var increaseSymbol = '+';
var decreaseSymbol = '-';
if ($.isWin) {
increaseSymbol = '';
decreaseSymbol = '';
}
var decreaseButton = '<a href="javascript:void(null)" class="button decrease">' + decreaseSymbol + '</a>';
var label = '<label>' + defaultValue + '</label><input type="text" value="' + defaultValue + '">';
var increaseButton = '<a href="javascript:void(null)" class="button increase">' + increaseSymbol + '</a>';
stepper.append(decreaseButton + label + increaseButton);
stepper.data('ui-value', {start: start, end: end, defaultValue: defaultValue});
var decreaseStepperValue = function() {
var currentValue = stepper.find('input').val();
var value = stepper.data('ui-value');
var start = value.start;
var newValue;
if (currentValue <= start) {
$(this).addClass('disabled');
} else {
newValue = Number(currentValue) - 1;
stepper.find('.button:last-of-type').removeClass('disabled');
stepper.find('label').text(newValue);
stepper.find('input')[0].value = newValue;
if (currentValue === start) {
$(this).addClass('disabled');
}
}
};
var increaseStepperValue = function() {
var currentValue = stepper.find('input').val();
var value = stepper.data('ui-value');
var end = value.end;
var newValue;
if (currentValue >= end) {
$(this).addClass('disabled');
} else {
newValue = Number(currentValue) + 1;
stepper.find('.button:first-of-type').removeClass('disabled');
stepper.find('label').text(newValue);
stepper.find('input')[0].value = newValue;
if (currentValue === end) {
$(this).addClass('disabled');
}
}
};
stepper.find('.button:first-of-type').on('singletap', function() {
decreaseStepperValue.call(this, stepper);
});
stepper.find('.button:last-of-type').on('singletap', function() {
increaseStepperValue.call(this, stepper);
});
}
});
$.extend({
///////////////////////////////////////////
// Pass the id of the stepper to reset.
// It's value will be reset to the default.
///////////////////////////////////////////
// Pass it the id of the stepper:
UIResetStepper : function ( stepper ) {
var defaultValue = stepper.data('ui-value').defaultValue;
stepper.find('label').html(defaultValue);
stepper.find('input')[0].value = defaultValue;
}
});
$.fn.extend({
////////////////////////////
// Initialize Switch Control
////////////////////////////
UISwitch : function ( ) {
var hasThumb = false;
this.forEach(function(ctx, idx) {
ctx.setAttribute('role','checkbox');
if ($(ctx).data('ui-setup') === true) return;
if (!ctx.querySelector('input')) {
ctx.insertAdjacentHTML('afterBegin', '<input type="checkbox">');
}
if (ctx.classList.contains('on')) {
ctx.querySelector('input').setAttribute('checked', 'checked');
}
if (ctx.querySelector('em')) hasThumb = true;
if (!hasThumb) {
ctx.insertAdjacentHTML('afterBegin', '<em></em>');
}
$(ctx).on('singletap', function() {
var checkbox = ctx.querySelector('input');
if (ctx.classList.contains('on')) {
ctx.classList.remove('on');
ctx.removeAttribute('aria-checked');
checkbox.removeAttribute('checked');
} else {
ctx.classList.add('on');
checkbox.setAttribute('checked', 'checked');
ctx.setAttribute('aria-checked', true);
}
});
$(ctx).on('swipeleft', function() {
var checkbox = ctx.querySelector('input');
if (ctx.classList.contains('on')) {
ctx.classList.remove('on');
ctx.removeAttribute('aria-checked');
checkbox.removeAttribute('checked');
}
});
$(ctx).on('swiperight', function() {
var checkbox = ctx.querySelector('input');
if (!ctx.classList.contains('on')) {
ctx.classList.add('on');
checkbox.setAttribute('checked', 'checked');
ctx.setAttribute('aria-checked', true);
}
});
$(ctx).data('ui-setup', true);
});
}
});
$.extend({
////////////////////////
// Create Switch Control
////////////////////////
UICreateSwitch : function ( options ) {
/* options = {
id : '#myId',
name: 'fruit.mango'
state : 'on' || 'off' //(off is default),
value : 'Mango' || '',
callback : callback
}
*/
var id = options ? options.id : $.Uuid();
var name = options && options.name ? (' name="' + options.name + '"') : '';
var value= options && options.value ? (' value="' + options.value + '"') : '';
var state = (options && options.state === 'on') ? (' ' + options.state) : '';
var checked = (options && options.state === 'on') ? ' checked="checked"' : '';
var _switch = $.concat('<span class="switch', state,
'" id="', id, '"><em></em>','<input type="checkbox"',
name, checked, value, '></span>');
return $(_switch);
}
});
$(function() {
//////////////////////////
// Handle Existing Switches:
//////////////////////////
$('.switch').UISwitch();
});
document.addEventListener('touchstart', function (e) {
var parent = e.target,
i = 0;
for (i = 0; i < 10; i += 1) {
if (parent !== null) {
if (parent.className !== undefined) {
if (parent.className.match('navigable')) {
if (parent.scrollTop === 0) {
parent.scrollTop = 1;
} else if ((parent.scrollTop + parent.offsetHeight) === parent.scrollHeight) {
parent.scrollTop = parent.scrollTop - 1;
}
}
}
parent = parent.parentNode;
}
}
});
$.extend({
///////////////////////////////////////////
// Creates a Tab Bar for Toggling Articles:
///////////////////////////////////////////
UITabbar : function ( options ) {
/*
var options = {
id: 'mySpecialTabbar',
tabs: 4,
labels: ["Refresh", "Add", "Info", "Downloads", "Favorite"],
icons: ["refresh", "add", "info", "downloads", "favorite"],
selected: 2
}
*/
if (!options) return;
$('body').addClass('hasTabBar');
if ($.isiOS6) $('body').addClass('isiOS6');
var id = options.id || $.Uuid();
var selected = options.selected || '';
var tabbar = '<div class="tabbar" id="' + id + '">';
var icon = ($.isiOS || $.isSafari) ? '<span class="icon"></span>' : '';
for (var i = 0; i < options.tabs; i++) {
tabbar += '<a class="button ' + options.icons[i];
if (selected === i+1) {
tabbar += ' selected';
}
tabbar += '">' + icon + '<label>' + options.labels[i] + '</label></a>';
}
tabbar += '</div>';
$('body').append(tabbar);
$('nav').removeClass('current').addClass('next');
$('nav').eq(selected).removeClass('next').addClass('current');
$('article').removeClass('current').addClass('next');
$('article').eq(selected-1).removeClass('next').addClass('current');
$('body').find('.tabbar').on('singletap', '.button', function() {
var $this = this;
var index;
var id;
$.publish('chui/navigate/leave', $('article.current')[0].id);
$this.classList.add('selected');
$(this).siblings('a').removeClass('selected');
index = $(this).index();
$('article.previous').removeClass('previous').addClass('next');
$('nav.previous').removeClass('previous').addClass('next');
$('article.current').removeClass('current').addClass('next');
$('nav.current').removeClass('current').addClass('next');
id = $('article').eq(index)[0].id;
$.publish('chui/navigate/enter', id);
if (window && window.jQuery) {
$('article').each(function(idx, ctx) {
$(ctx).scrollTop(0);
});
} else {
$('article').eq(index).siblings('article').forEach(function(ctx) {
ctx.scrollTop = 0;
});
}
$.UISetHashOnUrl('#'+id);
if ($.UINavigationHistory[0] === ('#' + id)) {
$.UINavigationHistory = [$.UINavigationHistory[0]];
} else if ($.UINavigationHistory.length === 1) {
if ($.UINavigationHistory[0] !== ('#' + id)) {
$.UINavigationHistory.push('#'+id);
}
} else if($.UINavigationHistory.length === 3) {
$.UINavigationHistory.pop();
} else {
$.UINavigationHistory[1] = '#'+id;
}
$('article').eq(index).removeClass('next').addClass('current');
$('nav').eq(index+1).removeClass('next').addClass('current');
});
}
});
$.extend({
/////////////////////////////
// Templating:
/////////////////////////////
templates : {},
template : function ( tmpl, variable ) {
var regex;
variable = variable || 'data';
regex = /\[\[=([\s\S]+?)\]\]/g;
var template = new Function(variable,
"var p=[];" + "p.push('" + tmpl
.replace(/[\r\t\n]/g, " ")
.split("'").join("\\'")
.replace(regex,"',$1,'")
.split('[[').join("');")
.split(']]').join("p.push('") + "');" +
"return p.join('');");
return template;
}
});
/////////////////////////
// Create a search input:
/////////////////////////
/*
$.UISearch({
articleId: '#products',
id: 'productSearch',
placeholder: 'Find a product',
results: 5
})
*/
$.extend({
UISearch : function(options) {
var article = options && options.articleId || $('article').eq(0);
var searchID = options && options.id || $.Uuid();
var placeholder = options && options.placeholder || 'search';
var results = options && options.results || 1;
var widget = '<div class="searchBar"><input placeholder="' + placeholder +'" type="search" results="' + results + '" id="'+ searchID + '"></div>';
$(article).find('section').prepend(widget);
if ($.isWin) {
$(article).prev().append(widget);
$('#' + searchID).parent().append('<span class="searchGlyph"></span>');
}
}
});
})(window.jQuery);
|
lozy219/Counter
|
static/js/chui-3.5.2.js
|
JavaScript
|
mit
| 69,261
|
/* eslint-disable react/no-array-index-key */
/* @flow */
import React from 'react';
import type { Node } from 'react';
import cn from 'classnames';
import { Dropdown, DropdownOption } from '../../Dropdown';
import type { FontFamilyConfig } from '../../../core/config';
export type Props = {
expanded: boolean,
onExpandEvent: Function,
doExpand: Function,
doCollapse: Function,
onChange: Function,
config: FontFamilyConfig,
currentState: any,
};
type State = {
defaultFontFamily: string,
};
class FontFamilyLayout extends React.Component<Props, State> {
state = {
defaultFontFamily: undefined,
};
componentDidMount(): void {
const editorElm = document.getElementsByClassName('DraftEditor-root');
if (editorElm && editorElm.length > 0) {
const styles = window.getComputedStyle(editorElm[0]);
const defaultFontFamily = styles.getPropertyValue('font-family');
this.setDefaultFam(defaultFontFamily);
}
}
setDefaultFam = defaultFont => {
this.setState({
defaultFontFamily: defaultFont,
});
};
props: Props;
render(): Node {
const { defaultFontFamily } = this.state;
const {
config: { options, title },
onChange,
expanded,
doCollapse,
onExpandEvent,
doExpand,
} = this.props;
let { currentState: { fontFamily: currentFontFamily } } = this.props;
currentFontFamily =
currentFontFamily ||
(options &&
defaultFontFamily &&
options.some(opt => opt.toLowerCase() === defaultFontFamily.toLowerCase()) &&
defaultFontFamily);
return (
<div className={cn('be-ctrl__group')} aria-label="be-fontfamily-control">
<Dropdown
onChange={onChange}
expanded={expanded}
doExpand={doExpand}
ariaLabel="be-dropdown-fontfamily-control"
doCollapse={doCollapse}
onExpandEvent={onExpandEvent}
title={title}>
<span className={cn('be-fontfamily__ph')}>{currentFontFamily || 'Font Family'}</span>
{options.map((family, index) => (
<DropdownOption active={currentFontFamily === family} value={family} key={index}>
{family}
</DropdownOption>
))}
</Dropdown>
</div>
);
}
}
export default FontFamilyLayout;
|
boldr/boldr
|
packages/editor/src/components/Controls/FontFamily/FontFamilyLayout.js
|
JavaScript
|
mit
| 2,326
|
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
// import 'core-js/es6/symbol';
// import 'core-js/es6/object';
// import 'core-js/es6/function';
// import 'core-js/es6/parse-int';
// import 'core-js/es6/parse-float';
// import 'core-js/es6/number';
// import 'core-js/es6/math';
// import 'core-js/es6/string';
// import 'core-js/es6/date';
// import 'core-js/es6/array';
// import 'core-js/es6/regexp';
// import 'core-js/es6/map';
// import 'core-js/es6/weak-map';
// import 'core-js/es6/set';
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js'; // Run `npm install --save classlist.js`.
/** IE10 and IE11 requires the following for the Reflect API. */
// import 'core-js/es6/reflect';
/** Evergreen browsers require these. **/
// Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove.
import 'core-js/es7/reflect';
/**
* Required to support Web Animations `@angular/platform-browser/animations`.
* Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation
**/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js/dist/zone'; // Included with Angular CLI.
/***************************************************************************************************
* APPLICATION IMPORTS
*/
|
wawyed/ng2
|
test-angular-versions/v5/src/polyfills.ts
|
TypeScript
|
mit
| 2,398
|
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var common = require('../common');
var assert = require('assert');
console.log('process.pid: ' + process.pid);
var first = 0,
second = 0;
var sighup = false;
process.addListener('SIGUSR1', function() {
console.log('Interrupted by SIGUSR1');
first += 1;
});
process.addListener('SIGUSR1', function() {
second += 1;
setTimeout(function() {
console.log('End.');
process.exit(0);
}, 5);
});
var i = 0;
setInterval(function() {
console.log('running process...' + ++i);
if (i == 5) {
process.kill(process.pid, 'SIGUSR1');
}
}, 1);
// Test addListener condition where a watcher for SIGNAL
// has been previously registered, and `process.listeners(SIGNAL).length === 1`
process.addListener('SIGHUP', function () {});
process.removeAllListeners('SIGHUP');
process.addListener('SIGHUP', function () { sighup = true });
process.kill(process.pid, 'SIGHUP');
process.addListener('exit', function() {
assert.equal(1, first);
assert.equal(1, second);
assert.equal(true, sighup);
});
|
csr1010/xmmagik
|
test/simple/test-signal-handler.js
|
JavaScript
|
mit
| 2,149
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace stress.codegen.utils
{
public interface IOutputWriter
{
void WriteInfo(string message);
void WriteWarning(string message);
void WriteError(string message);
}
public class ConsoleOutputWriter : IOutputWriter
{
public void WriteInfo(string message)
{
WriteToConsole(message);
}
public void WriteWarning(string message)
{
WriteToConsole(message, ConsoleColor.Yellow);
}
public void WriteError(string message)
{
WriteToConsole(message, ConsoleColor.Red);
}
private static void WriteToConsole(string message, ConsoleColor? color = null)
{
lock (s_consoleLock)
{
var origFgColor = Console.ForegroundColor;
if (color.HasValue)
{
Console.ForegroundColor = color.Value;
}
Console.WriteLine(message);
Console.ForegroundColor = origFgColor;
}
}
private static object s_consoleLock = new object();
}
//if TaskLog is
//outputs to the console with color formatting by default
public class CodeGenOutput
{
private static IOutputWriter s_writer = new ConsoleOutputWriter();
private CodeGenOutput() { }
//public static MSBuild.TaskLoggingHelper TaskLog { get; set; }
public static void Redirect(IOutputWriter writer)
{
s_writer = writer;
}
public static void Info(string message)
{
s_writer.WriteInfo(message);
}
public static void Warning(string message)
{
s_writer.WriteWarning(message);
}
public static void Error(string message)
{
s_writer.WriteError(message);
}
}
}
|
transsight/testproject
|
src/stress.codegen/utils/Output.cs
|
C#
|
mit
| 2,258
|
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
namespace EmptyKeys.UserInterface.Generator.Values
{
/// <summary>
/// Implements generator for DynamicResourceExtension
/// </summary>
public class ResourceExtGeneratorValue : IGeneratorValue
{
/// <summary>
/// Gets the type of the value.
/// </summary>
/// <value>
/// The type of the value.
/// </value>
public Type ValueType
{
get
{
return typeof(DynamicResourceExtension);
}
}
/// <summary>
/// Generates the specified parent class.
/// </summary>
/// <param name="parentClass">The parent class.</param>
/// <param name="method">The method.</param>
/// <param name="value">The value.</param>
/// <param name="baseName">Name of the base.</param>
/// <param name="dictionary">The dictionary.</param>
/// <returns></returns>
public CodeExpression Generate(CodeTypeDeclaration parentClass, CodeMemberMethod method, object value, string baseName, ResourceDictionary dictionary = null)
{
DynamicResourceExtension dynamicResource = value as DynamicResourceExtension;
return new CodeObjectCreateExpression("ResourceReferenceExpression", new CodePrimitiveExpression(dynamicResource.ResourceKey));
}
}
}
|
bbqchickenrobot/UI_Generator
|
UIGenerator/Values/ResourceExtGeneratorValue.cs
|
C#
|
mit
| 1,567
|
import Logger, { configure, levels } from '..';
import ConsoleHandler from 'nightingale-console';
import errorProcessor from 'nightingale-error-processor';
configure([
{
processors: [errorProcessor],
handlers: [new ConsoleHandler(levels.ALL)],
},
]);
const logger = new Logger('app');
logger.error(new Error('test'));
logger.error('test', { error: new Error('test') });
|
christophehurpeau/springbokjs-logger
|
examples/errors.js
|
JavaScript
|
mit
| 385
|
/*global module, require*/
'use strict';
function FtpMock() {
this.actions = {};
}
FtpMock.prototype.on = function (action, fn) {
this.actions[action] = fn;
};
FtpMock.prototype.connect = function (params) {
if (params.host !== 'rozklady.ztm.waw.pl') {
this.actions.error(new Error('Wrong address'));
} else {
this.actions.ready();
}
};
FtpMock.prototype.list = function (callback) {
callback(null, [{date: new Date(), name: 'RA123456.7z'}]);
};
FtpMock.prototype.end = function () {
};
module.exports = FtpMock;
|
stasm/ztm-parser
|
test/mock/ftp.js
|
JavaScript
|
mit
| 560
|
# frozen_string_literal: true
module ActiveRecord
module ConnectionAdapters
module OracleEnhanced
module JDBCQuoting
def _type_cast(value)
case value
when ActiveModel::Type::Binary::Data
blob = Java::OracleSql::BLOB.createTemporary(@connection.raw_connection, false, Java::OracleSql::BLOB::DURATION_SESSION)
blob.setBytes(1, value.to_s.to_java_bytes)
blob
when Type::OracleEnhanced::Text::Data
clob = Java::OracleSql::CLOB.createTemporary(@connection.raw_connection, false, Java::OracleSql::CLOB::DURATION_SESSION)
clob.setString(1, value.to_s)
clob
when Type::OracleEnhanced::NationalCharacterText::Data
clob = Java::OracleSql::NCLOB.createTemporary(@connection.raw_connection, false, Java::OracleSql::NCLOB::DURATION_SESSION)
clob.setString(1, value.to_s)
clob
else
super
end
end
end
end
end
end
module ActiveRecord
module ConnectionAdapters
module OracleEnhanced
module Quoting
prepend JDBCQuoting
end
end
end
end
|
cdinger/oracle-enhanced
|
lib/active_record/connection_adapters/oracle_enhanced/jdbc_quoting.rb
|
Ruby
|
mit
| 1,171
|
'use strict'
/**
* Protobuf interface
* from go-ipfs/pin/internal/pb/header.proto
*/
module.exports = `
syntax = "proto2";
package ipfs.pin;
option go_package = "pb";
message Set {
optional uint32 version = 1;
optional uint32 fanout = 2;
optional fixed32 seed = 3;
}
`
|
ipfs/node-ipfs
|
src/core/components/pin.proto.js
|
JavaScript
|
mit
| 298
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_66-internal) on Tue Dec 08 09:28:00 GMT 2015 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.jena.riot.thrift.wire (Apache Jena ARQ)</title>
<meta name="date" content="2015-12-08">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../../../org/apache/jena/riot/thrift/wire/package-summary.html" target="classFrame">org.apache.jena.riot.thrift.wire</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="RDF_ANY.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_ANY</a></li>
<li><a href="RDF_BNode.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_BNode</a></li>
<li><a href="RDF_DataTuple.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_DataTuple</a></li>
<li><a href="RDF_Decimal.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_Decimal</a></li>
<li><a href="RDF_IRI.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_IRI</a></li>
<li><a href="RDF_Literal.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_Literal</a></li>
<li><a href="RDF_PrefixDecl.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_PrefixDecl</a></li>
<li><a href="RDF_PrefixName.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_PrefixName</a></li>
<li><a href="RDF_Quad.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_Quad</a></li>
<li><a href="RDF_REPEAT.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_REPEAT</a></li>
<li><a href="RDF_StreamRow.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_StreamRow</a></li>
<li><a href="RDF_Term.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_Term</a></li>
<li><a href="RDF_Triple.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_Triple</a></li>
<li><a href="RDF_UNDEF.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_UNDEF</a></li>
<li><a href="RDF_VAR.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_VAR</a></li>
<li><a href="RDF_VarTuple.html" title="class in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_VarTuple</a></li>
</ul>
<h2 title="Enums">Enums</h2>
<ul title="Enums">
<li><a href="RDF_ANY._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_ANY._Fields</a></li>
<li><a href="RDF_BNode._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_BNode._Fields</a></li>
<li><a href="RDF_DataTuple._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_DataTuple._Fields</a></li>
<li><a href="RDF_Decimal._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_Decimal._Fields</a></li>
<li><a href="RDF_IRI._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_IRI._Fields</a></li>
<li><a href="RDF_Literal._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_Literal._Fields</a></li>
<li><a href="RDF_PrefixDecl._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_PrefixDecl._Fields</a></li>
<li><a href="RDF_PrefixName._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_PrefixName._Fields</a></li>
<li><a href="RDF_Quad._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_Quad._Fields</a></li>
<li><a href="RDF_REPEAT._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_REPEAT._Fields</a></li>
<li><a href="RDF_StreamRow._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_StreamRow._Fields</a></li>
<li><a href="RDF_Term._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_Term._Fields</a></li>
<li><a href="RDF_Triple._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_Triple._Fields</a></li>
<li><a href="RDF_UNDEF._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_UNDEF._Fields</a></li>
<li><a href="RDF_VAR._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_VAR._Fields</a></li>
<li><a href="RDF_VarTuple._Fields.html" title="enum in org.apache.jena.riot.thrift.wire" target="classFrame">RDF_VarTuple._Fields</a></li>
</ul>
</div>
</body>
</html>
|
manonsys/MVC
|
libs/Jena/javadoc-arq/org/apache/jena/riot/thrift/wire/package-frame.html
|
HTML
|
mit
| 5,002
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.11.4-master-5034a04
*/md-divider.md-THEME_NAME-theme{border-top-color:'{{foreground-4}}'}
|
t0930198/shoait
|
app/bower_components/angular-material/modules/js/divider/divider-default-theme.min.css
|
CSS
|
mit
| 182
|
'use strict';
module.exports = require('./CodeSlide');
|
AlexGilleran/babel-plugins-talk
|
spectacle-code-slide/lib/index.js
|
JavaScript
|
mit
| 55
|
/**
* Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.diirt.vtype;
import java.util.List;
/**
* Immutable VMultiDouble implementation.
*
* @author carcassi
*/
class IVMultiDouble extends IVNumeric implements VMultiDouble {
private final List<VDouble> values;
IVMultiDouble(List<VDouble> values, Alarm alarm, Time time, Display display) {
super(alarm, time, display);
this.values = values;
}
@Override
public List<VDouble> getValues() {
return values;
}
}
|
richardfearn/diirt
|
vtype/vtype/src/main/java/org/diirt/vtype/IVMultiDouble.java
|
Java
|
mit
| 617
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>XpkgHelper - FAKE - F# Make</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull">
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script src="http://code.jquery.com/ui/1.8.23/jquery-ui.js"></script>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" />
<script type="text/javascript" src="http://fsharp.github.io/FAKE/content/tips.js"></script>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li><a href="http://fsharp.org">fsharp.org</a></li>
<li><a href="http://github.com/fsharp/fake">github page</a></li>
</ul>
<h3 class="muted">FAKE - F# Make</h3>
</div>
<hr />
<div class="row">
<div class="span9" id="main">
<h1>XpkgHelper</h1>
<div class="xmldoc">
<p>Contains tasks to create packages in <a href="http://components.xamarin.com/">Xamarin's xpkg format</a></p>
</div>
<!-- Render nested types and modules, if there are any -->
<h2>Nested types and modules</h2>
<div>
<table class="table table-bordered type-list">
<thead>
<tr><td>Type</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="type-name">
<a href="fake-xpkghelper-xpkgparams.html">xpkgParams</a>
</td>
<td class="xmldoc"><p>Parameter type for xpkg tasks</p>
</td>
</tr>
</tbody>
</table>
</div>
<h3>Functions and values</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>Function or value</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '666', 666)" onmouseover="showTip(event, '666', 666)">
XpkgDefaults ()
</code>
<div class="tip" id="666">
<strong>Signature:</strong>unit -> xpkgParams<br />
</div>
</td>
<td class="xmldoc">
<p>Creates xpkg default parameters</p>
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/XpkgHelper.fs#L28-28" class="github-link">Go to GitHub source</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '667', 667)" onmouseover="showTip(event, '667', 667)">
xpkgPack setParams
</code>
<div class="tip" id="667">
<strong>Signature:</strong>setParams:(xpkgParams -> xpkgParams) -> unit<br />
</div>
</td>
<td class="xmldoc">
<p>Creates a new xpkg package based on the package file name</p>
<h2>Sample</h2>
<pre><code>Target "PackageXamarinDistribution" (fun _ ->
xpkgPack (fun p ->
{p with
ToolPath = xpkgExecutable;
Package = "Portable.Licensing";
Version = assemblyFileVersion;
OutputPath = publishDir
Project = "Portable.Licensing"
Summary = "Portable.Licensing is a cross platform licensing tool"
Publisher = "Nauck IT KG"
Website = "http://dev.nauck-it.de"
Details = "./Xamarin/Details.md"
License = "License.md"
GettingStarted = "./Xamarin/GettingStarted.md"
Icons = ["./Xamarin/Portable.Licensing_512x512.png"
"./Xamarin/Portable.Licensing_128x128.png"]
Libraries = ["mobile", "./Distribution/lib/Portable.Licensing.dll"]
Samples = ["Android Sample.", "./Samples/Android/Android.Sample.sln"
"iOS Sample.", "./Samples/iOS/iOS.Sample.sln"]
}
)
)
</code></pre>
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/XpkgHelper.fs#L76-76" class="github-link">Go to GitHub source</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '668', 668)" onmouseover="showTip(event, '668', 668)">
xpkgValidate setParams
</code>
<div class="tip" id="668">
<strong>Signature:</strong>setParams:(xpkgParams -> xpkgParams) -> unit<br />
</div>
</td>
<td class="xmldoc">
<p>Validates a xpkg package based on the package file name</p>
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/XpkgHelper.fs#L113-113" class="github-link">Go to GitHub source</a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="span3">
<img src="http://fsharp.github.io/FAKE/pics/logo.png" alt="FAKE - F# Make" style="width:150px;margin-left: 20px;" />
<ul class="nav nav-list" id="menu" style="margin-top: 20px;">
<li class="nav-header">FAKE - F# Make</li>
<li><a href="http://fsharp.github.io/FAKE/index.html">Home page</a></li>
<li class="divider"></li>
<li><a href="https://nuget.org/packages/Fake">Get FAKE via NuGet</a></li>
<li><a href="http://github.com/fsharp/fake">Source Code on GitHub</a></li>
<li><a href="https://github.com/fsharp/FAKE/blob/develop/License.txt">License (MS-PL)</a></li>
<li><a href="http://fsharp.github.io/FAKE/users.html">Who is using FAKE?</a></li>
<li><a href="http://fsharp.github.io/FAKE/RELEASE_NOTES.html">Release Notes</a></li>
<li><a href="http://fsharp.github.io/FAKE/contributing.html">Contributing to FAKE</a></li>
<li><a href="http://stackoverflow.com/questions/tagged/f%23-fake">Ask a question</a></li>
<li class="nav-header">Articles</li>
<li><a href="http://fsharp.github.io/FAKE/gettingstarted.html">Getting started</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/nuget.html">NuGet package restore</a></li>
<li><a href="http://fsharp.github.io/FAKE/fxcop.html">Using FxCop in a build</a></li>
<li><a href="http://fsharp.github.io/FAKE/assemblyinfo.html">Generating AssemblyInfo</a></li>
<li><a href="http://fsharp.github.io/FAKE/create-nuget-package.html">Create NuGet packages</a></li>
<li><a href="http://fsharp.github.io/FAKE/specifictargets.html">Running specific targets</a></li>
<li><a href="http://fsharp.github.io/FAKE/commandline.html">Running FAKE from command line</a></li>
<li><a href="http://fsharp.github.io/FAKE/customtasks.html">Creating custom tasks</a></li>
<li><a href="http://fsharp.github.io/FAKE/teamcity.html">TeamCity integration</a></li>
<li><a href="http://fsharp.github.io/FAKE/canopy.html">Running canopy tests</a></li>
<li><a href="http://fsharp.github.io/FAKE/octopusdeploy.html">Octopus Deploy</a></li>
<li><a href="http://fsharp.github.io/FAKE/typescript.html">TypeScript support</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/deploy.html">Fake.Deploy</a></li>
<li class="nav-header">Documentation</li>
<li><a href="http://fsharp.github.io/FAKE/apidocs/index.html">API Reference</a></li>
</ul>
</div>
</div>
</div>
<a href="http://github.com/fsharp/fake"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
</body>
</html>
|
TeaDrivenDev/Graphology
|
packages/FAKE/docs/apidocs/fake-xpkghelper.html
|
HTML
|
mit
| 8,360
|
/*! umbraco
* https://github.com/umbraco/umbraco-cms/
* Copyright (c) 2016 Umbraco HQ;
* Licensed
*/
(function() {
angular.module("umbraco.directives", ["umbraco.directives.editors", "umbraco.directives.html", "umbraco.directives.validation", "ui.sortable"]);
angular.module("umbraco.directives.editors", []);
angular.module("umbraco.directives.html", []);
angular.module("umbraco.directives.validation", []);
/**
* @ngdoc directive
* @name umbraco.directives.directive:autoScale
* @element div
* @deprecated
* We plan to remove this directive in the next major version of umbraco (8.0). The directive is not recommended to use.
* @function
* @description
* Resize div's automatically to fit to the bottom of the screen, as an optional parameter an y-axis offset can be set
* So if you only want to scale the div to 70 pixels from the bottom you pass "70"
* @example
* <example module="umbraco.directives">
* <file name="index.html">
* <div auto-scale="70" class="input-block-level"></div>
* </file>
* </example>
**/
angular.module("umbraco.directives")
.directive('autoScale', function ($window) {
return function (scope, el, attrs) {
var totalOffset = 0;
var offsety = parseInt(attrs.autoScale, 10);
var window = angular.element($window);
if (offsety !== undefined){
totalOffset += offsety;
}
setTimeout(function () {
el.height(window.height() - (el.offset().top + totalOffset));
}, 500);
window.bind("resize", function () {
el.height(window.height() - (el.offset().top + totalOffset));
});
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:detectFold
* @deprecated
* We plan to remove this directive in the next major version of umbraco (8.0). The directive is not recommended to use.
* @description This is used for the editor buttons to ensure they are displayed correctly if the horizontal overflow of the editor
* exceeds the height of the window
**/
angular.module("umbraco.directives.html")
.directive('detectFold', function ($timeout, $log, windowResizeListener) {
return {
require: "^?umbTabs",
restrict: 'A',
link: function (scope, el, attrs, tabsCtrl) {
var firstRun = false;
var parent = $(".umb-panel-body");
var winHeight = $(window).height();
var calculate = function () {
if (el && el.is(":visible") && !el.hasClass("umb-bottom-bar")) {
//now that the element is visible, set the flag in a couple of seconds,
// this will ensure that loading time of a current tab get's completed and that
// we eventually stop watching to save on CPU time
$timeout(function() {
firstRun = true;
}, 4000);
//var parent = el.parent();
var hasOverflow = parent.innerHeight() < parent[0].scrollHeight;
//var belowFold = (el.offset().top + el.height()) > winHeight;
if (hasOverflow) {
el.addClass("umb-bottom-bar");
//I wish we didn't have to put this logic here but unfortunately we
// do. This needs to calculate the left offest to place the bottom bar
// depending on if the left column splitter has been moved by the user
// (based on the nav-resize directive)
var wrapper = $("#mainwrapper");
var contentPanel = $("#leftcolumn").next();
var contentPanelLeftPx = contentPanel.css("left");
el.css({ left: contentPanelLeftPx });
}
}
return firstRun;
};
var resizeCallback = function(size) {
winHeight = size.height;
el.removeClass("umb-bottom-bar");
calculate();
};
windowResizeListener.register(resizeCallback);
//Only execute the watcher if this tab is the active (first) tab on load, otherwise there's no reason to execute
// the watcher since it will be recalculated when the tab changes!
if (el.closest(".umb-tab-pane").index() === 0) {
//run a watcher to ensure that the calculation occurs until it's firstRun but ensure
// the calculations are throttled to save a bit of CPU
var listener = scope.$watch(_.throttle(calculate, 1000), function (newVal, oldVal) {
if (newVal !== oldVal) {
listener();
}
});
}
//listen for tab changes
if (tabsCtrl != null) {
tabsCtrl.onTabShown(function (args) {
calculate();
});
}
//ensure to unregister
scope.$on('$destroy', function() {
windowResizeListener.unregister(resizeCallback);
});
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbItemSorter
* @deprecated
* We plan to remove this directive in the next major version of umbraco (8.0). The directive is not recommended to use.
* @function
* @element ANY
* @restrict E
* @description A re-usable directive for sorting items
**/
function umbItemSorter(angularHelper) {
return {
scope: {
model: "="
},
restrict: "E", // restrict to an element
replace: true, // replace the html element with the template
templateUrl: 'views/directives/_obsolete/umb-item-sorter.html',
link: function(scope, element, attrs, ctrl) {
var defaultModel = {
okButton: "Ok",
successMsg: "Sorting successful",
complete: false
};
//assign user vals to default
angular.extend(defaultModel, scope.model);
//re-assign merged to user
scope.model = defaultModel;
scope.performSort = function() {
scope.$emit("umbItemSorter.sorting", {
sortedItems: scope.model.itemsToSort
});
};
scope.handleCancel = function () {
scope.$emit("umbItemSorter.cancel");
};
scope.handleOk = function() {
scope.$emit("umbItemSorter.ok");
};
//defines the options for the jquery sortable
scope.sortableOptions = {
axis: 'y',
cursor: "move",
placeholder: "ui-sortable-placeholder",
update: function (ev, ui) {
//highlight the item when the position is changed
$(ui.item).effect("highlight", { color: "#049cdb" }, 500);
},
stop: function (ev, ui) {
//the ui-sortable directive already ensures that our list is re-sorted, so now we just
// need to update the sortOrder to the index of each item
angularHelper.safeApply(scope, function () {
angular.forEach(scope.itemsToSort, function (val, index) {
val.sortOrder = index + 1;
});
});
}
};
}
};
}
angular.module('umbraco.directives').directive("umbItemSorter", umbItemSorter);
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbContentName
* @deprecated
* We plan to remove this directive in the next major version of umbraco (8.0). The directive is not recommended to use.
* @restrict E
* @function
* @description
* Used by editors that require naming an entity. Shows a textbox/headline with a required validator within it's own form.
**/
angular.module("umbraco.directives")
.directive('umbContentName', function ($timeout, localizationService) {
return {
require: "ngModel",
restrict: 'E',
replace: true,
templateUrl: 'views/directives/_obsolete/umb-content-name.html',
scope: {
placeholder: '@placeholder',
model: '=ngModel',
ngDisabled: '='
},
link: function(scope, element, attrs, ngModel) {
var inputElement = element.find("input");
if(scope.placeholder && scope.placeholder[0] === "@"){
localizationService.localize(scope.placeholder.substring(1))
.then(function(value){
scope.placeholder = value;
});
}
var mX, mY, distance;
function calculateDistance(elem, mouseX, mouseY) {
var cx = Math.max(Math.min(mouseX, elem.offset().left + elem.width()), elem.offset().left);
var cy = Math.max(Math.min(mouseY, elem.offset().top + elem.height()), elem.offset().top);
return Math.sqrt((mouseX - cx) * (mouseX - cx) + (mouseY - cy) * (mouseY - cy));
}
var mouseMoveDebounce = _.throttle(function (e) {
mX = e.pageX;
mY = e.pageY;
// not focused and not over element
if (!inputElement.is(":focus") && !inputElement.hasClass("ng-invalid")) {
// on page
if (mX >= inputElement.offset().left) {
distance = calculateDistance(inputElement, mX, mY);
if (distance <= 155) {
distance = 1 - (100 / 150 * distance / 100);
inputElement.css("border", "1px solid rgba(175,175,175, " + distance + ")");
inputElement.css("background-color", "rgba(255,255,255, " + distance + ")");
}
}
}
}, 15);
$(document).bind("mousemove", mouseMoveDebounce);
$timeout(function(){
if(!scope.model){
scope.goEdit();
}
}, 100, false);
scope.goEdit = function(){
scope.editMode = true;
$timeout(function () {
inputElement.focus();
}, 100, false);
};
scope.exitEdit = function(){
if(scope.model && scope.model !== ""){
scope.editMode = false;
}
};
//unbind doc event!
scope.$on('$destroy', function () {
$(document).unbind("mousemove", mouseMoveDebounce);
});
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbHeader
* @deprecated
* We plan to remove this directive in the next major version of umbraco (8.0). The directive is not recommended to use.
* @restrict E
* @function
* @description
* The header on an editor that contains tabs using bootstrap tabs - THIS IS OBSOLETE, use umbTabHeader instead
**/
angular.module("umbraco.directives")
.directive('umbHeader', function ($parse, $timeout) {
return {
restrict: 'E',
replace: true,
transclude: 'true',
templateUrl: 'views/directives/_obsolete/umb-header.html',
//create a new isolated scope assigning a tabs property from the attribute 'tabs'
//which is bound to the parent scope property passed in
scope: {
tabs: "="
},
link: function (scope, iElement, iAttrs) {
scope.showTabs = iAttrs.tabs ? true : false;
scope.visibleTabs = [];
//since tabs are loaded async, we need to put a watch on them to determine
// when they are loaded, then we can close the watch
var tabWatch = scope.$watch("tabs", function (newValue, oldValue) {
angular.forEach(newValue, function(val, index){
var tab = {id: val.id, label: val.label};
scope.visibleTabs.push(tab);
});
//don't process if we cannot or have already done so
if (!newValue) {return;}
if (!newValue.length || newValue.length === 0){return;}
//we need to do a timeout here so that the current sync operation can complete
// and update the UI, then this will fire and the UI elements will be available.
$timeout(function () {
//use bootstrap tabs API to show the first one
iElement.find(".nav-tabs a:first").tab('show');
//enable the tab drop
iElement.find('.nav-pills, .nav-tabs').tabdrop();
//ensure to destroy tabdrop (unbinds window resize listeners)
scope.$on('$destroy', function () {
iElement.find('.nav-pills, .nav-tabs').tabdrop("destroy");
});
//stop watching now
tabWatch();
}, 200);
});
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbLogin
* @deprecated
* We plan to remove this directive in the next major version of umbraco (8.0). The directive is not recommended to use.
* @function
* @element ANY
* @restrict E
**/
function loginDirective() {
return {
restrict: "E", // restrict to an element
replace: true, // replace the html element with the template
templateUrl: 'views/directives/_obsolete/umb-login.html'
};
}
angular.module('umbraco.directives').directive("umbLogin", loginDirective);
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbOptionsMenu
* @deprecated
* We plan to remove this directive in the next major version of umbraco (8.0). The directive is not recommended to use.
* @function
* @element ANY
* @restrict E
**/
angular.module("umbraco.directives")
.directive('umbOptionsMenu', function ($injector, treeService, navigationService, umbModelMapper, appState) {
return {
scope: {
currentSection: "@",
currentNode: "="
},
restrict: 'E',
replace: true,
templateUrl: 'views/directives/_obsolete/umb-optionsmenu.html',
link: function (scope, element, attrs, ctrl) {
//adds a handler to the context menu item click, we need to handle this differently
//depending on what the menu item is supposed to do.
scope.executeMenuItem = function (action) {
navigationService.executeMenuAction(action, scope.currentNode, scope.currentSection);
};
//callback method to go and get the options async
scope.getOptions = function () {
if (!scope.currentNode) {
return;
}
//when the options item is selected, we need to set the current menu item in appState (since this is synonymous with a menu)
appState.setMenuState("currentNode", scope.currentNode);
if (!scope.actions) {
treeService.getMenu({ treeNode: scope.currentNode })
.then(function (data) {
scope.actions = data.menuItems;
});
}
};
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbPhotoFolder
* @deprecated
* We plan to remove this directive in the next major version of umbraco (8.0). The directive is not recommended to use.
* @restrict E
**/
angular.module("umbraco.directives.html")
.directive('umbPhotoFolder', function($compile, $log, $timeout, $filter, umbPhotoFolderHelper) {
return {
restrict: 'E',
replace: true,
require: '?ngModel',
terminate: true,
templateUrl: 'views/directives/_obsolete/umb-photo-folder.html',
link: function(scope, element, attrs, ngModel) {
var lastWatch = null;
ngModel.$render = function() {
if (ngModel.$modelValue) {
$timeout(function() {
var photos = ngModel.$modelValue;
scope.clickHandler = scope.$eval(element.attr('on-click'));
var imagesOnly = element.attr('images-only') === "true";
var margin = element.attr('border') ? parseInt(element.attr('border'), 10) : 5;
var startingIndex = element.attr('baseline') ? parseInt(element.attr('baseline'), 10) : 0;
var minWidth = element.attr('min-width') ? parseInt(element.attr('min-width'), 10) : 420;
var minHeight = element.attr('min-height') ? parseInt(element.attr('min-height'), 10) : 100;
var maxHeight = element.attr('max-height') ? parseInt(element.attr('max-height'), 10) : 300;
var idealImgPerRow = element.attr('ideal-items-per-row') ? parseInt(element.attr('ideal-items-per-row'), 10) : 5;
var fixedRowWidth = Math.max(element.width(), minWidth);
scope.containerStyle = { width: fixedRowWidth + "px" };
scope.rows = umbPhotoFolderHelper.buildGrid(photos, fixedRowWidth, maxHeight, startingIndex, minHeight, idealImgPerRow, margin, imagesOnly);
if (attrs.filterBy) {
//we track the watches that we create, we don't want to create multiple, so clear it
// if it already exists before creating another.
if (lastWatch) {
lastWatch();
}
//TODO: Need to debounce this so it doesn't filter too often!
lastWatch = scope.$watch(attrs.filterBy, function (newVal, oldVal) {
if (newVal && newVal !== oldVal) {
var p = $filter('filter')(photos, newVal, false);
scope.baseline = 0;
var m = umbPhotoFolderHelper.buildGrid(p, fixedRowWidth, maxHeight, startingIndex, minHeight, idealImgPerRow, margin, imagesOnly);
scope.rows = m;
}
});
}
}, 500); //end timeout
} //end if modelValue
}; //end $render
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbSort
* @deprecated
* We plan to remove this directive in the next major version of umbraco (8.0). The directive is not recommended to use.
*
* @element div
* @function
*
* @description
* Resize div's automatically to fit to the bottom of the screen, as an optional parameter an y-axis offset can be set
* So if you only want to scale the div to 70 pixels from the bottom you pass "70"
*
* @example
* <example module="umbraco.directives">
* <file name="index.html">
* <div umb-sort="70" class="input-block-level"></div>
* </file>
* </example>
**/
angular.module("umbraco.directives")
.value('umbSortContextInternal',{})
.directive('umbSort', function($log,umbSortContextInternal) {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
var adjustment;
var cfg = scope.$eval(element.attr('umb-sort')) || {};
scope.model = ngModel;
scope.opts = cfg;
scope.opts.containerSelector= cfg.containerSelector || ".umb-" + cfg.group + "-container",
scope.opts.nested= cfg.nested || true,
scope.opts.drop= cfg.drop || true,
scope.opts.drag= cfg.drag || true,
scope.opts.clone = cfg.clone || "<li/>";
scope.opts.mode = cfg.mode || "list";
scope.opts.itemSelectorFull = $.trim(scope.opts.itemPath + " " + scope.opts.itemSelector);
/*
scope.opts.isValidTarget = function(item, container) {
if(container.el.is(".umb-" + scope.opts.group + "-container")){
return true;
}
return false;
};
*/
element.addClass("umb-sort");
element.addClass("umb-" + cfg.group + "-container");
scope.opts.onDrag = function (item, position) {
if(scope.opts.mode === "list"){
item.css({
left: position.left - adjustment.left,
top: position.top - adjustment.top
});
}
};
scope.opts.onDrop = function (item, targetContainer, _super) {
if(scope.opts.mode === "list"){
//list mode
var clonedItem = $(scope.opts.clone).css({height: 0});
item.after(clonedItem);
clonedItem.animate({'height': item.height()});
item.animate(clonedItem.position(), function () {
clonedItem.detach();
_super(item);
});
}
var children = $(scope.opts.itemSelectorFull, targetContainer.el);
var targetIndex = children.index(item);
var targetScope = $(targetContainer.el[0]).scope();
if(targetScope === umbSortContextInternal.sourceScope){
if(umbSortContextInternal.sourceScope.opts.onSortHandler){
var _largs = {
oldIndex: umbSortContextInternal.sourceIndex,
newIndex: targetIndex,
scope: umbSortContextInternal.sourceScope
};
umbSortContextInternal.sourceScope.opts.onSortHandler.call(this, item, _largs);
}
}else{
if(targetScope.opts.onDropHandler){
var args = {
sourceScope: umbSortContextInternal.sourceScope,
sourceIndex: umbSortContextInternal.sourceIndex,
sourceContainer: umbSortContextInternal.sourceContainer,
targetScope: targetScope,
targetIndex: targetIndex,
targetContainer: targetContainer
};
targetScope.opts.onDropHandler.call(this, item, args);
}
if(umbSortContextInternal.sourceScope.opts.onReleaseHandler){
var _args = {
sourceScope: umbSortContextInternal.sourceScope,
sourceIndex: umbSortContextInternal.sourceIndex,
sourceContainer: umbSortContextInternal.sourceContainer,
targetScope: targetScope,
targetIndex: targetIndex,
targetContainer: targetContainer
};
umbSortContextInternal.sourceScope.opts.onReleaseHandler.call(this, item, _args);
}
}
};
scope.changeIndex = function(from, to){
scope.$apply(function(){
var i = ngModel.$modelValue.splice(from, 1)[0];
ngModel.$modelValue.splice(to, 0, i);
});
};
scope.move = function(args){
var from = args.sourceIndex;
var to = args.targetIndex;
if(args.sourceContainer === args.targetContainer){
scope.changeIndex(from, to);
}else{
scope.$apply(function(){
var i = args.sourceScope.model.$modelValue.splice(from, 1)[0];
args.targetScope.model.$modelvalue.splice(to,0, i);
});
}
};
scope.opts.onDragStart = function (item, container, _super) {
var children = $(scope.opts.itemSelectorFull, container.el);
var offset = item.offset();
umbSortContextInternal.sourceIndex = children.index(item);
umbSortContextInternal.sourceScope = $(container.el[0]).scope();
umbSortContextInternal.sourceContainer = container;
//current.item = ngModel.$modelValue.splice(current.index, 1)[0];
var pointer = container.rootGroup.pointer;
adjustment = {
left: pointer.left - offset.left,
top: pointer.top - offset.top
};
_super(item, container);
};
element.sortable( scope.opts );
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbTabView
* @deprecated
* We plan to remove this directive in the next major version of umbraco (8.0). The directive is not recommended to use.
*
* @restrict E
**/
angular.module("umbraco.directives")
.directive('umbTabView', function($timeout, $log){
return {
restrict: 'E',
replace: true,
transclude: 'true',
templateUrl: 'views/directives/_obsolete/umb-tab-view.html'
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbUploadDropzone
* @deprecated
* We plan to remove this directive in the next major version of umbraco (8.0). The directive is not recommended to use.
*
* @restrict E
**/
angular.module("umbraco.directives.html")
.directive('umbUploadDropzone', function(){
return {
restrict: 'E',
replace: true,
templateUrl: 'views/directives/_obsolete/umb-upload-dropzone.html'
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:navResize
* @restrict A
*
* @description
* Handles how the navigation responds to window resizing and controls how the draggable resize panel works
**/
angular.module("umbraco.directives")
.directive('navResize', function (appState, eventsService, windowResizeListener) {
return {
restrict: 'A',
link: function (scope, element, attrs, ctrl) {
var minScreenSize = 1100;
var resizeEnabled = false;
function setTreeMode() {
appState.setGlobalState("showNavigation", appState.getGlobalState("isTablet") === false);
}
function enableResize() {
//only enable when the size is correct and it's not already enabled
if (!resizeEnabled && appState.getGlobalState("isTablet") === false) {
element.resizable(
{
containment: $("#mainwrapper"),
autoHide: true,
handles: "e",
alsoResize: ".navigation-inner-container",
resize: function(e, ui) {
var wrapper = $("#mainwrapper");
var contentPanel = $("#contentwrapper");
var umbNotification = $("#umb-notifications-wrapper");
var apps = $("#applications");
var bottomBar = contentPanel.find(".umb-bottom-bar");
var navOffeset = $("#navOffset");
var leftPanelWidth = ui.element.width() + apps.width();
contentPanel.css({ left: leftPanelWidth });
bottomBar.css({ left: leftPanelWidth });
umbNotification.css({ left: leftPanelWidth });
navOffeset.css({ "margin-left": ui.element.outerWidth() });
},
stop: function (e, ui) {
}
});
resizeEnabled = true;
}
}
function resetResize() {
if (resizeEnabled) {
//kill the resize
element.resizable("destroy");
element.css("width", "");
var navInnerContainer = element.find(".navigation-inner-container");
navInnerContainer.css("width", "");
$("#contentwrapper").css("left", "");
$("#umb-notifications-wrapper").css("left", "");
$("#navOffset").css("margin-left", "");
resizeEnabled = false;
}
}
var evts = [];
//Listen for global state changes
evts.push(eventsService.on("appState.globalState.changed", function (e, args) {
if (args.key === "showNavigation") {
if (args.value === false) {
resetResize();
}
else {
enableResize();
}
}
}));
var resizeCallback = function(size) {
//set the global app state
appState.setGlobalState("isTablet", (size.width <= minScreenSize));
setTreeMode();
};
windowResizeListener.register(resizeCallback);
//ensure to unregister from all events and kill jquery plugins
scope.$on('$destroy', function () {
windowResizeListener.unregister(resizeCallback);
for (var e in evts) {
eventsService.unsubscribe(evts[e]);
}
var navInnerContainer = element.find(".navigation-inner-container");
navInnerContainer.resizable("destroy");
});
//init
//set the global app state
appState.setGlobalState("isTablet", ($(window).width() <= minScreenSize));
setTreeMode();
}
};
});
angular.module("umbraco.directives")
.directive('sectionIcon', function ($compile, iconHelper) {
return {
restrict: 'E',
replace: true,
link: function (scope, element, attrs) {
var icon = attrs.icon;
if (iconHelper.isLegacyIcon(icon)) {
//its a known legacy icon, convert to a new one
element.html("<i class='" + iconHelper.convertFromLegacyIcon(icon) + "'></i>");
}
else if (iconHelper.isFileBasedIcon(icon)) {
var convert = iconHelper.convertFromLegacyImage(icon);
if(convert){
element.html("<i class='icon-section " + convert + "'></i>");
}else{
element.html("<img class='icon-section' src='images/tray/" + icon + "'>");
}
//it's a file, normally legacy so look in the icon tray images
}
else {
//it's normal
element.html("<i class='icon-section " + icon + "'></i>");
}
}
};
});
angular.module("umbraco.directives")
.directive('umbContextMenu', function (navigationService) {
return {
scope: {
menuDialogTitle: "@",
currentSection: "@",
currentNode: "=",
menuActions: "="
},
restrict: 'E',
replace: true,
templateUrl: 'views/components/application/umb-contextmenu.html',
link: function (scope, element, attrs, ctrl) {
//adds a handler to the context menu item click, we need to handle this differently
//depending on what the menu item is supposed to do.
scope.executeMenuItem = function (action) {
navigationService.executeMenuAction(action, scope.currentNode, scope.currentSection);
};
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbNavigation
* @restrict E
**/
function umbNavigationDirective() {
return {
restrict: "E", // restrict to an element
replace: true, // replace the html element with the template
templateUrl: 'views/components/application/umb-navigation.html'
};
}
angular.module('umbraco.directives').directive("umbNavigation", umbNavigationDirective);
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbSections
* @restrict E
**/
function sectionsDirective($timeout, $window, navigationService, treeService, sectionResource, appState, eventsService, $location) {
return {
restrict: "E", // restrict to an element
replace: true, // replace the html element with the template
templateUrl: 'views/components/application/umb-sections.html',
link: function (scope, element, attr, ctrl) {
//setup scope vars
scope.maxSections = 7;
scope.overflowingSections = 0;
scope.sections = [];
scope.currentSection = appState.getSectionState("currentSection");
scope.showTray = false; //appState.getGlobalState("showTray");
scope.stickyNavigation = appState.getGlobalState("stickyNavigation");
scope.needTray = false;
scope.trayAnimation = function() {
if (scope.showTray) {
return 'slide';
}
else if (scope.showTray === false) {
return 'slide';
}
else {
return '';
}
};
function loadSections(){
sectionResource.getSections()
.then(function (result) {
scope.sections = result;
calculateHeight();
});
}
function calculateHeight(){
$timeout(function(){
//total height minus room for avatar and help icon
var height = $(window).height()-200;
scope.totalSections = scope.sections.length;
scope.maxSections = Math.floor(height / 70);
scope.needTray = false;
if(scope.totalSections > scope.maxSections){
scope.needTray = true;
scope.overflowingSections = scope.maxSections - scope.totalSections;
}
});
}
var evts = [];
//Listen for global state changes
evts.push(eventsService.on("appState.globalState.changed", function(e, args) {
if (args.key === "showTray") {
scope.showTray = args.value;
}
if (args.key === "stickyNavigation") {
scope.stickyNavigation = args.value;
}
}));
evts.push(eventsService.on("appState.sectionState.changed", function(e, args) {
if (args.key === "currentSection") {
scope.currentSection = args.value;
}
}));
evts.push(eventsService.on("app.reInitialize", function(e, args) {
//re-load the sections if we're re-initializing (i.e. package installed)
loadSections();
}));
//ensure to unregister from all events!
scope.$on('$destroy', function () {
for (var e in evts) {
eventsService.unsubscribe(evts[e]);
}
});
//on page resize
window.onresize = calculateHeight;
scope.avatarClick = function(){
if(scope.helpDialog) {
closeHelpDialog();
}
if(!scope.userDialog) {
scope.userDialog = {
view: "user",
show: true,
close: function(oldModel) {
closeUserDialog();
}
};
} else {
closeUserDialog();
}
};
function closeUserDialog() {
scope.userDialog.show = false;
scope.userDialog = null;
}
scope.helpClick = function(){
if(scope.userDialog) {
closeUserDialog();
}
if(!scope.helpDialog) {
scope.helpDialog = {
view: "help",
show: true,
close: function(oldModel) {
closeHelpDialog();
}
};
} else {
closeHelpDialog();
}
};
function closeHelpDialog() {
scope.helpDialog.show = false;
scope.helpDialog = null;
}
scope.sectionClick = function (event, section) {
if (event.ctrlKey ||
event.shiftKey ||
event.metaKey || // apple
(event.button && event.button === 1) // middle click, >IE9 + everyone else
) {
return;
}
if (scope.userDialog) {
closeUserDialog();
}
if (scope.helpDialog) {
closeHelpDialog();
}
navigationService.hideSearch();
navigationService.showTree(section.alias);
$location.path("/" + section.alias);
};
scope.sectionDblClick = function(section){
navigationService.reloadSection(section.alias);
};
scope.trayClick = function () {
// close dialogs
if (scope.userDialog) {
closeUserDialog();
}
if (scope.helpDialog) {
closeHelpDialog();
}
if (appState.getGlobalState("showTray") === true) {
navigationService.hideTray();
} else {
navigationService.showTray();
}
};
loadSections();
}
};
}
angular.module('umbraco.directives').directive("umbSections", sectionsDirective);
/**
@ngdoc directive
@name umbraco.directives.directive:umbButton
@restrict E
@scope
@description
Use this directive to render an umbraco button. The directive can be used to generate all types of buttons, set type, style, translation, shortcut and much more.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-button
action="vm.clickButton()"
type="button"
button-style="success"
state="vm.buttonState"
shortcut="ctrl+c"
label="My button"
disabled="vm.buttonState === 'busy'">
</umb-button>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller(myService) {
var vm = this;
vm.buttonState = "init";
vm.clickButton = clickButton;
function clickButton() {
vm.buttonState = "busy";
myService.clickButton().then(function() {
vm.buttonState = "success";
}, function() {
vm.buttonState = "error";
});
}
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {callback} action The button action which should be performed when the button is clicked.
@param {string=} href Url/Path to navigato to.
@param {string=} type Set the button type ("button" or "submit").
@param {string=} buttonStyle Set the style of the button. The directive uses the default bootstrap styles ("primary", "info", "success", "warning", "danger", "inverse", "link").
@param {string=} state Set a progress state on the button ("init", "busy", "success", "error").
@param {string=} shortcut Set a keyboard shortcut for the button ("ctrl+c").
@param {string=} label Set the button label.
@param {string=} labelKey Set a localization key to make a multi lingual button ("general_buttonText").
@param {string=} icon Set a button icon. Can only be used when buttonStyle is "link".
@param {boolean=} disabled Set to <code>true</code> to disable the button.
**/
(function() {
'use strict';
function ButtonDirective($timeout) {
function link(scope, el, attr, ctrl) {
scope.style = null;
function activate() {
if (!scope.state) {
scope.state = "init";
}
if (scope.buttonStyle) {
scope.style = "btn-" + scope.buttonStyle;
}
}
activate();
var unbindStateWatcher = scope.$watch('state', function(newValue, oldValue) {
if (newValue === 'success' || newValue === 'error') {
$timeout(function() {
scope.state = 'init';
}, 2000);
}
});
scope.$on('$destroy', function() {
unbindStateWatcher();
});
}
var directive = {
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/buttons/umb-button.html',
link: link,
scope: {
action: "&?",
href: "@?",
type: "@",
buttonStyle: "@?",
state: "=?",
shortcut: "@?",
shortcutWhenHidden: "@",
label: "@?",
labelKey: "@?",
icon: "@?",
disabled: "="
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbButton', ButtonDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbButtonGroup
@restrict E
@scope
@description
Use this directive to render a button with a dropdown of alternative actions.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-button-group
ng-if="vm.buttonGroup"
default-button="vm.buttonGroup.defaultButton"
sub-buttons="vm.buttonGroup.subButtons"
direction="down"
float="right">
</umb-button-group>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.buttonGroup = {
defaultButton: {
labelKey: "general_defaultButton",
hotKey: "ctrl+d",
hotKeyWhenHidden: true,
handler: function() {
// do magic here
}
},
subButtons: [
{
labelKey: "general_subButton",
hotKey: "ctrl+b",
hotKeyWhenHidden: true,
handler: function() {
// do magic here
}
}
]
};
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
<h3>Button model description</h3>
<ul>
<li>
<strong>labekKey</strong>
<small>(string)</small> -
Set a localization key to make a multi lingual button ("general_buttonText").
</li>
<li>
<strong>hotKey</strong>
<small>(array)</small> -
Set a keyboard shortcut for the button ("ctrl+c").
</li>
<li>
<strong>hotKeyWhenHidden</strong>
<small>(boolean)</small> -
As a default the hotkeys only works on elements visible in the UI. Set to <code>true</code> to set a hotkey on the hidden sub buttons.
</li>
<li>
<strong>handler</strong>
<small>(callback)</small> -
Set a callback to handle button click events.
</li>
</ul>
@param {object} defaultButton The model of the default button.
@param {array} subButtons Array of sub buttons.
@param {string=} state Set a progress state on the button ("init", "busy", "success", "error").
@param {string=} direction Set the direction of the dropdown ("up", "down").
@param {string=} float Set the float of the dropdown. ("left", "right").
**/
(function() {
'use strict';
function ButtonGroupDirective() {
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/buttons/umb-button-group.html',
scope: {
defaultButton: "=",
subButtons: "=",
state: "=?",
direction: "@?",
float: "@?"
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbButtonGroup', ButtonGroupDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbEditorSubHeader
@restrict E
@description
Use this directive to construct a sub header in the main editor window.
The sub header is sticky and will follow along down the page when scrolling.
<h3>Markup example</h3>
<pre>
<div ng-controller="MySection.Controller as vm">
<form name="mySectionForm" novalidate>
<umb-editor-view>
<umb-editor-container>
<umb-editor-sub-header>
// sub header content here
</umb-editor-sub-header>
</umb-editor-container>
</umb-editor-view>
</form>
</div>
</pre>
<h3>Use in combination with</h3>
<ul>
<li>{@link umbraco.directives.directive:umbEditorSubHeaderContentLeft umbEditorSubHeaderContentLeft}</li>
<li>{@link umbraco.directives.directive:umbEditorSubHeaderContentRight umbEditorSubHeaderContentRight}</li>
<li>{@link umbraco.directives.directive:umbEditorSubHeaderSection umbEditorSubHeaderSection}</li>
</ul>
**/
(function() {
'use strict';
function EditorSubHeaderDirective() {
var directive = {
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/subheader/umb-editor-sub-header.html'
};
return directive;
}
angular.module('umbraco.directives').directive('umbEditorSubHeader', EditorSubHeaderDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbEditorSubHeaderContentLeft
@restrict E
@description
Use this directive to left align content in a sub header in the main editor window.
<h3>Markup example</h3>
<pre>
<div ng-controller="MySection.Controller as vm">
<form name="mySectionForm" novalidate>
<umb-editor-view>
<umb-editor-container>
<umb-editor-sub-header>
<umb-editor-sub-header-content-left>
// left content here
</umb-editor-sub-header-content-left>
<umb-editor-sub-header-content-right>
// right content here
</umb-editor-sub-header-content-right>
</umb-editor-sub-header>
</umb-editor-container>
</umb-editor-view>
</form>
</div>
</pre>
<h3>Use in combination with</h3>
<ul>
<li>{@link umbraco.directives.directive:umbEditorSubHeader umbEditorSubHeader}</li>
<li>{@link umbraco.directives.directive:umbEditorSubHeaderContentRight umbEditorSubHeaderContentRight}</li>
<li>{@link umbraco.directives.directive:umbEditorSubHeaderSection umbEditorSubHeaderSection}</li>
</ul>
**/
(function() {
'use strict';
function EditorSubHeaderContentLeftDirective() {
var directive = {
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/subheader/umb-editor-sub-header-content-left.html'
};
return directive;
}
angular.module('umbraco.directives').directive('umbEditorSubHeaderContentLeft', EditorSubHeaderContentLeftDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbEditorSubHeaderContentRight
@restrict E
@description
Use this directive to rigt align content in a sub header in the main editor window.
<h3>Markup example</h3>
<pre>
<div ng-controller="MySection.Controller as vm">
<form name="mySectionForm" novalidate>
<umb-editor-view>
<umb-editor-container>
<umb-editor-sub-header>
<umb-editor-sub-header-content-left>
// left content here
</umb-editor-sub-header-content-left>
<umb-editor-sub-header-content-right>
// right content here
</umb-editor-sub-header-content-right>
</umb-editor-sub-header>
</umb-editor-container>
</umb-editor-view>
</form>
</div>
</pre>
<h3>Use in combination with</h3>
<ul>
<li>{@link umbraco.directives.directive:umbEditorSubHeader umbEditorSubHeader}</li>
<li>{@link umbraco.directives.directive:umbEditorSubHeaderContentLeft umbEditorSubHeaderContentLeft}</li>
<li>{@link umbraco.directives.directive:umbEditorSubHeaderSection umbEditorSubHeaderSection}</li>
</ul>
**/
(function() {
'use strict';
function EditorSubHeaderContentRightDirective() {
var directive = {
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/subheader/umb-editor-sub-header-content-right.html'
};
return directive;
}
angular.module('umbraco.directives').directive('umbEditorSubHeaderContentRight', EditorSubHeaderContentRightDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbEditorSubHeaderSection
@restrict E
@description
Use this directive to create sections, divided by borders, in a sub header in the main editor window.
<h3>Markup example</h3>
<pre>
<div ng-controller="MySection.Controller as vm">
<form name="mySectionForm" novalidate>
<umb-editor-view>
<umb-editor-container>
<umb-editor-sub-header>
<umb-editor-sub-header-content-right>
<umb-editor-sub-header-section>
// section content here
</umb-editor-sub-header-section>
<umb-editor-sub-header-section>
// section content here
</umb-editor-sub-header-section>
<umb-editor-sub-header-section>
// section content here
</umb-editor-sub-header-section>
</umb-editor-sub-header-content-right>
</umb-editor-sub-header>
</umb-editor-container>
</umb-editor-view>
</form>
</div>
</pre>
<h3>Use in combination with</h3>
<ul>
<li>{@link umbraco.directives.directive:umbEditorSubHeader umbEditorSubHeader}</li>
<li>{@link umbraco.directives.directive:umbEditorSubHeaderContentLeft umbEditorSubHeaderContentLeft}</li>
<li>{@link umbraco.directives.directive:umbEditorSubHeaderContentRight umbEditorSubHeaderContentRight}</li>
</ul>
**/
(function() {
'use strict';
function EditorSubHeaderSectionDirective() {
var directive = {
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/subheader/umb-editor-sub-header-section.html'
};
return directive;
}
angular.module('umbraco.directives').directive('umbEditorSubHeaderSection', EditorSubHeaderSectionDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbBreadcrumbs
@restrict E
@scope
@description
Use this directive to generate a list of breadcrumbs.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-breadcrumbs
ng-if="vm.ancestors && vm.ancestors.length > 0"
ancestors="vm.ancestors"
entity-type="content">
</umb-breadcrumbs>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller(myService) {
var vm = this;
vm.ancestors = [];
myService.getAncestors().then(function(ancestors){
vm.ancestors = ancestors;
});
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {array} ancestors Array of ancestors
@param {string} entityType The content entity type (member, media, content).
**/
(function() {
'use strict';
function BreadcrumbsDirective() {
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/umb-breadcrumbs.html',
scope: {
ancestors: "=",
entityType: "@"
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbBreadcrumbs', BreadcrumbsDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbEditorContainer
@restrict E
@description
Use this directive to construct a main content area inside the main editor window.
<h3>Markup example</h3>
<pre>
<div ng-controller="Umbraco.Controller as vm">
<umb-editor-view>
<umb-editor-header
// header configuration>
</umb-editor-header>
<umb-editor-container>
// main content here
</umb-editor-container>
<umb-editor-footer>
// footer content here
</umb-editor-footer>
</umb-editor-view>
</div>
</pre>
<h3>Use in combination with</h3>
<ul>
<li>{@link umbraco.directives.directive:umbEditorView umbEditorView}</li>
<li>{@link umbraco.directives.directive:umbEditorHeader umbEditorHeader}</li>
<li>{@link umbraco.directives.directive:umbEditorFooter umbEditorFooter}</li>
</ul>
**/
(function() {
'use strict';
function EditorContainerDirective(overlayHelper) {
function link(scope, el, attr, ctrl) {
scope.numberOfOverlays = 0;
scope.$watch(function(){
return overlayHelper.getNumberOfOverlays();
}, function (newValue) {
scope.numberOfOverlays = newValue;
});
}
var directive = {
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/umb-editor-container.html',
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbEditorContainer', EditorContainerDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbEditorFooter
@restrict E
@description
Use this directive to construct a footer inside the main editor window.
<h3>Markup example</h3>
<pre>
<div ng-controller="MySection.Controller as vm">
<form name="mySectionForm" novalidate>
<umb-editor-view>
<umb-editor-header
// header configuration>
</umb-editor-header>
<umb-editor-container>
// main content here
</umb-editor-container>
<umb-editor-footer>
// footer content here
</umb-editor-footer>
</umb-editor-view>
</form>
</div>
</pre>
<h3>Use in combination with</h3>
<ul>
<li>{@link umbraco.directives.directive:umbEditorView umbEditorView}</li>
<li>{@link umbraco.directives.directive:umbEditorHeader umbEditorHeader}</li>
<li>{@link umbraco.directives.directive:umbEditorContainer umbEditorContainer}</li>
<li>{@link umbraco.directives.directive:umbEditorFooterContentLeft umbEditorFooterContentLeft}</li>
<li>{@link umbraco.directives.directive:umbEditorFooterContentRight umbEditorFooterContentRight}</li>
</ul>
**/
(function() {
'use strict';
function EditorFooterDirective() {
var directive = {
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/umb-editor-footer.html'
};
return directive;
}
angular.module('umbraco.directives').directive('umbEditorFooter', EditorFooterDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbEditorFooterContentLeft
@restrict E
@description
Use this directive to align content left inside the main editor footer.
<h3>Markup example</h3>
<pre>
<div ng-controller="MySection.Controller as vm">
<form name="mySectionForm" novalidate>
<umb-editor-view>
<umb-editor-footer>
<umb-editor-footer-content-left>
// align content left
</umb-editor-footer-content-left>
<umb-editor-footer-content-right>
// align content right
</umb-editor-footer-content-right>
</umb-editor-footer>
</umb-editor-view>
</form>
</div>
</pre>
<h3>Use in combination with</h3>
<ul>
<li>{@link umbraco.directives.directive:umbEditorView umbEditorView}</li>
<li>{@link umbraco.directives.directive:umbEditorHeader umbEditorHeader}</li>
<li>{@link umbraco.directives.directive:umbEditorContainer umbEditorContainer}</li>
<li>{@link umbraco.directives.directive:umbEditorFooter umbEditorFooter}</li>
<li>{@link umbraco.directives.directive:umbEditorFooterContentRight umbEditorFooterContentRight}</li>
</ul>
**/
(function() {
'use strict';
function EditorFooterContentLeftDirective() {
var directive = {
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/umb-editor-footer-content-left.html'
};
return directive;
}
angular.module('umbraco.directives').directive('umbEditorFooterContentLeft', EditorFooterContentLeftDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbEditorFooterContentRight
@restrict E
@description
Use this directive to align content right inside the main editor footer.
<h3>Markup example</h3>
<pre>
<div ng-controller="MySection.Controller as vm">
<form name="mySectionForm" novalidate>
<umb-editor-view>
<umb-editor-footer>
<umb-editor-footer-content-left>
// align content left
</umb-editor-footer-content-left>
<umb-editor-footer-content-right>
// align content right
</umb-editor-footer-content-right>
</umb-editor-footer>
</umb-editor-view>
</form>
</div>
</pre>
<h3>Use in combination with</h3>
<ul>
<li>{@link umbraco.directives.directive:umbEditorView umbEditorView}</li>
<li>{@link umbraco.directives.directive:umbEditorHeader umbEditorHeader}</li>
<li>{@link umbraco.directives.directive:umbEditorContainer umbEditorContainer}</li>
<li>{@link umbraco.directives.directive:umbEditorFooter umbEditorFooter}</li>
<li>{@link umbraco.directives.directive:umbEditorFooterContentLeft umbEditorFooterContentLeft}</li>
</ul>
**/
(function() {
'use strict';
function EditorFooterContentRightDirective() {
var directive = {
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/umb-editor-footer-content-right.html'
};
return directive;
}
angular.module('umbraco.directives').directive('umbEditorFooterContentRight', EditorFooterContentRightDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbEditorHeader
@restrict E
@scope
@description
Use this directive to construct a header inside the main editor window.
<h3>Markup example</h3>
<pre>
<div ng-controller="MySection.Controller as vm">
<form name="mySectionForm" novalidate>
<umb-editor-view>
<umb-editor-header
name="vm.content.name"
hide-alias="true"
hide-description="true"
hide-icon="true">
</umb-editor-header>
<umb-editor-container>
// main content here
</umb-editor-container>
<umb-editor-footer>
// footer content here
</umb-editor-footer>
</umb-editor-view>
</form>
</div>
</pre>
<h3>Markup example - with tabs</h3>
<pre>
<div ng-controller="MySection.Controller as vm">
<form name="mySectionForm" val-form-manager novalidate>
<umb-editor-view umb-tabs>
<umb-editor-header
name="vm.content.name"
tabs="vm.content.tabs"
hide-alias="true"
hide-description="true"
hide-icon="true">
</umb-editor-header>
<umb-editor-container>
<umb-tabs-content class="form-horizontal" view="true">
<umb-tab id="tab{{tab.id}}" ng-repeat="tab in vm.content.tabs" rel="{{tab.id}}">
<div ng-show="tab.alias==='tab1'">
// tab 1 content
</div>
<div ng-show="tab.alias==='tab2'">
// tab 2 content
</div>
</umb-tab>
</umb-tabs-content>
</umb-editor-container>
<umb-editor-footer>
// footer content here
</umb-editor-footer>
</umb-editor-view>
</form>
</div>
</pre>
<h3>Controller example - with tabs</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.content = {
name: "",
tabs: [
{
id: 1,
label: "Tab 1",
alias: "tab1",
active: true
},
{
id: 2,
label: "Tab 2",
alias: "tab2",
active: false
}
]
};
}
angular.module("umbraco").controller("MySection.Controller", Controller);
})();
</pre>
<h3>Markup example - with sub views</h3>
<pre>
<div ng-controller="MySection.Controller as vm">
<form name="mySectionForm" val-form-manager novalidate>
<umb-editor-view>
<umb-editor-header
name="vm.content.name"
navigation="vm.content.navigation"
hide-alias="true"
hide-description="true"
hide-icon="true">
</umb-editor-header>
<umb-editor-container>
<umb-editor-sub-views
sub-views="vm.content.navigation"
model="vm.content">
</umb-editor-sub-views>
</umb-editor-container>
<umb-editor-footer>
// footer content here
</umb-editor-footer>
</umb-editor-view>
</form>
</div>
</pre>
<h3>Controller example - with sub views</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.content = {
name: "",
navigation: [
{
"name": "Section 1",
"icon": "icon-document-dashed-line",
"view": "/App_Plugins/path/to/html.html",
"active": true
},
{
"name": "Section 2",
"icon": "icon-list",
"view": "/App_Plugins/path/to/html.html",
}
]
};
}
angular.module("umbraco").controller("MySection.Controller", Controller);
})();
</pre>
<h3>Use in combination with</h3>
<ul>
<li>{@link umbraco.directives.directive:umbEditorView umbEditorView}</li>
<li>{@link umbraco.directives.directive:umbEditorContainer umbEditorContainer}</li>
<li>{@link umbraco.directives.directive:umbEditorFooter umbEditorFooter}</li>
</ul>
@param {string} name The content name.
@param {array=} tabs Array of tabs. See example above.
@param {array=} navigation Array of sub views. See example above.
@param {boolean=} nameLocked Set to <code>true</code> to lock the name.
@param {object=} menu Add a context menu to the editor.
@param {string=} icon Show and edit the content icon. Opens an overlay to change the icon.
@param {boolean=} hideIcon Set to <code>true</code> to hide icon.
@param {string=} alias show and edit the content alias.
@param {boolean=} hideAlias Set to <code>true</code> to hide alias.
@param {string=} description Add a description to the content.
@param {boolean=} hideDescription Set to <code>true</code> to hide description.
**/
(function() {
'use strict';
function EditorHeaderDirective(iconHelper) {
function link(scope, el, attr, ctrl) {
scope.openIconPicker = function() {
scope.dialogModel = {
view: "iconpicker",
show: true,
submit: function (model) {
/* ensure an icon is selected, because on focus on close button
or an element in background no icon is submitted. So don't clear/update existing icon/preview.
*/
if (model.icon) {
if (model.color) {
scope.icon = model.icon + " " + model.color;
} else {
scope.icon = model.icon;
}
// set form to dirty
ctrl.$setDirty();
}
scope.dialogModel.show = false;
scope.dialogModel = null;
}
};
};
}
var directive = {
require: '^form',
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/umb-editor-header.html',
scope: {
tabs: "=",
actions: "=",
name: "=",
nameLocked: "=",
menu: "=",
icon: "=",
hideIcon: "@",
alias: "=",
hideAlias: "@",
description: "=",
hideDescription: "@",
navigation: "="
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbEditorHeader', EditorHeaderDirective);
})();
(function() {
'use strict';
function EditorMenuDirective($injector, treeService, navigationService, umbModelMapper, appState) {
function link(scope, el, attr, ctrl) {
//adds a handler to the context menu item click, we need to handle this differently
//depending on what the menu item is supposed to do.
scope.executeMenuItem = function (action) {
navigationService.executeMenuAction(action, scope.currentNode, scope.currentSection);
};
//callback method to go and get the options async
scope.getOptions = function () {
if (!scope.currentNode) {
return;
}
//when the options item is selected, we need to set the current menu item in appState (since this is synonymous with a menu)
appState.setMenuState("currentNode", scope.currentNode);
if (!scope.actions) {
treeService.getMenu({ treeNode: scope.currentNode })
.then(function (data) {
scope.actions = data.menuItems;
});
}
};
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/umb-editor-menu.html',
link: link,
scope: {
currentNode: "=",
currentSection: "@"
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbEditorMenu', EditorMenuDirective);
})();
(function() {
'use strict';
function EditorNavigationDirective() {
function link(scope, el, attr, ctrl) {
scope.showNavigation = true;
scope.clickNavigationItem = function(selectedItem) {
setItemToActive(selectedItem);
runItemAction(selectedItem);
};
function runItemAction(selectedItem) {
if (selectedItem.action) {
selectedItem.action(selectedItem);
}
}
function setItemToActive(selectedItem) {
// set all other views to inactive
if (selectedItem.view) {
for (var index = 0; index < scope.navigation.length; index++) {
var item = scope.navigation[index];
item.active = false;
}
// set view to active
selectedItem.active = true;
}
}
function activate() {
// hide navigation if there is only 1 item
if (scope.navigation.length <= 1) {
scope.showNavigation = false;
}
}
activate();
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/umb-editor-navigation.html',
scope: {
navigation: "="
},
link: link
};
return directive;
}
angular.module('umbraco.directives.html').directive('umbEditorNavigation', EditorNavigationDirective);
})();
(function() {
'use strict';
function EditorSubViewsDirective() {
function link(scope, el, attr, ctrl) {
scope.activeView = {};
// set toolbar from selected navigation item
function setActiveView(items) {
for (var index = 0; index < items.length; index++) {
var item = items[index];
if (item.active && item.view) {
scope.activeView = item;
}
}
}
// watch for navigation changes
scope.$watch('subViews', function(newValue, oldValue) {
if (newValue) {
setActiveView(newValue);
}
}, true);
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/umb-editor-sub-views.html',
scope: {
subViews: "=",
model: "="
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbEditorSubViews', EditorSubViewsDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbEditorView
@restrict E
@scope
@description
Use this directive to construct the main editor window.
<h3>Markup example</h3>
<pre>
<div ng-controller="MySection.Controller as vm">
<form name="mySectionForm" novalidate>
<umb-editor-view>
<umb-editor-header
name="vm.content.name"
hide-alias="true"
hide-description="true"
hide-icon="true">
</umb-editor-header>
<umb-editor-container>
// main content here
</umb-editor-container>
<umb-editor-footer>
// footer content here
</umb-editor-footer>
</umb-editor-view>
</form>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
}
angular.module("umbraco").controller("MySection.Controller", Controller);
})();
</pre>
<h3>Use in combination with</h3>
<ul>
<li>{@link umbraco.directives.directive:umbEditorHeader umbEditorHeader}</li>
<li>{@link umbraco.directives.directive:umbEditorContainer umbEditorContainer}</li>
<li>{@link umbraco.directives.directive:umbEditorFooter umbEditorFooter}</li>
</ul>
**/
(function() {
'use strict';
function EditorViewDirective() {
function link(scope, el, attr) {
if(attr.footer) {
scope.footer = attr.footer;
}
}
var directive = {
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/umb-editor-view.html',
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbEditorView', EditorViewDirective);
})();
/**
* @description Utillity directives for key and field events
**/
angular.module('umbraco.directives')
.directive('onKeyup', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onKeyup);
};
elm.on("keyup", f);
scope.$on("$destroy", function(){ elm.off("keyup", f);} );
}
};
})
.directive('onKeydown', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onKeydown);
};
elm.on("keydown", f);
scope.$on("$destroy", function(){ elm.off("keydown", f);} );
}
};
})
.directive('onBlur', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onBlur);
};
elm.on("blur", f);
scope.$on("$destroy", function(){ elm.off("blur", f);} );
}
};
})
.directive('onFocus', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onFocus);
};
elm.on("focus", f);
scope.$on("$destroy", function(){ elm.off("focus", f);} );
}
};
})
.directive('onDragEnter', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onDragEnter);
};
elm.on("dragenter", f);
scope.$on("$destroy", function(){ elm.off("dragenter", f);} );
}
};
})
.directive('onDragLeave', function () {
return function (scope, elm, attrs) {
var f = function (event) {
var rect = this.getBoundingClientRect();
var getXY = function getCursorPosition(event) {
var x, y;
if (typeof event.clientX === 'undefined') {
// try touch screen
x = event.pageX + document.documentElement.scrollLeft;
y = event.pageY + document.documentElement.scrollTop;
} else {
x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
return { x: x, y : y };
};
var e = getXY(event.originalEvent);
// Check the mouseEvent coordinates are outside of the rectangle
if (e.x > rect.left + rect.width - 1 || e.x < rect.left || e.y > rect.top + rect.height - 1 || e.y < rect.top) {
scope.$apply(attrs.onDragLeave);
}
};
elm.on("dragleave", f);
scope.$on("$destroy", function(){ elm.off("dragleave", f);} );
};
})
.directive('onDragOver', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onDragOver);
};
elm.on("dragover", f);
scope.$on("$destroy", function(){ elm.off("dragover", f);} );
}
};
})
.directive('onDragStart', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onDragStart);
};
elm.on("dragstart", f);
scope.$on("$destroy", function(){ elm.off("dragstart", f);} );
}
};
})
.directive('onDragEnd', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onDragEnd);
};
elm.on("dragend", f);
scope.$on("$destroy", function(){ elm.off("dragend", f);} );
}
};
})
.directive('onDrop', function () {
return {
link: function (scope, elm, attrs) {
var f = function () {
scope.$apply(attrs.onDrop);
};
elm.on("drop", f);
scope.$on("$destroy", function(){ elm.off("drop", f);} );
}
};
})
.directive('onOutsideClick', function ($timeout) {
return function (scope, element, attrs) {
var eventBindings = [];
function oneTimeClick(event) {
var el = event.target.nodeName;
//ignore link and button clicks
var els = ["INPUT","A","BUTTON"];
if(els.indexOf(el) >= 0){return;}
// ignore children of links and buttons
// ignore clicks on new overlay
var parents = $(event.target).parents("a,button,.umb-overlay");
if(parents.length > 0){
return;
}
// ignore clicks on dialog from old dialog service
var oldDialog = $(el).parents("#old-dialog-service");
if (oldDialog.length === 1) {
return;
}
// ignore clicks in tinyMCE dropdown(floatpanel)
var floatpanel = $(el).parents(".mce-floatpanel");
if (floatpanel.length === 1) {
return;
}
//ignore clicks inside this element
if( $(element).has( $(event.target) ).length > 0 ){
return;
}
scope.$apply(attrs.onOutsideClick);
}
$timeout(function(){
if ("bindClickOn" in attrs) {
eventBindings.push(scope.$watch(function() {
return attrs.bindClickOn;
}, function(newValue) {
if (newValue === "true") {
$(document).on("click", oneTimeClick);
} else {
$(document).off("click", oneTimeClick);
}
}));
} else {
$(document).on("click", oneTimeClick);
}
scope.$on("$destroy", function() {
$(document).off("click", oneTimeClick);
// unbind watchers
for (var e in eventBindings) {
eventBindings[e]();
}
});
}); // Temp removal of 1 sec timeout to prevent bug where overlay does not open. We need to find a better solution.
};
})
.directive('onRightClick',function(){
document.oncontextmenu = function (e) {
if(e.target.hasAttribute('on-right-click')) {
e.preventDefault();
e.stopPropagation();
return false;
}
};
return function(scope,el,attrs){
el.on('contextmenu',function(e){
e.preventDefault();
e.stopPropagation();
scope.$apply(attrs.onRightClick);
return false;
});
};
})
.directive('onDelayedMouseleave', function ($timeout, $parse) {
return {
restrict: 'A',
link: function (scope, element, attrs, ctrl) {
var active = false;
var fn = $parse(attrs.onDelayedMouseleave);
var leave_f = function(event) {
var callback = function() {
fn(scope, {$event:event});
};
active = false;
$timeout(function(){
if(active === false){
scope.$apply(callback);
}
}, 650);
};
var enter_f = function(event, args){
active = true;
};
element.on("mouseleave", leave_f);
element.on("mouseenter", enter_f);
//unsub events
scope.$on("$destroy", function(){
element.off("mouseleave", leave_f);
element.off("mouseenter", enter_f);
});
}
};
});
/*
http://vitalets.github.io/checklist-model/
<label ng-repeat="role in roles">
<input type="checkbox" checklist-model="user.roles" checklist-value="role.id"> {{role.text}}
</label>
*/
angular.module('umbraco.directives')
.directive('checklistModel', ['$parse', '$compile', function($parse, $compile) {
// contains
function contains(arr, item) {
if (angular.isArray(arr)) {
for (var i = 0; i < arr.length; i++) {
if (angular.equals(arr[i], item)) {
return true;
}
}
}
return false;
}
// add
function add(arr, item) {
arr = angular.isArray(arr) ? arr : [];
for (var i = 0; i < arr.length; i++) {
if (angular.equals(arr[i], item)) {
return arr;
}
}
arr.push(item);
return arr;
}
// remove
function remove(arr, item) {
if (angular.isArray(arr)) {
for (var i = 0; i < arr.length; i++) {
if (angular.equals(arr[i], item)) {
arr.splice(i, 1);
break;
}
}
}
return arr;
}
// http://stackoverflow.com/a/19228302/1458162
function postLinkFn(scope, elem, attrs) {
// compile with `ng-model` pointing to `checked`
$compile(elem)(scope);
// getter / setter for original model
var getter = $parse(attrs.checklistModel);
var setter = getter.assign;
// value added to list
var value = $parse(attrs.checklistValue)(scope.$parent);
// watch UI checked change
scope.$watch('checked', function(newValue, oldValue) {
if (newValue === oldValue) {
return;
}
var current = getter(scope.$parent);
if (newValue === true) {
setter(scope.$parent, add(current, value));
} else {
setter(scope.$parent, remove(current, value));
}
});
// watch original model change
scope.$parent.$watch(attrs.checklistModel, function(newArr, oldArr) {
scope.checked = contains(newArr, value);
}, true);
}
return {
restrict: 'A',
priority: 1000,
terminal: true,
scope: true,
compile: function(tElement, tAttrs) {
if (tElement[0].tagName !== 'INPUT' || !tElement.attr('type', 'checkbox')) {
throw 'checklist-model should be applied to `input[type="checkbox"]`.';
}
if (!tAttrs.checklistValue) {
throw 'You should provide `checklist-value`.';
}
// exclude recursion
tElement.removeAttr('checklist-model');
// local scope var storing individual checkbox model
tElement.attr('ng-model', 'checked');
return postLinkFn;
}
};
}]);
angular.module("umbraco.directives")
.directive("contenteditable", function() {
return {
require: "ngModel",
link: function(scope, element, attrs, ngModel) {
function read() {
ngModel.$setViewValue(element.html());
}
ngModel.$render = function() {
element.html(ngModel.$viewValue || "");
};
element.bind("focus", function(){
var range = document.createRange();
range.selectNodeContents(element[0]);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
});
element.bind("blur keyup change", function() {
scope.$apply(read);
});
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:fixNumber
* @restrict A
* @description Used in conjunction with type='number' input fields to ensure that the bound value is converted to a number when using ng-model
* because normally it thinks it's a string and also validation doesn't work correctly due to an angular bug.
**/
function fixNumber($parse) {
return {
restrict: "A",
require: "ngModel",
link: function (scope, elem, attrs, ctrl) {
//parse ngModel onload
var modelVal = scope.$eval(attrs.ngModel);
if (modelVal) {
var asNum = parseFloat(modelVal, 10);
if (!isNaN(asNum)) {
$parse(attrs.ngModel).assign(scope, asNum);
}
}
//always return an int to the model
ctrl.$parsers.push(function (value) {
if (value === 0) {
return 0;
}
return parseFloat(value || '', 10);
});
//always try to format the model value as an int
ctrl.$formatters.push(function (value) {
if (angular.isString(value)) {
return parseFloat(value, 10);
}
return value;
});
//This fixes this angular issue:
//https://github.com/angular/angular.js/issues/2144
// which doesn't actually validate the number input properly since the model only changes when a real number is entered
// but the input box still allows non-numbers to be entered which do not validate (only via html5)
if (typeof elem.prop('validity') === 'undefined') {
return;
}
elem.bind('input', function (e) {
var validity = elem.prop('validity');
scope.$apply(function () {
ctrl.$setValidity('number', !validity.badInput);
});
});
}
};
}
angular.module('umbraco.directives').directive("fixNumber", fixNumber);
angular.module("umbraco.directives").directive('focusWhen', function ($timeout) {
return {
restrict: 'A',
link: function (scope, elm, attrs, ctrl) {
attrs.$observe("focusWhen", function (newValue) {
if (newValue === "true") {
$timeout(function () {
elm.focus();
});
}
});
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:hexBgColor
* @restrict A
* @description Used to set a hex background color on an element, this will detect valid hex and when it is valid it will set the color, otherwise
* a color will not be set.
**/
function hexBgColor() {
return {
restrict: "A",
link: function (scope, element, attr, formCtrl) {
var origColor = null;
if (attr.hexBgOrig) {
//set the orig based on the attribute if there is one
origColor = attr.hexBgOrig;
}
attr.$observe("hexBgColor", function (newVal) {
if (newVal) {
if (!origColor) {
//get the orig color before changing it
origColor = element.css("border-color");
}
//validate it - test with and without the leading hash.
if (/^([0-9a-f]{3}|[0-9a-f]{6})$/i.test(newVal)) {
element.css("background-color", "#" + newVal);
return;
}
if (/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(newVal)) {
element.css("background-color", newVal);
return;
}
}
element.css("background-color", origColor);
});
}
};
}
angular.module('umbraco.directives').directive("hexBgColor", hexBgColor);
/**
* @ngdoc directive
* @name umbraco.directives.directive:hotkey
**/
angular.module("umbraco.directives")
.directive('hotkey', function($window, keyboardService, $log) {
return function(scope, el, attrs) {
var options = {};
var keyCombo = attrs.hotkey;
if (!keyCombo) {
//support data binding
keyCombo = scope.$eval(attrs["hotkey"]);
}
function activate() {
if (keyCombo) {
// disable shortcuts in input fields if keycombo is 1 character
if (keyCombo.length === 1) {
options = {
inputDisabled: true
};
}
keyboardService.bind(keyCombo, function() {
var element = $(el);
var activeElementType = document.activeElement.tagName;
var clickableElements = ["A", "BUTTON"];
if (element.is("a,div,button,input[type='button'],input[type='submit'],input[type='checkbox']") && !element.is(':disabled')) {
if (element.is(':visible') || attrs.hotkeyWhenHidden) {
if (attrs.hotkeyWhen && attrs.hotkeyWhen === "false") {
return;
}
// when keycombo is enter and a link or button has focus - click the link or button instead of using the hotkey
if (keyCombo === "enter" && clickableElements.indexOf(activeElementType) === 0) {
document.activeElement.click();
} else {
element.click();
}
}
} else {
element.focus();
}
}, options);
el.on('$destroy', function() {
keyboardService.unbind(keyCombo);
});
}
}
activate();
};
});
/**
@ngdoc directive
@name umbraco.directives.directive:preventDefault
@description
Use this directive to prevent default action of an element. Effectively implementing <a href="https://api.jquery.com/event.preventdefault/">jQuery's preventdefault</a>
<h3>Markup example</h3>
<pre>
<a href="https://umbraco.com" prevent-default>Don't go to Umbraco.com</a>
</pre>
**/
angular.module("umbraco.directives")
.directive('preventDefault', function() {
return function(scope, element, attrs) {
var enabled = true;
//check if there's a value for the attribute, if there is and it's false then we conditionally don't
//prevent default.
if (attrs.preventDefault) {
attrs.$observe("preventDefault", function (newVal) {
enabled = (newVal === "false" || newVal === 0 || newVal === false) ? false : true;
});
}
$(element).click(function (event) {
if (event.metaKey || event.ctrlKey) {
return;
}
else {
if (enabled === true) {
event.preventDefault();
}
}
});
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:preventEnterSubmit
* @description prevents a form from submitting when the enter key is pressed on an input field
**/
angular.module("umbraco.directives")
.directive('preventEnterSubmit', function() {
return function(scope, element, attrs) {
var enabled = true;
//check if there's a value for the attribute, if there is and it's false then we conditionally don't
//prevent default.
if (attrs.preventEnterSubmit) {
attrs.$observe("preventEnterSubmit", function (newVal) {
enabled = (newVal === "false" || newVal === 0 || newVal === false) ? false : true;
});
}
$(element).keypress(function (event) {
if (event.which === 13) {
event.preventDefault();
}
});
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:resizeToContent
* @element div
* @function
*
* @description
* Resize iframe's automatically to fit to the content they contain
*
* @example
<example module="umbraco.directives">
<file name="index.html">
<iframe resize-to-content src="meh.html"></iframe>
</file>
</example>
*/
angular.module("umbraco.directives")
.directive('resizeToContent', function ($window, $timeout) {
return function (scope, el, attrs) {
var iframe = el[0];
var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
if (iframeWin.document.body) {
$timeout(function(){
var height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
el.height(height);
}, 3000);
}
};
});
angular.module("umbraco.directives")
.directive('selectOnFocus', function () {
return function (scope, el, attrs) {
$(el).bind("click", function () {
var editmode = $(el).data("editmode");
//If editmode is true a click is handled like a normal click
if (!editmode) {
//Initial click, select entire text
this.select();
//Set the edit mode so subsequent clicks work normally
$(el).data("editmode", true);
}
}).
bind("blur", function () {
//Reset on focus lost
$(el).data("editmode", false);
});
};
});
angular.module("umbraco.directives")
.directive('umbAutoFocus', function($timeout) {
return function(scope, element, attr){
var update = function() {
//if it uses its default naming
if(element.val() === "" || attr.focusOnFilled){
element.focus();
}
};
$timeout(function() {
update();
});
};
});
angular.module("umbraco.directives")
.directive('umbAutoResize', function($timeout) {
return {
require: ["^?umbTabs", "ngModel"],
link: function(scope, element, attr, controllersArr) {
var domEl = element[0];
var domElType = domEl.type;
var umbTabsController = controllersArr[0];
var ngModelController = controllersArr[1];
// IE elements
var isIEFlag = false;
var wrapper = angular.element('#umb-ie-resize-input-wrapper');
var mirror = angular.element('<span style="white-space:pre;"></span>');
function isIE() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./) || navigator.userAgent.match(/Edge\/\d+/)) {
return true;
} else {
return false;
}
}
function activate() {
// check if browser is Internet Explorere
isIEFlag = isIE();
// scrollWidth on element does not work in IE on inputs
// we have to do some dirty dom element copying.
if (isIEFlag === true && domElType === "text") {
setupInternetExplorerElements();
}
}
function setupInternetExplorerElements() {
if (!wrapper.length) {
wrapper = angular.element('<div id="umb-ie-resize-input-wrapper" style="position:fixed; top:-999px; left:0;"></div>');
angular.element('body').append(wrapper);
}
angular.forEach(['fontFamily', 'fontSize', 'fontWeight', 'fontStyle',
'letterSpacing', 'textTransform', 'wordSpacing', 'textIndent',
'boxSizing', 'borderRightWidth', 'borderLeftWidth', 'borderLeftStyle', 'borderRightStyle',
'paddingLeft', 'paddingRight', 'marginLeft', 'marginRight'
], function(value) {
mirror.css(value, element.css(value));
});
wrapper.append(mirror);
}
function resizeInternetExplorerInput() {
mirror.text(element.val() || attr.placeholder);
element.css('width', mirror.outerWidth() + 1);
}
function resizeInput() {
if (domEl.scrollWidth !== domEl.clientWidth) {
if (ngModelController.$modelValue) {
element.width(domEl.scrollWidth);
}
}
if(!ngModelController.$modelValue && attr.placeholder) {
attr.$set('size', attr.placeholder.length);
element.width('auto');
}
}
function resizeTextarea() {
if(domEl.scrollHeight !== domEl.clientHeight) {
element.height(domEl.scrollHeight);
}
}
var update = function(force) {
if (force === true) {
if (domElType === "textarea") {
element.height(0);
} else if (domElType === "text") {
element.width(0);
}
}
if (isIEFlag === true && domElType === "text") {
resizeInternetExplorerInput();
} else {
if (domElType === "textarea") {
resizeTextarea();
} else if (domElType === "text") {
resizeInput();
}
}
};
activate();
//listen for tab changes
if (umbTabsController != null) {
umbTabsController.onTabShown(function(args) {
update();
});
}
// listen for ng-model changes
var unbindModelWatcher = scope.$watch(function() {
return ngModelController.$modelValue;
}, function(newValue) {
update(true);
});
scope.$on('$destroy', function() {
element.unbind('keyup keydown keypress change', update);
element.unbind('blur', update(true));
unbindModelWatcher();
// clean up IE dom element
if (isIEFlag === true && domElType === "text") {
mirror.remove();
}
});
}
};
});
/*
example usage: <textarea json-edit="myObject" rows="8" class="form-control"></textarea>
jsonEditing is a string which we edit in a textarea. we try parsing to JSON with each change. when it is valid, propagate model changes via ngModelCtrl
use isolate scope to prevent model propagation when invalid - will update manually. cannot replace with template, or will override ngModelCtrl, and not hide behind facade
will override element type to textarea and add own attribute ngModel tied to jsonEditing
*/
angular.module("umbraco.directives")
.directive('umbRawModel', function () {
return {
restrict: 'A',
require: 'ngModel',
template: '<textarea ng-model="jsonEditing"></textarea>',
replace : true,
scope: {
model: '=umbRawModel',
validateOn:'='
},
link: function (scope, element, attrs, ngModelCtrl) {
function setEditing (value) {
scope.jsonEditing = angular.copy( jsonToString(value));
}
function updateModel (value) {
scope.model = stringToJson(value);
}
function setValid() {
ngModelCtrl.$setValidity('json', true);
}
function setInvalid () {
ngModelCtrl.$setValidity('json', false);
}
function stringToJson(text) {
try {
return angular.fromJson(text);
} catch (err) {
setInvalid();
return text;
}
}
function jsonToString(object) {
// better than JSON.stringify(), because it formats + filters $$hashKey etc.
// NOTE that this will remove all $-prefixed values
return angular.toJson(object, true);
}
function isValidJson(model) {
var flag = true;
try {
angular.fromJson(model);
} catch (err) {
flag = false;
}
return flag;
}
//init
setEditing(scope.model);
var onInputChange = function(newval,oldval){
if (newval !== oldval) {
if (isValidJson(newval)) {
setValid();
updateModel(newval);
} else {
setInvalid();
}
}
};
if(scope.validateOn){
element.on(scope.validateOn, function(){
scope.$apply(function(){
onInputChange(scope.jsonEditing);
});
});
}else{
//check for changes going out
scope.$watch('jsonEditing', onInputChange, true);
}
//check for changes coming in
scope.$watch('model', function (newval, oldval) {
if (newval !== oldval) {
setEditing(newval);
}
}, true);
}
};
});
(function() {
'use strict';
function SelectWhen($timeout) {
function link(scope, el, attr, ctrl) {
attr.$observe("umbSelectWhen", function(newValue) {
if (newValue === "true") {
$timeout(function() {
el.select();
});
}
});
}
var directive = {
restrict: 'A',
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbSelectWhen', SelectWhen);
})();
angular.module("umbraco.directives")
.directive('gridRte', function (tinyMceService, stylesheetResource, angularHelper, assetsService, $q, $timeout) {
return {
scope: {
uniqueId: '=',
value: '=',
onClick: '&',
onFocus: '&',
onBlur: '&',
configuration:"=",
onMediaPickerClick: "=",
onEmbedClick: "=",
onMacroPickerClick: "=",
onLinkPickerClick: "="
},
template: "<textarea ng-model=\"value\" rows=\"10\" class=\"mceNoEditor\" style=\"overflow:hidden\" id=\"{{uniqueId}}\"></textarea>",
replace: true,
link: function (scope, element, attrs) {
var initTiny = function () {
//we always fetch the default one, and then override parts with our own
tinyMceService.configuration().then(function (tinyMceConfig) {
//config value from general tinymce.config file
var validElements = tinyMceConfig.validElements;
var fallbackStyles = [{title: "Page header", block: "h2"}, {title: "Section header", block: "h3"}, {title: "Paragraph header", block: "h4"}, {title: "Normal", block: "p"}, {title: "Quote", block: "blockquote"}, {title: "Code", block: "code"}];
//These are absolutely required in order for the macros to render inline
//we put these as extended elements because they get merged on top of the normal allowed elements by tiny mce
var extendedValidElements = "@[id|class|style],-div[id|dir|class|align|style],ins[datetime|cite],-ul[class|style],-li[class|style],-h1[id|dir|class|align|style],-h2[id|dir|class|align|style],-h3[id|dir|class|align|style],-h4[id|dir|class|align|style],-h5[id|dir|class|align|style],-h6[id|style|dir|class|align],span[id|class|style]";
var invalidElements = tinyMceConfig.inValidElements;
var plugins = _.map(tinyMceConfig.plugins, function (plugin) {
if (plugin.useOnFrontend) {
return plugin.name;
}
}).join(" ") + " autoresize";
//config value on the data type
var toolbar = ["code", "styleselect", "bold", "italic", "alignleft", "aligncenter", "alignright", "bullist", "numlist", "link", "umbmediapicker", "umbembeddialog"].join(" | ");
var stylesheets = [];
var styleFormats = [];
var await = [];
//queue file loading
if (typeof (tinymce) === "undefined") {
await.push(assetsService.loadJs("lib/tinymce/tinymce.min.js", scope));
}
if(scope.configuration && scope.configuration.toolbar){
toolbar = scope.configuration.toolbar.join(' | ');
}
if(scope.configuration && scope.configuration.stylesheets){
angular.forEach(scope.configuration.stylesheets, function(stylesheet, key){
stylesheets.push(Umbraco.Sys.ServerVariables.umbracoSettings.cssPath + "/" + stylesheet + ".css");
await.push(stylesheetResource.getRulesByName(stylesheet).then(function (rules) {
angular.forEach(rules, function (rule) {
var r = {};
var split = "";
r.title = rule.name;
if (rule.selector[0] === ".") {
r.inline = "span";
r.classes = rule.selector.substring(1);
}else if (rule.selector[0] === "#") {
//Even though this will render in the style drop down, it will not actually be applied
// to the elements, don't think TinyMCE even supports this and it doesn't really make much sense
// since only one element can have one id.
r.inline = "span";
r.attributes = { id: rule.selector.substring(1) };
}else if (rule.selector[0] !== "." && rule.selector.indexOf(".") > -1) {
split = rule.selector.split(".");
r.block = split[0];
r.classes = rule.selector.substring(rule.selector.indexOf(".") + 1).replace(".", " ");
}else if (rule.selector[0] !== "#" && rule.selector.indexOf("#") > -1) {
split = rule.selector.split("#");
r.block = split[0];
r.classes = rule.selector.substring(rule.selector.indexOf("#") + 1);
}else {
r.block = rule.selector;
}
styleFormats.push(r);
});
}));
});
}else{
stylesheets.push("views/propertyeditors/grid/config/grid.default.rtestyles.css");
styleFormats = fallbackStyles;
}
//stores a reference to the editor
var tinyMceEditor = null;
$q.all(await).then(function () {
var uniqueId = scope.uniqueId;
//create a baseline Config to exten upon
var baseLineConfigObj = {
mode: "exact",
skin: "umbraco",
plugins: plugins,
valid_elements: validElements,
invalid_elements: invalidElements,
extended_valid_elements: extendedValidElements,
menubar: false,
statusbar: false,
relative_urls: false,
toolbar: toolbar,
content_css: stylesheets,
style_formats: styleFormats,
autoresize_bottom_margin: 0
};
if (tinyMceConfig.customConfig) {
//if there is some custom config, we need to see if the string value of each item might actually be json and if so, we need to
// convert it to json instead of having it as a string since this is what tinymce requires
for (var i in tinyMceConfig.customConfig) {
var val = tinyMceConfig.customConfig[i];
if (val) {
val = val.toString().trim();
if (val.detectIsJson()) {
try {
tinyMceConfig.customConfig[i] = JSON.parse(val);
//now we need to check if this custom config key is defined in our baseline, if it is we don't want to
//overwrite the baseline config item if it is an array, we want to concat the items in the array, otherwise
//if it's an object it will overwrite the baseline
if (angular.isArray(baseLineConfigObj[i]) && angular.isArray(tinyMceConfig.customConfig[i])) {
//concat it and below this concat'd array will overwrite the baseline in angular.extend
tinyMceConfig.customConfig[i] = baseLineConfigObj[i].concat(tinyMceConfig.customConfig[i]);
}
}
catch (e) {
//cannot parse, we'll just leave it
}
}
}
}
angular.extend(baseLineConfigObj, tinyMceConfig.customConfig);
}
//set all the things that user configs should not be able to override
baseLineConfigObj.elements = uniqueId;
baseLineConfigObj.setup = function (editor) {
//set the reference
tinyMceEditor = editor;
//enable browser based spell checking
editor.on('init', function (e) {
editor.getBody().setAttribute('spellcheck', true);
//force overflow to hidden to prevent no needed scroll
editor.getBody().style.overflow = "hidden";
$timeout(function(){
if(scope.value === null){
editor.focus();
}
}, 400);
});
//when we leave the editor (maybe)
editor.on('blur', function (e) {
editor.save();
angularHelper.safeApply(scope, function () {
scope.value = editor.getContent();
var _toolbar = $(editor.editorContainer)
.find(".mce-toolbar");
if(scope.onBlur){
scope.onBlur();
}
});
});
// Focus on editor
editor.on('focus', function (e) {
angularHelper.safeApply(scope, function () {
if(scope.onFocus){
scope.onFocus();
}
});
});
// Click on editor
editor.on('click', function (e) {
angularHelper.safeApply(scope, function () {
if(scope.onClick){
scope.onClick();
}
});
});
//when buttons modify content
editor.on('ExecCommand', function (e) {
editor.save();
angularHelper.safeApply(scope, function () {
scope.value = editor.getContent();
});
});
// Update model on keypress
editor.on('KeyUp', function (e) {
editor.save();
angularHelper.safeApply(scope, function () {
scope.value = editor.getContent();
});
});
// Update model on change, i.e. copy/pasted text, plugins altering content
editor.on('SetContent', function (e) {
if (!e.initial) {
editor.save();
angularHelper.safeApply(scope, function () {
scope.value = editor.getContent();
});
}
});
editor.on('ObjectResized', function (e) {
var qs = "?width=" + e.width + "&height=" + e.height;
var srcAttr = $(e.target).attr("src");
var path = srcAttr.split("?")[0];
$(e.target).attr("data-mce-src", path + qs);
});
//Create the insert link plugin
tinyMceService.createLinkPicker(editor, scope, function(currentTarget, anchorElement){
if(scope.onLinkPickerClick) {
scope.onLinkPickerClick(editor, currentTarget, anchorElement);
}
});
//Create the insert media plugin
tinyMceService.createMediaPicker(editor, scope, function(currentTarget, userData){
if(scope.onMediaPickerClick) {
scope.onMediaPickerClick(editor, currentTarget, userData);
}
});
//Create the embedded plugin
tinyMceService.createInsertEmbeddedMedia(editor, scope, function(){
if(scope.onEmbedClick) {
scope.onEmbedClick(editor);
}
});
//Create the insert macro plugin
tinyMceService.createInsertMacro(editor, scope, function(dialogData){
if(scope.onMacroPickerClick) {
scope.onMacroPickerClick(editor, dialogData);
}
});
};
/** Loads in the editor */
function loadTinyMce() {
//we need to add a timeout here, to force a redraw so TinyMCE can find
//the elements needed
$timeout(function () {
tinymce.DOM.events.domLoaded = true;
tinymce.init(baseLineConfigObj);
}, 150, false);
}
loadTinyMce();
//here we declare a special method which will be called whenever the value has changed from the server
//this is instead of doing a watch on the model.value = faster
//scope.model.onValueChanged = function (newVal, oldVal) {
// //update the display val again if it has changed from the server;
// tinyMceEditor.setContent(newVal, { format: 'raw' });
// //we need to manually fire this event since it is only ever fired based on loading from the DOM, this
// // is required for our plugins listening to this event to execute
// tinyMceEditor.fire('LoadContent', null);
//};
//listen for formSubmitting event (the result is callback used to remove the event subscription)
var unsubscribe = scope.$on("formSubmitting", function () {
//TODO: Here we should parse out the macro rendered content so we can save on a lot of bytes in data xfer
// we do parse it out on the server side but would be nice to do that on the client side before as well.
scope.value = tinyMceEditor.getContent();
});
//when the element is disposed we need to unsubscribe!
// NOTE: this is very important otherwise if this is part of a modal, the listener still exists because the dom
// element might still be there even after the modal has been hidden.
scope.$on('$destroy', function () {
unsubscribe();
});
});
});
};
initTiny();
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbControlGroup
* @restrict E
**/
angular.module("umbraco.directives.html")
.directive('umbControlGroup', function (localizationService) {
return {
scope: {
label: "@label",
description: "@",
hideLabel: "@",
alias: "@"
},
require: '?^form',
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/html/umb-control-group.html',
link: function (scope, element, attr, formCtrl) {
scope.formValid = function() {
if (formCtrl) {
return formCtrl.$valid;
}
//there is no form.
return true;
};
if (scope.label && scope.label[0] === "@") {
scope.labelstring = localizationService.localize(scope.label.substring(1));
}
else {
scope.labelstring = scope.label;
}
if (scope.description && scope.description[0] === "@") {
scope.descriptionstring = localizationService.localize(scope.description.substring(1));
}
else {
scope.descriptionstring = scope.description;
}
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbPane
* @restrict E
**/
angular.module("umbraco.directives.html")
.directive('umbPane', function () {
return {
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/html/umb-pane.html'
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbPanel
* @restrict E
**/
angular.module("umbraco.directives.html")
.directive('umbPanel', function($timeout, $log){
return {
restrict: 'E',
replace: true,
transclude: 'true',
templateUrl: 'views/components/html/umb-panel.html'
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbImageCrop
* @restrict E
* @function
**/
angular.module("umbraco.directives")
.directive('umbImageCrop',
function ($timeout, localizationService, cropperHelper, $log) {
return {
restrict: 'E',
replace: true,
templateUrl: 'views/components/imaging/umb-image-crop.html',
scope: {
src: '=',
width: '@',
height: '@',
crop: "=",
center: "=",
maxSize: '@'
},
link: function(scope, element, attrs) {
scope.width = 400;
scope.height = 320;
scope.dimensions = {
image: {},
cropper:{},
viewport:{},
margin: 20,
scale: {
min: 0.3,
max: 3,
current: 1
}
};
//live rendering of viewport and image styles
scope.style = function () {
return {
'height': (parseInt(scope.dimensions.viewport.height, 10)) + 'px',
'width': (parseInt(scope.dimensions.viewport.width, 10)) + 'px'
};
};
//elements
var $viewport = element.find(".viewport");
var $image = element.find("img");
var $overlay = element.find(".overlay");
var $container = element.find(".crop-container");
//default constraints for drag n drop
var constraints = {left: {max: scope.dimensions.margin, min: scope.dimensions.margin}, top: {max: scope.dimensions.margin, min: scope.dimensions.margin}, };
scope.constraints = constraints;
//set constaints for cropping drag and drop
var setConstraints = function(){
constraints.left.min = scope.dimensions.margin + scope.dimensions.cropper.width - scope.dimensions.image.width;
constraints.top.min = scope.dimensions.margin + scope.dimensions.cropper.height - scope.dimensions.image.height;
};
var setDimensions = function(originalImage){
originalImage.width("auto");
originalImage.height("auto");
var image = {};
image.originalWidth = originalImage.width();
image.originalHeight = originalImage.height();
image.width = image.originalWidth;
image.height = image.originalHeight;
image.left = originalImage[0].offsetLeft;
image.top = originalImage[0].offsetTop;
scope.dimensions.image = image;
//unscaled editor size
//var viewPortW = $viewport.width();
//var viewPortH = $viewport.height();
var _viewPortW = parseInt(scope.width, 10);
var _viewPortH = parseInt(scope.height, 10);
//if we set a constraint we will scale it down if needed
if(scope.maxSize){
var ratioCalculation = cropperHelper.scaleToMaxSize(
_viewPortW,
_viewPortH,
scope.maxSize);
//so if we have a max size, override the thumb sizes
_viewPortW = ratioCalculation.width;
_viewPortH = ratioCalculation.height;
}
scope.dimensions.viewport.width = _viewPortW + 2 * scope.dimensions.margin;
scope.dimensions.viewport.height = _viewPortH + 2 * scope.dimensions.margin;
scope.dimensions.cropper.width = _viewPortW; // scope.dimensions.viewport.width - 2 * scope.dimensions.margin;
scope.dimensions.cropper.height = _viewPortH; // scope.dimensions.viewport.height - 2 * scope.dimensions.margin;
};
//when loading an image without any crop info, we center and fit it
var resizeImageToEditor = function(){
//returns size fitting the cropper
var size = cropperHelper.calculateAspectRatioFit(
scope.dimensions.image.width,
scope.dimensions.image.height,
scope.dimensions.cropper.width,
scope.dimensions.cropper.height,
true);
//sets the image size and updates the scope
scope.dimensions.image.width = size.width;
scope.dimensions.image.height = size.height;
//calculate the best suited ratios
scope.dimensions.scale.min = size.ratio;
scope.dimensions.scale.max = 2;
scope.dimensions.scale.current = size.ratio;
//center the image
var position = cropperHelper.centerInsideViewPort(scope.dimensions.image, scope.dimensions.cropper);
scope.dimensions.top = position.top;
scope.dimensions.left = position.left;
setConstraints();
};
//resize to a given ratio
var resizeImageToScale = function(ratio){
//do stuff
var size = cropperHelper.calculateSizeToRatio(scope.dimensions.image.originalWidth, scope.dimensions.image.originalHeight, ratio);
scope.dimensions.image.width = size.width;
scope.dimensions.image.height = size.height;
setConstraints();
validatePosition(scope.dimensions.image.left, scope.dimensions.image.top);
};
//resize the image to a predefined crop coordinate
var resizeImageToCrop = function(){
scope.dimensions.image = cropperHelper.convertToStyle(
scope.crop,
{width: scope.dimensions.image.originalWidth, height: scope.dimensions.image.originalHeight},
scope.dimensions.cropper,
scope.dimensions.margin);
var ratioCalculation = cropperHelper.calculateAspectRatioFit(
scope.dimensions.image.originalWidth,
scope.dimensions.image.originalHeight,
scope.dimensions.cropper.width,
scope.dimensions.cropper.height,
true);
scope.dimensions.scale.current = scope.dimensions.image.ratio;
//min max based on original width/height
scope.dimensions.scale.min = ratioCalculation.ratio;
scope.dimensions.scale.max = 2;
};
var validatePosition = function(left, top){
if(left > constraints.left.max)
{
left = constraints.left.max;
}
if(left <= constraints.left.min){
left = constraints.left.min;
}
if(top > constraints.top.max)
{
top = constraints.top.max;
}
if(top <= constraints.top.min){
top = constraints.top.min;
}
if(scope.dimensions.image.left !== left){
scope.dimensions.image.left = left;
}
if(scope.dimensions.image.top !== top){
scope.dimensions.image.top = top;
}
};
//sets scope.crop to the recalculated % based crop
var calculateCropBox = function(){
scope.crop = cropperHelper.pixelsToCoordinates(scope.dimensions.image, scope.dimensions.cropper.width, scope.dimensions.cropper.height, scope.dimensions.margin);
};
//Drag and drop positioning, using jquery ui draggable
var onStartDragPosition, top, left;
$overlay.draggable({
drag: function(event, ui) {
scope.$apply(function(){
validatePosition(ui.position.left, ui.position.top);
});
},
stop: function(event, ui){
scope.$apply(function(){
//make sure that every validates one more time...
validatePosition(ui.position.left, ui.position.top);
calculateCropBox();
scope.dimensions.image.rnd = Math.random();
});
}
});
var init = function(image){
scope.loaded = false;
//set dimensions on image, viewport, cropper etc
setDimensions(image);
//if we have a crop already position the image
if(scope.crop){
resizeImageToCrop();
}else{
resizeImageToEditor();
}
//sets constaints for the cropper
setConstraints();
scope.loaded = true;
};
/// WATCHERS ////
scope.$watchCollection('[width, height]', function(newValues, oldValues){
//we have to reinit the whole thing if
//one of the external params changes
if(newValues !== oldValues){
setDimensions($image);
setConstraints();
}
});
var throttledResizing = _.throttle(function(){
resizeImageToScale(scope.dimensions.scale.current);
calculateCropBox();
}, 100);
//happens when we change the scale
scope.$watch("dimensions.scale.current", function(){
if(scope.loaded){
throttledResizing();
}
});
//ie hack
if(window.navigator.userAgent.indexOf("MSIE ")){
var ranger = element.find("input");
ranger.bind("change",function(){
scope.$apply(function(){
scope.dimensions.scale.current = ranger.val();
});
});
}
//// INIT /////
$image.load(function(){
$timeout(function(){
init($image);
});
});
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbImageGravity
* @restrict E
* @function
* @description
**/
angular.module("umbraco.directives")
.directive('umbImageGravity', function ($timeout, localizationService, $log) {
return {
restrict: 'E',
replace: true,
templateUrl: 'views/components/imaging/umb-image-gravity.html',
scope: {
src: '=',
center: "=",
onImageLoaded: "="
},
link: function(scope, element, attrs) {
//Internal values for keeping track of the dot and the size of the editor
scope.dimensions = {
width: 0,
height: 0,
left: 0,
top: 0
};
scope.loaded = false;
//elements
var $viewport = element.find(".viewport");
var $image = element.find("img");
var $overlay = element.find(".overlay");
scope.style = function () {
if(scope.dimensions.width <= 0){
setDimensions();
}
return {
'top': scope.dimensions.top + 'px',
'left': scope.dimensions.left + 'px'
};
};
scope.setFocalPoint = function(event) {
scope.$emit("imageFocalPointStart");
var offsetX = event.offsetX - 10;
var offsetY = event.offsetY - 10;
calculateGravity(offsetX, offsetY);
lazyEndEvent();
};
var setDimensions = function(){
scope.dimensions.width = $image.width();
scope.dimensions.height = $image.height();
if(scope.center){
scope.dimensions.left = scope.center.left * scope.dimensions.width -10;
scope.dimensions.top = scope.center.top * scope.dimensions.height -10;
}else{
scope.center = { left: 0.5, top: 0.5 };
}
};
var calculateGravity = function(offsetX, offsetY){
scope.dimensions.left = offsetX;
scope.dimensions.top = offsetY;
scope.center.left = (scope.dimensions.left+10) / scope.dimensions.width;
scope.center.top = (scope.dimensions.top+10) / scope.dimensions.height;
};
var lazyEndEvent = _.debounce(function(){
scope.$apply(function(){
scope.$emit("imageFocalPointStop");
});
}, 2000);
//Drag and drop positioning, using jquery ui draggable
//TODO ensure that the point doesnt go outside the box
$overlay.draggable({
containment: "parent",
start: function(){
scope.$apply(function(){
scope.$emit("imageFocalPointStart");
});
},
stop: function() {
scope.$apply(function(){
var offsetX = $overlay[0].offsetLeft;
var offsetY = $overlay[0].offsetTop;
calculateGravity(offsetX, offsetY);
});
lazyEndEvent();
}
});
//// INIT /////
$image.load(function(){
$timeout(function(){
setDimensions();
scope.loaded = true;
scope.onImageLoaded();
});
});
$(window).on('resize.umbImageGravity', function(){
scope.$apply(function(){
$timeout(function(){
setDimensions();
});
var offsetX = $overlay[0].offsetLeft;
var offsetY = $overlay[0].offsetTop;
calculateGravity(offsetX, offsetY);
});
});
scope.$on('$destroy', function() {
$(window).off('.umbImageGravity');
});
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbImageThumbnail
* @restrict E
* @function
* @description
**/
angular.module("umbraco.directives")
.directive('umbImageThumbnail',
function ($timeout, localizationService, cropperHelper, $log) {
return {
restrict: 'E',
replace: true,
templateUrl: 'views/components/imaging/umb-image-thumbnail.html',
scope: {
src: '=',
width: '@',
height: '@',
center: "=",
crop: "=",
maxSize: '@'
},
link: function(scope, element, attrs) {
//// INIT /////
var $image = element.find("img");
scope.loaded = false;
$image.load(function(){
$timeout(function(){
$image.width("auto");
$image.height("auto");
scope.image = {};
scope.image.width = $image[0].width;
scope.image.height = $image[0].height;
//we force a lower thumbnail size to fit the max size
//we do not compare to the image dimensions, but the thumbs
if(scope.maxSize){
var ratioCalculation = cropperHelper.calculateAspectRatioFit(
scope.width,
scope.height,
scope.maxSize,
scope.maxSize,
false);
//so if we have a max size, override the thumb sizes
scope.width = ratioCalculation.width;
scope.height = ratioCalculation.height;
}
setPreviewStyle();
scope.loaded = true;
});
});
/// WATCHERS ////
scope.$watchCollection('[crop, center]', function(newValues, oldValues){
//we have to reinit the whole thing if
//one of the external params changes
setPreviewStyle();
});
scope.$watch("center", function(){
setPreviewStyle();
}, true);
function setPreviewStyle(){
if(scope.crop && scope.image){
scope.preview = cropperHelper.convertToStyle(
scope.crop,
scope.image,
{width: scope.width, height: scope.height},
0);
}else if(scope.image){
//returns size fitting the cropper
var p = cropperHelper.calculateAspectRatioFit(
scope.image.width,
scope.image.height,
scope.width,
scope.height,
true);
if(scope.center){
var xy = cropperHelper.alignToCoordinates(p, scope.center, {width: scope.width, height: scope.height});
p.top = xy.top;
p.left = xy.left;
}else{
}
p.position = "absolute";
scope.preview = p;
}
}
}
};
});
angular.module("umbraco.directives")
/**
* @ngdoc directive
* @name umbraco.directives.directive:localize
* @restrict EA
* @function
* @description Localize directive
**/
.directive('localize', function ($log, localizationService) {
return {
restrict: 'E',
scope:{
key: '@'
},
replace: true,
link: function (scope, element, attrs) {
var key = scope.key;
localizationService.localize(key).then(function(value){
element.html(value);
});
}
};
})
.directive('localize', function ($log, localizationService) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var keys = attrs.localize.split(',');
angular.forEach(keys, function(value, key){
var attr = element.attr(value);
if(attr){
if(attr[0] === '@'){
var t = localizationService.tokenize(attr.substring(1), scope);
localizationService.localize(t.key, t.tokens).then(function(val){
element.attr(value, val);
});
}
}
});
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbNotifications
*/
(function() {
'use strict';
function NotificationDirective(notificationsService) {
function link(scope, el, attr, ctrl) {
//subscribes to notifications in the notification service
scope.notifications = notificationsService.current;
scope.$watch('notificationsService.current', function (newVal, oldVal, scope) {
if (newVal) {
scope.notifications = newVal;
}
});
}
var directive = {
restrict: "E",
replace: true,
templateUrl: 'views/components/notifications/umb-notifications.html',
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbNotifications', NotificationDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbOverlay
@restrict E
@scope
@description
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<button type="button" ng-click="vm.openOverlay()"></button>
<umb-overlay
ng-if="vm.overlay.show"
model="vm.overlay"
view="vm.overlay.view"
position="right">
</umb-overlay>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.openOverlay = openOverlay;
function openOverlay() {
vm.overlay = {
view: "mediapicker",
show: true,
submit: function(model) {
vm.overlay.show = false;
vm.overlay = null;
},
close: function(oldModel) {
vm.overlay.show = false;
vm.overlay = null;
}
}
};
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
<h1>General Options</h1>
Lorem ipsum dolor sit amet..
<table>
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tr>
<td>model.title</td>
<td>String</td>
<td>Set the title of the overlay.</td>
</tr>
<tr>
<td>model.subTitle</td>
<td>String</td>
<td>Set the subtitle of the overlay.</td>
</tr>
<tr>
<td>model.submitButtonLabel</td>
<td>String</td>
<td>Set an alternate submit button text</td>
</tr>
<tr>
<td>model.submitButtonLabelKey</td>
<td>String</td>
<td>Set an alternate submit button label key for localized texts</td>
</tr>
<tr>
<td>model.hideSubmitButton</td>
<td>Boolean</td>
<td>Hides the submit button</td>
</tr>
<tr>
<td>model.closeButtonLabel</td>
<td>String</td>
<td>Set an alternate close button text</td>
</tr>
<tr>
<td>model.closeButtonLabelKey</td>
<td>String</td>
<td>Set an alternate close button label key for localized texts</td>
</tr>
<tr>
<td>model.show</td>
<td>Boolean</td>
<td>Show/hide the overlay</td>
</tr>
<tr>
<td>model.submit</td>
<td>Function</td>
<td>Callback function when the overlay submits. Returns the overlay model object</td>
</tr>
<tr>
<td>model.close</td>
<td>Function</td>
<td>Callback function when the overlay closes. Returns a copy of the overlay model object before being modified</td>
</tr>
</table>
<h1>Content Picker</h1>
Opens a content picker.</br>
<strong>view: </strong>contentpicker
<table>
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tr>
<td>model.multiPicker</td>
<td>Boolean</td>
<td>Pick one or multiple items</td>
</tr>
</table>
<table>
<thead>
<tr>
<th>Returns</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tr>
<td>model.selection</td>
<td>Array</td>
<td>Array of content objects</td>
</tr>
</table>
<h1>Icon Picker</h1>
Opens an icon picker.</br>
<strong>view: </strong>iconpicker
<table>
<thead>
<tr>
<th>Returns</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tr>
<td>model.icon</td>
<td>String</td>
<td>The icon class</td>
</tr>
</table>
<h1>Item Picker</h1>
Opens an item picker.</br>
<strong>view: </strong>itempicker
<table>
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>model.availableItems</td>
<td>Array</td>
<td>Array of available items</td>
</tr>
<tr>
<td>model.selectedItems</td>
<td>Array</td>
<td>Array of selected items. When passed in the selected items will be filtered from the available items.</td>
</tr>
<tr>
<td>model.filter</td>
<td>Boolean</td>
<td>Set to false to hide the filter</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Returns</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tr>
<td>model.selectedItem</td>
<td>Object</td>
<td>The selected item</td>
</tr>
</table>
<h1>Macro Picker</h1>
Opens a media picker.</br>
<strong>view: </strong>macropicker
<table>
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>model.dialogData</td>
<td>Object</td>
<td>Object which contains array of allowedMacros. Set to <code>null</code> to allow all.</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Returns</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>model.macroParams</td>
<td>Array</td>
<td>Array of macro params</td>
</tr>
<tr>
<td>model.selectedMacro</td>
<td>Object</td>
<td>The selected macro</td>
</tr>
</tbody>
</table>
<h1>Media Picker</h1>
Opens a media picker.</br>
<strong>view: </strong>mediapicker
<table>
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>model.multiPicker</td>
<td>Boolean</td>
<td>Pick one or multiple items</td>
</tr>
<tr>
<td>model.onlyImages</td>
<td>Boolean</td>
<td>Only display files that have an image file-extension</td>
</tr>
<tr>
<td>model.disableFolderSelect</td>
<td>Boolean</td>
<td>Disable folder selection</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Returns</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>model.selectedImages</td>
<td>Array</td>
<td>Array of selected images</td>
</tr>
</tbody>
</table>
<h1>Member Group Picker</h1>
Opens a member group picker.</br>
<strong>view: </strong>membergrouppicker
<table>
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>model.multiPicker</td>
<td>Boolean</td>
<td>Pick one or multiple items</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Returns</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>model.selectedMemberGroup</td>
<td>String</td>
<td>The selected member group</td>
</tr>
<tr>
<td>model.selectedMemberGroups (multiPicker)</td>
<td>Array</td>
<td>The selected member groups</td>
</tr>
</tbody>
</table>
<h1>Member Picker</h1>
Opens a member picker. </br>
<strong>view: </strong>memberpicker
<table>
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>model.multiPicker</td>
<td>Boolean</td>
<td>Pick one or multiple items</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Returns</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>model.selection</td>
<td>Array</td>
<td>Array of selected members/td>
</tr>
</tbody>
</table>
<h1>YSOD</h1>
Opens an overlay to show a custom YSOD. </br>
<strong>view: </strong>ysod
<table>
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>model.error</td>
<td>Object</td>
<td>Error object</td>
</tr>
</tbody>
</table>
@param {object} model Overlay options.
@param {string} view Path to view or one of the default view names.
@param {string} position The overlay position ("left", "right", "center": "target").
**/
(function() {
'use strict';
function OverlayDirective($timeout, formHelper, overlayHelper, localizationService) {
function link(scope, el, attr, ctrl) {
scope.directive = {
enableConfirmButton: false
};
var overlayNumber = 0;
var numberOfOverlays = 0;
var isRegistered = false;
var modelCopy = {};
function activate() {
setView();
setButtonText();
modelCopy = makeModelCopy(scope.model);
$timeout(function() {
if (scope.position === "target") {
setTargetPosition();
}
// this has to be done inside a timeout to ensure the destroy
// event on other overlays is run before registering a new one
registerOverlay();
setOverlayIndent();
});
}
function setView() {
if (scope.view) {
if (scope.view.indexOf(".html") === -1) {
var viewAlias = scope.view.toLowerCase();
scope.view = "views/common/overlays/" + viewAlias + "/" + viewAlias + ".html";
}
}
}
function setButtonText() {
if (!scope.model.closeButtonLabelKey && !scope.model.closeButtonLabel) {
scope.model.closeButtonLabel = localizationService.localize("general_close");
}
if (!scope.model.submitButtonLabelKey && !scope.model.submitButtonLabel) {
scope.model.submitButtonLabel = localizationService.localize("general_submit");
}
}
function registerOverlay() {
overlayNumber = overlayHelper.registerOverlay();
$(document).bind("keydown.overlay-" + overlayNumber, function(event) {
if (event.which === 27) {
numberOfOverlays = overlayHelper.getNumberOfOverlays();
if(numberOfOverlays === overlayNumber) {
scope.closeOverLay();
}
event.preventDefault();
}
if (event.which === 13) {
numberOfOverlays = overlayHelper.getNumberOfOverlays();
if(numberOfOverlays === overlayNumber) {
var activeElementType = document.activeElement.tagName;
var clickableElements = ["A", "BUTTON"];
var submitOnEnter = document.activeElement.hasAttribute("overlay-submit-on-enter");
if(clickableElements.indexOf(activeElementType) === 0) {
document.activeElement.click();
event.preventDefault();
} else if(activeElementType === "TEXTAREA" && !submitOnEnter) {
} else {
scope.$apply(function () {
scope.submitForm(scope.model);
});
event.preventDefault();
}
}
}
});
isRegistered = true;
}
function unregisterOverlay() {
if(isRegistered) {
overlayHelper.unregisterOverlay();
$(document).unbind("keydown.overlay-" + overlayNumber);
isRegistered = false;
}
}
function makeModelCopy(object) {
var newObject = {};
for (var key in object) {
if (key !== "event") {
newObject[key] = angular.copy(object[key]);
}
}
return newObject;
}
function setOverlayIndent() {
var overlayIndex = overlayNumber - 1;
var indentSize = overlayIndex * 20;
var overlayWidth = el.context.clientWidth;
el.css('width', overlayWidth - indentSize);
if(scope.position === "center" || scope.position === "target") {
var overlayTopPosition = el.context.offsetTop;
el.css('top', overlayTopPosition + indentSize);
}
}
function setTargetPosition() {
var container = $("#contentwrapper");
var containerLeft = container[0].offsetLeft;
var containerRight = containerLeft + container[0].offsetWidth;
var containerTop = container[0].offsetTop;
var containerBottom = containerTop + container[0].offsetHeight;
var mousePositionClickX = null;
var mousePositionClickY = null;
var elementHeight = null;
var elementWidth = null;
var position = {
right: "inherit",
left: "inherit",
top: "inherit",
bottom: "inherit"
};
// if mouse click position is know place element with mouse in center
if (scope.model.event && scope.model.event) {
// click position
mousePositionClickX = scope.model.event.pageX;
mousePositionClickY = scope.model.event.pageY;
// element size
elementHeight = el.context.clientHeight;
elementWidth = el.context.clientWidth;
// move element to this position
position.left = mousePositionClickX - (elementWidth / 2);
position.top = mousePositionClickY - (elementHeight / 2);
// check to see if element is outside screen
// outside right
if (position.left + elementWidth > containerRight) {
position.right = 10;
position.left = "inherit";
}
// outside bottom
if (position.top + elementHeight > containerBottom) {
position.bottom = 10;
position.top = "inherit";
}
// outside left
if (position.left < containerLeft) {
position.left = containerLeft + 10;
position.right = "inherit";
}
// outside top
if (position.top < containerTop) {
position.top = 10;
position.bottom = "inherit";
}
el.css(position);
}
}
scope.submitForm = function(model) {
if(scope.model.submit) {
if (formHelper.submitForm({scope: scope})) {
formHelper.resetForm({ scope: scope });
if(scope.model.confirmSubmit && scope.model.confirmSubmit.enable && !scope.directive.enableConfirmButton) {
scope.model.submit(model, modelCopy, scope.directive.enableConfirmButton);
} else {
unregisterOverlay();
scope.model.submit(model, modelCopy, scope.directive.enableConfirmButton);
}
}
}
};
scope.cancelConfirmSubmit = function() {
scope.model.confirmSubmit.show = false;
};
scope.closeOverLay = function() {
unregisterOverlay();
if (scope.model.close) {
scope.model = modelCopy;
scope.model.close(scope.model);
} else {
scope.model.show = false;
scope.model = null;
}
};
// angular does not support ng-show on custom directives
// width isolated scopes. So we have to make our own.
if (attr.hasOwnProperty("ngShow")) {
scope.$watch("ngShow", function(value) {
if (value) {
el.show();
activate();
} else {
unregisterOverlay();
el.hide();
}
});
} else {
activate();
}
scope.$on('$destroy', function(){
unregisterOverlay();
});
}
var directive = {
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/overlays/umb-overlay.html',
scope: {
ngShow: "=",
model: "=",
view: "=",
position: "@"
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbOverlay', OverlayDirective);
})();
(function() {
'use strict';
function OverlayBackdropDirective(overlayHelper) {
function link(scope, el, attr, ctrl) {
scope.numberOfOverlays = 0;
scope.$watch(function(){
return overlayHelper.getNumberOfOverlays();
}, function (newValue) {
scope.numberOfOverlays = newValue;
});
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/overlays/umb-overlay-backdrop.html',
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbOverlayBackdrop', OverlayBackdropDirective);
})();
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbProperty
* @restrict E
**/
angular.module("umbraco.directives")
.directive('umbProperty', function (umbPropEditorHelper) {
return {
scope: {
property: "="
},
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/property/umb-property.html',
link: function(scope) {
scope.propertyAlias = Umbraco.Sys.ServerVariables.isDebuggingEnabled === true ? scope.property.alias : null;
},
//Define a controller for this directive to expose APIs to other directives
controller: function ($scope, $timeout) {
var self = this;
//set the API properties/methods
self.property = $scope.property;
self.setPropertyError = function(errorMsg) {
$scope.property.propertyErrorMessage = errorMsg;
};
}
};
});
/**
* @ngdoc directive
* @function
* @name umbraco.directives.directive:umbPropertyEditor
* @requires formController
* @restrict E
**/
//share property editor directive function
var _umbPropertyEditor = function (umbPropEditorHelper) {
return {
scope: {
model: "=",
isPreValue: "@",
preview: "@"
},
require: "^form",
restrict: 'E',
replace: true,
templateUrl: 'views/components/property/umb-property-editor.html',
link: function (scope, element, attrs, ctrl) {
//we need to copy the form controller val to our isolated scope so that
//it get's carried down to the child scopes of this!
//we'll also maintain the current form name.
scope[ctrl.$name] = ctrl;
if(!scope.model.alias){
scope.model.alias = Math.random().toString(36).slice(2);
}
scope.$watch("model.view", function(val){
scope.propertyEditorView = umbPropEditorHelper.getViewPath(scope.model.view, scope.isPreValue);
});
}
};
};
//Preffered is the umb-property-editor as its more explicit - but we keep umb-editor for backwards compat
angular.module("umbraco.directives").directive('umbPropertyEditor', _umbPropertyEditor);
angular.module("umbraco.directives").directive('umbEditor', _umbPropertyEditor);
angular.module("umbraco.directives.html")
.directive('umbPropertyGroup', function () {
return {
transclude: true,
restrict: 'E',
replace: true,
templateUrl: 'views/components/property/umb-property-group.html'
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbTab
* @restrict E
**/
angular.module("umbraco.directives")
.directive('umbTab', function ($parse, $timeout) {
return {
restrict: 'E',
replace: true,
transclude: 'true',
templateUrl: 'views/components/tabs/umb-tab.html'
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbTabs
* @restrict A
* @description Used to bind to bootstrap tab events so that sub directives can use this API to listen to tab changes
**/
angular.module("umbraco.directives")
.directive('umbTabs', function () {
return {
restrict: 'A',
controller: function ($scope, $element, $attrs) {
var callbacks = [];
this.onTabShown = function(cb) {
callbacks.push(cb);
};
function tabShown(event) {
var curr = $(event.target); // active tab
var prev = $(event.relatedTarget); // previous tab
for (var c in callbacks) {
callbacks[c].apply(this, [{current: curr, previous: prev}]);
}
}
//NOTE: it MUST be done this way - binding to an ancestor element that exists
// in the DOM to bind to the dynamic elements that will be created.
// It would be nicer to create this event handler as a directive for which child
// directives can attach to.
$element.on('shown', '.nav-tabs a', tabShown);
//ensure to unregister
$scope.$on('$destroy', function () {
$element.off('shown', '.nav-tabs a', tabShown);
for (var c in callbacks) {
delete callbacks[c];
}
callbacks = null;
});
}
};
});
(function() {
'use strict';
function UmbTabsContentDirective() {
function link(scope, el, attr, ctrl) {
scope.view = attr.view;
}
var directive = {
restrict: "E",
replace: true,
transclude: 'true',
templateUrl: "views/components/tabs/umb-tabs-content.html",
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbTabsContent', UmbTabsContentDirective);
})();
(function() {
'use strict';
function UmbTabsNavDirective($timeout) {
function link(scope, el, attr) {
function activate() {
$timeout(function () {
//use bootstrap tabs API to show the first one
el.find("a:first").tab('show');
//enable the tab drop
el.tabdrop();
});
}
var unbindModelWatch = scope.$watch('model', function(newValue, oldValue){
activate();
});
scope.$on('$destroy', function () {
//ensure to destroy tabdrop (unbinds window resize listeners)
el.tabdrop("destroy");
unbindModelWatch();
});
}
var directive = {
restrict: "E",
replace: true,
templateUrl: "views/components/tabs/umb-tabs-nav.html",
scope: {
model: "=",
tabdrop: "="
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbTabsNav', UmbTabsNavDirective);
})();
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbTree
* @restrict E
**/
function umbTreeDirective($compile, $log, $q, $rootScope, treeService, notificationsService, $timeout, userService) {
return {
restrict: 'E',
replace: true,
terminal: false,
scope: {
section: '@',
treealias: '@',
hideoptions: '@',
hideheader: '@',
cachekey: '@',
isdialog: '@',
//Custom query string arguments to pass in to the tree as a string, example: "startnodeid=123&something=value"
customtreeparams: '@',
eventhandler: '=',
enablecheckboxes: '@',
enablelistviewsearch: '@'
},
compile: function(element, attrs) {
//config
//var showheader = (attrs.showheader !== 'false');
var hideoptions = (attrs.hideoptions === 'true') ? "hide-options" : "";
var template = '<ul class="umb-tree ' + hideoptions + '"><li class="root">';
template += '<div ng-hide="hideheader" on-right-click="altSelect(tree.root, $event)">' +
'<h5>' +
'<a href="#/{{section}}" ng-click="select(tree.root, $event)" class="root-link"><i ng-if="enablecheckboxes == \'true\'" ng-class="selectEnabledNodeClass(tree.root)"></i> {{tree.name}}</a></h5>' +
'<a class="umb-options" ng-hide="tree.root.isContainer || !tree.root.menuUrl" ng-click="options(tree.root, $event)" ng-swipe-right="options(tree.root, $event)"><i></i><i></i><i></i></a>' +
'</div>';
template += '<ul>' +
'<umb-tree-item ng-repeat="child in tree.root.children" eventhandler="eventhandler" node="child" current-node="currentNode" tree="this" section="{{section}}" ng-animate="animation()"></umb-tree-item>' +
'</ul>' +
'</li>' +
'</ul>';
element.replaceWith(template);
return function(scope, elem, attr, controller) {
//flag to track the last loaded section when the tree 'un-loads'. We use this to determine if we should
// re-load the tree again. For example, if we hover over 'content' the content tree is shown. Then we hover
// outside of the tree and the tree 'un-loads'. When we re-hover over 'content', we don't want to re-load the
// entire tree again since we already still have it in memory. Of course if the section is different we will
// reload it. This saves a lot on processing if someone is navigating in and out of the same section many times
// since it saves on data retreival and DOM processing.
var lastSection = "";
//setup a default internal handler
if (!scope.eventhandler) {
scope.eventhandler = $({});
}
//flag to enable/disable delete animations
var deleteAnimations = false;
/** Helper function to emit tree events */
function emitEvent(eventName, args) {
if (scope.eventhandler) {
$(scope.eventhandler).trigger(eventName, args);
}
}
/** This will deleteAnimations to true after the current digest */
function enableDeleteAnimations() {
//do timeout so that it re-enables them after this digest
$timeout(function () {
//enable delete animations
deleteAnimations = true;
}, 0, false);
}
/*this is the only external interface a tree has */
function setupExternalEvents() {
if (scope.eventhandler) {
scope.eventhandler.clearCache = function(section) {
treeService.clearCache({ section: section });
};
scope.eventhandler.load = function(section) {
scope.section = section;
loadTree();
};
scope.eventhandler.reloadNode = function(node) {
if (!node) {
node = scope.currentNode;
}
if (node) {
scope.loadChildren(node, true);
}
};
/**
Used to do the tree syncing. If the args.tree is not specified we are assuming it has been
specified previously using the _setActiveTreeType
*/
scope.eventhandler.syncTree = function(args) {
if (!args) {
throw "args cannot be null";
}
if (!args.path) {
throw "args.path cannot be null";
}
var deferred = $q.defer();
//this is super complex but seems to be working in other places, here we're listening for our
// own events, once the tree is sycned we'll resolve our promise.
scope.eventhandler.one("treeSynced", function (e, syncArgs) {
deferred.resolve(syncArgs);
});
//this should normally be set unless it is being called from legacy
// code, so set the active tree type before proceeding.
if (args.tree) {
loadActiveTree(args.tree);
}
if (angular.isString(args.path)) {
args.path = args.path.replace('"', '').split(',');
}
//reset current node selection
//scope.currentNode = null;
//Filter the path for root node ids (we don't want to pass in -1 or 'init')
args.path = _.filter(args.path, function (item) { return (item !== "init" && item !== "-1"); });
//Once those are filtered we need to check if the current user has a special start node id,
// if they do, then we're going to trim the start of the array for anything found from that start node
// and previous so that the tree syncs properly. The tree syncs from the top down and if there are parts
// of the tree's path in there that don't actually exist in the dom/model then syncing will not work.
userService.getCurrentUser().then(function(userData) {
var startNodes = [userData.startContentId, userData.startMediaId];
_.each(startNodes, function (i) {
var found = _.find(args.path, function (p) {
return String(p) === String(i);
});
if (found) {
args.path = args.path.splice(_.indexOf(args.path, found));
}
});
loadPath(args.path, args.forceReload, args.activate);
});
return deferred.promise;
};
/**
Internal method that should ONLY be used by the legacy API wrapper, the legacy API used to
have to set an active tree and then sync, the new API does this in one method by using syncTree.
loadChildren is optional but if it is set, it will set the current active tree and load the root
node's children - this is synonymous with the legacy refreshTree method - again should not be used
and should only be used for the legacy code to work.
*/
scope.eventhandler._setActiveTreeType = function(treeAlias, loadChildren) {
loadActiveTree(treeAlias, loadChildren);
};
}
}
//helper to load a specific path on the active tree as soon as its ready
function loadPath(path, forceReload, activate) {
if (scope.activeTree) {
syncTree(scope.activeTree, path, forceReload, activate);
}
else {
scope.eventhandler.one("activeTreeLoaded", function (e, args) {
syncTree(args.tree, path, forceReload, activate);
});
}
}
//given a tree alias, this will search the current section tree for the specified tree alias and
//set that to the activeTree
//NOTE: loadChildren is ONLY used for legacy purposes, do not use this when syncing the tree as it will cause problems
// since there will be double request and event handling operations.
function loadActiveTree(treeAlias, loadChildren) {
if (!treeAlias) {
return;
}
scope.activeTree = undefined;
function doLoad(tree) {
var childrenAndSelf = [tree].concat(tree.children);
scope.activeTree = _.find(childrenAndSelf, function (node) {
if(node && node.metaData && node.metaData.treeAlias) {
return node.metaData.treeAlias.toUpperCase() === treeAlias.toUpperCase();
}
return false;
});
if (!scope.activeTree) {
throw "Could not find the tree " + treeAlias + ", activeTree has not been set";
}
//This is only used for the legacy tree method refreshTree!
if (loadChildren) {
scope.activeTree.expanded = true;
scope.loadChildren(scope.activeTree, false).then(function() {
emitEvent("activeTreeLoaded", { tree: scope.activeTree });
});
}
else {
emitEvent("activeTreeLoaded", { tree: scope.activeTree });
}
}
if (scope.tree) {
doLoad(scope.tree.root);
}
else {
scope.eventhandler.one("treeLoaded", function(e, args) {
doLoad(args.tree.root);
});
}
}
/** Method to load in the tree data */
function loadTree() {
if (!scope.loading && scope.section) {
scope.loading = true;
//anytime we want to load the tree we need to disable the delete animations
deleteAnimations = false;
//default args
var args = { section: scope.section, tree: scope.treealias, cacheKey: scope.cachekey, isDialog: scope.isdialog ? scope.isdialog : false };
//add the extra query string params if specified
if (scope.customtreeparams) {
args["queryString"] = scope.customtreeparams;
}
treeService.getTree(args)
.then(function(data) {
//set the data once we have it
scope.tree = data;
enableDeleteAnimations();
scope.loading = false;
//set the root as the current active tree
scope.activeTree = scope.tree.root;
emitEvent("treeLoaded", { tree: scope.tree });
emitEvent("treeNodeExpanded", { tree: scope.tree, node: scope.tree.root, children: scope.tree.root.children });
}, function(reason) {
scope.loading = false;
notificationsService.error("Tree Error", reason);
});
}
}
/** syncs the tree, the treeNode can be ANY tree node in the tree that requires syncing */
function syncTree(treeNode, path, forceReload, activate) {
deleteAnimations = false;
treeService.syncTree({
node: treeNode,
path: path,
forceReload: forceReload
}).then(function (data) {
if (activate === undefined || activate === true) {
scope.currentNode = data;
}
emitEvent("treeSynced", { node: data, activate: activate });
enableDeleteAnimations();
});
}
scope.selectEnabledNodeClass = function (node) {
return node ?
node.selected ?
'icon umb-tree-icon sprTree icon-check blue temporary' :
'' :
'';
};
/** method to set the current animation for the node.
* This changes dynamically based on if we are changing sections or just loading normal tree data.
* When changing sections we don't want all of the tree-ndoes to do their 'leave' animations.
*/
scope.animation = function() {
if (deleteAnimations && scope.tree && scope.tree.root && scope.tree.root.expanded) {
return { leave: 'tree-node-delete-leave' };
}
else {
return {};
}
};
/* helper to force reloading children of a tree node */
scope.loadChildren = function(node, forceReload) {
var deferred = $q.defer();
//emit treeNodeExpanding event, if a callback object is set on the tree
emitEvent("treeNodeExpanding", { tree: scope.tree, node: node });
//standardising
if (!node.children) {
node.children = [];
}
if (forceReload || (node.hasChildren && node.children.length === 0)) {
//get the children from the tree service
treeService.loadNodeChildren({ node: node, section: scope.section })
.then(function(data) {
//emit expanded event
emitEvent("treeNodeExpanded", { tree: scope.tree, node: node, children: data });
enableDeleteAnimations();
deferred.resolve(data);
});
}
else {
emitEvent("treeNodeExpanded", { tree: scope.tree, node: node, children: node.children });
node.expanded = true;
enableDeleteAnimations();
deferred.resolve(node.children);
}
return deferred.promise;
};
/**
Method called when the options button next to the root node is called.
The tree doesnt know about this, so it raises an event to tell the parent controller
about it.
*/
scope.options = function(n, ev) {
emitEvent("treeOptionsClick", { element: elem, node: n, event: ev });
};
/**
Method called when an item is clicked in the tree, this passes the
DOM element, the tree node object and the original click
and emits it as a treeNodeSelect element if there is a callback object
defined on the tree
*/
scope.select = function (n, ev) {
//on tree select we need to remove the current node -
// whoever handles this will need to make sure the correct node is selected
//reset current node selection
scope.currentNode = null;
emitEvent("treeNodeSelect", { element: elem, node: n, event: ev });
};
scope.altSelect = function(n, ev) {
emitEvent("treeNodeAltSelect", { element: elem, tree: scope.tree, node: n, event: ev });
};
//watch for section changes
scope.$watch("section", function(newVal, oldVal) {
if (!scope.tree) {
loadTree();
}
if (!newVal) {
//store the last section loaded
lastSection = oldVal;
}
else if (newVal !== oldVal && newVal !== lastSection) {
//only reload the tree data and Dom if the newval is different from the old one
// and if the last section loaded is different from the requested one.
loadTree();
//store the new section to be loaded as the last section
//clear any active trees to reset lookups
lastSection = newVal;
}
});
setupExternalEvents();
loadTree();
};
}
};
}
angular.module("umbraco.directives").directive('umbTree', umbTreeDirective);
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbTreeItem
* @element li
* @function
*
* @description
* Renders a list item, representing a single node in the tree.
* Includes element to toggle children, and a menu toggling button
*
* **note:** This directive is only used internally in the umbTree directive
*
* @example
<example module="umbraco">
<file name="index.html">
<umb-tree-item ng-repeat="child in tree.children" node="child" callback="callback" section="content"></umb-tree-item>
</file>
</example>
*/
angular.module("umbraco.directives")
.directive('umbTreeItem', function ($compile, $http, $templateCache, $interpolate, $log, $location, $rootScope, $window, treeService, $timeout, localizationService) {
return {
restrict: 'E',
replace: true,
scope: {
section: '@',
eventhandler: '=',
currentNode: '=',
node: '=',
tree: '='
},
//TODO: Remove more of the binding from this template and move the DOM manipulation to be manually done in the link function,
// this will greatly improve performance since there's potentially a lot of nodes being rendered = a LOT of watches!
template: '<li ng-class="{\'current\': (node == currentNode), \'has-children\': node.hasChildren}" on-right-click="altSelect(node, $event)">' +
'<div ng-class="getNodeCssClass(node)" ng-swipe-right="options(node, $event)" >' +
//NOTE: This ins element is used to display the search icon if the node is a container/listview and the tree is currently in dialog
//'<ins ng-if="tree.enablelistviewsearch && node.metaData.isContainer" class="umb-tree-node-search icon-search" ng-click="searchNode(node, $event)" alt="searchAltText"></ins>' +
'<ins ng-class="{\'icon-navigation-right\': !node.expanded, \'icon-navigation-down\': node.expanded}" ng-click="load(node)"> </ins>' +
'<i class="icon umb-tree-icon sprTree" ng-click="select(node, $event)"></i>' +
'<a href="#/{{node.routePath}}" ng-click="select(node, $event)"></a>' +
//NOTE: These are the 'option' elipses
'<a class="umb-options" ng-click="options(node, $event)"><i></i><i></i><i></i></a>' +
'<div ng-show="node.loading" class="l"><div></div></div>' +
'</div>' +
'</li>',
link: function (scope, element, attrs) {
localizationService.localize("general_search").then(function (value) {
scope.searchAltText = value;
});
//flag to enable/disable delete animations, default for an item is true
var deleteAnimations = true;
// Helper function to emit tree events
function emitEvent(eventName, args) {
if (scope.eventhandler) {
$(scope.eventhandler).trigger(eventName, args);
}
}
// updates the node's DOM/styles
function setupNodeDom(node, tree) {
//get the first div element
element.children(":first")
//set the padding
.css("padding-left", (node.level * 20) + "px");
//toggle visibility of last 'ins' depending on children
//visibility still ensure the space is "reserved", so both nodes with and without children are aligned.
if (!node.hasChildren) {
element.find("ins").last().css("visibility", "hidden");
}
else {
element.find("ins").last().css("visibility", "visible");
}
var icon = element.find("i:first");
icon.addClass(node.cssClass);
icon.attr("title", node.routePath);
element.find("a:first").text(node.name);
if (!node.menuUrl) {
element.find("a.umb-options").remove();
}
if (node.style) {
element.find("i:first").attr("style", node.style);
}
}
//This will deleteAnimations to true after the current digest
function enableDeleteAnimations() {
//do timeout so that it re-enables them after this digest
$timeout(function () {
//enable delete animations
deleteAnimations = true;
}, 0, false);
}
/** Returns the css classses assigned to the node (div element) */
scope.getNodeCssClass = function (node) {
if (!node) {
return '';
}
var css = [];
if (node.cssClasses) {
_.each(node.cssClasses, function(c) {
css.push(c);
});
}
if (node.selected) {
css.push("umb-tree-node-checked");
}
return css.join(" ");
};
//add a method to the node which we can use to call to update the node data if we need to ,
// this is done by sync tree, we don't want to add a $watch for each node as that would be crazy insane slow
// so we have to do this
scope.node.updateNodeData = function (newNode) {
_.extend(scope.node, newNode);
//now update the styles
setupNodeDom(scope.node, scope.tree);
};
/**
Method called when the options button next to a node is called
In the main tree this opens the menu, but internally the tree doesnt
know about this, so it simply raises an event to tell the parent controller
about it.
*/
scope.options = function (n, ev) {
emitEvent("treeOptionsClick", { element: element, tree: scope.tree, node: n, event: ev });
};
/**
Method called when an item is clicked in the tree, this passes the
DOM element, the tree node object and the original click
and emits it as a treeNodeSelect element if there is a callback object
defined on the tree
*/
scope.select = function (n, ev) {
if (ev.ctrlKey ||
ev.shiftKey ||
ev.metaKey || // apple
(ev.button && ev.button === 1) // middle click, >IE9 + everyone else
) {
return;
}
emitEvent("treeNodeSelect", { element: element, tree: scope.tree, node: n, event: ev });
ev.preventDefault();
};
/**
Method called when an item is right-clicked in the tree, this passes the
DOM element, the tree node object and the original click
and emits it as a treeNodeSelect element if there is a callback object
defined on the tree
*/
scope.altSelect = function (n, ev) {
emitEvent("treeNodeAltSelect", { element: element, tree: scope.tree, node: n, event: ev });
};
/** method to set the current animation for the node.
* This changes dynamically based on if we are changing sections or just loading normal tree data.
* When changing sections we don't want all of the tree-ndoes to do their 'leave' animations.
*/
scope.animation = function () {
if (scope.node.showHideAnimation) {
return scope.node.showHideAnimation;
}
if (deleteAnimations && scope.node.expanded) {
return { leave: 'tree-node-delete-leave' };
}
else {
return {};
}
};
/**
Method called when a node in the tree is expanded, when clicking the arrow
takes the arrow DOM element and node data as parameters
emits treeNodeCollapsing event if already expanded and treeNodeExpanding if collapsed
*/
scope.load = function (node) {
if (node.expanded) {
deleteAnimations = false;
emitEvent("treeNodeCollapsing", { tree: scope.tree, node: node, element: element });
node.expanded = false;
}
else {
scope.loadChildren(node, false);
}
};
/* helper to force reloading children of a tree node */
scope.loadChildren = function (node, forceReload) {
//emit treeNodeExpanding event, if a callback object is set on the tree
emitEvent("treeNodeExpanding", { tree: scope.tree, node: node });
if (node.hasChildren && (forceReload || !node.children || (angular.isArray(node.children) && node.children.length === 0))) {
//get the children from the tree service
treeService.loadNodeChildren({ node: node, section: scope.section })
.then(function (data) {
//emit expanded event
emitEvent("treeNodeExpanded", { tree: scope.tree, node: node, children: data });
enableDeleteAnimations();
});
}
else {
emitEvent("treeNodeExpanded", { tree: scope.tree, node: node, children: node.children });
node.expanded = true;
enableDeleteAnimations();
}
};
//if the current path contains the node id, we will auto-expand the tree item children
setupNodeDom(scope.node, scope.tree);
var template = '<ul ng-class="{collapsed: !node.expanded}"><umb-tree-item ng-repeat="child in node.children" eventhandler="eventhandler" tree="tree" current-node="currentNode" node="child" section="{{section}}" ng-animate="animation()"></umb-tree-item></ul>';
var newElement = angular.element(template);
$compile(newElement)(scope);
element.append(newElement);
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbTreeSearchBox
* @function
* @element ANY
* @restrict E
**/
function treeSearchBox(localizationService, searchService, $q) {
return {
scope: {
searchFromId: "@",
searchFromName: "@",
showSearch: "@",
section: "@",
hideSearchCallback: "=",
searchCallback: "="
},
restrict: "E", // restrict to an element
replace: true, // replace the html element with the template
templateUrl: 'views/components/tree/umb-tree-search-box.html',
link: function (scope, element, attrs, ctrl) {
scope.term = "";
scope.hideSearch = function() {
scope.term = "";
scope.hideSearchCallback();
};
localizationService.localize("general_typeToSearch").then(function (value) {
scope.searchPlaceholderText = value;
});
if (!scope.showSearch) {
scope.showSearch = "false";
}
//used to cancel any request in progress if another one needs to take it's place
var canceler = null;
function performSearch() {
if (scope.term) {
scope.results = [];
//a canceler exists, so perform the cancelation operation and reset
if (canceler) {
canceler.resolve();
canceler = $q.defer();
}
else {
canceler = $q.defer();
}
var searchArgs = {
term: scope.term,
canceler: canceler
};
//append a start node context if there is one
if (scope.searchFromId) {
searchArgs["searchFrom"] = scope.searchFromId;
}
searcher(searchArgs).then(function (data) {
scope.searchCallback(data);
//set back to null so it can be re-created
canceler = null;
});
}
}
scope.$watch("term", _.debounce(function(newVal, oldVal) {
scope.$apply(function() {
if (newVal !== null && newVal !== undefined && newVal !== oldVal) {
performSearch();
}
});
}, 200));
var searcher = searchService.searchContent;
//search
if (scope.section === "member") {
searcher = searchService.searchMembers;
}
else if (scope.section === "media") {
searcher = searchService.searchMedia;
}
}
};
}
angular.module('umbraco.directives').directive("umbTreeSearchBox", treeSearchBox);
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbTreeSearchResults
* @function
* @element ANY
* @restrict E
**/
function treeSearchResults() {
return {
scope: {
results: "=",
selectResultCallback: "="
},
restrict: "E", // restrict to an element
replace: true, // replace the html element with the template
templateUrl: 'views/components/tree/umb-tree-search-results.html',
link: function (scope, element, attrs, ctrl) {
}
};
}
angular.module('umbraco.directives').directive("umbTreeSearchResults", treeSearchResults);
/**
@ngdoc directive
@name umbraco.directives.directive:umbGenerateAlias
@restrict E
@scope
@description
Use this directive to generate a camelCased umbraco alias.
When the aliasFrom value is changed the directive will get a formatted alias from the server and update the alias model. If "enableLock" is set to <code>true</code>
the directive will use {@link umbraco.directives.directive:umbLockedField umbLockedField} to lock and unlock the alias.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<input type="text" ng-model="vm.name" />
<umb-generate-alias
enable-lock="true"
alias-from="vm.name"
alias="vm.alias">
</umb-generate-alias>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.name = "";
vm.alias = "";
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {string} alias (<code>binding</code>): The model where the alias is bound.
@param {string} aliasFrom (<code>binding</code>): The model to generate the alias from.
@param {boolean=} enableLock (<code>binding</code>): Set to <code>true</code> to add a lock next to the alias from where it can be unlocked and changed.
**/
angular.module("umbraco.directives")
.directive('umbGenerateAlias', function ($timeout, entityResource) {
return {
restrict: 'E',
templateUrl: 'views/components/umb-generate-alias.html',
replace: true,
scope: {
alias: '=',
aliasFrom: '=',
enableLock: '=?',
serverValidationField: '@'
},
link: function (scope, element, attrs, ctrl) {
var eventBindings = [];
var bindWatcher = true;
var generateAliasTimeout = "";
var updateAlias = false;
scope.locked = true;
scope.placeholderText = "Enter alias...";
function generateAlias(value) {
if (generateAliasTimeout) {
$timeout.cancel(generateAliasTimeout);
}
if( value !== undefined && value !== "" && value !== null) {
scope.alias = "";
scope.placeholderText = "Generating Alias...";
generateAliasTimeout = $timeout(function () {
updateAlias = true;
entityResource.getSafeAlias(value, true).then(function (safeAlias) {
if (updateAlias) {
scope.alias = safeAlias.alias;
}
});
}, 500);
} else {
updateAlias = true;
scope.alias = "";
scope.placeholderText = "Enter alias...";
}
}
// if alias gets unlocked - stop watching alias
eventBindings.push(scope.$watch('locked', function(newValue, oldValue){
if(newValue === false) {
bindWatcher = false;
}
}));
// validate custom entered alias
eventBindings.push(scope.$watch('alias', function(newValue, oldValue){
if(scope.alias === "" && bindWatcher === true || scope.alias === null && bindWatcher === true) {
// add watcher
eventBindings.push(scope.$watch('aliasFrom', function(newValue, oldValue) {
if(bindWatcher) {
generateAlias(newValue);
}
}));
}
}));
// clean up
scope.$on('$destroy', function(){
// unbind watchers
for(var e in eventBindings) {
eventBindings[e]();
}
});
}
};
});
/**
@ngdoc directive
@name umbraco.directives.directive:umbAvatar
@restrict E
@scope
@description
Use this directive to render an avatar.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-avatar
size="xs"
img-src="{{vm.avatar[0].value}}"
img-srcset="{{vm.avatar[1].value}} 2x, {{vm.avatar[2].value}} 3x">
</umb-avatar>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.avatar = [
{ value: "assets/logo.png" },
{ value: "assets/logo@2x.png" },
{ value: "assets/logo@3x.png" }
];
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {string} size (<code>attribute</code>): The size of the avatar (xs, s, m, l, xl).
@param {string} img-src (<code>attribute</code>): The image source to the avatar.
@param {string} img-srcset (<code>atribute</code>): Reponsive support for the image source.
**/
(function() {
'use strict';
function AvatarDirective() {
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-avatar.html',
scope: {
size: "@",
imgSrc: "@",
imgSrcset: "@"
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbAvatar', AvatarDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbChildSelector
@restrict E
@scope
@description
Use this directive to render a ui component for selecting child items to a parent node.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-child-selector
selected-children="vm.selectedChildren"
available-children="vm.availableChildren"
parent-name="vm.name"
parent-icon="vm.icon"
parent-id="vm.id"
on-add="vm.addChild"
on-remove="vm.removeChild">
</umb-child-selector>
<!-- use overlay to select children from -->
<umb-overlay
ng-if="vm.overlay.show"
model="vm.overlay"
position="target"
view="vm.overlay.view">
</umb-overlay>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.id = 1;
vm.name = "My Parent element";
vm.icon = "icon-document";
vm.selectedChildren = [];
vm.availableChildren = [
{
id: 1,
alias: "item1",
name: "Item 1",
icon: "icon-document"
},
{
id: 2,
alias: "item2",
name: "Item 2",
icon: "icon-document"
}
];
vm.addChild = addChild;
vm.removeChild = removeChild;
function addChild($event) {
vm.overlay = {
view: "itempicker",
title: "Choose child",
availableItems: vm.availableChildren,
selectedItems: vm.selectedChildren,
event: $event,
show: true,
submit: function(model) {
// add selected child
vm.selectedChildren.push(model.selectedItem);
// close overlay
vm.overlay.show = false;
vm.overlay = null;
}
};
}
function removeChild($index) {
vm.selectedChildren.splice($index, 1);
}
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {array} selectedChildren (<code>binding</code>): Array of selected children.
@param {array} availableChildren (<code>binding</code>: Array of items available for selection.
@param {string} parentName (<code>binding</code>): The parent name.
@param {string} parentIcon (<code>binding</code>): The parent icon.
@param {number} parentId (<code>binding</code>): The parent id.
@param {callback} onRemove (<code>binding</code>): Callback when the remove button is clicked on an item.
<h3>The callback returns:</h3>
<ul>
<li><code>child</code>: The selected item.</li>
<li><code>$index</code>: The selected item index.</li>
</ul>
@param {callback} onAdd (<code>binding</code>): Callback when the add button is clicked.
<h3>The callback returns:</h3>
<ul>
<li><code>$event</code>: The select event.</li>
</ul>
**/
(function() {
'use strict';
function ChildSelectorDirective() {
function link(scope, el, attr, ctrl) {
var eventBindings = [];
scope.dialogModel = {};
scope.showDialog = false;
scope.removeChild = function(selectedChild, $index) {
if(scope.onRemove) {
scope.onRemove(selectedChild, $index);
}
};
scope.addChild = function($event) {
if(scope.onAdd) {
scope.onAdd($event);
}
};
function syncParentName() {
// update name on available item
angular.forEach(scope.availableChildren, function(availableChild){
if(availableChild.id === scope.parentId) {
availableChild.name = scope.parentName;
}
});
// update name on selected child
angular.forEach(scope.selectedChildren, function(selectedChild){
if(selectedChild.id === scope.parentId) {
selectedChild.name = scope.parentName;
}
});
}
function syncParentIcon() {
// update icon on available item
angular.forEach(scope.availableChildren, function(availableChild){
if(availableChild.id === scope.parentId) {
availableChild.icon = scope.parentIcon;
}
});
// update icon on selected child
angular.forEach(scope.selectedChildren, function(selectedChild){
if(selectedChild.id === scope.parentId) {
selectedChild.icon = scope.parentIcon;
}
});
}
eventBindings.push(scope.$watch('parentName', function(newValue, oldValue){
if (newValue === oldValue) { return; }
if ( oldValue === undefined || newValue === undefined) { return; }
syncParentName();
}));
eventBindings.push(scope.$watch('parentIcon', function(newValue, oldValue){
if (newValue === oldValue) { return; }
if ( oldValue === undefined || newValue === undefined) { return; }
syncParentIcon();
}));
// clean up
scope.$on('$destroy', function(){
// unbind watchers
for(var e in eventBindings) {
eventBindings[e]();
}
});
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-child-selector.html',
scope: {
selectedChildren: '=',
availableChildren: "=",
parentName: "=",
parentIcon: "=",
parentId: "=",
onRemove: "=",
onAdd: "="
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbChildSelector', ChildSelectorDirective);
})();
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbConfirm
* @function
* @description
* A confirmation dialog
*
* @restrict E
*/
function confirmDirective() {
return {
restrict: "E", // restrict to an element
replace: true, // replace the html element with the template
templateUrl: 'views/components/umb-confirm.html',
scope: {
onConfirm: '=',
onCancel: '=',
caption: '@'
},
link: function (scope, element, attr, ctrl) {
}
};
}
angular.module('umbraco.directives').directive("umbConfirm", confirmDirective);
/**
@ngdoc directive
@name umbraco.directives.directive:umbConfirmAction
@restrict E
@scope
@description
<p>Use this directive to toggle a confirmation prompt for an action.
The prompt consists of a checkmark and a cross to confirm or cancel the action.
The prompt can be opened in four direction up, down, left or right.</p>
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<div class="my-action" style="position:relative;">
<i class="icon-trash" ng-click="vm.showPrompt()"></i>
<umb-confirm-action
ng-if="vm.promptIsVisible"
direction="left"
on-confirm="vm.confirmAction()"
on-cancel="vm.hidePrompt()">
</umb-confirm-action>
</div>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.promptIsVisible = false;
vm.confirmAction = confirmAction;
vm.showPrompt = showPrompt;
vm.hidePrompt = hidePrompt;
function confirmAction() {
// confirm logic here
}
function showPrompt() {
vm.promptIsVisible = true;
}
function hidePrompt() {
vm.promptIsVisible = false;
}
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {string} direction The direction the prompt opens ("up", "down", "left", "right").
@param {callback} onConfirm Callback when the checkmark is clicked.
@param {callback} onCancel Callback when the cross is clicked.
**/
(function() {
'use strict';
function ConfirmAction() {
function link(scope, el, attr, ctrl) {
scope.clickConfirm = function() {
if(scope.onConfirm) {
scope.onConfirm();
}
};
scope.clickCancel = function() {
if(scope.onCancel) {
scope.onCancel();
}
};
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-confirm-action.html',
scope: {
direction: "@",
onConfirm: "&",
onCancel: "&"
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbConfirmAction', ConfirmAction);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbContentGrid
@restrict E
@scope
@description
Use this directive to generate a list of content items presented as a flexbox grid.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-content-grid
content="vm.contentItems"
content-properties="vm.includeProperties"
on-click="vm.selectItem"
on-click-name="vm.clickItem">
</umb-content-grid>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.contentItems = [
{
"name": "Cape",
"published": true,
"icon": "icon-document",
"updateDate": "15-02-2016",
"owner": "Mr. Batman",
"selected": false
},
{
"name": "Utility Belt",
"published": true,
"icon": "icon-document",
"updateDate": "15-02-2016",
"owner": "Mr. Batman",
"selected": false
},
{
"name": "Cave",
"published": true,
"icon": "icon-document",
"updateDate": "15-02-2016",
"owner": "Mr. Batman",
"selected": false
}
];
vm.includeProperties = [
{
"alias": "updateDate",
"header": "Last edited"
},
{
"alias": "owner",
"header": "Created by"
}
];
vm.clickItem = clickItem;
vm.selectItem = selectItem;
function clickItem(item, $event, $index){
// do magic here
}
function selectItem(item, $event, $index) {
// set item.selected = true; to select the item
// do magic here
}
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {array} content (<code>binding</code>): Array of content items.
@param {array=} contentProperties (<code>binding</code>): Array of content item properties to include in the item. If left empty the item will only show the item icon and name.
@param {callback=} onClick (<code>binding</code>): Callback method to handle click events on the content item.
<h3>The callback returns:</h3>
<ul>
<li><code>item</code>: The clicked item</li>
<li><code>$event</code>: The select event</li>
<li><code>$index</code>: The item index</li>
</ul>
@param {callback=} onClickName (<code>binding</code>): Callback method to handle click events on the checkmark icon.
<h3>The callback returns:</h3>
<ul>
<li><code>item</code>: The selected item</li>
<li><code>$event</code>: The select event</li>
<li><code>$index</code>: The item index</li>
</ul>
**/
(function() {
'use strict';
function ContentGridDirective() {
function link(scope, el, attr, ctrl) {
scope.clickItem = function(item, $event, $index) {
if(scope.onClick) {
scope.onClick(item, $event, $index);
}
};
scope.clickItemName = function(item, $event, $index) {
if(scope.onClickName) {
scope.onClickName(item, $event, $index);
}
};
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-content-grid.html',
scope: {
content: '=',
contentProperties: "=",
onClick: "=",
onClickName: "="
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbContentGrid', ContentGridDirective);
})();
(function() {
'use strict';
function UmbDisableFormValidation() {
var directive = {
restrict: 'A',
require: '?form',
link: function (scope, elm, attrs, ctrl) {
//override the $setValidity function of the form to disable validation
ctrl.$setValidity = function () { };
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbDisableFormValidation', UmbDisableFormValidation);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbEmptyState
@restrict E
@scope
@description
Use this directive to show an empty state message.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-empty-state
ng-if="!vm.items"
position="center">
// Empty state content
</umb-empty-state>
</div>
</pre>
@param {string=} size Set the size of the text ("small", "large").
@param {string=} position Set the position of the text ("center").
**/
(function() {
'use strict';
function EmptyStateDirective() {
var directive = {
restrict: 'E',
replace: true,
transclude: true,
templateUrl: 'views/components/umb-empty-state.html',
scope: {
size: '@',
position: '@'
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbEmptyState', EmptyStateDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbFolderGrid
@restrict E
@scope
@description
Use this directive to generate a list of folders presented as a flexbox grid.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-folder-grid
ng-if="vm.folders.length > 0"
folders="vm.folders"
on-click="vm.clickFolder"
on-select="vm.selectFolder">
</umb-folder-grid>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller(myService) {
var vm = this;
vm.folders = [
{
"name": "Folder 1",
"icon": "icon-folder",
"selected": false
},
{
"name": "Folder 2",
"icon": "icon-folder",
"selected": false
}
];
vm.clickFolder = clickFolder;
vm.selectFolder = selectFolder;
myService.getFolders().then(function(folders){
vm.folders = folders;
});
function clickFolder(folder){
// Execute when clicking folder name/link
}
function selectFolder(folder, event, index) {
// Execute when clicking folder
// set folder.selected = true; to show checkmark icon
}
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {array} folders (<code>binding</code>): Array of folders
@param {callback=} onClick (<code>binding</code>): Callback method to handle click events on the folder.
<h3>The callback returns:</h3>
<ul>
<li><code>folder</code>: The selected folder</li>
</ul>
@param {callback=} onSelect (<code>binding</code>): Callback method to handle click events on the checkmark icon.
<h3>The callback returns:</h3>
<ul>
<li><code>folder</code>: The selected folder</li>
<li><code>$event</code>: The select event</li>
<li><code>$index</code>: The folder index</li>
</ul>
**/
(function() {
'use strict';
function FolderGridDirective() {
function link(scope, el, attr, ctrl) {
scope.clickFolder = function(folder, $event, $index) {
if(scope.onClick) {
scope.onClick(folder, $event, $index);
}
};
scope.clickFolderName = function(folder, $event, $index) {
if(scope.onClickName) {
scope.onClickName(folder, $event, $index);
$event.stopPropagation();
}
};
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-folder-grid.html',
scope: {
folders: '=',
onClick: "=",
onClickName: "="
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbFolderGrid', FolderGridDirective);
})();
(function() {
'use strict';
function GridSelector() {
function link(scope, el, attr, ctrl) {
var eventBindings = [];
scope.dialogModel = {};
scope.showDialog = false;
scope.itemLabel = "";
// set default item name
if(!scope.itemName){
scope.itemLabel = "item";
} else {
scope.itemLabel = scope.itemName;
}
scope.removeItem = function(selectedItem) {
var selectedItemIndex = scope.selectedItems.indexOf(selectedItem);
scope.selectedItems.splice(selectedItemIndex, 1);
};
scope.removeDefaultItem = function() {
// it will be the last item so we can clear the array
scope.selectedItems = [];
// remove as default item
scope.defaultItem = null;
};
scope.openItemPicker = function($event){
scope.dialogModel = {
view: "itempicker",
title: "Choose " + scope.itemLabel,
availableItems: scope.availableItems,
selectedItems: scope.selectedItems,
event: $event,
show: true,
submit: function(model) {
scope.selectedItems.push(model.selectedItem);
// if no default item - set item as default
if(scope.defaultItem === null) {
scope.setAsDefaultItem(model.selectedItem);
}
scope.dialogModel.show = false;
scope.dialogModel = null;
}
};
};
scope.setAsDefaultItem = function(selectedItem) {
// clear default item
scope.defaultItem = {};
// set as default item
scope.defaultItem = selectedItem;
};
function updatePlaceholders() {
// update default item
if(scope.defaultItem !== null && scope.defaultItem.placeholder) {
scope.defaultItem.name = scope.name;
if(scope.alias !== null && scope.alias !== undefined) {
scope.defaultItem.alias = scope.alias;
}
}
// update selected items
angular.forEach(scope.selectedItems, function(selectedItem) {
if(selectedItem.placeholder) {
selectedItem.name = scope.name;
if(scope.alias !== null && scope.alias !== undefined) {
selectedItem.alias = scope.alias;
}
}
});
// update availableItems
angular.forEach(scope.availableItems, function(availableItem) {
if(availableItem.placeholder) {
availableItem.name = scope.name;
if(scope.alias !== null && scope.alias !== undefined) {
availableItem.alias = scope.alias;
}
}
});
}
function activate() {
// add watchers for updating placeholde name and alias
if(scope.updatePlaceholder) {
eventBindings.push(scope.$watch('name', function(newValue, oldValue){
updatePlaceholders();
}));
eventBindings.push(scope.$watch('alias', function(newValue, oldValue){
updatePlaceholders();
}));
}
}
activate();
// clean up
scope.$on('$destroy', function(){
// clear watchers
for(var e in eventBindings) {
eventBindings[e]();
}
});
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-grid-selector.html',
scope: {
name: "=",
alias: "=",
selectedItems: '=',
availableItems: "=",
defaultItem: "=",
itemName: "@",
updatePlaceholder: "="
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbGridSelector', GridSelector);
})();
(function() {
'use strict';
function GroupsBuilderDirective(contentTypeHelper, contentTypeResource, mediaTypeResource, dataTypeHelper, dataTypeResource, $filter, iconHelper, $q, $timeout, notificationsService, localizationService) {
function link(scope, el, attr, ctrl) {
var validationTranslated = "";
var tabNoSortOrderTranslated = "";
scope.sortingMode = false;
scope.toolbar = [];
scope.sortableOptionsGroup = {};
scope.sortableOptionsProperty = {};
scope.sortingButtonKey = "general_reorder";
function activate() {
setSortingOptions();
// set placeholder property on each group
if (scope.model.groups.length !== 0) {
angular.forEach(scope.model.groups, function(group) {
addInitProperty(group);
});
}
// add init tab
addInitGroup(scope.model.groups);
activateFirstGroup(scope.model.groups);
// localize texts
localizationService.localize("validation_validation").then(function(value) {
validationTranslated = value;
});
localizationService.localize("contentTypeEditor_tabHasNoSortOrder").then(function(value) {
tabNoSortOrderTranslated = value;
});
}
function setSortingOptions() {
scope.sortableOptionsGroup = {
distance: 10,
tolerance: "pointer",
opacity: 0.7,
scroll: true,
cursor: "move",
placeholder: "umb-group-builder__group-sortable-placeholder",
zIndex: 6000,
handle: ".umb-group-builder__group-handle",
items: ".umb-group-builder__group-sortable",
start: function(e, ui) {
ui.placeholder.height(ui.item.height());
},
stop: function(e, ui) {
updateTabsSortOrder();
},
};
scope.sortableOptionsProperty = {
distance: 10,
tolerance: "pointer",
connectWith: ".umb-group-builder__properties",
opacity: 0.7,
scroll: true,
cursor: "move",
placeholder: "umb-group-builder__property_sortable-placeholder",
zIndex: 6000,
handle: ".umb-group-builder__property-handle",
items: ".umb-group-builder__property-sortable",
start: function(e, ui) {
ui.placeholder.height(ui.item.height());
},
stop: function(e, ui) {
updatePropertiesSortOrder();
}
};
}
function updateTabsSortOrder() {
var first = true;
var prevSortOrder = 0;
scope.model.groups.map(function(group){
var index = scope.model.groups.indexOf(group);
if(group.tabState !== "init") {
// set the first not inherited tab to sort order 0
if(!group.inherited && first) {
// set the first tab sort order to 0 if prev is 0
if( prevSortOrder === 0 ) {
group.sortOrder = 0;
// when the first tab is inherited and sort order is not 0
} else {
group.sortOrder = prevSortOrder + 1;
}
first = false;
} else if(!group.inherited && !first) {
// find next group
var nextGroup = scope.model.groups[index + 1];
// if a groups is dropped in the middle of to groups with
// same sort order. Give it the dropped group same sort order
if( prevSortOrder === nextGroup.sortOrder ) {
group.sortOrder = prevSortOrder;
} else {
group.sortOrder = prevSortOrder + 1;
}
}
// store this tabs sort order as reference for the next
prevSortOrder = group.sortOrder;
}
});
}
function filterAvailableCompositions(selectedContentType, selecting) {
//selecting = true if the user has check the item, false if the user has unchecked the item
var selectedContentTypeAliases = selecting ?
//the user has selected the item so add to the current list
_.union(scope.compositionsDialogModel.compositeContentTypes, [selectedContentType.alias]) :
//the user has unselected the item so remove from the current list
_.reject(scope.compositionsDialogModel.compositeContentTypes, function(i) {
return i === selectedContentType.alias;
});
//get the currently assigned property type aliases - ensure we pass these to the server side filer
var propAliasesExisting = _.filter(_.flatten(_.map(scope.model.groups, function(g) {
return _.map(g.properties, function(p) {
return p.alias;
});
})), function (f) {
return f !== null && f !== undefined;
});
//use a different resource lookup depending on the content type type
var resourceLookup = scope.contentType === "documentType" ? contentTypeResource.getAvailableCompositeContentTypes : mediaTypeResource.getAvailableCompositeContentTypes;
return resourceLookup(scope.model.id, selectedContentTypeAliases, propAliasesExisting).then(function (filteredAvailableCompositeTypes) {
_.each(scope.compositionsDialogModel.availableCompositeContentTypes, function (current) {
//reset first
current.allowed = true;
//see if this list item is found in the response (allowed) list
var found = _.find(filteredAvailableCompositeTypes, function (f) {
return current.contentType.alias === f.contentType.alias;
});
//allow if the item was found in the response (allowed) list -
// and ensure its set to allowed if it is currently checked,
// DO not allow if it's a locked content type.
current.allowed = scope.model.lockedCompositeContentTypes.indexOf(current.contentType.alias) === -1 &&
(selectedContentTypeAliases.indexOf(current.contentType.alias) !== -1) || ((found !== null && found !== undefined) ? found.allowed : false);
});
});
}
function updatePropertiesSortOrder() {
angular.forEach(scope.model.groups, function(group){
if( group.tabState !== "init" ) {
group.properties = contentTypeHelper.updatePropertiesSortOrder(group.properties);
}
});
}
function setupAvailableContentTypesModel(result) {
scope.compositionsDialogModel.availableCompositeContentTypes = result;
//iterate each one and set it up
_.each(scope.compositionsDialogModel.availableCompositeContentTypes, function (c) {
//enable it if it's part of the selected model
if (scope.compositionsDialogModel.compositeContentTypes.indexOf(c.contentType.alias) !== -1) {
c.allowed = true;
}
//set the inherited flags
c.inherited = false;
if (scope.model.lockedCompositeContentTypes.indexOf(c.contentType.alias) > -1) {
c.inherited = true;
}
// convert icons for composite content types
iconHelper.formatContentTypeIcons([c.contentType]);
});
}
/* ---------- DELETE PROMT ---------- */
scope.togglePrompt = function (object) {
object.deletePrompt = !object.deletePrompt;
};
scope.hidePrompt = function (object) {
object.deletePrompt = false;
};
/* ---------- TOOLBAR ---------- */
scope.toggleSortingMode = function(tool) {
if (scope.sortingMode === true) {
var sortOrderMissing = false;
for (var i = 0; i < scope.model.groups.length; i++) {
var group = scope.model.groups[i];
if (group.tabState !== "init" && group.sortOrder === undefined) {
sortOrderMissing = true;
group.showSortOrderMissing = true;
notificationsService.error(validationTranslated + ": " + group.name + " " + tabNoSortOrderTranslated);
}
}
if (!sortOrderMissing) {
scope.sortingMode = false;
scope.sortingButtonKey = "general_reorder";
}
} else {
scope.sortingMode = true;
scope.sortingButtonKey = "general_reorderDone";
}
};
scope.openCompositionsDialog = function() {
scope.compositionsDialogModel = {
title: "Compositions",
contentType: scope.model,
compositeContentTypes: scope.model.compositeContentTypes,
view: "views/common/overlays/contenttypeeditor/compositions/compositions.html",
confirmSubmit: {
title: "Warning",
description: "Removing a composition will delete all the associated property data. Once you save the document type there's no way back, are you sure?",
checkboxLabel: "I know what I'm doing",
enable: true
},
submit: function(model, oldModel, confirmed) {
var compositionRemoved = false;
// check if any compositions has been removed
for(var i = 0; oldModel.compositeContentTypes.length > i; i++) {
var oldComposition = oldModel.compositeContentTypes[i];
if(_.contains(model.compositeContentTypes, oldComposition) === false) {
compositionRemoved = true;
}
}
// show overlay confirm box if compositions has been removed.
if(compositionRemoved && confirmed === false) {
scope.compositionsDialogModel.confirmSubmit.show = true;
// submit overlay if no compositions has been removed
// or the action has been confirmed
} else {
// make sure that all tabs has an init property
if (scope.model.groups.length !== 0) {
angular.forEach(scope.model.groups, function(group) {
addInitProperty(group);
});
}
// remove overlay
scope.compositionsDialogModel.show = false;
scope.compositionsDialogModel = null;
}
},
close: function(oldModel) {
// reset composition changes
scope.model.groups = oldModel.contentType.groups;
scope.model.compositeContentTypes = oldModel.contentType.compositeContentTypes;
// remove overlay
scope.compositionsDialogModel.show = false;
scope.compositionsDialogModel = null;
},
selectCompositeContentType: function (selectedContentType) {
//first check if this is a new selection - we need to store this value here before any further digests/async
// because after that the scope.model.compositeContentTypes will be populated with the selected value.
var newSelection = scope.model.compositeContentTypes.indexOf(selectedContentType.alias) === -1;
if (newSelection) {
//merge composition with content type
//use a different resource lookup depending on the content type type
var resourceLookup = scope.contentType === "documentType" ? contentTypeResource.getById : mediaTypeResource.getById;
resourceLookup(selectedContentType.id).then(function (composition) {
//based on the above filtering we shouldn't be able to select an invalid one, but let's be safe and
// double check here.
var overlappingAliases = contentTypeHelper.validateAddingComposition(scope.model, composition);
if (overlappingAliases.length > 0) {
//this will create an invalid composition, need to uncheck it
scope.compositionsDialogModel.compositeContentTypes.splice(
scope.compositionsDialogModel.compositeContentTypes.indexOf(composition.alias), 1);
//dissallow this until something else is unchecked
selectedContentType.allowed = false;
}
else {
contentTypeHelper.mergeCompositeContentType(scope.model, composition);
}
//based on the selection, we need to filter the available composite types list
filterAvailableCompositions(selectedContentType, newSelection).then(function () {
//TODO: Here we could probably re-enable selection if we previously showed a throbber or something
});
});
}
else {
// split composition from content type
contentTypeHelper.splitCompositeContentType(scope.model, selectedContentType);
//based on the selection, we need to filter the available composite types list
filterAvailableCompositions(selectedContentType, newSelection).then(function () {
//TODO: Here we could probably re-enable selection if we previously showed a throbber or something
});
}
}
};
var availableContentTypeResource = scope.contentType === "documentType" ? contentTypeResource.getAvailableCompositeContentTypes : mediaTypeResource.getAvailableCompositeContentTypes;
var countContentTypeResource = scope.contentType === "documentType" ? contentTypeResource.getCount : mediaTypeResource.getCount;
//get the currently assigned property type aliases - ensure we pass these to the server side filer
var propAliasesExisting = _.filter(_.flatten(_.map(scope.model.groups, function(g) {
return _.map(g.properties, function(p) {
return p.alias;
});
})), function(f) {
return f !== null && f !== undefined;
});
$q.all([
//get available composite types
availableContentTypeResource(scope.model.id, [], propAliasesExisting).then(function (result) {
setupAvailableContentTypesModel(result);
}),
//get content type count
countContentTypeResource().then(function(result) {
scope.compositionsDialogModel.totalContentTypes = parseInt(result, 10);
})
]).then(function() {
//resolves when both other promises are done, now show it
scope.compositionsDialogModel.show = true;
});
};
/* ---------- GROUPS ---------- */
scope.addGroup = function(group) {
// set group sort order
var index = scope.model.groups.indexOf(group);
var prevGroup = scope.model.groups[index - 1];
if( index > 0) {
// set index to 1 higher than the previous groups sort order
group.sortOrder = prevGroup.sortOrder + 1;
} else {
// first group - sort order will be 0
group.sortOrder = 0;
}
// activate group
scope.activateGroup(group);
};
scope.activateGroup = function(selectedGroup) {
// set all other groups that are inactive to active
angular.forEach(scope.model.groups, function(group) {
// skip init tab
if (group.tabState !== "init") {
group.tabState = "inActive";
}
});
selectedGroup.tabState = "active";
};
scope.removeGroup = function(groupIndex) {
scope.model.groups.splice(groupIndex, 1);
addInitGroup(scope.model.groups);
};
scope.updateGroupTitle = function(group) {
if (group.properties.length === 0) {
addInitProperty(group);
}
};
scope.changeSortOrderValue = function(group) {
if (group.sortOrder !== undefined) {
group.showSortOrderMissing = false;
}
scope.model.groups = $filter('orderBy')(scope.model.groups, 'sortOrder');
};
function addInitGroup(groups) {
// check i init tab already exists
var addGroup = true;
angular.forEach(groups, function(group) {
if (group.tabState === "init") {
addGroup = false;
}
});
if (addGroup) {
groups.push({
properties: [],
parentTabContentTypes: [],
parentTabContentTypeNames: [],
name: "",
tabState: "init"
});
}
return groups;
}
function activateFirstGroup(groups) {
if (groups && groups.length > 0) {
var firstGroup = groups[0];
if(!firstGroup.tabState || firstGroup.tabState === "inActive") {
firstGroup.tabState = "active";
}
}
}
/* ---------- PROPERTIES ---------- */
scope.addProperty = function(property, group) {
// set property sort order
var index = group.properties.indexOf(property);
var prevProperty = group.properties[index - 1];
if( index > 0) {
// set index to 1 higher than the previous property sort order
property.sortOrder = prevProperty.sortOrder + 1;
} else {
// first property - sort order will be 0
property.sortOrder = 0;
}
// open property settings dialog
scope.editPropertyTypeSettings(property, group);
};
scope.editPropertyTypeSettings = function(property, group) {
if (!property.inherited && !property.locked) {
scope.propertySettingsDialogModel = {};
scope.propertySettingsDialogModel.title = "Property settings";
scope.propertySettingsDialogModel.property = property;
scope.propertySettingsDialogModel.contentType = scope.contentType;
scope.propertySettingsDialogModel.contentTypeName = scope.model.name;
scope.propertySettingsDialogModel.view = "views/common/overlays/contenttypeeditor/propertysettings/propertysettings.html";
scope.propertySettingsDialogModel.show = true;
// set state to active to access the preview
property.propertyState = "active";
// set property states
property.dialogIsOpen = true;
scope.propertySettingsDialogModel.submit = function(model) {
property.inherited = false;
property.dialogIsOpen = false;
// update existing data types
if(model.updateSameDataTypes) {
updateSameDataTypes(property);
}
// remove dialog
scope.propertySettingsDialogModel.show = false;
scope.propertySettingsDialogModel = null;
// push new init property to group
addInitProperty(group);
// set focus on init property
var numberOfProperties = group.properties.length;
group.properties[numberOfProperties - 1].focus = true;
// push new init tab to the scope
addInitGroup(scope.model.groups);
};
scope.propertySettingsDialogModel.close = function(oldModel) {
// reset all property changes
property.label = oldModel.property.label;
property.alias = oldModel.property.alias;
property.description = oldModel.property.description;
property.config = oldModel.property.config;
property.editor = oldModel.property.editor;
property.view = oldModel.property.view;
property.dataTypeId = oldModel.property.dataTypeId;
property.dataTypeIcon = oldModel.property.dataTypeIcon;
property.dataTypeName = oldModel.property.dataTypeName;
property.validation.mandatory = oldModel.property.validation.mandatory;
property.validation.pattern = oldModel.property.validation.pattern;
property.showOnMemberProfile = oldModel.property.showOnMemberProfile;
property.memberCanEdit = oldModel.property.memberCanEdit;
// because we set state to active, to show a preview, we have to check if has been filled out
// label is required so if it is not filled we know it is a placeholder
if(oldModel.property.editor === undefined || oldModel.property.editor === null || oldModel.property.editor === "") {
property.propertyState = "init";
} else {
property.propertyState = oldModel.property.propertyState;
}
// remove dialog
scope.propertySettingsDialogModel.show = false;
scope.propertySettingsDialogModel = null;
};
}
};
scope.deleteProperty = function(tab, propertyIndex) {
// remove property
tab.properties.splice(propertyIndex, 1);
// if the last property in group is an placeholder - remove add new tab placeholder
if(tab.properties.length === 1 && tab.properties[0].propertyState === "init") {
angular.forEach(scope.model.groups, function(group, index, groups){
if(group.tabState === 'init') {
groups.splice(index, 1);
}
});
}
};
function addInitProperty(group) {
var addInitPropertyBool = true;
var initProperty = {
label: null,
alias: null,
propertyState: "init",
validation: {
mandatory: false,
pattern: null
}
};
// check if there already is an init property
angular.forEach(group.properties, function(property) {
if (property.propertyState === "init") {
addInitPropertyBool = false;
}
});
if (addInitPropertyBool) {
group.properties.push(initProperty);
}
return group;
}
function updateSameDataTypes(newProperty) {
// find each property
angular.forEach(scope.model.groups, function(group){
angular.forEach(group.properties, function(property){
if(property.dataTypeId === newProperty.dataTypeId) {
// update property data
property.config = newProperty.config;
property.editor = newProperty.editor;
property.view = newProperty.view;
property.dataTypeId = newProperty.dataTypeId;
property.dataTypeIcon = newProperty.dataTypeIcon;
property.dataTypeName = newProperty.dataTypeName;
}
});
});
}
var unbindModelWatcher = scope.$watch('model', function(newValue, oldValue) {
if (newValue !== undefined && newValue.groups !== undefined) {
activate();
}
});
// clean up
scope.$on('$destroy', function(){
unbindModelWatcher();
});
}
var directive = {
restrict: "E",
replace: true,
templateUrl: "views/components/umb-groups-builder.html",
scope: {
model: "=",
compositions: "=",
sorting: "=",
contentType: "@"
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbGroupsBuilder', GroupsBuilderDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbkeyboardShortcutsOverview
@restrict E
@scope
@description
<p>Use this directive to show an overview of keyboard shortcuts in an editor.
The directive will render an overview trigger wich shows how the overview is opened.
When this combination is hit an overview is opened with shortcuts based on the model sent to the directive.</p>
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-keyboard-shortcuts-overview
model="vm.keyboardShortcutsOverview">
</umb-keyboard-shortcuts-overview>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.keyboardShortcutsOverview = [
{
"name": "Sections",
"shortcuts": [
{
"description": "Navigate sections",
"keys": [
{"key": "1"},
{"key": "4"}
],
"keyRange": true
}
]
},
{
"name": "Design",
"shortcuts": [
{
"description": "Add tab",
"keys": [
{"key": "alt"},
{"key": "shift"},
{"key": "t"}
]
}
]
}
];
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
<h3>Model description</h3>
<ul>
<li>
<strong>name</strong>
<small>(string)</small> -
Sets the shortcut section name.
</li>
<li>
<strong>shortcuts</strong>
<small>(array)</small> -
Array of available shortcuts in the section.
</li>
<ul>
<li>
<strong>description</strong>
<small>(string)</small> -
Short description of the shortcut.
</li>
<li>
<strong>keys</strong>
<small>(array)</small> -
Array of keys in the shortcut.
</li>
<ul>
<li>
<strong>key</strong>
<small>(string)</small> -
The invidual key in the shortcut.
</li>
</ul>
<li>
<strong>keyRange</strong>
<small>(boolean)</small> -
Set to <code>true</code> to show a key range. It combines the shortcut keys with "-" instead of "+".
</li>
</ul>
</ul>
@param {object} model keyboard shortcut model. See description and example above.
**/
(function() {
'use strict';
function KeyboardShortcutsOverviewDirective() {
function link(scope, el, attr, ctrl) {
scope.shortcutOverlay = false;
scope.toggleShortcutsOverlay = function() {
scope.shortcutOverlay = !scope.shortcutOverlay;
};
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-keyboard-shortcuts-overview.html',
link: link,
scope: {
model: "="
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbKeyboardShortcutsOverview', KeyboardShortcutsOverviewDirective);
})();
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbLaunchMiniEditor
* @restrict E
* @function
* @description
* Used on a button to launch a mini content editor editor dialog
**/
angular.module("umbraco.directives")
.directive('umbLaunchMiniEditor', function (dialogService, editorState, fileManager, contentEditingHelper) {
return {
restrict: 'A',
replace: false,
scope: {
node: '=umbLaunchMiniEditor',
},
link: function(scope, element, attrs) {
var launched = false;
element.click(function() {
if (launched === true) {
return;
}
launched = true;
//We need to store the current files selected in the file manager locally because the fileManager
// is a singleton and is shared globally. The mini dialog will also be referencing the fileManager
// and we don't want it to be sharing the same files as the main editor. So we'll store the current files locally here,
// clear them out and then launch the dialog. When the dialog closes, we'll reset the fileManager to it's previous state.
var currFiles = _.groupBy(fileManager.getFiles(), "alias");
fileManager.clearFiles();
//We need to store the original editorState entity because it will need to change when the mini editor is loaded so that
// any property editors that are working with editorState get given the correct entity, otherwise strange things will
// start happening.
var currEditorState = editorState.getCurrent();
dialogService.open({
template: "views/common/dialogs/content/edit.html",
id: scope.node.id,
closeOnSave: true,
tabFilter: ["Generic properties"],
callback: function (data) {
//set the node name back
scope.node.name = data.name;
//reset the fileManager to what it was
fileManager.clearFiles();
_.each(currFiles, function (val, key) {
fileManager.setFiles(key, _.map(currFiles['upload'], function (i) { return i.file; }));
});
//reset the editor state
editorState.set(currEditorState);
//Now we need to check if the content item that was edited was actually the same content item
// as the main content editor and if so, update all property data
if (data.id === currEditorState.id) {
var changed = contentEditingHelper.reBindChangedProperties(currEditorState, data);
}
launched = false;
},
closeCallback: function () {
//reset the fileManager to what it was
fileManager.clearFiles();
_.each(currFiles, function (val, key) {
fileManager.setFiles(key, _.map(currFiles['upload'], function (i) { return i.file; }));
});
//reset the editor state
editorState.set(currEditorState);
launched = false;
}
});
});
}
};
});
(function() {
'use strict';
function LayoutSelectorDirective() {
function link(scope, el, attr, ctrl) {
scope.layoutDropDownIsOpen = false;
scope.showLayoutSelector = true;
function activate() {
setVisibility();
setActiveLayout(scope.layouts);
}
function setVisibility() {
var numberOfAllowedLayouts = getNumberOfAllowedLayouts(scope.layouts);
if(numberOfAllowedLayouts === 1) {
scope.showLayoutSelector = false;
}
}
function getNumberOfAllowedLayouts(layouts) {
var allowedLayouts = 0;
for (var i = 0; layouts.length > i; i++) {
var layout = layouts[i];
if(layout.selected === true) {
allowedLayouts++;
}
}
return allowedLayouts;
}
function setActiveLayout(layouts) {
for (var i = 0; layouts.length > i; i++) {
var layout = layouts[i];
if(layout.path === scope.activeLayout.path) {
layout.active = true;
}
}
}
scope.pickLayout = function(selectedLayout) {
if(scope.onLayoutSelect) {
scope.onLayoutSelect(selectedLayout);
scope.layoutDropDownIsOpen = false;
}
};
scope.toggleLayoutDropdown = function() {
scope.layoutDropDownIsOpen = !scope.layoutDropDownIsOpen;
};
scope.closeLayoutDropdown = function() {
scope.layoutDropDownIsOpen = false;
};
activate();
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-layout-selector.html',
scope: {
layouts: '=',
activeLayout: '=',
onLayoutSelect: "="
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbLayoutSelector', LayoutSelectorDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbLightbox
@restrict E
@scope
@description
<p>Use this directive to open a gallery in a lightbox overlay.</p>
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<div class="my-gallery">
<a href="" ng-repeat="image in images" ng-click="vm.openLightbox($index, images)">
<img ng-src="image.source" />
</a>
</div>
<umb-lightbox
ng-if="vm.lightbox.show"
items="vm.lightbox.items"
active-item-index="vm.lightbox.activeIndex"
on-close="vm.closeLightbox">
</umb-lightbox>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.images = [
{
"source": "linkToImage"
},
{
"source": "linkToImage"
}
]
vm.openLightbox = openLightbox;
vm.closeLightbox = closeLightbox;
function openLightbox(itemIndex, items) {
vm.lightbox = {
show: true,
items: items,
activeIndex: itemIndex
};
}
function closeLightbox() {
vm.lightbox.show = false;
vm.lightbox = null;
}
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {array} items Array of gallery items.
@param {callback} onClose Callback when the lightbox is closed.
@param {number} activeItemIndex Index of active item.
**/
(function() {
'use strict';
function LightboxDirective() {
function link(scope, el, attr, ctrl) {
function activate() {
var eventBindings = [];
el.appendTo("body");
// clean up
scope.$on('$destroy', function() {
// unbind watchers
for (var e in eventBindings) {
eventBindings[e]();
}
});
}
scope.next = function() {
var nextItemIndex = scope.activeItemIndex + 1;
if( nextItemIndex < scope.items.length) {
scope.items[scope.activeItemIndex].active = false;
scope.items[nextItemIndex].active = true;
scope.activeItemIndex = nextItemIndex;
}
};
scope.prev = function() {
var prevItemIndex = scope.activeItemIndex - 1;
if( prevItemIndex >= 0) {
scope.items[scope.activeItemIndex].active = false;
scope.items[prevItemIndex].active = true;
scope.activeItemIndex = prevItemIndex;
}
};
scope.close = function() {
if(scope.onClose) {
scope.onClose();
}
};
activate();
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-lightbox.html',
scope: {
items: '=',
onClose: "=",
activeItemIndex: "="
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbLightbox', LightboxDirective);
})();
(function() {
'use strict';
function ListViewLayoutDirective() {
function link(scope, el, attr, ctrl) {
scope.getContent = function(contentId) {
if(scope.onGetContent) {
scope.onGetContent(contentId);
}
};
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-list-view-layout.html',
scope: {
contentId: '=',
folders: '=',
items: '=',
selection: '=',
options: '=',
entityType: '@',
onGetContent: '='
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbListViewLayout', ListViewLayoutDirective);
})();
(function() {
'use strict';
function ListViewSettingsDirective(contentTypeResource, dataTypeResource, dataTypeHelper, listViewPrevalueHelper) {
function link(scope, el, attr, ctrl) {
scope.dataType = {};
scope.editDataTypeSettings = false;
scope.customListViewCreated = false;
/* ---------- INIT ---------- */
function activate() {
if(scope.enableListView) {
dataTypeResource.getByName(scope.listViewName)
.then(function(dataType) {
scope.dataType = dataType;
listViewPrevalueHelper.setPrevalues(dataType.preValues);
scope.customListViewCreated = checkForCustomListView();
});
} else {
scope.dataType = {};
}
}
/* ----------- LIST VIEW SETTINGS --------- */
scope.toggleEditListViewDataTypeSettings = function() {
scope.editDataTypeSettings = !scope.editDataTypeSettings;
};
scope.saveListViewDataType = function() {
var preValues = dataTypeHelper.createPreValueProps(scope.dataType.preValues);
dataTypeResource.save(scope.dataType, preValues, false).then(function(dataType) {
// store data type
scope.dataType = dataType;
// hide settings panel
scope.editDataTypeSettings = false;
});
};
/* ---------- CUSTOM LIST VIEW ---------- */
scope.createCustomListViewDataType = function() {
dataTypeResource.createCustomListView(scope.modelAlias).then(function(dataType) {
// store data type
scope.dataType = dataType;
// set list view name on scope
scope.listViewName = dataType.name;
// change state to custom list view
scope.customListViewCreated = true;
// show settings panel
scope.editDataTypeSettings = true;
});
};
scope.removeCustomListDataType = function() {
scope.editDataTypeSettings = false;
// delete custom list view data type
dataTypeResource.deleteById(scope.dataType.id).then(function(dataType) {
// set list view name on scope
if(scope.contentType === "documentType") {
scope.listViewName = "List View - Content";
} else if(scope.contentType === "mediaType") {
scope.listViewName = "List View - Media";
}
// get default data type
dataTypeResource.getByName(scope.listViewName)
.then(function(dataType) {
// store data type
scope.dataType = dataType;
// change state to default list view
scope.customListViewCreated = false;
});
});
};
/* ----------- SCOPE WATCHERS ----------- */
var unbindEnableListViewWatcher = scope.$watch('enableListView', function(newValue, oldValue){
if(newValue !== undefined) {
activate();
}
});
// clean up
scope.$on('$destroy', function(){
unbindEnableListViewWatcher();
});
/* ----------- METHODS ---------- */
function checkForCustomListView() {
return scope.dataType.name === "List View - " + scope.modelAlias;
}
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-list-view-settings.html',
scope: {
enableListView: "=",
listViewName: "=",
modelAlias: "=",
contentType: "@"
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbListViewSettings', ListViewSettingsDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbLoadIndicator
@restrict E
@description
Use this directive to generate a loading indicator.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-load-indicator
ng-if="vm.loading">
</umb-load-indicator>
<div class="content" ng-if="!vm.loading">
<p>{{content}}</p>
</div>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller(myService) {
var vm = this;
vm.content = "";
vm.loading = true;
myService.getContent().then(function(content){
vm.content = content;
vm.loading = false;
});
}
½
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
**/
(function() {
'use strict';
function UmbLoadIndicatorDirective() {
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-load-indicator.html'
};
return directive;
}
angular.module('umbraco.directives').directive('umbLoadIndicator', UmbLoadIndicatorDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbLockedField
@restrict E
@scope
@description
Use this directive to render a value with a lock next to it. When the lock is clicked the value gets unlocked and can be edited.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-locked-field
ng-model="vm.value"
placeholder-text="'Click to unlock...'">
</umb-locked-field>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.value = "My locked text";
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {string} ngModel (<code>binding</code>): The locked text.
@param {boolean=} locked (<code>binding</code>): <Code>true</code> by default. Set to <code>false</code> to unlock the text.
@param {string=} placeholderText (<code>binding</code>): If ngModel is empty this text will be shown.
@param {string=} regexValidation (<code>binding</code>): Set a regex expression for validation of the field.
@param {string=} serverValidationField (<code>attribute</code>): Set a server validation field.
**/
(function() {
'use strict';
function LockedFieldDirective($timeout, localizationService) {
function link(scope, el, attr, ngModelCtrl) {
function activate() {
// if locked state is not defined as an attr set default state
if (scope.locked === undefined || scope.locked === null) {
scope.locked = true;
}
// if regex validation is not defined as an attr set default state
// if this is set to an empty string then regex validation can be ignored.
if (scope.regexValidation === undefined || scope.regexValidation === null) {
scope.regexValidation = "^[a-zA-Z]\\w.*$";
}
if (scope.serverValidationField === undefined || scope.serverValidationField === null) {
scope.serverValidationField = "";
}
// if locked state is not defined as an attr set default state
if (scope.placeholderText === undefined || scope.placeholderText === null) {
scope.placeholderText = "Enter value...";
}
}
scope.lock = function() {
scope.locked = true;
};
scope.unlock = function() {
scope.locked = false;
};
activate();
}
var directive = {
require: "ngModel",
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-locked-field.html',
scope: {
ngModel: "=",
locked: "=?",
placeholderText: "=?",
regexValidation: "=?",
serverValidationField: "@"
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbLockedField', LockedFieldDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbMediaGrid
@restrict E
@scope
@description
Use this directive to generate a thumbnail grid of media items.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-media-grid
items="vm.mediaItems"
on-click="vm.clickItem"
on-click-name="vm.clickItemName">
</umb-media-grid>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.mediaItems = [];
vm.clickItem = clickItem;
vm.clickItemName = clickItemName;
myService.getMediaItems().then(function (mediaItems) {
vm.mediaItems = mediaItems;
});
function clickItem(item, $event, $index){
// do magic here
}
function clickItemName(item, $event, $index) {
// set item.selected = true; to select the item
// do magic here
}
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {array} items (<code>binding</code>): Array of media items.
@param {callback=} onDetailsHover (<code>binding</code>): Callback method when the details icon is hovered.
<h3>The callback returns:</h3>
<ul>
<li><code>item</code>: The hovered item</li>
<li><code>$event</code>: The hover event</li>
<li><code>hover</code>: Boolean to tell if the item is hovered or not</li>
</ul>
@param {callback=} onClick (<code>binding</code>): Callback method to handle click events on the media item.
<h3>The callback returns:</h3>
<ul>
<li><code>item</code>: The clicked item</li>
<li><code>$event</code>: The click event</li>
<li><code>$index</code>: The item index</li>
</ul>
@param {callback=} onClickName (<code>binding</code>): Callback method to handle click events on the media item name.
<h3>The callback returns:</h3>
<ul>
<li><code>item</code>: The clicked item</li>
<li><code>$event</code>: The click event</li>
<li><code>$index</code>: The item index</li>
</ul>
@param {string=} filterBy (<code>binding</code>): String to filter media items by
@param {string=} itemMaxWidth (<code>attribute</code>): Sets a max width on the media item thumbnails.
@param {string=} itemMaxHeight (<code>attribute</code>): Sets a max height on the media item thumbnails.
@param {string=} itemMinWidth (<code>attribute</code>): Sets a min width on the media item thumbnails.
@param {string=} itemMinHeight (<code>attribute</code>): Sets a min height on the media item thumbnails.
**/
(function() {
'use strict';
function MediaGridDirective($filter, mediaHelper) {
function link(scope, el, attr, ctrl) {
var itemDefaultHeight = 200;
var itemDefaultWidth = 200;
var itemMaxWidth = 200;
var itemMaxHeight = 200;
var itemMinWidth = 125;
var itemMinHeight = 125;
function activate() {
if (scope.itemMaxWidth) {
itemMaxWidth = scope.itemMaxWidth;
}
if (scope.itemMaxHeight) {
itemMaxHeight = scope.itemMaxHeight;
}
if (scope.itemMinWidth) {
itemMinWidth = scope.itemMinWidth;
}
if (scope.itemMinWidth) {
itemMinHeight = scope.itemMinHeight;
}
for (var i = 0; scope.items.length > i; i++) {
var item = scope.items[i];
setItemData(item);
setOriginalSize(item, itemMaxHeight);
// remove non images when onlyImages is set to true
if(scope.onlyImages === "true" && !item.isFolder && !item.thumbnail){
scope.items.splice(i, 1);
i--;
}
}
if (scope.items.length > 0) {
setFlexValues(scope.items);
}
}
function setItemData(item) {
item.isFolder = !mediaHelper.hasFilePropertyType(item);
if (!item.isFolder) {
item.thumbnail = mediaHelper.resolveFile(item, true);
item.image = mediaHelper.resolveFile(item, false);
var fileProp = _.find(item.properties, function (v) {
return (v.alias === "umbracoFile");
});
if (fileProp && fileProp.value) {
item.file = fileProp.value;
}
var extensionProp = _.find(item.properties, function (v) {
return (v.alias === "umbracoExtension");
});
if (extensionProp && extensionProp.value) {
item.extension = extensionProp.value;
}
}
}
function setOriginalSize(item, maxHeight) {
//set to a square by default
item.width = itemDefaultWidth;
item.height = itemDefaultHeight;
item.aspectRatio = 1;
var widthProp = _.find(item.properties, function(v) {
return (v.alias === "umbracoWidth");
});
if (widthProp && widthProp.value) {
item.width = parseInt(widthProp.value, 10);
if (isNaN(item.width)) {
item.width = itemDefaultWidth;
}
}
var heightProp = _.find(item.properties, function(v) {
return (v.alias === "umbracoHeight");
});
if (heightProp && heightProp.value) {
item.height = parseInt(heightProp.value, 10);
if (isNaN(item.height)) {
item.height = itemDefaultWidth;
}
}
item.aspectRatio = item.width / item.height;
// set max width and height
// landscape
if (item.aspectRatio >= 1) {
if (item.width > itemMaxWidth) {
item.width = itemMaxWidth;
item.height = itemMaxWidth / item.aspectRatio;
}
// portrait
} else {
if (item.height > itemMaxHeight) {
item.height = itemMaxHeight;
item.width = itemMaxHeight * item.aspectRatio;
}
}
}
function setFlexValues(mediaItems) {
var flexSortArray = mediaItems;
var smallestImageWidth = null;
var widestImageAspectRatio = null;
// sort array after image width with the widest image first
flexSortArray = $filter('orderBy')(flexSortArray, 'width', true);
// find widest image aspect ratio
widestImageAspectRatio = flexSortArray[0].aspectRatio;
// find smallest image width
smallestImageWidth = flexSortArray[flexSortArray.length - 1].width;
for (var i = 0; flexSortArray.length > i; i++) {
var mediaItem = flexSortArray[i];
var flex = 1 / (widestImageAspectRatio / mediaItem.aspectRatio);
if (flex === 0) {
flex = 1;
}
var imageMinFlexWidth = smallestImageWidth * flex;
var flexStyle = {
"flex": flex + " 1 " + imageMinFlexWidth + "px",
"max-width": mediaItem.width + "px",
"min-width": itemMinWidth + "px",
"min-height": itemMinHeight + "px"
};
mediaItem.flexStyle = flexStyle;
}
}
scope.clickItem = function(item, $event, $index) {
if (scope.onClick) {
scope.onClick(item, $event, $index);
}
};
scope.clickItemName = function(item, $event, $index) {
if (scope.onClickName) {
scope.onClickName(item, $event, $index);
$event.stopPropagation();
}
};
scope.hoverItemDetails = function(item, $event, hover) {
if (scope.onDetailsHover) {
scope.onDetailsHover(item, $event, hover);
}
};
var unbindItemsWatcher = scope.$watch('items', function(newValue, oldValue) {
if (angular.isArray(newValue)) {
activate();
}
});
scope.$on('$destroy', function() {
unbindItemsWatcher();
});
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-media-grid.html',
scope: {
items: '=',
onDetailsHover: "=",
onClick: '=',
onClickName: "=",
filterBy: "=",
itemMaxWidth: "@",
itemMaxHeight: "@",
itemMinWidth: "@",
itemMinHeight: "@",
onlyImages: "@"
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbMediaGrid', MediaGridDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbPagination
@restrict E
@scope
@description
Use this directive to generate a pagination.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-pagination
page-number="vm.pagination.pageNumber"
total-pages="vm.pagination.totalPages"
on-next="vm.nextPage"
on-prev="vm.prevPage"
on-go-to-page="vm.goToPage">
</umb-pagination>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.pagination = {
pageNumber: 1,
totalPages: 10
}
vm.nextPage = nextPage;
vm.prevPage = prevPage;
vm.goToPage = goToPage;
function nextPage(pageNumber) {
// do magic here
console.log(pageNumber);
alert("nextpage");
}
function prevPage(pageNumber) {
// do magic here
console.log(pageNumber);
alert("prevpage");
}
function goToPage(pageNumber) {
// do magic here
console.log(pageNumber);
alert("go to");
}
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {number} pageNumber (<code>binding</code>): Current page number.
@param {number} totalPages (<code>binding</code>): The total number of pages.
@param {callback} onNext (<code>binding</code>): Callback method to go to the next page.
<h3>The callback returns:</h3>
<ul>
<li><code>pageNumber</code>: The page number</li>
</ul>
@param {callback=} onPrev (<code>binding</code>): Callback method to go to the previous page.
<h3>The callback returns:</h3>
<ul>
<li><code>pageNumber</code>: The page number</li>
</ul>
@param {callback=} onGoToPage (<code>binding</code>): Callback method to go to a specific page.
<h3>The callback returns:</h3>
<ul>
<li><code>pageNumber</code>: The page number</li>
</ul>
**/
(function() {
'use strict';
function PaginationDirective() {
function link(scope, el, attr, ctrl) {
function activate() {
scope.pagination = [];
var i = 0;
if (scope.totalPages <= 10) {
for (i = 0; i < scope.totalPages; i++) {
scope.pagination.push({
val: (i + 1),
isActive: scope.pageNumber === (i + 1)
});
}
}
else {
//if there is more than 10 pages, we need to do some fancy bits
//get the max index to start
var maxIndex = scope.totalPages - 10;
//set the start, but it can't be below zero
var start = Math.max(scope.pageNumber - 5, 0);
//ensure that it's not too far either
start = Math.min(maxIndex, start);
for (i = start; i < (10 + start) ; i++) {
scope.pagination.push({
val: (i + 1),
isActive: scope.pageNumber === (i + 1)
});
}
//now, if the start is greater than 0 then '1' will not be displayed, so do the elipses thing
if (start > 0) {
scope.pagination.unshift({ name: "First", val: 1, isActive: false }, {val: "...",isActive: false});
}
//same for the end
if (start < maxIndex) {
scope.pagination.push({ val: "...", isActive: false }, { name: "Last", val: scope.totalPages, isActive: false });
}
}
}
scope.next = function() {
if (scope.onNext && scope.pageNumber < scope.totalPages) {
scope.pageNumber++;
scope.onNext(scope.pageNumber);
}
};
scope.prev = function(pageNumber) {
if (scope.onPrev && scope.pageNumber > 1) {
scope.pageNumber--;
scope.onPrev(scope.pageNumber);
}
};
scope.goToPage = function(pageNumber) {
if(scope.onGoToPage) {
scope.pageNumber = pageNumber + 1;
scope.onGoToPage(scope.pageNumber);
}
};
var unbindPageNumberWatcher = scope.$watch('pageNumber', function(newValue, oldValue){
activate();
});
scope.$on('$destroy', function(){
unbindPageNumberWatcher();
});
activate();
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-pagination.html',
scope: {
pageNumber: "=",
totalPages: "=",
onNext: "=",
onPrev: "=",
onGoToPage: "="
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbPagination', PaginationDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbProgressBar
@restrict E
@scope
@description
Use this directive to generate a progress bar.
<h3>Markup example</h3>
<pre>
<umb-progress-bar
percentage="60">
</umb-progress-bar>
</pre>
@param {number} percentage (<code>attribute</code>): The progress in percentage.
**/
(function() {
'use strict';
function ProgressBarDirective() {
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-progress-bar.html',
scope: {
percentage: "@"
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbProgressBar', ProgressBarDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbStickyBar
@restrict A
@description
Use this directive make an element sticky and follow the page when scrolling.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<div
class="my-sticky-bar"
umb-sticky-bar
scrollable-container=".container">
</div>
</div>
</pre>
<h3>CSS example</h3>
<pre>
.my-sticky-bar {
padding: 15px 0;
background: #000000;
position: relative;
top: 0;
}
.my-sticky-bar.-umb-sticky-bar {
top: 100px;
}
</pre>
@param {string} scrollableContainer Set the class (".element") or the id ("#element") of the scrollable container element.
**/
(function() {
'use strict';
function StickyBarDirective($rootScope) {
function link(scope, el, attr, ctrl) {
var bar = $(el);
var scrollableContainer = null;
var clonedBar = null;
var cloneIsMade = false;
var barTop = bar.context.offsetTop;
function activate() {
if (attr.scrollableContainer) {
scrollableContainer = $(attr.scrollableContainer);
} else {
scrollableContainer = $(window);
}
scrollableContainer.on('scroll.umbStickyBar', determineVisibility).trigger("scroll");
$(window).on('resize.umbStickyBar', determineVisibility);
scope.$on('$destroy', function() {
scrollableContainer.off('.umbStickyBar');
$(window).off('.umbStickyBar');
});
}
function determineVisibility() {
var scrollTop = scrollableContainer.scrollTop();
if (scrollTop > barTop) {
if (!cloneIsMade) {
createClone();
clonedBar.css({
'visibility': 'visible'
});
} else {
calculateSize();
}
} else {
if (cloneIsMade) {
//remove cloned element (switched places with original on creation)
bar.remove();
bar = clonedBar;
clonedBar = null;
bar.removeClass('-umb-sticky-bar');
bar.css({
position: 'relative',
'width': 'auto',
'height': 'auto',
'z-index': 'auto',
'visibility': 'visible'
});
cloneIsMade = false;
}
}
}
function calculateSize() {
clonedBar.css({
width: bar.outerWidth(),
height: bar.height()
});
}
function createClone() {
//switch place with cloned element, to keep binding intact
clonedBar = bar;
bar = clonedBar.clone();
clonedBar.after(bar);
clonedBar.addClass('-umb-sticky-bar');
clonedBar.css({
'position': 'fixed',
'z-index': 500,
'visibility': 'hidden'
});
cloneIsMade = true;
calculateSize();
}
activate();
}
var directive = {
restrict: 'A',
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbStickyBar', StickyBarDirective);
})();
(function () {
'use strict';
function TableDirective() {
function link(scope, el, attr, ctrl) {
scope.clickItem = function (item, $event) {
if (scope.onClick) {
scope.onClick(item);
$event.stopPropagation();
}
};
scope.selectItem = function (item, $index, $event) {
if (scope.onSelect) {
scope.onSelect(item, $index, $event);
$event.stopPropagation();
}
};
scope.selectAll = function ($event) {
if (scope.onSelectAll) {
scope.onSelectAll($event);
}
};
scope.isSelectedAll = function () {
if (scope.onSelectedAll && scope.items && scope.items.length > 0) {
return scope.onSelectedAll();
}
};
scope.isSortDirection = function (col, direction) {
if (scope.onSortingDirection) {
return scope.onSortingDirection(col, direction);
}
};
scope.sort = function (field, allow, isSystem) {
if (scope.onSort) {
scope.onSort(field, allow, isSystem);
}
};
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-table.html',
scope: {
items: '=',
itemProperties: '=',
allowSelectAll: '=',
onSelect: '=',
onClick: '=',
onSelectAll: '=',
onSelectedAll: '=',
onSortingDirection: '=',
onSort: '='
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbTable', TableDirective);
})();
/**
@ngdoc directive
@name umbraco.directives.directive:umbTooltip
@restrict E
@scope
@description
Use this directive to render a tooltip.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<div
ng-mouseover="vm.mouseOver($event)"
ng-mouseleave="vm.mouseLeave()">
Hover me
</div>
<umb-tooltip
ng-if="vm.tooltip.show"
event="vm.tooltip.event">
// tooltip content here
</umb-tooltip>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.tooltip = {
show: false,
event: null
};
vm.mouseOver = mouseOver;
vm.mouseLeave = mouseLeave;
function mouseOver($event) {
vm.tooltip = {
show: true,
event: $event
};
}
function mouseLeave() {
vm.tooltip = {
show: false,
event: null
};
}
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {string} event Set the $event from the target element to position the tooltip relative to the mouse cursor.
**/
(function() {
'use strict';
function TooltipDirective($timeout) {
function link(scope, el, attr, ctrl) {
scope.tooltipStyles = {};
scope.tooltipStyles.left = 0;
scope.tooltipStyles.top = 0;
function activate() {
$timeout(function() {
setTooltipPosition(scope.event);
});
}
function setTooltipPosition(event) {
var container = $("#contentwrapper");
var containerLeft = container[0].offsetLeft;
var containerRight = containerLeft + container[0].offsetWidth;
var containerTop = container[0].offsetTop;
var containerBottom = containerTop + container[0].offsetHeight;
var elementHeight = null;
var elementWidth = null;
var position = {
right: "inherit",
left: "inherit",
top: "inherit",
bottom: "inherit"
};
// element size
elementHeight = el.context.clientHeight;
elementWidth = el.context.clientWidth;
position.left = event.pageX - (elementWidth / 2);
position.top = event.pageY;
// check to see if element is outside screen
// outside right
if (position.left + elementWidth > containerRight) {
position.right = 10;
position.left = "inherit";
}
// outside bottom
if (position.top + elementHeight > containerBottom) {
position.bottom = 10;
position.top = "inherit";
}
// outside left
if (position.left < containerLeft) {
position.left = containerLeft + 10;
position.right = "inherit";
}
// outside top
if (position.top < containerTop) {
position.top = 10;
position.bottom = "inherit";
}
scope.tooltipStyles = position;
el.css(position);
}
activate();
}
var directive = {
restrict: 'E',
transclude: true,
replace: true,
templateUrl: 'views/components/umb-tooltip.html',
scope: {
event: "="
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbTooltip', TooltipDirective);
})();
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbFileDropzone
* @restrict E
* @function
* @description
* Used by editors that require naming an entity. Shows a textbox/headline with a required validator within it's own form.
**/
/*
TODO
.directive("umbFileDrop", function ($timeout, $upload, localizationService, umbRequestHelper){
return{
restrict: "A",
link: function(scope, element, attrs){
//load in the options model
}
}
})
*/
angular.module("umbraco.directives")
.directive('umbFileDropzone', function ($timeout, Upload, localizationService, umbRequestHelper) {
return {
restrict: 'E',
replace: true,
templateUrl: 'views/components/upload/umb-file-dropzone.html',
scope: {
parentId: '@',
contentTypeAlias: '@',
propertyAlias: '@',
accept: '@',
maxFileSize: '@',
compact: '@',
hideDropzone: '@',
filesQueued: '=',
handleFile: '=',
filesUploaded: '='
},
link: function(scope, element, attrs) {
scope.queue = [];
scope.done = [];
scope.rejected = [];
scope.currentFile = undefined;
function _filterFile(file) {
var ignoreFileNames = ['Thumbs.db'];
var ignoreFileTypes = ['directory'];
// ignore files with names from the list
// ignore files with types from the list
// ignore files which starts with "."
if(ignoreFileNames.indexOf(file.name) === -1 &&
ignoreFileTypes.indexOf(file.type) === -1 &&
file.name.indexOf(".") !== 0) {
return true;
} else {
return false;
}
}
function _filesQueued(files, event){
//Push into the queue
angular.forEach(files, function(file){
if(_filterFile(file) === true) {
if(file.$error) {
scope.rejected.push(file);
} else {
scope.queue.push(file);
}
}
});
//when queue is done, kick the uploader
if(!scope.working){
_processQueueItem();
}
}
function _processQueueItem(){
if(scope.queue.length > 0){
scope.currentFile = scope.queue.shift();
_upload(scope.currentFile);
}else if(scope.done.length > 0){
if(scope.filesUploaded){
//queue is empty, trigger the done action
scope.filesUploaded(scope.done);
}
//auto-clear the done queue after 3 secs
var currentLength = scope.done.length;
$timeout(function(){
scope.done.splice(0, currentLength);
}, 3000);
}
}
function _upload(file) {
scope.propertyAlias = scope.propertyAlias ? scope.propertyAlias : "umbracoFile";
scope.contentTypeAlias = scope.contentTypeAlias ? scope.contentTypeAlias : "Image";
Upload.upload({
url: umbRequestHelper.getApiUrl("mediaApiBaseUrl", "PostAddFile"),
fields: {
'currentFolder': scope.parentId,
'contentTypeAlias': scope.contentTypeAlias,
'propertyAlias': scope.propertyAlias,
'path': file.path
},
file: file
}).progress(function (evt) {
// calculate progress in percentage
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total, 10);
// set percentage property on file
file.uploadProgress = progressPercentage;
// set uploading status on file
file.uploadStatus = "uploading";
}).success(function (data, status, headers, config) {
if(data.notifications && data.notifications.length > 0) {
// set error status on file
file.uploadStatus = "error";
// Throw message back to user with the cause of the error
file.serverErrorMessage = data.notifications[0].message;
// Put the file in the rejected pool
scope.rejected.push(file);
} else {
// set done status on file
file.uploadStatus = "done";
// set date/time for when done - used for sorting
file.doneDate = new Date();
// Put the file in the done pool
scope.done.push(file);
}
scope.currentFile = undefined;
//after processing, test if everthing is done
_processQueueItem();
}).error( function (evt, status, headers, config) {
// set status done
file.uploadStatus = "error";
//if the service returns a detailed error
if (evt.InnerException) {
file.serverErrorMessage = evt.InnerException.ExceptionMessage;
//Check if its the common "too large file" exception
if (evt.InnerException.StackTrace && evt.InnerException.StackTrace.indexOf("ValidateRequestEntityLength") > 0) {
file.serverErrorMessage = "File too large to upload";
}
} else if (evt.Message) {
file.serverErrorMessage = evt.Message;
}
// If file not found, server will return a 404 and display this message
if(status === 404 ) {
file.serverErrorMessage = "File not found";
}
//after processing, test if everthing is done
scope.rejected.push(file);
scope.currentFile = undefined;
_processQueueItem();
});
}
scope.handleFiles = function(files, event){
if(scope.filesQueued){
scope.filesQueued(files, event);
}
_filesQueued(files, event);
};
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbFileUpload
* @function
* @restrict A
* @scope
* @description
* Listens for file input control changes and emits events when files are selected for use in other controllers.
**/
function umbFileUpload() {
return {
restrict: "A",
scope: true, //create a new scope
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var files = event.target.files;
//emit event upward
scope.$emit("filesSelected", { files: files });
});
}
};
}
angular.module('umbraco.directives').directive("umbFileUpload", umbFileUpload);
/**
* @ngdoc directive
* @name umbraco.directives.directive:umbSingleFileUpload
* @function
* @restrict A
* @scope
* @description
* A single file upload field that will reset itself based on the object passed in for the rebuild parameter. This
* is required because the only way to reset an upload control is to replace it's html.
**/
function umbSingleFileUpload($compile) {
return {
restrict: "E",
scope: {
rebuild: "="
},
replace: true,
template: "<div><input type='file' umb-file-upload /></div>",
link: function (scope, el, attrs) {
scope.$watch("rebuild", function (newVal, oldVal) {
if (newVal && newVal !== oldVal) {
//recompile it!
el.html("<input type='file' umb-file-upload />");
$compile(el.contents())(scope);
}
});
}
};
}
angular.module('umbraco.directives').directive("umbSingleFileUpload", umbSingleFileUpload);
/**
* Konami Code directive for AngularJS
* @version v0.0.1
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
angular.module('umbraco.directives')
.directive('konamiCode', ['$document', function ($document) {
var konamiKeysDefault = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
return {
restrict: 'A',
link: function (scope, element, attr) {
if (!attr.konamiCode) {
throw ('Konami directive must receive an expression as value.');
}
// Let user define a custom code.
var konamiKeys = attr.konamiKeys || konamiKeysDefault;
var keyIndex = 0;
/**
* Fired when konami code is type.
*/
function activated() {
if ('konamiOnce' in attr) {
stopListening();
}
// Execute expression.
scope.$eval(attr.konamiCode);
}
/**
* Handle keydown events.
*/
function keydown(e) {
if (e.keyCode === konamiKeys[keyIndex++]) {
if (keyIndex === konamiKeys.length) {
keyIndex = 0;
activated();
}
} else {
keyIndex = 0;
}
}
/**
* Stop to listen typing.
*/
function stopListening() {
$document.off('keydown', keydown);
}
// Start listening to key typing.
$document.on('keydown', keydown);
// Stop listening when scope is destroyed.
scope.$on('$destroy', stopListening);
}
};
}]);
/**
* @ngdoc directive
* @name umbraco.directives.directive:noDirtyCheck
* @restrict A
* @description Can be attached to form inputs to prevent them from setting the form as dirty (http://stackoverflow.com/questions/17089090/prevent-input-from-setting-form-dirty-angularjs)
**/
function noDirtyCheck() {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
elm.focus(function () {
ctrl.$pristine = false;
});
}
};
}
angular.module('umbraco.directives.validation').directive("noDirtyCheck", noDirtyCheck);
(function() {
'use strict';
function SetDirtyOnChange() {
function link(scope, el, attr, ctrl) {
var initValue = attr.umbSetDirtyOnChange;
attr.$observe("umbSetDirtyOnChange", function (newValue) {
if(newValue !== initValue) {
ctrl.$setDirty();
}
});
}
var directive = {
require: "^form",
restrict: 'A',
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbSetDirtyOnChange', SetDirtyOnChange);
})();
/**
* General-purpose validator for ngModel.
* angular.js comes with several built-in validation mechanism for input fields (ngRequired, ngPattern etc.) but using
* an arbitrary validation function requires creation of a custom formatters and / or parsers.
* The ui-validate directive makes it easy to use any function(s) defined in scope as a validator function(s).
* A validator function will trigger validation on both model and input changes.
*
* @example <input val-custom=" 'myValidatorFunction($value)' ">
* @example <input val-custom="{ foo : '$value > anotherModel', bar : 'validateFoo($value)' }">
* @example <input val-custom="{ foo : '$value > anotherModel' }" val-custom-watch=" 'anotherModel' ">
* @example <input val-custom="{ foo : '$value > anotherModel', bar : 'validateFoo($value)' }" val-custom-watch=" { foo : 'anotherModel' } ">
*
* @param val-custom {string|object literal} If strings is passed it should be a scope's function to be used as a validator.
* If an object literal is passed a key denotes a validation error key while a value should be a validator function.
* In both cases validator function should take a value to validate as its argument and should return true/false indicating a validation result.
*/
/*
This code comes from the angular UI project, we had to change the directive name and module
but other then that its unmodified
*/
angular.module('umbraco.directives.validation')
.directive('valCustom', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
var validateFn, watch, validators = {},
validateExpr = scope.$eval(attrs.valCustom);
if (!validateExpr){ return;}
if (angular.isString(validateExpr)) {
validateExpr = { validator: validateExpr };
}
angular.forEach(validateExpr, function (exprssn, key) {
validateFn = function (valueToValidate) {
var expression = scope.$eval(exprssn, { '$value' : valueToValidate });
if (angular.isObject(expression) && angular.isFunction(expression.then)) {
// expression is a promise
expression.then(function(){
ctrl.$setValidity(key, true);
}, function(){
ctrl.$setValidity(key, false);
});
return valueToValidate;
} else if (expression) {
// expression is true
ctrl.$setValidity(key, true);
return valueToValidate;
} else {
// expression is false
ctrl.$setValidity(key, false);
return undefined;
}
};
validators[key] = validateFn;
ctrl.$parsers.push(validateFn);
});
function apply_watch(watch)
{
//string - update all validators on expression change
if (angular.isString(watch))
{
scope.$watch(watch, function(){
angular.forEach(validators, function(validatorFn){
validatorFn(ctrl.$modelValue);
});
});
return;
}
//array - update all validators on change of any expression
if (angular.isArray(watch))
{
angular.forEach(watch, function(expression){
scope.$watch(expression, function()
{
angular.forEach(validators, function(validatorFn){
validatorFn(ctrl.$modelValue);
});
});
});
return;
}
//object - update appropriate validator
if (angular.isObject(watch))
{
angular.forEach(watch, function(expression, validatorKey)
{
//value is string - look after one expression
if (angular.isString(expression))
{
scope.$watch(expression, function(){
validators[validatorKey](ctrl.$modelValue);
});
}
//value is array - look after all expressions in array
if (angular.isArray(expression))
{
angular.forEach(expression, function(intExpression)
{
scope.$watch(intExpression, function(){
validators[validatorKey](ctrl.$modelValue);
});
});
}
});
}
}
// Support for val-custom-watch
if (attrs.valCustomWatch){
apply_watch( scope.$eval(attrs.valCustomWatch) );
}
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:valHighlight
* @restrict A
* @description Used on input fields when you want to signal that they are in error, this will highlight the item for 1 second
**/
function valHighlight($timeout) {
return {
restrict: "A",
link: function (scope, element, attrs, ctrl) {
attrs.$observe("valHighlight", function (newVal) {
if (newVal === "true") {
element.addClass("highlight-error");
$timeout(function () {
//set the bound scope property to false
scope[attrs.valHighlight] = false;
}, 1000);
}
else {
element.removeClass("highlight-error");
}
});
}
};
}
angular.module('umbraco.directives.validation').directive("valHighlight", valHighlight);
angular.module('umbraco.directives.validation')
.directive('valCompare',function () {
return {
require: "ngModel",
link: function (scope, elem, attrs, ctrl) {
//TODO: Pretty sure this should be done using a requires ^form in the directive declaration
var otherInput = elem.inheritedData("$formController")[attrs.valCompare];
ctrl.$parsers.push(function(value) {
if(value === otherInput.$viewValue) {
ctrl.$setValidity("valCompare", true);
return value;
}
ctrl.$setValidity("valCompare", false);
});
otherInput.$parsers.push(function(value) {
ctrl.$setValidity("valCompare", value === ctrl.$viewValue);
return value;
});
}
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:valEmail
* @restrict A
* @description A custom directive to validate an email address string, this is required because angular's default validator is incorrect.
**/
function valEmail(valEmailExpression) {
return {
require: 'ngModel',
restrict: "A",
link: function (scope, elm, attrs, ctrl) {
var patternValidator = function (viewValue) {
//NOTE: we don't validate on empty values, use required validator for that
if (!viewValue || valEmailExpression.EMAIL_REGEXP.test(viewValue)) {
// it is valid
ctrl.$setValidity('valEmail', true);
//assign a message to the validator
ctrl.errorMsg = "";
return viewValue;
}
else {
// it is invalid, return undefined (no model update)
ctrl.$setValidity('valEmail', false);
//assign a message to the validator
ctrl.errorMsg = "Invalid email";
return undefined;
}
};
//if there is an attribute: type="email" then we need to remove those formatters and parsers
if (attrs.type === "email") {
//we need to remove the existing parsers = the default angular one which is created by
// type="email", but this has a regex issue, so we'll remove that and add our custom one
ctrl.$parsers.pop();
//we also need to remove the existing formatter - the default angular one will not render
// what it thinks is an invalid email address, so it will just be blank
ctrl.$formatters.pop();
}
ctrl.$parsers.push(patternValidator);
}
};
}
angular.module('umbraco.directives.validation')
.directive("valEmail", valEmail)
.factory('valEmailExpression', function () {
//NOTE: This is the fixed regex which is part of the newer angular
return {
EMAIL_REGEXP: /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i
};
});
/**
* @ngdoc directive
* @name umbraco.directives.directive:valFormManager
* @restrict A
* @require formController
* @description Used to broadcast an event to all elements inside this one to notify that form validation has
* changed. If we don't use this that means you have to put a watch for each directive on a form's validation
* changing which would result in much higher processing. We need to actually watch the whole $error collection of a form
* because just watching $valid or $invalid doesn't acurrately trigger form validation changing.
* This also sets the show-validation (or a custom) css class on the element when the form is invalid - this lets
* us css target elements to be displayed when the form is submitting/submitted.
* Another thing this directive does is to ensure that any .control-group that contains form elements that are invalid will
* be marked with the 'error' css class. This ensures that labels included in that control group are styled correctly.
**/
function valFormManager(serverValidationManager, $rootScope, $log, $timeout, notificationsService, eventsService, $routeParams) {
return {
require: "form",
restrict: "A",
controller: function($scope) {
//This exposes an API for direct use with this directive
var unsubscribe = [];
var self = this;
//This is basically the same as a directive subscribing to an event but maybe a little
// nicer since the other directive can use this directive's API instead of a magical event
this.onValidationStatusChanged = function (cb) {
unsubscribe.push($scope.$on("valStatusChanged", function(evt, args) {
cb.apply(self, [evt, args]);
}));
};
//Ensure to remove the event handlers when this instance is destroyted
$scope.$on('$destroy', function () {
for (var u in unsubscribe) {
unsubscribe[u]();
}
});
},
link: function (scope, element, attr, formCtrl) {
scope.$watch(function () {
return formCtrl.$error;
}, function (e) {
scope.$broadcast("valStatusChanged", { form: formCtrl });
//find all invalid elements' .control-group's and apply the error class
var inError = element.find(".control-group .ng-invalid").closest(".control-group");
inError.addClass("error");
//find all control group's that have no error and ensure the class is removed
var noInError = element.find(".control-group .ng-valid").closest(".control-group").not(inError);
noInError.removeClass("error");
}, true);
var className = attr.valShowValidation ? attr.valShowValidation : "show-validation";
var savingEventName = attr.savingEvent ? attr.savingEvent : "formSubmitting";
var savedEvent = attr.savedEvent ? attr.savingEvent : "formSubmitted";
//This tracks if the user is currently saving a new item, we use this to determine
// if we should display the warning dialog that they are leaving the page - if a new item
// is being saved we never want to display that dialog, this will also cause problems when there
// are server side validation issues.
var isSavingNewItem = false;
//we should show validation if there are any msgs in the server validation collection
if (serverValidationManager.items.length > 0) {
element.addClass(className);
}
var unsubscribe = [];
//listen for the forms saving event
unsubscribe.push(scope.$on(savingEventName, function(ev, args) {
element.addClass(className);
//set the flag so we can check to see if we should display the error.
isSavingNewItem = $routeParams.create;
}));
//listen for the forms saved event
unsubscribe.push(scope.$on(savedEvent, function(ev, args) {
//remove validation class
element.removeClass(className);
//clear form state as at this point we retrieve new data from the server
//and all validation will have cleared at this point
formCtrl.$setPristine();
}));
//This handles the 'unsaved changes' dialog which is triggered when a route is attempting to be changed but
// the form has pending changes
var locationEvent = $rootScope.$on('$locationChangeStart', function(event, nextLocation, currentLocation) {
if (!formCtrl.$dirty || isSavingNewItem) {
return;
}
var path = nextLocation.split("#")[1];
if (path) {
if (path.indexOf("%253") || path.indexOf("%252")) {
path = decodeURIComponent(path);
}
if (!notificationsService.hasView()) {
var msg = { view: "confirmroutechange", args: { path: path, listener: locationEvent } };
notificationsService.add(msg);
}
//prevent the route!
event.preventDefault();
//raise an event
eventsService.emit("valFormManager.pendingChanges", true);
}
});
unsubscribe.push(locationEvent);
//Ensure to remove the event handler when this instance is destroyted
scope.$on('$destroy', function() {
for (var u in unsubscribe) {
unsubscribe[u]();
}
});
$timeout(function(){
formCtrl.$setPristine();
}, 1000);
}
};
}
angular.module('umbraco.directives.validation').directive("valFormManager", valFormManager);
/**
* @ngdoc directive
* @name umbraco.directives.directive:valPropertyMsg
* @restrict A
* @element textarea
* @requires formController
* @description This directive is used to control the display of the property level validation message.
* We will listen for server side validation changes
* and when an error is detected for this property we'll show the error message.
* In order for this directive to work, the valStatusChanged directive must be placed on the containing form.
**/
function valPropertyMsg(serverValidationManager) {
return {
scope: {
property: "="
},
require: "^form", //require that this directive is contained within an ngForm
replace: true, //replace the element with the template
restrict: "E", //restrict to element
template: "<div ng-show=\"errorMsg != ''\" class='alert alert-error property-error' >{{errorMsg}}</div>",
/**
Our directive requries a reference to a form controller
which gets passed in to this parameter
*/
link: function (scope, element, attrs, formCtrl) {
var watcher = null;
// Gets the error message to display
function getErrorMsg() {
//this can be null if no property was assigned
if (scope.property) {
//first try to get the error msg from the server collection
var err = serverValidationManager.getPropertyError(scope.property.alias, "");
//if there's an error message use it
if (err && err.errorMsg) {
return err.errorMsg;
}
else {
return scope.property.propertyErrorMessage ? scope.property.propertyErrorMessage : "Property has errors";
}
}
return "Property has errors";
}
// We need to subscribe to any changes to our model (based on user input)
// This is required because when we have a server error we actually invalidate
// the form which means it cannot be resubmitted.
// So once a field is changed that has a server error assigned to it
// we need to re-validate it for the server side validator so the user can resubmit
// the form. Of course normal client-side validators will continue to execute.
function startWatch() {
//if there's not already a watch
if (!watcher) {
watcher = scope.$watch("property.value", function (newValue, oldValue) {
if (!newValue || angular.equals(newValue, oldValue)) {
return;
}
var errCount = 0;
for (var e in formCtrl.$error) {
if (angular.isArray(formCtrl.$error[e])) {
errCount++;
}
}
//we are explicitly checking for valServer errors here, since we shouldn't auto clear
// based on other errors. We'll also check if there's no other validation errors apart from valPropertyMsg, if valPropertyMsg
// is the only one, then we'll clear.
if ((errCount === 1 && angular.isArray(formCtrl.$error.valPropertyMsg)) || (formCtrl.$invalid && angular.isArray(formCtrl.$error.valServer))) {
scope.errorMsg = "";
formCtrl.$setValidity('valPropertyMsg', true);
stopWatch();
}
}, true);
}
}
//clear the watch when the property validator is valid again
function stopWatch() {
if (watcher) {
watcher();
watcher = null;
}
}
//if there's any remaining errors in the server validation service then we should show them.
var showValidation = serverValidationManager.items.length > 0;
var hasError = false;
//create properties on our custom scope so we can use it in our template
scope.errorMsg = "";
var unsubscribe = [];
//listen for form error changes
unsubscribe.push(scope.$on("valStatusChanged", function(evt, args) {
if (args.form.$invalid) {
//first we need to check if the valPropertyMsg validity is invalid
if (formCtrl.$error.valPropertyMsg && formCtrl.$error.valPropertyMsg.length > 0) {
//since we already have an error we'll just return since this means we've already set the
// hasError and errorMsg properties which occurs below in the serverValidationManager.subscribe
return;
}
else if (element.closest(".umb-control-group").find(".ng-invalid").length > 0) {
//check if it's one of the properties that is invalid in the current content property
hasError = true;
//update the validation message if we don't already have one assigned.
if (showValidation && scope.errorMsg === "") {
scope.errorMsg = getErrorMsg();
}
}
else {
hasError = false;
scope.errorMsg = "";
}
}
else {
hasError = false;
scope.errorMsg = "";
}
}, true));
//listen for the forms saving event
unsubscribe.push(scope.$on("formSubmitting", function(ev, args) {
showValidation = true;
if (hasError && scope.errorMsg === "") {
scope.errorMsg = getErrorMsg();
}
else if (!hasError) {
scope.errorMsg = "";
stopWatch();
}
}));
//listen for the forms saved event
unsubscribe.push(scope.$on("formSubmitted", function(ev, args) {
showValidation = false;
scope.errorMsg = "";
formCtrl.$setValidity('valPropertyMsg', true);
stopWatch();
}));
//listen for server validation changes
// NOTE: we pass in "" in order to listen for all validation changes to the content property, not for
// validation changes to fields in the property this is because some server side validators may not
// return the field name for which the error belongs too, just the property for which it belongs.
// It's important to note that we need to subscribe to server validation changes here because we always must
// indicate that a content property is invalid at the property level since developers may not actually implement
// the correct field validation in their property editors.
if (scope.property) { //this can be null if no property was assigned
serverValidationManager.subscribe(scope.property.alias, "", function (isValid, propertyErrors, allErrors) {
hasError = !isValid;
if (hasError) {
//set the error message to the server message
scope.errorMsg = propertyErrors[0].errorMsg;
//flag that the current validator is invalid
formCtrl.$setValidity('valPropertyMsg', false);
startWatch();
}
else {
scope.errorMsg = "";
//flag that the current validator is valid
formCtrl.$setValidity('valPropertyMsg', true);
stopWatch();
}
});
//when the element is disposed we need to unsubscribe!
// NOTE: this is very important otherwise when this controller re-binds the previous subscriptsion will remain
// but they are a different callback instance than the above.
element.bind('$destroy', function () {
stopWatch();
serverValidationManager.unsubscribe(scope.property.alias, "");
});
}
//when the scope is disposed we need to unsubscribe
scope.$on('$destroy', function () {
for (var u in unsubscribe) {
unsubscribe[u]();
}
});
}
};
}
angular.module('umbraco.directives.validation').directive("valPropertyMsg", valPropertyMsg);
/**
* @ngdoc directive
* @name umbraco.directives.directive:valPropertyValidator
* @restrict A
* @description Performs any custom property value validation checks on the client side. This allows property editors to be highly flexible when it comes to validation
on the client side. Typically if a property editor stores a primitive value (i.e. string) then the client side validation can easily be taken care of
with standard angular directives such as ng-required. However since some property editors store complex data such as JSON, a given property editor
might require custom validation. This directive can be used to validate an Umbraco property in any way that a developer would like by specifying a
callback method to perform the validation. The result of this method must return an object in the format of
{isValid: true, errorKey: 'required', errorMsg: 'Something went wrong' }
The error message returned will also be displayed for the property level validation message.
This directive should only be used when dealing with complex models, if custom validation needs to be performed with primitive values, use the simpler
angular validation directives instead since this will watch the entire model.
**/
function valPropertyValidator(serverValidationManager) {
return {
scope: {
valPropertyValidator: "="
},
// The element must have ng-model attribute and be inside an umbProperty directive
require: ['ngModel', '?^umbProperty'],
restrict: "A",
link: function (scope, element, attrs, ctrls) {
var modelCtrl = ctrls[0];
var propCtrl = ctrls.length > 1 ? ctrls[1] : null;
// Check whether the scope has a valPropertyValidator method
if (!scope.valPropertyValidator || !angular.isFunction(scope.valPropertyValidator)) {
throw new Error('val-property-validator directive must specify a function to call');
}
var initResult = scope.valPropertyValidator();
// Validation method
var validate = function (viewValue) {
// Calls the validition method
var result = scope.valPropertyValidator();
if (!result.errorKey || result.isValid === undefined || !result.errorMsg) {
throw "The result object from valPropertyValidator does not contain required properties: isValid, errorKey, errorMsg";
}
if (result.isValid === true) {
// Tell the controller that the value is valid
modelCtrl.$setValidity(result.errorKey, true);
if (propCtrl) {
propCtrl.setPropertyError(null);
}
}
else {
// Tell the controller that the value is invalid
modelCtrl.$setValidity(result.errorKey, false);
if (propCtrl) {
propCtrl.setPropertyError(result.errorMsg);
}
}
};
// Parsers are called as soon as the value in the form input is modified
modelCtrl.$parsers.push(validate);
}
};
}
angular.module('umbraco.directives.validation').directive("valPropertyValidator", valPropertyValidator);
/**
* @ngdoc directive
* @name umbraco.directives.directive:valRegex
* @restrict A
* @description A custom directive to allow for matching a value against a regex string.
* NOTE: there's already an ng-pattern but this requires that a regex expression is set, not a regex string
**/
function valRegex() {
return {
require: 'ngModel',
restrict: "A",
link: function (scope, elm, attrs, ctrl) {
var flags = "";
var regex;
var eventBindings = [];
attrs.$observe("valRegexFlags", function (newVal) {
if (newVal) {
flags = newVal;
}
});
attrs.$observe("valRegex", function (newVal) {
if (newVal) {
try {
var resolved = newVal;
if (resolved) {
regex = new RegExp(resolved, flags);
}
else {
regex = new RegExp(attrs.valRegex, flags);
}
}
catch (e) {
regex = new RegExp(attrs.valRegex, flags);
}
}
});
eventBindings.push(scope.$watch('ngModel', function(newValue, oldValue){
if(newValue && newValue !== oldValue) {
patternValidator(newValue);
}
}));
var patternValidator = function (viewValue) {
if (regex) {
//NOTE: we don't validate on empty values, use required validator for that
if (!viewValue || regex.test(viewValue.toString())) {
// it is valid
ctrl.$setValidity('valRegex', true);
//assign a message to the validator
ctrl.errorMsg = "";
return viewValue;
}
else {
// it is invalid, return undefined (no model update)
ctrl.$setValidity('valRegex', false);
//assign a message to the validator
ctrl.errorMsg = "Value is invalid, it does not match the correct pattern";
return undefined;
}
}
};
scope.$on('$destroy', function(){
// unbind watchers
for(var e in eventBindings) {
eventBindings[e]();
}
});
}
};
}
angular.module('umbraco.directives.validation').directive("valRegex", valRegex);
(function() {
'use strict';
function ValRequireComponentDirective() {
function link(scope, el, attr, ngModel) {
var unbindModelWatcher = scope.$watch(function () {
return ngModel.$modelValue;
}, function(newValue) {
if(newValue === undefined || newValue === null || newValue === "") {
ngModel.$setValidity("valRequiredComponent", false);
} else {
ngModel.$setValidity("valRequiredComponent", true);
}
});
// clean up
scope.$on('$destroy', function(){
unbindModelWatcher();
});
}
var directive = {
require: 'ngModel',
restrict: "A",
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('valRequireComponent', ValRequireComponentDirective);
})();
/**
* @ngdoc directive
* @name umbraco.directives.directive:valServer
* @restrict A
* @description This directive is used to associate a content property with a server-side validation response
* so that the validators in angular are updated based on server-side feedback.
**/
function valServer(serverValidationManager) {
return {
require: ['ngModel', '?^umbProperty'],
restrict: "A",
link: function (scope, element, attr, ctrls) {
var modelCtrl = ctrls[0];
var umbPropCtrl = ctrls.length > 1 ? ctrls[1] : null;
if (!umbPropCtrl) {
//we cannot proceed, this validator will be disabled
return;
}
var watcher = null;
//Need to watch the value model for it to change, previously we had subscribed to
//modelCtrl.$viewChangeListeners but this is not good enough if you have an editor that
// doesn't specifically have a 2 way ng binding. This is required because when we
// have a server error we actually invalidate the form which means it cannot be
// resubmitted. So once a field is changed that has a server error assigned to it
// we need to re-validate it for the server side validator so the user can resubmit
// the form. Of course normal client-side validators will continue to execute.
function startWatch() {
//if there's not already a watch
if (!watcher) {
watcher = scope.$watch(function () {
return modelCtrl.$modelValue;
}, function (newValue, oldValue) {
if (!newValue || angular.equals(newValue, oldValue)) {
return;
}
if (modelCtrl.$invalid) {
modelCtrl.$setValidity('valServer', true);
stopWatch();
}
}, true);
}
}
function stopWatch() {
if (watcher) {
watcher();
watcher = null;
}
}
var currentProperty = umbPropCtrl.property;
//default to 'value' if nothing is set
var fieldName = "value";
if (attr.valServer) {
fieldName = scope.$eval(attr.valServer);
if (!fieldName) {
//eval returned nothing so just use the string
fieldName = attr.valServer;
}
}
//subscribe to the server validation changes
serverValidationManager.subscribe(currentProperty.alias, fieldName, function (isValid, propertyErrors, allErrors) {
if (!isValid) {
modelCtrl.$setValidity('valServer', false);
//assign an error msg property to the current validator
modelCtrl.errorMsg = propertyErrors[0].errorMsg;
startWatch();
}
else {
modelCtrl.$setValidity('valServer', true);
//reset the error message
modelCtrl.errorMsg = "";
stopWatch();
}
});
//when the element is disposed we need to unsubscribe!
// NOTE: this is very important otherwise when this controller re-binds the previous subscriptsion will remain
// but they are a different callback instance than the above.
element.bind('$destroy', function () {
stopWatch();
serverValidationManager.unsubscribe(currentProperty.alias, fieldName);
});
}
};
}
angular.module('umbraco.directives.validation').directive("valServer", valServer);
/**
* @ngdoc directive
* @name umbraco.directives.directive:valServerField
* @restrict A
* @description This directive is used to associate a content field (not user defined) with a server-side validation response
* so that the validators in angular are updated based on server-side feedback.
**/
function valServerField(serverValidationManager) {
return {
require: 'ngModel',
restrict: "A",
link: function (scope, element, attr, ctrl) {
var fieldName = null;
var eventBindings = [];
attr.$observe("valServerField", function (newVal) {
if (newVal && fieldName === null) {
fieldName = newVal;
//subscribe to the changed event of the view model. This is required because when we
// have a server error we actually invalidate the form which means it cannot be
// resubmitted. So once a field is changed that has a server error assigned to it
// we need to re-validate it for the server side validator so the user can resubmit
// the form. Of course normal client-side validators will continue to execute.
eventBindings.push(scope.$watch('ngModel', function(newValue){
if (ctrl.$invalid) {
ctrl.$setValidity('valServerField', true);
}
}));
//subscribe to the server validation changes
serverValidationManager.subscribe(null, fieldName, function (isValid, fieldErrors, allErrors) {
if (!isValid) {
ctrl.$setValidity('valServerField', false);
//assign an error msg property to the current validator
ctrl.errorMsg = fieldErrors[0].errorMsg;
}
else {
ctrl.$setValidity('valServerField', true);
//reset the error message
ctrl.errorMsg = "";
}
});
//when the element is disposed we need to unsubscribe!
// NOTE: this is very important otherwise when this controller re-binds the previous subscriptsion will remain
// but they are a different callback instance than the above.
element.bind('$destroy', function () {
serverValidationManager.unsubscribe(null, fieldName);
});
}
});
scope.$on('$destroy', function(){
// unbind watchers
for(var e in eventBindings) {
eventBindings[e]();
}
});
}
};
}
angular.module('umbraco.directives.validation').directive("valServerField", valServerField);
/**
* @ngdoc directive
* @name umbraco.directives.directive:valSubView
* @restrict A
* @description Used to show validation warnings for a editor sub view to indicate that the section content has validation errors in its data.
* In order for this directive to work, the valFormManager directive must be placed on the containing form.
**/
(function() {
'use strict';
function valSubViewDirective() {
function link(scope, el, attr, ctrl) {
var valFormManager = ctrl[1];
scope.subView.hasError = false;
//listen for form validation changes
valFormManager.onValidationStatusChanged(function (evt, args) {
if (!args.form.$valid) {
var subViewContent = el.find(".ng-invalid");
if (subViewContent.length > 0) {
scope.subView.hasError = true;
} else {
scope.subView.hasError = false;
}
}
else {
scope.subView.hasError = false;
}
});
}
var directive = {
require: ['^form', '^valFormManager'],
restrict: "A",
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('valSubView', valSubViewDirective);
})();
/**
* @ngdoc directive
* @name umbraco.directives.directive:valTab
* @restrict A
* @description Used to show validation warnings for a tab to indicate that the tab content has validations errors in its data.
* In order for this directive to work, the valFormManager directive must be placed on the containing form.
**/
function valTab() {
return {
require: ['^form', '^valFormManager'],
restrict: "A",
link: function (scope, element, attr, ctrs) {
var valFormManager = ctrs[1];
var tabId = "tab" + scope.tab.id;
scope.tabHasError = false;
//listen for form validation changes
valFormManager.onValidationStatusChanged(function (evt, args) {
if (!args.form.$valid) {
var tabContent = element.closest(".umb-panel").find("#" + tabId);
//check if the validation messages are contained inside of this tabs
if (tabContent.find(".ng-invalid").length > 0) {
scope.tabHasError = true;
} else {
scope.tabHasError = false;
}
}
else {
scope.tabHasError = false;
}
});
}
};
}
angular.module('umbraco.directives.validation').directive("valTab", valTab);
function valToggleMsg(serverValidationManager) {
return {
require: "^form",
restrict: "A",
/**
Our directive requries a reference to a form controller which gets passed in to this parameter
*/
link: function (scope, element, attr, formCtrl) {
if (!attr.valToggleMsg){
throw "valToggleMsg requires that a reference to a validator is specified";
}
if (!attr.valMsgFor){
throw "valToggleMsg requires that the attribute valMsgFor exists on the element";
}
if (!formCtrl[attr.valMsgFor]) {
throw "valToggleMsg cannot find field " + attr.valMsgFor + " on form " + formCtrl.$name;
}
//if there's any remaining errors in the server validation service then we should show them.
var showValidation = serverValidationManager.items.length > 0;
var hasCustomMsg = element.contents().length > 0;
//add a watch to the validator for the value (i.e. myForm.value.$error.required )
scope.$watch(function () {
//sometimes if a dialog closes in the middle of digest we can get null references here
return (formCtrl && formCtrl[attr.valMsgFor]) ? formCtrl[attr.valMsgFor].$error[attr.valToggleMsg] : null;
}, function () {
//sometimes if a dialog closes in the middle of digest we can get null references here
if ((formCtrl && formCtrl[attr.valMsgFor])) {
if (formCtrl[attr.valMsgFor].$error[attr.valToggleMsg] && showValidation) {
element.show();
//display the error message if this element has no contents
if (!hasCustomMsg) {
element.html(formCtrl[attr.valMsgFor].errorMsg);
}
}
else {
element.hide();
}
}
});
var unsubscribe = [];
//listen for the saving event (the result is a callback method which is called to unsubscribe)
unsubscribe.push(scope.$on("formSubmitting", function(ev, args) {
showValidation = true;
if (formCtrl[attr.valMsgFor].$error[attr.valToggleMsg]) {
element.show();
//display the error message if this element has no contents
if (!hasCustomMsg) {
element.html(formCtrl[attr.valMsgFor].errorMsg);
}
}
else {
element.hide();
}
}));
//listen for the saved event (the result is a callback method which is called to unsubscribe)
unsubscribe.push(scope.$on("formSubmitted", function(ev, args) {
showValidation = false;
element.hide();
}));
//when the element is disposed we need to unsubscribe!
// NOTE: this is very important otherwise if this directive is part of a modal, the listener still exists because the dom
// element might still be there even after the modal has been hidden.
element.bind('$destroy', function () {
for (var u in unsubscribe) {
unsubscribe[u]();
}
});
}
};
}
/**
* @ngdoc directive
* @name umbraco.directives.directive:valToggleMsg
* @restrict A
* @element input
* @requires formController
* @description This directive will show/hide an error based on: is the value + the given validator invalid? AND, has the form been submitted ?
**/
angular.module('umbraco.directives.validation').directive("valToggleMsg", valToggleMsg);
angular.module('umbraco.directives.validation')
.directive('valTriggerChange', function($sniffer) {
return {
link : function(scope, elem, attrs) {
elem.bind('click', function(){
$(attrs.valTriggerChange).trigger($sniffer.hasEvent('input') ? 'input' : 'change');
});
},
priority : 1
};
});
})();
|
clausjensen/Merchello
|
src/Merchello.FastTrack.Ui/Umbraco/Js/umbraco.directives.js
|
JavaScript
|
mit
| 355,872
|
include ../common.mk
CP_FILES:=$(wildcard *.classpath)
JS_LIB_FILES=$(addprefix $(JS_PUB_DIR)/, $(CP_FILES:.classpath=-last.js))
JS_LIB_FILES_WITH_VERSION=$(addprefix $(JS_PUB_DIR)/, $(CP_FILES:.classpath=-$(JS_VERSION).js))
JS_LIB_PRODUCTION_FILES=$(addprefix $(JS_PUB_DIR)/, $(CP_FILES:.classpath=-last.min.js))
JS_LIB_PRODUCTION_FILES_WITH_VERSION=$(addprefix $(JS_PUB_DIR)/, $(CP_FILES:.classpath=-$(JS_VERSION).min.js))
all: clear $(JS_LIB_FILES) $(JS_LIB_PRODUCTION_FILES) $(JS_LIB_FILES_WITH_VERSION) $(JS_LIB_PRODUCTION_FILES_WITH_VERSION)
force: clear all
$(JS_PUB_DIR)/%-$(JS_VERSION).js: $(JS_PUB_DIR)/%-last.js
$(CP) $(JS_PUB_DIR)/$*-last.js $@
$(JS_PUB_DIR)/%-$(JS_VERSION).min.js: $(JS_PUB_DIR)/%-last.min.js
$(CP) $(JS_PUB_DIR)/$*-last.min.js $@
$(JS_PUB_DIR)/%-last.min.js: $(JS_PUB_DIR)/%-last.js
$(CAT) $(JS_PUB_DIR)/$*-last.js | $(COMPRESSOR) > $@
$(JS_PUB_DIR)/%-last.js: %.classpath $(JS_PUB_DIR)
$(CHECK) --targetClassesFile "$*.classpath" --classPath "." --isTupaiCore
$(MERGE) --targetClassesFile "$*.classpath" --classPath "." --output "$@" --isTupaiCore --append --noLog --ignoreNotFound
$(JS_PUB_DIR):
$(MKDIR) -p $(JS_PUB_DIR)
clear:
$(RM) $(JS_LIB_FILES)
$(RM) $(JS_LIB_FILES_WITH_VERSION)
$(RM) $(JS_LIB_PRODUCTION_FILES)
$(RM) $(JS_LIB_PRODUCTION_FILES_WITH_VERSION)
|
deyunanhai/tupai.js
|
libs/Makefile
|
Makefile
|
mit
| 1,318
|
package realtime
import (
"log"
"github.com/Jeffail/gabs"
"github.com/lnxjedi/gopherbot/connectors/rocket/models"
)
// GetPublicSettings gets public settings
//
// https://rocket.chat/docs/developer-guides/realtime-api/method-calls/get-public-settings
func (c *Client) GetPublicSettings() ([]models.Setting, error) {
rawResponse, err := c.ddp.Call("public-settings/get")
if err != nil {
return nil, err
}
document, _ := gabs.Consume(rawResponse)
sett, _ := document.Children()
var settings []models.Setting
for _, rawSetting := range sett {
setting := models.Setting{
ID: stringOrZero(rawSetting.Path("_id").Data()),
Type: stringOrZero(rawSetting.Path("type").Data()),
}
switch setting.Type {
case "boolean":
setting.ValueBool = rawSetting.Path("value").Data().(bool)
case "string":
setting.Value = stringOrZero(rawSetting.Path("value").Data())
case "code":
setting.Value = stringOrZero(rawSetting.Path("value").Data())
case "color":
setting.Value = stringOrZero(rawSetting.Path("value").Data())
case "int":
setting.ValueInt = rawSetting.Path("value").Data().(float64)
case "asset":
setting.ValueAsset = models.Asset{
DefaultUrl: stringOrZero(rawSetting.Path("value").Data().(map[string]interface{})["defaultUrl"]),
}
default:
log.Println(setting.Type, rawSetting.Path("value").Data())
}
settings = append(settings, setting)
}
return settings, nil
}
|
parsley42/gopherbot
|
connectors/rocket/realtime/settings.go
|
GO
|
mit
| 1,435
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions;
using osu.Framework.Input.Bindings;
using osu.Framework.Testing;
using osu.Game.Database;
using osu.Game.Graphics.UserInterface;
using osu.Game.Input.Bindings;
using osu.Game.Overlays.Settings.Sections.Input;
using osu.Game.Screens.Play;
using osu.Game.Screens.Select;
using osu.Game.Tests.Beatmaps.IO;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Navigation
{
public class TestSceneChangeAndUseGameplayBindings : OsuGameTestScene
{
[Test]
public void TestGameplayKeyBindings()
{
AddAssert("databased key is default", () => firstOsuRulesetKeyBindings.KeyCombination.Keys.SequenceEqual(new[] { InputKey.Z }));
AddStep("open settings", () => { Game.Settings.Show(); });
// Until step requires as settings has a delayed load.
AddUntilStep("wait for button", () => configureBindingsButton?.Enabled.Value == true);
AddStep("scroll to section", () => Game.Settings.SectionsContainer.ScrollTo(configureBindingsButton));
AddStep("press button", () => configureBindingsButton.TriggerClick());
AddUntilStep("wait for panel", () => keyBindingPanel?.IsLoaded == true);
AddUntilStep("wait for osu subsection", () => osuBindingSubsection?.IsLoaded == true);
AddStep("scroll to section", () => keyBindingPanel.SectionsContainer.ScrollTo(osuBindingSubsection));
AddWaitStep("wait for scroll to end", 3);
AddStep("start rebinding first osu! key", () =>
{
var button = osuBindingSubsection.ChildrenOfType<KeyBindingRow>().First();
InputManager.MoveMouseTo(button);
InputManager.Click(MouseButton.Left);
});
AddStep("Press 's'", () => InputManager.Key(Key.S));
AddUntilStep("wait for database updated", () => firstOsuRulesetKeyBindings.KeyCombination.Keys.SequenceEqual(new[] { InputKey.S }));
AddStep("close settings", () => Game.Settings.Hide());
AddStep("import beatmap", () => BeatmapImportHelper.LoadQuickOszIntoOsu(Game).WaitSafely());
PushAndConfirm(() => new PlaySongSelect());
AddUntilStep("wait for selection", () => !Game.Beatmap.IsDefault);
AddStep("enter gameplay", () => InputManager.Key(Key.Enter));
AddUntilStep("wait for player", () =>
{
// dismiss any notifications that may appear (ie. muted notification).
clickMouseInCentre();
return player != null;
});
AddUntilStep("wait for gameplay", () => player?.IsBreakTime.Value == false);
AddStep("press 'z'", () => InputManager.Key(Key.Z));
AddAssert("key counter didn't increase", () => keyCounter.CountPresses == 0);
AddStep("press 's'", () => InputManager.Key(Key.S));
AddAssert("key counter did increase", () => keyCounter.CountPresses == 1);
}
private void clickMouseInCentre()
{
InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.Centre);
InputManager.Click(MouseButton.Left);
}
private KeyBindingsSubsection osuBindingSubsection => keyBindingPanel
.ChildrenOfType<VariantBindingsSubsection>()
.FirstOrDefault(s => s.Ruleset.ShortName == "osu");
private OsuButton configureBindingsButton => Game.Settings
.ChildrenOfType<BindingSettings>().SingleOrDefault()?
.ChildrenOfType<OsuButton>()?
.First(b => b.Text.ToString() == "Configure");
private KeyBindingPanel keyBindingPanel => Game.Settings
.ChildrenOfType<KeyBindingPanel>().SingleOrDefault();
private RealmKeyBinding firstOsuRulesetKeyBindings => Game.Dependencies
.Get<RealmAccess>().Realm
.All<RealmKeyBinding>()
.AsEnumerable()
.First(k => k.RulesetName == "osu" && k.ActionInt == 0);
private Player player => Game.ScreenStack.CurrentScreen as Player;
private KeyCounter keyCounter => player.ChildrenOfType<KeyCounter>().First();
}
}
|
ppy/osu
|
osu.Game.Tests/Visual/Navigation/TestSceneChangeAndUseGameplayBindings.cs
|
C#
|
mit
| 4,911
|
/**
* Developer: Alexandr Voronyansky
* E-mail: alexandr@voronynsky.com
* Date: 04.10.13
* Time: 10:07
*/
(function( $, global ){
document.fullScreen = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement||
document.documentElement.requestFullscreen || document.documentElement.mozRequestFullScreen || document.documentElement.webkitRequestFullscreen;
document.cancelFullScreen = document.cancelFullScreen || document.mozCancelFullScreen || document.webkitCancelFullScreen;
/**
* Настройки презентации по умолчанию
*
* @type {{slideClass: string, autoplay: boolean, autoplayDelay: number, progressBar: boolean, slideIndex: boolean, thumbnails: boolean, controls: Array, enableScroll: boolean, toggleEffect: string}}
*/
var defaultSettings = {
slideClass: "",
autoplay: false,
autoplayDelay: 2000,
progressBar: true,
slideIndex: true,
thumbnails: false,
controls: ["next", "prev", "play", "fullscreen"],
enableHotKeys: false,
enableScroll: false,
toggleEffect: "base"
};
/**
* Данные для генерации навигационной панели
* @type {{}}
*/
var controlData = {
/* пространство имен "_ss" нужно для безопасной поддержки метода destroy */
next: {
text: 'вперед',
hotKeyHelp: " ( Пробел, →, ↑ )",
className: 'ss-next',
title: 'листаем вперед',
init: function ( p ){
var _self = this;
$( this ).on( "click._ss", ".ss-next", function( e ){
shareMethods.next.apply( _self );
e.preventDefault();
});
}
},
prev: {
text: 'назад',
hotKeyHelp: " ( Backspace, ←, ↓ )",
className: 'ss-prev',
title: 'листаем назад',
init: function ( p ){
var _self = this;
$( this ).on( "click._ss", ".ss-prev", function( e ){
shareMethods.prev.apply( _self );
e.preventDefault();
})
}
},
play: {
text: 'воспроизвести',
hotKeyHelp: " (Ctrl + P, Ctrl + Enter)",
textActive: 'остановить',
className: 'ss-play',
title: 'воспроизвести',
titleActive: 'отановить',
init: function ( p ){
var _self = this;
$( this ).on( "click._ss", ".ss-play", function( e ){
if ( p.isPlaying ){
shareMethods.stop.apply( _self );
}else{
shareMethods.play.apply( _self );
}
e.preventDefault();
})
}
},
fullscreen: {
text: 'на весь экран',
hotKeyHelp: " (Ctrl + F)",
textActive: 'обычный режим',
className: 'ss-fullscreen',
title: 'развернуть презентацию в полноэкранном режиме',
titleActive: 'выйти из полноэкранного режима (ESC)',
init: function ( p ){
var _self = this;
$( this ).on( "click._ss", ".ss-fullscreen", function( e ){
shareMethods.fullscreen.apply( _self );
e.preventDefault();
});
}
}
};
/**
* Анимирующие функции, импользуются для смены активного слайда.
* Можно легко реализовать возможность добавления пользователем своих анимирующих функций в систему
*
* @type {{base: Function, fade: Function, scrolllr: Function, scrolltb: Function}}
*/
var animateFunctions = {
base: function ( actualSlide, requireSlide ){
var defer = new $.Deferred();
actualSlide.removeClass( "active" );
requireSlide.addClass( "active" );
defer.resolve();
return defer.promise();
},
fade: function( actualSlide, requireSlide ){
requireSlide.css( "opacity", 0).addClass( "active" );
return $.when(
actualSlide.animate( {"opacity": 0}, 200, function(){
actualSlide.removeClass( "active" ).css( "opacity", 1 );
}),
requireSlide.animate( {"opacity": 1}, 150 )
).promise();
},
scrolllr: function( actualSlide, requireSlide ){
requireSlide.css( "left", "-" + requireSlide.width() + "px" ).addClass( "active" );
return $.when(
actualSlide.animate( {"left": actualSlide.width() + "px"}, 500, function(){
actualSlide.removeClass( "active" ).css( "left", 0 );
}),
requireSlide.animate( {"left": 0}, 500 )
).promise();
},
scrolltb: function( actualSlide, requireSlide ){
requireSlide.css( "top", "-" + requireSlide.height() + "px" ).addClass( "active" );
return $.when(
actualSlide.animate( {"top": actualSlide.height() + 200 + "px"}, 500, function(){
actualSlide.removeClass( "active" ).css( "top", 0 );
}),
requireSlide.animate( {"top": 0}, 500 )
).promise();
}
};
/**
* Внутренние сервисные методы. Недоступны для пользователя
*
* @type {{init: Function, loadSlide: Function, toggleSlides: Function, getPersentage: Function}}
*/
var helperMethod = {
/**
* Инициализатор системы
* @param options
*/
init: function( options ){
var _self = this,
container = $(this),
p = {};
/* если презентация уже инициализирована */
if ( !!container.data( "ss_data" ) ) return;
if ( options && options.controls === "all" ){
options.controls = defaultSettings.controls;
}
p.settings = $.extend( $.extend( {},defaultSettings ), options || {} );
p.allSlides = container.children( p.settings.slideClass );
p.isPlaying = false;
p.tick = null;
if ( p.allSlides.length == 0 ) return;
var enableSlides = p.allSlides.filter( function(){
return !$( this ).hasClass( "ss-disabled" );
}),
firstRequest = enableSlides.filter( ".ss-start" );
p.enableSlideCount = enableSlides.length;
p.actualSlide = null;
container.addClass( "ss-slide-show" );
if ( container.css( "position" ) === "static" ){
container.css( {position: "relative"} );
}
p.allSlides.addClass( "ss-slide" ).css(
{
position: "absolute"
}
);
$.each( enableSlides, function( index, el){
var slide = $( el );
slide.addClass( "ss-inqueue" ).data( "ss_index", index + 1 );
});
p.actualSlide = firstRequest.length == 0 ? enableSlides.first() : firstRequest.first();
p.actualIndex = p.actualSlide.data( "ss_index" );
p.actualSlide.addClass( "active" );
/* инициализация панели управления */
if ( p.settings.controls && Object.prototype.toString.call( p.settings.controls ) === "[object Array]" ){
var controlArr = p.settings.controls,
control, i;
for ( i = 0; i < controlArr.length && controlData.hasOwnProperty( controlArr[i] ); i++ ){
control = $( "." + controlData[controlArr[i]].className, container );
if ( control.length == 0 ){
control = $('<a class="' + controlData[controlArr[i]].className +
'" href="#">' + controlData[controlArr[i]].text + '</a>');
control.appendTo( container );
}
control.addClass( "ss-control" );
control.attr( "title", p.settings.enableHotKeys ?
controlData[controlArr[i]].title + controlData[controlArr[i]].hotKeyHelp :
controlData[controlArr[i]].title );
controlData[ controlArr[i] ].init.apply( this, [p] );
}
}
/* инициализация прогрессбара */
if ( p.settings.progressBar ){
p.progressBar = $(".ss-progress", container );
if ( p.progressBar.length == 0 ){
p.progressBar = $('<div class="ss-control ss-progress"></div>');
p.progressBar.css(
{
width: helperMethod.getPersentage( p.enableSlideCount, p.actualIndex ) + "%"
}
).appendTo(container );
}
}
/* инициализация счетчика слайдов */
if ( p.settings.slideIndex && p.actualIndex ){
p.slideIndex = $(".ss-slide-index", container );
if ( p.slideIndex.length == 0 ){
p.slideIndex = $('<div class="ss-control ss-slide-index">' + p.actualIndex + '</div>');
p.slideIndex.appendTo(container );
}
}
/* инициализация управления с клавиатуры */
if ( p.settings.enableHotKeys ){
$( document).on( "keydown._ss", function( e ){
if ( e.ctrlKey ){
if ( e.keyCode == 80 || e.keyCode == 13 ){
shareMethods.play.apply( _self );
e.preventDefault();
}
if ( e.keyCode == 70 ){
shareMethods.fullscreen.apply( _self );
e.preventDefault();
}
}else{
if ( e.keyCode == 37 || e.keyCode == 40 || e.keyCode == 8 ){
shareMethods.prev.apply( _self );
e.preventDefault();
}
if ( e.keyCode == 32 || e.keyCode == 38 || e.keyCode == 39 ){
shareMethods.next.apply( _self );
e.preventDefault();
}
}
});
}
/* инициализация поддержки скроллинга */
if ( p.settings.enableScroll ){
var throttledPrev = $.throttle( 300, true, shareMethods.prev),
throttledNext = $.throttle( 300, true, shareMethods.next );
container.on( "mousewheel._ss", function( e, delta, deltaX, deltaY ){
if ( deltaY > 0 ){
throttledPrev.apply( _self );
}else{
throttledNext.apply( _self );
}
e.preventDefault();
})
}
/* инициализация панели с миниатюрами */
if ( p.settings.thumbnails ){
var thumbPanel = $( p.settings.thumbnails );
if ( thumbPanel.length ){
var actualIndex = 0;
$.each( p.allSlides, function( index, el ){
var slide = $( el ),
thumb = $('<div class="ss-thumb"></div>');
thumb.appendTo( thumbPanel );
if ( !slide.hasClass( "ss-disabled" ) ){
actualIndex += 1;
thumb.data( "ss_index", actualIndex).addClass( "ss-inqueue").text( actualIndex );
if ( actualIndex == p.actualIndex ){
thumb.addClass( "active" );
}
}else{
thumb.addClass( "ss-disabled" );
}
helperMethod.generateThumb.apply( this, [ slide, thumb ] );
});
if ( p.allSlides.length ){
thumbPanel.on( "click._ss", ".ss-inqueue", function( e ){
var thumb = $( this ),
index = thumb.data( "ss_index" );
shareMethods.stop.apply( _self );
helperMethod.loadSlide.apply( _self, [index] );
$( ".active", thumbPanel ).removeClass( "active" );
thumb.addClass( "active" );
e.preventDefault();
});
}
if ( container.has( thumbPanel ) ){
thumbPanel.addClass( "ss-control" );
}
}
}
$( ".ss-control", container ).css(
{
"z-index": 3000
}
);
container.data( "ss_data", p );
if ( p.settings.autoplay ){
shareMethods.play.apply( this );
}
},
/**
* Загрузчик нового активного слайда. Может обрабатывать как указание направдения "next" или "prev",
* так и запросы на загрузку конкретных слайдов по номерам
*
* @param param
* @returns {null|*}
*/
loadSlide: function( param ){
var container = $( this ),
p = container.data( "ss_data" ),
requireSlide = null;
if ( Object.prototype.toString.call( param ) === "[object Number]" ){
param--;
if ( param != p.actualIndex - 1 && param >= 0 && param < p.enableSlideCount ){
requireSlide = $( ".ss-inqueue:eq(" + param + ")", container );
}
}else{
var searchNode = p.actualSlide[param]( ".ss-slide" );
while ( requireSlide == null && searchNode.length ){
if ( searchNode.hasClass( "ss-disabled" ) ){
searchNode = searchNode[param]( ".ss-slide" );
continue;
}
requireSlide = searchNode;
}
}
if ( requireSlide && requireSlide != p.actualSlide ){
helperMethod.toggleSlides( p.actualSlide, requireSlide, p.settings, function( slideIndex ){
if ( p.settings.progressBar ){
p.progressBar.css(
{
width: helperMethod.getPersentage( p.enableSlideCount, slideIndex ) + "%"
}
);
}
if ( p.settings.slideIndex ){
p.slideIndex.text( slideIndex );
}
});
p.actualSlide = requireSlide;
p.actualIndex = p.actualSlide.data( "ss_index" );
if ( p.settings.thumbnails ){
var thumbPanel = $( p.settings.thumbnails );
$(".active", thumbPanel).removeClass("active");
$(".ss-inqueue:eq(" + ( p.actualIndex - 1 ) + ")", thumbPanel).addClass( "active" );
}
}
/* вернуть загружаемый слайд */
return requireSlide || p.actualSlide ;
},
/**
* Вспомогательный метод, управляет сменой текушего и нового активного слайдов.
*
* @param actualSlide - текущий слайд
* @param requireSlide - слайд, ожидающий загрузки
* @param settings - настройки презентации
* @param callback - вызывается после окончания смены слайдов
*/
toggleSlides: function( actualSlide, requireSlide, settings, callback ){
var effect = requireSlide.attr( "data-effect"),
animateFunction = animateFunctions.hasOwnProperty( effect ) ? animateFunctions[effect] :
animateFunctions.hasOwnProperty( settings.toggleEffect ) ? animateFunctions[settings.toggleEffect] : animateFunctions.base,
animateRequest = animateFunction( actualSlide, requireSlide );
if ( callback ){
animateRequest.done( callback( requireSlide.data("ss_index")) );
}
},
/**
* Вспомогательный метод. Возвращает процентную долю числа от целого.
* Используется для управления прогрессбаром презентации
*
* @param total
* @param part
* @returns {number}
*/
getPersentage: function( total, part ){
if ( total == 0 ) return 0;
return part / total * 100;
},
/**
* Сгенерировать эскиз слайда
*
* @param slide
* @param thumb
*/
generateThumb: function( slide, thumb ){
var desc = slide.attr( "data-desc" );
if ( !!desc ){
$( '<h3 class="ss-thumb-desc">' + desc + '</h3>').appendTo( thumb );
}
if ( slide.css( "display" ) === "none" ){
slide.get(0).style.display = "block";
}
try{ /* попытка сгенерировать эскиз слайда */
html2canvas( slide.get(0), {
onrendered: function ( canvas ){
if ( !canvas.toDataURL ) return;
var jqCanvas = $( canvas );
jqCanvas.appendTo( "body" );
thumb.css( 'background-image', 'url("' + canvas.toDataURL() + '")');
jqCanvas.remove();
slide.get(0).style.display = null;
}
});
}catch( e ){ /* намеренно тушим исключение */ }
}
};
/**
* Методы, достыпнве для пользователя системы
*
* @type {{next: Function, prev: Function, go: Function, play: Function, stop: Function, fullscreen: Function}}
*/
var shareMethods = {
/**
* Загружает слайд из очереди, следующий за текущим
* Позволяет двигаться по очереди слайдов вперед
*
*/
next: function(){
shareMethods.stop.apply( this );
helperMethod.loadSlide.apply( this, ["next"] );
},
/**
* Загружает слайд из очереди, следующий перед текущим
* Позволяет двигаться по очереди слайдов назад
*
*/
prev: function(){
shareMethods.stop.apply( this );
helperMethod.loadSlide.apply( this, ["prev"] );
},
/**
* Позволяет перейти к указанному слайду
* Позволяет произвольно перемещаться по очереди слайдов
*
* @param slideIndex
*/
go: function( slideIndex ){
helperMethod.loadSlide.apply( this, [slideIndex] );
},
/**
* Запускает автопроигрывание презентации
*/
play: function(){
var container = $( this ),
_self = this,
p = container.data( "ss_data" );
if ( !p.isPlaying ){
var playBtn = container.find(".ss-play"),
lastSlide = p.actualSlide;
playBtn.addClass( "ss-playing" ).text( controlData.play.textActive).attr( "title", controlData.play.titleActive );
p.isPlaying = true;
p.tick = setInterval( function(){
var slide = helperMethod.loadSlide.apply( _self, ["next"] );
if ( slide == lastSlide ){
shareMethods.stop.apply( _self );
}else{
lastSlide = slide;
}
} , p.settings.autoplayDelay);
container.data( "ss_data", p );
}
},
/**
* Останавливает автопроигрывание презентации
*/
stop: function(){
var container = $( this ),
p = container.data( "ss_data" );
if ( p.isPlaying ){
p.isPlaying = false;
clearInterval( p.tick );
container.find( ".ss-play" ).removeClass( "ss-playing" ).text( controlData.play.text).attr( "title", controlData.play.title );
container.data( "ss_data", p );
}
},
/**
* Включает полноэкранный режим презентации
*/
fullscreen: function(){
//TODO: не срабатывает при вызове через API
var container = $( this ),
_self = this;
if ( !container.hasClass( "ss-fs-active" ) ){
if ( document.fullScreen ){
document.fullScreen.call( this[0] );
}else{
$( "body" ).addClass("ss-fs-active" );
container.css( {position: "fixed"} );
}
container.find( ".ss-fullscreen" )
.addClass( "ss-expanded")
.text( controlData.fullscreen.textActive)
.attr( "title", controlData.fullscreen.titleActive );
container.addClass( "ss-fs-active" );
/* перехватываем ESC для режима эмуляции и обновления состояния кнопки в современном режиме*/
$( document ).on( "keyup._ss_esc", function( e ){
if ( e.keyCode == 27 ){
shareMethods.fullscreen.apply( _self );
}
});
}else{
if ( document.cancelFullScreen ){
document.cancelFullScreen();
}else{
$( "body" ).removeClass( "ss-fs-active" );
container.css( {position: "relative"} );
}
container.find( ".ss-fullscreen" )
.removeClass( "ss-expanded" )
.text( controlData.fullscreen.text )
.attr( "title", controlData.fullscreen.title );
container.removeClass( "ss-fs-active" );
/* удалить обработчик перехвата ESC */
$( document ).off( "keyup._ss_esc" );
}
},
/**
* Откат к неинициализированному состоянию
*/
destroy: function(){
var container = $( this ),
p = container.data( "ss_data" );
if ( p.settings.enableHotKeys ){
$( document).off( "keydown._ss" );
}
if ( p.settings.enableScroll ){
container.off( "mousewheel._ss" );
}
if ( p.settings.thumbnails ){
var thumbContainer = $( p.settings.thumbnails );
thumbContainer.off( "click._ss" );
$( ".ss-thumb", thumbContainer).remove();
}
$( ".ss-slide", container ).removeClass( "ss-slide ss-inqueue active" );
$( ".ss-control", container ).remove();
container.off( "click._ss" );
container.removeData( "ss_data" );
}
};
$.fn.presentation = function( options ){
if ( this.length > 1 ){
$.each( this, function( index, el){
$( el).presentation( options );
});
}else{
if ( shareMethods.hasOwnProperty( options ) ){
shareMethods[options].apply( this, Array.prototype.slice.call( arguments, 1 ) );
}else if ( !options || Object.prototype.toString.call( options ) === "[object Object]" ){
helperMethod.init.apply( this, arguments );
}else{
throw new Error( "Method [" + options + "] not found in presentation api." );
}
}
return this;
}
}( jQuery, window ));
|
BelirafoN/slideSystem
|
src/slide_system.js
|
JavaScript
|
mit
| 26,072
|
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
archive = require('./archive.js'),
modelUtils = require('./modelUtils'),
config = require('meanio').loadConfig() ;
var FolderSchema = new Schema({
created: {
type: Date,
default: Date.now
},
updated: {
type: Date
},
recycled: {
type: Date,
},
title: {
type: String
},
office: {
type: Schema.ObjectId,
ref: 'Office'
},
discussion: {
type: Schema.ObjectId,
ref: 'Discussion'
},
creator: {
type: Schema.ObjectId,
ref: 'User'
},
manager: {
type: Schema.ObjectId,
ref: 'User'
},
signature: {
circles: {},
codes: {}
},
color: {
type: String,
required: true
},
status: {
type: String,
enum: ['new', 'in-progress', 'canceled', 'done', 'archived'],
default: 'new'
},
tags: [String],
description: {
type: String
},
//should we maybe have finer grain control on this
watchers: [
{
type: Schema.ObjectId,
ref: 'User'
}
],
bolded: [
{
_id: false,
id: {type: Schema.ObjectId, ref: 'User'},
bolded: Boolean,
lastViewed: Date
}
],
permissions: [
{
_id: false,
id: {type: Schema.ObjectId, ref: 'User'},
level: {
type: String,
enum: ['viewer', 'commenter', 'editor'],
default: 'viewer'
}
}
],
parent: {
type: Schema.ObjectId,
ref: 'Folder'
},
room: {
type: String
},
hasRoom: {
type: Boolean,
default: false
},
sources: [String],
circles: {
type: Schema.Types.Mixed
},
WantRoom: {
type: Boolean,
default: false
},
roomName: {
type: String
}
});
var starVirtual = FolderSchema.virtual('star');
starVirtual.get(function() {
return this._star;
});
starVirtual.set(function(value) {
this._star = value;
});
FolderSchema.set('toJSON', {
virtuals: true
});
FolderSchema.set('toObject', {
virtuals: true
});
/**
* Validations
*/
FolderSchema.path('color').validate(function(color) {
return /^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/i.test(color);
}, 'Invalid HEX color.');
/**
* Statics
*/
FolderSchema.statics.load = function(id, cb) {
this.findOne({
_id: id
}).populate('creator', 'name username').exec(cb);
};
FolderSchema.statics.office = function(id, cb) {
require('./office');
var Office = mongoose.model('Office');
Office.findById(id, function(err, office) {
cb(err, office || {});
});
};
/**
* Post middleware
*/
var elasticsearch = require('../controllers/elasticsearch');
FolderSchema.post('save', function(req, next) {
var task = this;
FolderSchema.statics.office(this.office, function(err, office) {
if(err) {
return err;
}
elasticsearch.save(task, 'folder');
});
next();
});
FolderSchema.pre('remove', function(next) {
var task = this;
FolderSchema.statics.office(this.office, function(err, office) {
if(err) {
return err;
}
elasticsearch.delete(task, 'task', next);
});
next();
});
/**
* middleware
*/
// Will not execute until the first middleware calls `next()`
FolderSchema.pre('save', function(next) {
let entity = this ;
config.superSeeAll ? modelUtils.superSeeAll(entity,next) : next() ;
});
FolderSchema.post('save', function(req, next) {
elasticsearch.save(this, 'folder');
next();
});
FolderSchema.pre('remove', function(next) {
elasticsearch.delete(this, 'folder', next);
next();
});
FolderSchema.plugin(archive, 'folder');
module.exports = mongoose.model('Folder', FolderSchema);
|
linnovate/icu
|
packages/custom/icu/server/models/folder.js
|
JavaScript
|
mit
| 3,595
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>InvalidMangledStaticArg - F# Compiler Services</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Microsoft Corporation, Dave Thomas, Anh-Dung Phan, Tomas Petricek">
<script src="https://code.jquery.com/jquery-1.8.0.js"></script>
<script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script>
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="./content/style.css" />
<link type="text/css" rel="stylesheet" href="./content/fcs.css" />
<script type="text/javascript" src="./content/tips.js"></script>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="https://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li><a href="http://fsharp.org">fsharp.org</a></li>
<li><a href="http://github.com/fsharp/FSharp.Compiler.Service">github page</a></li>
</ul>
<h3 class="muted">F# Compiler Services</h3>
</div>
<hr />
<div class="row">
<div class="span9" id="main">
<h1>InvalidMangledStaticArg</h1>
<p>
<span>Namespace: FSharp.Compiler</span><br />
<span>Parent Module: <a href="fsharp-compiler-prettynaming.html">PrettyNaming</a></span>
</p>
<div class="xmldoc">
</div>
<h3>Record Fields</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>Record Field</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1652', 1652)" onmouseover="showTip(event, '1652', 1652)">
Data0
</code>
<div class="tip" id="1652">
<strong>Signature:</strong> string<br />
</div>
</td>
<td class="xmldoc">
</td>
</tr>
</tbody>
</table>
</div>
<div class="span3">
<a href="https://nuget.org/packages/FSharp.Compiler.Service">
<img src="./images/logo.png" style="width:140px;height:140px;margin:10px 0px 0px 35px;border-style:none;" />
</a>
<ul class="nav nav-list" id="menu">
<li class="nav-header">
<a href="./ja/index.html" class="nflag"><img src="./images/ja.png" /></a>
<a href="./index.html" class="nflag nflag2"><img src="./images/en.png" /></a>
F# Compiler Services
</li>
<li><a href="./index.html">Home page</a></li>
<li class="divider"></li>
<li><a href="https://www.nuget.org/packages/FSharp.Compiler.Service">Get Library via NuGet</a></li>
<li><a href="http://github.com/fsharp/FSharp.Compiler.Service">Source Code on GitHub</a></li>
<li><a href="http://github.com/fsharp/FSharp.Compiler.Service/blob/master/LICENSE">License</a></li>
<li><a href="http://github.com/fsharp/FSharp.Compiler.Service/blob/master/RELEASE_NOTES.md">Release Notes</a></li>
<li class="nav-header">Getting started</li>
<li><a href="./index.html">Home page</a></li>
<li><a href="./devnotes.html">Developer notes</a></li>
<li><a href="./fsharp-readme.html">F# compiler readme</a></li>
<li class="nav-header">Available services</li>
<li><a href="./tokenizer.html">F# Language tokenizer</a></li>
<li><a href="./untypedtree.html">Processing untyped AST</a></li>
<li><a href="./editor.html">Using editor (IDE) services</a></li>
<li><a href="./symbols.html">Using resolved symbols</a></li>
<li><a href="./typedtree.html">Using resolved expressions</a></li>
<li><a href="./project.html">Whole-project analysis</a></li>
<li><a href="./interactive.html">Embedding F# interactive</a></li>
<li><a href="./compiler.html">Embedding F# compiler</a></li>
<li><a href="./filesystem.html">Virtualized file system</a></li>
<li class="nav-header">Design Notes</li>
<li><a href="./queue.html">The FSharpChecker operations queue</a></li>
<li><a href="./caches.html">The FSharpChecker caches</a></li>
<li><a href="./corelib.html">Notes on FSharp.Core.dll</a></li>
<li class="nav-header">Documentation</li>
<li><a href="./reference/index.html">API Reference</a>
</li>
</ul>
</div>
</div>
</div>
<a href="http://github.com/fsharp/FSharp.Compiler.Service"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
</body>
</html>
|
dsyme/FSharp.Compiler.Service
|
docs/reference/fsharp-compiler-prettynaming-invalidmangledstaticarg.html
|
HTML
|
mit
| 5,175
|
package nxt.http;
import nxt.Alias;
import nxt.util.Convert;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;
import javax.servlet.http.HttpServletRequest;
import static nxt.http.JSONResponses.INCORRECT_ALIAS;
import static nxt.http.JSONResponses.MISSING_ALIAS;
import static nxt.http.JSONResponses.UNKNOWN_ALIAS;
public final class GetAlias extends APIServlet.APIRequestHandler {
static final GetAlias instance = new GetAlias();
private GetAlias() {
super("alias");
}
@Override
JSONStreamAware processRequest(HttpServletRequest req) {
String alias = req.getParameter("alias");
if (alias == null) {
return MISSING_ALIAS;
}
Alias aliasData;
try {
aliasData = Alias.getAlias(Convert.parseUnsignedLong(alias));
if (aliasData == null) {
return UNKNOWN_ALIAS;
}
} catch (RuntimeException e) {
return INCORRECT_ALIAS;
}
JSONObject response = new JSONObject();
response.put("account", Convert.toUnsignedLong(aliasData.getAccount().getId()));
response.put("alias", aliasData.getAliasName());
if (aliasData.getURI().length() > 0) {
response.put("uri", aliasData.getURI());
}
response.put("timestamp", aliasData.getTimestamp());
return response;
}
}
|
aspnmy/NasCoin
|
src/java/nxt/http/GetAlias.java
|
Java
|
mit
| 1,409
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# dodotable documentation build configuration file, created by
# sphinx-quickstart on Thu Sep 17 11:47:28 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
from dodotable import __version__, __version_info__
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#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.intersphinx',
]
# 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 encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'dodotable'
copyright = '2016, Spoqa, Inc'
author = 'Kang Hyojun'
# 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 = '.'.join(str(v) for v in __version_info__[:2])
# The full version, including alpha/beta/rc tags.
release = __version__
# 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
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# 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 = 'alabaster'
# 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 themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# 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']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'dodotabledoc'
# -- 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, 'dodotable.tex', 'dodotable Documentation',
'Kang Hyojun', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- 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, 'dodotable', 'dodotable Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- 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, 'dodotable', 'dodotable Documentation',
author, 'dodotable', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'python': ('http://docs.python.org/', None),
'sqlalchemy': ('http://docs.sqlalchemy.org/en/latest/', None),
'flask': ('http://flask.pocoo.org/docs/', None)
}
|
heejongahn/dodotable
|
docs/conf.py
|
Python
|
mit
| 9,622
|
using System.IO;
namespace GostCryptography.Asn1.Ber
{
class Asn1CerInputStream : Asn1BerInputStream
{
public Asn1CerInputStream(Stream inputStream)
: base(inputStream)
{
}
}
}
|
kapitanov/GostCryptography
|
Source/GostCryptography/Asn1/Ber/Asn1CerInputStream.cs
|
C#
|
mit
| 192
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_07_01;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.Resource;
import com.microsoft.azure.arm.resources.models.GroupableResourceCore;
import com.microsoft.azure.arm.resources.models.HasResourceGroup;
import com.microsoft.azure.arm.model.Refreshable;
import com.microsoft.azure.arm.model.Updatable;
import com.microsoft.azure.arm.model.Appliable;
import com.microsoft.azure.arm.model.Creatable;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.network.v2019_07_01.implementation.NetworkManager;
import java.util.List;
import com.microsoft.azure.SubResource;
import com.microsoft.azure.management.network.v2019_07_01.implementation.VirtualRouterInner;
/**
* Type representing VirtualRouter.
*/
public interface VirtualRouter extends HasInner<VirtualRouterInner>, Resource, GroupableResourceCore<NetworkManager, VirtualRouterInner>, HasResourceGroup, Refreshable<VirtualRouter>, Updatable<VirtualRouter.Update>, HasManager<NetworkManager> {
/**
* @return the etag value.
*/
String etag();
/**
* @return the hostedGateway value.
*/
SubResource hostedGateway();
/**
* @return the hostedSubnet value.
*/
SubResource hostedSubnet();
/**
* @return the peerings value.
*/
List<SubResource> peerings();
/**
* @return the provisioningState value.
*/
ProvisioningState provisioningState();
/**
* @return the virtualRouterAsn value.
*/
Long virtualRouterAsn();
/**
* @return the virtualRouterIps value.
*/
List<String> virtualRouterIps();
/**
* The entirety of the VirtualRouter definition.
*/
interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate {
}
/**
* Grouping of VirtualRouter definition stages.
*/
interface DefinitionStages {
/**
* The first stage of a VirtualRouter definition.
*/
interface Blank extends GroupableResourceCore.DefinitionWithRegion<WithGroup> {
}
/**
* The stage of the VirtualRouter definition allowing to specify the resource group.
*/
interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup<WithCreate> {
}
/**
* The stage of the virtualrouter definition allowing to specify HostedGateway.
*/
interface WithHostedGateway {
/**
* Specifies hostedGateway.
* @param hostedGateway The Gateway on which VirtualRouter is hosted
* @return the next definition stage
*/
WithCreate withHostedGateway(SubResource hostedGateway);
}
/**
* The stage of the virtualrouter definition allowing to specify HostedSubnet.
*/
interface WithHostedSubnet {
/**
* Specifies hostedSubnet.
* @param hostedSubnet The Subnet on which VirtualRouter is hosted
* @return the next definition stage
*/
WithCreate withHostedSubnet(SubResource hostedSubnet);
}
/**
* The stage of the virtualrouter definition allowing to specify VirtualRouterAsn.
*/
interface WithVirtualRouterAsn {
/**
* Specifies virtualRouterAsn.
* @param virtualRouterAsn VirtualRouter ASN
* @return the next definition stage
*/
WithCreate withVirtualRouterAsn(Long virtualRouterAsn);
}
/**
* The stage of the virtualrouter definition allowing to specify VirtualRouterIps.
*/
interface WithVirtualRouterIps {
/**
* Specifies virtualRouterIps.
* @param virtualRouterIps VirtualRouter IPs
* @return the next definition stage
*/
WithCreate withVirtualRouterIps(List<String> virtualRouterIps);
}
/**
* The stage of the definition which contains all the minimum required inputs for
* the resource to be created (via {@link WithCreate#create()}), but also allows
* for any other optional settings to be specified.
*/
interface WithCreate extends Creatable<VirtualRouter>, Resource.DefinitionWithTags<WithCreate>, DefinitionStages.WithHostedGateway, DefinitionStages.WithHostedSubnet, DefinitionStages.WithVirtualRouterAsn, DefinitionStages.WithVirtualRouterIps {
}
}
/**
* The template for a VirtualRouter update operation, containing all the settings that can be modified.
*/
interface Update extends Appliable<VirtualRouter>, Resource.UpdateWithTags<Update>, UpdateStages.WithHostedGateway, UpdateStages.WithHostedSubnet, UpdateStages.WithVirtualRouterAsn, UpdateStages.WithVirtualRouterIps {
}
/**
* Grouping of VirtualRouter update stages.
*/
interface UpdateStages {
/**
* The stage of the virtualrouter update allowing to specify HostedGateway.
*/
interface WithHostedGateway {
/**
* Specifies hostedGateway.
* @param hostedGateway The Gateway on which VirtualRouter is hosted
* @return the next update stage
*/
Update withHostedGateway(SubResource hostedGateway);
}
/**
* The stage of the virtualrouter update allowing to specify HostedSubnet.
*/
interface WithHostedSubnet {
/**
* Specifies hostedSubnet.
* @param hostedSubnet The Subnet on which VirtualRouter is hosted
* @return the next update stage
*/
Update withHostedSubnet(SubResource hostedSubnet);
}
/**
* The stage of the virtualrouter update allowing to specify VirtualRouterAsn.
*/
interface WithVirtualRouterAsn {
/**
* Specifies virtualRouterAsn.
* @param virtualRouterAsn VirtualRouter ASN
* @return the next update stage
*/
Update withVirtualRouterAsn(Long virtualRouterAsn);
}
/**
* The stage of the virtualrouter update allowing to specify VirtualRouterIps.
*/
interface WithVirtualRouterIps {
/**
* Specifies virtualRouterIps.
* @param virtualRouterIps VirtualRouter IPs
* @return the next update stage
*/
Update withVirtualRouterIps(List<String> virtualRouterIps);
}
}
}
|
selvasingh/azure-sdk-for-java
|
sdk/network/mgmt-v2019_07_01/src/main/java/com/microsoft/azure/management/network/v2019_07_01/VirtualRouter.java
|
Java
|
mit
| 6,979
|
var searchData=
[
['angle',['Angle',['../classlm_1_1_angle.html#a5128c164b47782001ec59ee549c925b8',1,'lm::Angle::Angle()'],['../classlm_1_1_angle.html#af18023849e8f9d286bcf729a7a9d108c',1,'lm::Angle::Angle(double angle)']]],
['append',['append',['../classlm_1_1_shader_pipeline.html#ae51f0a50859ab30b849b43e444b6b9a2',1,'lm::ShaderPipeline']]],
['atlas',['atlas',['../classlm_1_1_sprite.html#a2e03615ff467524b10ea476816d99003',1,'lm::Sprite::atlas()'],['../classlm_1_1_texture.html#a5eeb6175e0d38870aac74f85d1eb6bf5',1,'lm::Texture::atlas()']]],
['attach',['attach',['../classlm_1_1_game_object.html#a00ea48a39b06fdbc49c113285bdbcac1',1,'lm::GameObject::attach()'],['../classlm_1_1_shader_program.html#a1e3620e5bfa37edb9b79941a02bf5d39',1,'lm::ShaderProgram::attach()']]]
];
|
Lums-proj/Lums
|
doc/search/functions_0.js
|
JavaScript
|
mit
| 783
|
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands;
using Microsoft.eShopOnContainers.Services.Ordering.API.Application.Queries;
using Microsoft.eShopOnContainers.Services.Ordering.API.Controllers;
using Microsoft.eShopOnContainers.Services.Ordering.API.Infrastructure.Services;
using Moq;
using Ordering.API.Application.Commands;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace UnitTest.Ordering.Application
{
public class OrdersWebApiTest
{
private readonly Mock<IMediator> _mediatorMock;
private readonly Mock<IOrderQueries> _orderQueriesMock;
private readonly Mock<IIdentityService> _identityServiceMock;
public OrdersWebApiTest()
{
_mediatorMock = new Mock<IMediator>();
_orderQueriesMock = new Mock<IOrderQueries>();
_identityServiceMock = new Mock<IIdentityService>();
}
[Fact]
public async Task Create_order_with_requestId_success()
{
//Arrange
_mediatorMock.Setup(x => x.Send(It.IsAny<IdentifiedCommand<CancelOrderCommand, bool>>(), default(CancellationToken)))
.Returns(Task.FromResult(true));
//Act
var orderController = new OrdersController(_mediatorMock.Object, _orderQueriesMock.Object, _identityServiceMock.Object);
var actionResult = await orderController.CancelOrder(new CancelOrderCommand(1), Guid.NewGuid().ToString()) as OkResult;
//Assert
Assert.Equal(actionResult.StatusCode, (int)System.Net.HttpStatusCode.OK);
}
[Fact]
public async Task Cancel_order_bad_request()
{
//Arrange
_mediatorMock.Setup(x => x.Send(It.IsAny<IdentifiedCommand<CancelOrderCommand, bool>>(), default(CancellationToken)))
.Returns(Task.FromResult(true));
//Act
var orderController = new OrdersController(_mediatorMock.Object, _orderQueriesMock.Object, _identityServiceMock.Object);
var actionResult = await orderController.CancelOrder(new CancelOrderCommand(1), String.Empty) as BadRequestResult;
//Assert
Assert.Equal(actionResult.StatusCode, (int)System.Net.HttpStatusCode.BadRequest);
}
[Fact]
public async Task Ship_order_with_requestId_success()
{
//Arrange
_mediatorMock.Setup(x => x.Send(It.IsAny<IdentifiedCommand<CreateOrderCommand, bool>>(), default(System.Threading.CancellationToken)))
.Returns(Task.FromResult(true));
//Act
var orderController = new OrdersController(_mediatorMock.Object, _orderQueriesMock.Object, _identityServiceMock.Object);
var actionResult = await orderController.ShipOrder(new ShipOrderCommand(1), Guid.NewGuid().ToString()) as OkResult;
//Assert
Assert.Equal(actionResult.StatusCode, (int)System.Net.HttpStatusCode.OK);
}
[Fact]
public async Task Ship_order_bad_request()
{
//Arrange
_mediatorMock.Setup(x => x.Send(It.IsAny<IdentifiedCommand<CreateOrderCommand, bool>>(), default(System.Threading.CancellationToken)))
.Returns(Task.FromResult(true));
//Act
var orderController = new OrdersController(_mediatorMock.Object, _orderQueriesMock.Object, _identityServiceMock.Object);
var actionResult = await orderController.ShipOrder(new ShipOrderCommand(1), String.Empty) as BadRequestResult;
//Assert
Assert.Equal(actionResult.StatusCode, (int)System.Net.HttpStatusCode.BadRequest);
}
[Fact]
public async Task Get_orders_success()
{
//Arrange
var fakeDynamicResult = Enumerable.Empty<object>();
_orderQueriesMock.Setup(x => x.GetOrdersAsync())
.Returns(Task.FromResult(fakeDynamicResult));
//Act
var orderController = new OrdersController(_mediatorMock.Object, _orderQueriesMock.Object, _identityServiceMock.Object);
var actionResult = await orderController.GetOrders() as OkObjectResult;
//Assert
Assert.Equal(actionResult.StatusCode, (int)System.Net.HttpStatusCode.OK);
}
[Fact]
public async Task Get_order_success()
{
//Arrange
var fakeOrderId = 123;
var fakeDynamicResult = new Object();
_orderQueriesMock.Setup(x => x.GetOrderAsync(It.IsAny<int>()))
.Returns(Task.FromResult(fakeDynamicResult));
//Act
var orderController = new OrdersController(_mediatorMock.Object, _orderQueriesMock.Object, _identityServiceMock.Object);
var actionResult = await orderController.GetOrder(fakeOrderId) as OkObjectResult;
//Assert
Assert.Equal(actionResult.StatusCode, (int)System.Net.HttpStatusCode.OK);
}
[Fact]
public async Task Get_cardTypes_success()
{
//Arrange
var fakeDynamicResult = Enumerable.Empty<object>();
_orderQueriesMock.Setup(x => x.GetCardTypesAsync())
.Returns(Task.FromResult(fakeDynamicResult));
//Act
var orderController = new OrdersController(_mediatorMock.Object, _orderQueriesMock.Object, _identityServiceMock.Object);
var actionResult = await orderController.GetCardTypes() as OkObjectResult;
//Assert
Assert.Equal(actionResult.StatusCode, (int)System.Net.HttpStatusCode.OK);
}
}
}
|
TypeW/eShopOnContainers
|
test/Services/UnitTest/Ordering/Application/OrdersWebApiTest.cs
|
C#
|
mit
| 5,759
|
/**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the mingw-w64 runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
typedef WINBOOL (CALLBACK *PFIND_DEBUG_FILE_CALLBACK)(HANDLE FileHandle,PCSTR FileName,PVOID CallerData);
typedef WINBOOL (CALLBACK *PFIND_DEBUG_FILE_CALLBACKW)(HANDLE FileHandle,PCWSTR FileName,PVOID CallerData);
typedef WINBOOL (CALLBACK *PFINDFILEINPATHCALLBACK)(PCSTR filename,PVOID context);
typedef WINBOOL (CALLBACK *PFINDFILEINPATHCALLBACKW)(PCWSTR filename,PVOID context);
typedef WINBOOL (CALLBACK *PFIND_EXE_FILE_CALLBACK)(HANDLE FileHandle,PCSTR FileName,PVOID CallerData);
typedef WINBOOL (CALLBACK *PFIND_EXE_FILE_CALLBACKW)(HANDLE FileHandle,PCWSTR FileName,PVOID CallerData);
typedef WINBOOL (WINAPI *PSYMBOLSERVERPROC)(LPCSTR,LPCSTR,PVOID,DWORD,DWORD,LPSTR);
typedef WINBOOL (WINAPI *PSYMBOLSERVEROPENPROC)(VOID);
typedef WINBOOL (WINAPI *PSYMBOLSERVERCLOSEPROC)(VOID);
typedef WINBOOL (WINAPI *PSYMBOLSERVERSETOPTIONSPROC)(UINT_PTR,ULONG64);
typedef WINBOOL (CALLBACK WINAPI *PSYMBOLSERVERCALLBACKPROC)(UINT_PTR action,ULONG64 data,ULONG64 context);
typedef UINT_PTR (WINAPI *PSYMBOLSERVERGETOPTIONSPROC)();
typedef WINBOOL (WINAPI *PSYMBOLSERVERPINGPROC)(LPCSTR);
HANDLE IMAGEAPI FindDebugInfoFile(PCSTR FileName,PCSTR SymbolPath,PSTR DebugFilePath);
HANDLE IMAGEAPI FindDebugInfoFileEx(PCSTR FileName,PCSTR SymbolPath,PSTR DebugFilePath,PFIND_DEBUG_FILE_CALLBACK Callback,PVOID CallerData);
HANDLE IMAGEAPI FindDebugInfoFileExW(PCWSTR FileName,PCWSTR SymbolPath,PWSTR DebugFilePath,PFIND_DEBUG_FILE_CALLBACKW Callback,PVOID CallerData);
WINBOOL IMAGEAPI SymFindFileInPath(HANDLE hprocess,PCSTR SearchPath,PCSTR FileName,PVOID id,DWORD two,DWORD three,DWORD flags,LPSTR FoundFile,PFINDFILEINPATHCALLBACK callback,PVOID context);
WINBOOL IMAGEAPI SymFindFileInPathW(HANDLE hprocess,PCWSTR SearchPath,PCWSTR FileName,PVOID id,DWORD two,DWORD three,DWORD flags,LPSTR FoundFile,PFINDFILEINPATHCALLBACKW callback,PVOID context);
HANDLE IMAGEAPI FindExecutableImage(PCSTR FileName,PCSTR SymbolPath,PSTR ImageFilePath);
HANDLE IMAGEAPI FindExecutableImageEx(PCSTR FileName,PCSTR SymbolPath,PSTR ImageFilePath,PFIND_EXE_FILE_CALLBACK Callback,PVOID CallerData);
HANDLE IMAGEAPI FindExecutableImageExW(PCWSTR FileName,PCWSTR SymbolPath,PWSTR ImageFilePath,PFIND_EXE_FILE_CALLBACKW Callback,PVOID CallerData);
PIMAGE_NT_HEADERS IMAGEAPI ImageNtHeader(PVOID Base);
PVOID IMAGEAPI ImageDirectoryEntryToDataEx(PVOID Base,BOOLEAN MappedAsImage,USHORT DirectoryEntry,PULONG Size,PIMAGE_SECTION_HEADER *FoundHeader);
PVOID IMAGEAPI ImageDirectoryEntryToData(PVOID Base,BOOLEAN MappedAsImage,USHORT DirectoryEntry,PULONG Size);
PIMAGE_SECTION_HEADER IMAGEAPI ImageRvaToSection(PIMAGE_NT_HEADERS NtHeaders,PVOID Base,ULONG Rva);
PVOID IMAGEAPI ImageRvaToVa(PIMAGE_NT_HEADERS NtHeaders,PVOID Base,ULONG Rva,PIMAGE_SECTION_HEADER *LastRvaSection);
#define SSRVOPT_CALLBACK 0x0001
#define SSRVOPT_DWORD 0x0002
#define SSRVOPT_DWORDPTR 0x0004
#define SSRVOPT_GUIDPTR 0x0008
#define SSRVOPT_OLDGUIDPTR 0x0010
#define SSRVOPT_UNATTENDED 0x0020
#define SSRVOPT_NOCOPY 0x0040
#define SSRVOPT_PARENTWIN 0x0080
#define SSRVOPT_PARAMTYPE 0x0100
#define SSRVOPT_SECURE 0x0200
#define SSRVOPT_TRACE 0x0400
#define SSRVOPT_SETCONTEXT 0x0800
#define SSRVOPT_PROXY 0x1000
#define SSRVOPT_DOWNSTREAM_STORE 0x2000
#define SSRVOPT_RESET ((ULONG_PTR)-1)
#define SSRVACTION_TRACE 1
#define SSRVACTION_QUERYCANCEL 2
#define SSRVACTION_EVENT 3
#ifndef _WIN64
typedef struct _IMAGE_DEBUG_INFORMATION {
LIST_ENTRY List;
DWORD ReservedSize;
PVOID ReservedMappedBase;
USHORT ReservedMachine;
USHORT ReservedCharacteristics;
DWORD ReservedCheckSum;
DWORD ImageBase;
DWORD SizeOfImage;
DWORD ReservedNumberOfSections;
PIMAGE_SECTION_HEADER ReservedSections;
DWORD ReservedExportedNamesSize;
PSTR ReservedExportedNames;
DWORD ReservedNumberOfFunctionTableEntries;
PIMAGE_FUNCTION_ENTRY ReservedFunctionTableEntries;
DWORD ReservedLowestFunctionStartingAddress;
DWORD ReservedHighestFunctionEndingAddress;
DWORD ReservedNumberOfFpoTableEntries;
PFPO_DATA ReservedFpoTableEntries;
DWORD SizeOfCoffSymbols;
PIMAGE_COFF_SYMBOLS_HEADER CoffSymbols;
DWORD ReservedSizeOfCodeViewSymbols;
PVOID ReservedCodeViewSymbols;
PSTR ImageFilePath;
PSTR ImageFileName;
PSTR ReservedDebugFilePath;
DWORD ReservedTimeDateStamp;
WINBOOL ReservedRomImage;
PIMAGE_DEBUG_DIRECTORY ReservedDebugDirectory;
DWORD ReservedNumberOfDebugDirectories;
DWORD ReservedOriginalFunctionTableBaseAddress;
DWORD Reserved[2];
} IMAGE_DEBUG_INFORMATION,*PIMAGE_DEBUG_INFORMATION;
PIMAGE_DEBUG_INFORMATION IMAGEAPI MapDebugInformation(HANDLE FileHandle,PSTR FileName,PSTR SymbolPath,DWORD ImageBase);
WINBOOL IMAGEAPI UnmapDebugInformation(PIMAGE_DEBUG_INFORMATION DebugInfo);
#endif
typedef WINBOOL (CALLBACK *PENUMDIRTREE_CALLBACK)(LPCSTR FilePath,PVOID CallerData);
WINBOOL IMAGEAPI SearchTreeForFile(PSTR RootPath,PSTR InputPathName,PSTR OutputPathBuffer);
WINBOOL IMAGEAPI SearchTreeForFileW(PWSTR RootPath,PWSTR InputPathName,PWSTR OutputPathBuffer);
WINBOOL IMAGEAPI EnumDirTree(HANDLE hProcess,PSTR RootPath,PSTR InputPathName,PSTR OutputPathBuffer,PENUMDIRTREE_CALLBACK Callback,PVOID CallbackData);
WINBOOL IMAGEAPI MakeSureDirectoryPathExists(PCSTR DirPath);
#define UNDNAME_COMPLETE (0x0000)
#define UNDNAME_NO_LEADING_UNDERSCORES (0x0001)
#define UNDNAME_NO_MS_KEYWORDS (0x0002)
#define UNDNAME_NO_FUNCTION_RETURNS (0x0004)
#define UNDNAME_NO_ALLOCATION_MODEL (0x0008)
#define UNDNAME_NO_ALLOCATION_LANGUAGE (0x0010)
#define UNDNAME_NO_MS_THISTYPE (0x0020)
#define UNDNAME_NO_CV_THISTYPE (0x0040)
#define UNDNAME_NO_THISTYPE (0x0060)
#define UNDNAME_NO_ACCESS_SPECIFIERS (0x0080)
#define UNDNAME_NO_THROW_SIGNATURES (0x0100)
#define UNDNAME_NO_MEMBER_TYPE (0x0200)
#define UNDNAME_NO_RETURN_UDT_MODEL (0x0400)
#define UNDNAME_32_BIT_DECODE (0x0800)
#define UNDNAME_NAME_ONLY (0x1000)
#define UNDNAME_NO_ARGUMENTS (0x2000)
#define UNDNAME_NO_SPECIAL_SYMS (0x4000)
#define UNDNAME_NO_ARGUMENTS (0x2000)
#define UNDNAME_NO_SPECIAL_SYMS (0x4000)
DWORD IMAGEAPI WINAPI UnDecorateSymbolName(PCSTR DecoratedName,PSTR UnDecoratedName,DWORD UndecoratedLength,DWORD Flags);
DWORD IMAGEAPI WINAPI UnDecorateSymbolNameW(PCWSTR DecoratedName,PWSTR UnDecoratedName,DWORD UndecoratedLength,DWORD Flags);
#ifdef DBGHELP_TRANSLATE_TCHAR
#define UnDecorateSymbolName UnDecorateSymbolNameW
#endif
#define DBHHEADER_DEBUGDIRS 0x1
#define DBHHEADER_CVMISC 0x2
typedef struct _MODLOAD_CVMISC {
DWORD oCV;
size_t cCV;
DWORD oMisc;
size_t cMisc;
DWORD dtImage;
DWORD cImage;
} MODLOAD_CVMISC, *PMODLOAD_CVMISC;
typedef enum {
AddrMode1616,
AddrMode1632,
AddrModeReal,
AddrModeFlat
} ADDRESS_MODE;
typedef struct _tagADDRESS64 {
DWORD64 Offset;
WORD Segment;
ADDRESS_MODE Mode;
} ADDRESS64,*LPADDRESS64;
#ifdef _IMAGEHLP64
#define ADDRESS ADDRESS64
#define LPADDRESS LPADDRESS64
#else
typedef struct _tagADDRESS {
DWORD Offset;
WORD Segment;
ADDRESS_MODE Mode;
} ADDRESS,*LPADDRESS;
static __inline void Address32To64(LPADDRESS a32,LPADDRESS64 a64) {
a64->Offset = (ULONG64)(LONG64)(LONG)a32->Offset;
a64->Segment = a32->Segment;
a64->Mode = a32->Mode;
}
static __inline void Address64To32(LPADDRESS64 a64,LPADDRESS a32) {
a32->Offset = (ULONG)a64->Offset;
a32->Segment = a64->Segment;
a32->Mode = a64->Mode;
}
#endif
typedef struct _KDHELP64 {
DWORD64 Thread;
DWORD ThCallbackStack;
DWORD ThCallbackBStore;
DWORD NextCallback;
DWORD FramePointer;
DWORD64 KiCallUserMode;
DWORD64 KeUserCallbackDispatcher;
DWORD64 SystemRangeStart;
DWORD64 KiUserExceptionDispatcher;
DWORD64 StackBase;
DWORD64 StackLimit;
DWORD64 Reserved[5];
} KDHELP64,*PKDHELP64;
#ifdef _IMAGEHLP64
#define KDHELP KDHELP64
#define PKDHELP PKDHELP64
#else
typedef struct _KDHELP {
DWORD Thread;
DWORD ThCallbackStack;
DWORD NextCallback;
DWORD FramePointer;
DWORD KiCallUserMode;
DWORD KeUserCallbackDispatcher;
DWORD SystemRangeStart;
DWORD ThCallbackBStore;
DWORD KiUserExceptionDispatcher;
DWORD StackBase;
DWORD StackLimit;
DWORD Reserved[5];
} KDHELP,*PKDHELP;
static __inline void KdHelp32To64(PKDHELP p32,PKDHELP64 p64) {
p64->Thread = p32->Thread;
p64->ThCallbackStack = p32->ThCallbackStack;
p64->NextCallback = p32->NextCallback;
p64->FramePointer = p32->FramePointer;
p64->KiCallUserMode = p32->KiCallUserMode;
p64->KeUserCallbackDispatcher = p32->KeUserCallbackDispatcher;
p64->SystemRangeStart = p32->SystemRangeStart;
p64->KiUserExceptionDispatcher = p32->KiUserExceptionDispatcher;
p64->StackBase = p32->StackBase;
p64->StackLimit = p32->StackLimit;
}
#endif
typedef struct _tagSTACKFRAME64 {
ADDRESS64 AddrPC;
ADDRESS64 AddrReturn;
ADDRESS64 AddrFrame;
ADDRESS64 AddrStack;
ADDRESS64 AddrBStore;
PVOID FuncTableEntry;
DWORD64 Params[4];
WINBOOL Far;
WINBOOL Virtual;
DWORD64 Reserved[3];
KDHELP64 KdHelp;
} STACKFRAME64,*LPSTACKFRAME64;
#ifdef _IMAGEHLP64
#define STACKFRAME STACKFRAME64
#define LPSTACKFRAME LPSTACKFRAME64
#else
typedef struct _tagSTACKFRAME {
ADDRESS AddrPC;
ADDRESS AddrReturn;
ADDRESS AddrFrame;
ADDRESS AddrStack;
PVOID FuncTableEntry;
DWORD Params[4];
WINBOOL Far;
WINBOOL Virtual;
DWORD Reserved[3];
KDHELP KdHelp;
ADDRESS AddrBStore;
} STACKFRAME,*LPSTACKFRAME;
#endif
typedef WINBOOL (WINAPI *PREAD_PROCESS_MEMORY_ROUTINE64)(HANDLE hProcess,DWORD64 qwBaseAddress,PVOID lpBuffer,DWORD nSize,LPDWORD lpNumberOfBytesRead);
typedef PVOID (WINAPI *PFUNCTION_TABLE_ACCESS_ROUTINE64)(HANDLE hProcess,DWORD64 AddrBase);
typedef DWORD64 (WINAPI *PGET_MODULE_BASE_ROUTINE64)(HANDLE hProcess,DWORD64 Address);
typedef DWORD64 (WINAPI *PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE hProcess,HANDLE hThread,LPADDRESS64 lpaddr);
WINBOOL IMAGEAPI StackWalk64(DWORD MachineType,HANDLE hProcess,HANDLE hThread,LPSTACKFRAME64 StackFrame,PVOID ContextRecord,PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,PGET_MODULE_BASE_ROUTINE64
GetModuleBaseRoutine,PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
#ifdef _IMAGEHLP64
#define PREAD_PROCESS_MEMORY_ROUTINE PREAD_PROCESS_MEMORY_ROUTINE64
#define PFUNCTION_TABLE_ACCESS_ROUTINE PFUNCTION_TABLE_ACCESS_ROUTINE64
#define PGET_MODULE_BASE_ROUTINE PGET_MODULE_BASE_ROUTINE64
#define PTRANSLATE_ADDRESS_ROUTINE PTRANSLATE_ADDRESS_ROUTINE64
#define StackWalk StackWalk64
#else
typedef WINBOOL (WINAPI *PREAD_PROCESS_MEMORY_ROUTINE)(HANDLE hProcess,DWORD lpBaseAddress,PVOID lpBuffer,DWORD nSize,PDWORD lpNumberOfBytesRead);
typedef PVOID (WINAPI *PFUNCTION_TABLE_ACCESS_ROUTINE)(HANDLE hProcess,DWORD AddrBase);
typedef DWORD (WINAPI *PGET_MODULE_BASE_ROUTINE)(HANDLE hProcess,DWORD Address);
typedef DWORD (WINAPI *PTRANSLATE_ADDRESS_ROUTINE)(HANDLE hProcess,HANDLE hThread,LPADDRESS lpaddr);
WINBOOL IMAGEAPI StackWalk(DWORD MachineType,HANDLE hProcess,HANDLE hThread,LPSTACKFRAME StackFrame,PVOID ContextRecord,PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,PGET_MODULE_BASE_ROUTINE
GetModuleBaseRoutine,PTRANSLATE_ADDRESS_ROUTINE TranslateAddress);
#endif
#define API_VERSION_NUMBER 11
typedef struct API_VERSION {
USHORT MajorVersion;
USHORT MinorVersion;
USHORT Revision;
USHORT Reserved;
} API_VERSION,*LPAPI_VERSION;
LPAPI_VERSION IMAGEAPI ImagehlpApiVersion(VOID);
LPAPI_VERSION IMAGEAPI ImagehlpApiVersionEx(LPAPI_VERSION AppVersion);
DWORD IMAGEAPI GetTimestampForLoadedLibrary(HMODULE Module);
typedef WINBOOL (CALLBACK *PSYM_ENUMMODULES_CALLBACK64)(PCSTR ModuleName,DWORD64 BaseOfDll,PVOID UserContext);
typedef WINBOOL (CALLBACK *PSYM_ENUMMODULES_CALLBACKW64)(PCWSTR ModuleName,DWORD64 BaseOfDll,PVOID UserContext);
typedef WINBOOL (CALLBACK *PSYM_ENUMSYMBOLS_CALLBACK64)(PCSTR SymbolName,DWORD64 SymbolAddress,ULONG SymbolSize,PVOID UserContext);
typedef WINBOOL (CALLBACK *PSYM_ENUMSYMBOLS_CALLBACK64W)(PCWSTR SymbolName,DWORD64 SymbolAddress,ULONG SymbolSize,PVOID UserContext);
typedef WINBOOL (CALLBACK *PENUMLOADED_MODULES_CALLBACK64)(PCSTR ModuleName,DWORD64 ModuleBase,ULONG ModuleSize,PVOID UserContext);
typedef WINBOOL (CALLBACK *PENUMLOADED_MODULES_CALLBACKW64)(PCWSTR ModuleName,DWORD64 ModuleBase,ULONG ModuleSize,PVOID UserContext);
typedef WINBOOL (CALLBACK *PSYMBOL_REGISTERED_CALLBACK64)(HANDLE hProcess,ULONG ActionCode,ULONG64 CallbackData,ULONG64 UserContext);
typedef PVOID (CALLBACK *PSYMBOL_FUNCENTRY_CALLBACK)(HANDLE hProcess,DWORD AddrBase,PVOID UserContext);
typedef PVOID (CALLBACK *PSYMBOL_FUNCENTRY_CALLBACK64)(HANDLE hProcess,ULONG64 AddrBase,ULONG64 UserContext);
#ifdef _IMAGEHLP64
#define PSYM_ENUMMODULES_CALLBACK PSYM_ENUMMODULES_CALLBACK64
#define PSYM_ENUMSYMBOLS_CALLBACK PSYM_ENUMSYMBOLS_CALLBACK64
#define PSYM_ENUMSYMBOLS_CALLBACKW PSYM_ENUMSYMBOLS_CALLBACK64W
#define PENUMLOADED_MODULES_CALLBACK PENUMLOADED_MODULES_CALLBACK64
#define PSYMBOL_REGISTERED_CALLBACK PSYMBOL_REGISTERED_CALLBACK64
#define PSYMBOL_FUNCENTRY_CALLBACK PSYMBOL_FUNCENTRY_CALLBACK64
#else
typedef WINBOOL (CALLBACK *PSYM_ENUMMODULES_CALLBACK)(PCSTR ModuleName,ULONG BaseOfDll,PVOID UserContext);
typedef WINBOOL (CALLBACK *PSYM_ENUMSYMBOLS_CALLBACK)(PCSTR SymbolName,ULONG SymbolAddress,ULONG SymbolSize,PVOID UserContext);
typedef WINBOOL (CALLBACK *PSYM_ENUMSYMBOLS_CALLBACKW)(PCWSTR SymbolName,ULONG SymbolAddress,ULONG SymbolSize,PVOID UserContext);
typedef WINBOOL (CALLBACK *PENUMLOADED_MODULES_CALLBACK)(PCSTR ModuleName,ULONG ModuleBase,ULONG ModuleSize,PVOID UserContext);
typedef WINBOOL (CALLBACK *PSYMBOL_REGISTERED_CALLBACK)(HANDLE hProcess,ULONG ActionCode,PVOID CallbackData,PVOID UserContext);
#endif
#define SYMFLAG_VALUEPRESENT 0x00000001
#define SYMFLAG_REGISTER 0x00000008
#define SYMFLAG_REGREL 0x00000010
#define SYMFLAG_FRAMEREL 0x00000020
#define SYMFLAG_PARAMETER 0x00000040
#define SYMFLAG_LOCAL 0x00000080
#define SYMFLAG_CONSTANT 0x00000100
#define SYMFLAG_EXPORT 0x00000200
#define SYMFLAG_FORWARDER 0x00000400
#define SYMFLAG_FUNCTION 0x00000800
#define SYMFLAG_VIRTUAL 0x00001000
#define SYMFLAG_THUNK 0x00002000
#define SYMFLAG_TLSREL 0x00004000
typedef enum {
SymNone = 0,
SymCoff,
SymCv,
SymPdb,
SymExport,
SymDeferred,
SymSym,
SymDia,
SymVirtual,
NumSymTypes
} SYM_TYPE;
typedef struct _IMAGEHLP_SYMBOL64 {
DWORD SizeOfStruct;
DWORD64 Address;
DWORD Size;
DWORD Flags;
DWORD MaxNameLength;
CHAR Name[1];
} IMAGEHLP_SYMBOL64,*PIMAGEHLP_SYMBOL64;
typedef struct _IMAGEHLP_SYMBOL64_PACKAGE {
IMAGEHLP_SYMBOL64 sym;
CHAR name[MAX_SYM_NAME + 1];
} IMAGEHLP_SYMBOL64_PACKAGE,*PIMAGEHLP_SYMBOL64_PACKAGE;
#ifdef _IMAGEHLP64
#define IMAGEHLP_SYMBOL IMAGEHLP_SYMBOL64
#define PIMAGEHLP_SYMBOL PIMAGEHLP_SYMBOL64
#define IMAGEHLP_SYMBOL_PACKAGE IMAGEHLP_SYMBOL64_PACKAGE
#define PIMAGEHLP_SYMBOL_PACKAGE PIMAGEHLP_SYMBOL64_PACKAGE
#else
typedef struct _IMAGEHLP_SYMBOL {
DWORD SizeOfStruct;
DWORD Address;
DWORD Size;
DWORD Flags;
DWORD MaxNameLength;
CHAR Name[1];
} IMAGEHLP_SYMBOL,*PIMAGEHLP_SYMBOL;
typedef struct _IMAGEHLP_SYMBOL_PACKAGE {
IMAGEHLP_SYMBOL sym;
CHAR name[MAX_SYM_NAME + 1];
} IMAGEHLP_SYMBOL_PACKAGE,*PIMAGEHLP_SYMBOL_PACKAGE;
#endif
typedef struct _IMAGEHLP_MODULE64 {
DWORD SizeOfStruct;
DWORD64 BaseOfImage;
DWORD ImageSize;
DWORD TimeDateStamp;
DWORD CheckSum;
DWORD NumSyms;
SYM_TYPE SymType;
CHAR ModuleName[32];
CHAR ImageName[256];
CHAR LoadedImageName[256];
CHAR LoadedPdbName[256];
DWORD CVSig;
CHAR CVData[MAX_PATH*3];
DWORD PdbSig;
GUID PdbSig70;
DWORD PdbAge;
WINBOOL PdbUnmatched;
WINBOOL DbgUnmatched;
WINBOOL LineNumbers;
WINBOOL GlobalSymbols;
WINBOOL TypeInfo;
WINBOOL SourceIndexed;
WINBOOL Publics;
} IMAGEHLP_MODULE64,*PIMAGEHLP_MODULE64;
typedef struct _IMAGEHLP_MODULE64W {
DWORD SizeOfStruct;
DWORD64 BaseOfImage;
DWORD ImageSize;
DWORD TimeDateStamp;
DWORD CheckSum;
DWORD NumSyms;
SYM_TYPE SymType;
WCHAR ModuleName[32];
WCHAR ImageName[256];
WCHAR LoadedImageName[256];
WCHAR LoadedPdbName[256];
DWORD CVSig;
WCHAR CVData[MAX_PATH*3];
DWORD PdbSig;
GUID PdbSig70;
DWORD PdbAge;
WINBOOL PdbUnmatched;
WINBOOL DbgUnmatched;
WINBOOL LineNumbers;
WINBOOL GlobalSymbols;
WINBOOL TypeInfo;
WINBOOL SourceIndexed;
WINBOOL Publics;
} IMAGEHLP_MODULEW64,*PIMAGEHLP_MODULEW64;
#ifdef _IMAGEHLP64
#define IMAGEHLP_MODULE IMAGEHLP_MODULE64
#define PIMAGEHLP_MODULE PIMAGEHLP_MODULE64
#define IMAGEHLP_MODULEW IMAGEHLP_MODULEW64
#define PIMAGEHLP_MODULEW PIMAGEHLP_MODULEW64
#else
typedef struct _IMAGEHLP_MODULE {
DWORD SizeOfStruct;
DWORD BaseOfImage;
DWORD ImageSize;
DWORD TimeDateStamp;
DWORD CheckSum;
DWORD NumSyms;
SYM_TYPE SymType;
CHAR ModuleName[32];
CHAR ImageName[256];
CHAR LoadedImageName[256];
} IMAGEHLP_MODULE,*PIMAGEHLP_MODULE;
typedef struct _IMAGEHLP_MODULEW {
DWORD SizeOfStruct;
DWORD BaseOfImage;
DWORD ImageSize;
DWORD TimeDateStamp;
DWORD CheckSum;
DWORD NumSyms;
SYM_TYPE SymType;
WCHAR ModuleName[32];
WCHAR ImageName[256];
WCHAR LoadedImageName[256];
} IMAGEHLP_MODULEW,*PIMAGEHLP_MODULEW;
#endif
typedef struct _IMAGEHLP_LINE64 {
DWORD SizeOfStruct;
PVOID Key;
DWORD LineNumber;
PCHAR FileName;
DWORD64 Address;
} IMAGEHLP_LINE64,*PIMAGEHLP_LINE64;
typedef struct _IMAGEHLP_LINEW64 {
DWORD SizeOfStruct;
PVOID Key;
DWORD LineNumber;
PWSTR FileName;
DWORD64 Address;
} IMAGEHLP_LINEW64, *PIMAGEHLP_LINEW64;
#ifdef _IMAGEHLP64
#define IMAGEHLP_LINE IMAGEHLP_LINE64
#define PIMAGEHLP_LINE PIMAGEHLP_LINE64
#else
typedef struct _IMAGEHLP_LINE {
DWORD SizeOfStruct;
PVOID Key;
DWORD LineNumber;
PCHAR FileName;
DWORD Address;
} IMAGEHLP_LINE,*PIMAGEHLP_LINE;
#endif
typedef struct _SOURCEFILE {
DWORD64 ModBase;
PCHAR FileName;
} SOURCEFILE,*PSOURCEFILE;
typedef struct _SOURCEFILEW {
DWORD64 ModBase;
PWCHAR FileName;
} SOURCEFILEW,*PSOURCEFILEW;
#define CBA_DEFERRED_SYMBOL_LOAD_START 0x00000001
#define CBA_DEFERRED_SYMBOL_LOAD_COMPLETE 0x00000002
#define CBA_DEFERRED_SYMBOL_LOAD_FAILURE 0x00000003
#define CBA_SYMBOLS_UNLOADED 0x00000004
#define CBA_DUPLICATE_SYMBOL 0x00000005
#define CBA_READ_MEMORY 0x00000006
#define CBA_DEFERRED_SYMBOL_LOAD_CANCEL 0x00000007
#define CBA_SET_OPTIONS 0x00000008
#define CBA_EVENT 0x00000010
#define CBA_DEFERRED_SYMBOL_LOAD_PARTIAL 0x00000020
#define CBA_DEBUG_INFO 0x10000000
#define CBA_SRCSRV_INFO 0x20000000
#define CBA_SRCSRV_EVENT 0x40000000
typedef struct _IMAGEHLP_CBA_READ_MEMORY {
DWORD64 addr;
PVOID buf;
DWORD bytes;
DWORD *bytesread;
} IMAGEHLP_CBA_READ_MEMORY,*PIMAGEHLP_CBA_READ_MEMORY;
enum {
sevInfo = 0,
sevProblem,
sevAttn,
sevFatal,
sevMax
};
typedef struct _IMAGEHLP_CBA_EVENT {
DWORD severity;
DWORD code;
PCHAR desc;
PVOID object;
} IMAGEHLP_CBA_EVENT,*PIMAGEHLP_CBA_EVENT;
typedef struct _IMAGEHLP_DEFERRED_SYMBOL_LOAD64 {
DWORD SizeOfStruct;
DWORD64 BaseOfImage;
DWORD CheckSum;
DWORD TimeDateStamp;
CHAR FileName[MAX_PATH];
BOOLEAN Reparse;
HANDLE hFile;
DWORD Flags;
} IMAGEHLP_DEFERRED_SYMBOL_LOAD64,*PIMAGEHLP_DEFERRED_SYMBOL_LOAD64;
#define DSLFLAG_MISMATCHED_PDB 0x1
#define DSLFLAG_MISMATCHED_DBG 0x2
#ifdef _IMAGEHLP64
#define IMAGEHLP_DEFERRED_SYMBOL_LOAD IMAGEHLP_DEFERRED_SYMBOL_LOAD64
#define PIMAGEHLP_DEFERRED_SYMBOL_LOAD PIMAGEHLP_DEFERRED_SYMBOL_LOAD64
#else
typedef struct _IMAGEHLP_DEFERRED_SYMBOL_LOAD {
DWORD SizeOfStruct;
DWORD BaseOfImage;
DWORD CheckSum;
DWORD TimeDateStamp;
CHAR FileName[MAX_PATH];
BOOLEAN Reparse;
HANDLE hFile;
} IMAGEHLP_DEFERRED_SYMBOL_LOAD,*PIMAGEHLP_DEFERRED_SYMBOL_LOAD;
#endif
typedef struct _IMAGEHLP_DUPLICATE_SYMBOL64 {
DWORD SizeOfStruct;
DWORD NumberOfDups;
PIMAGEHLP_SYMBOL64 Symbol;
DWORD SelectedSymbol;
} IMAGEHLP_DUPLICATE_SYMBOL64,*PIMAGEHLP_DUPLICATE_SYMBOL64;
#ifdef _IMAGEHLP64
#define IMAGEHLP_DUPLICATE_SYMBOL IMAGEHLP_DUPLICATE_SYMBOL64
#define PIMAGEHLP_DUPLICATE_SYMBOL PIMAGEHLP_DUPLICATE_SYMBOL64
#else
typedef struct _IMAGEHLP_DUPLICATE_SYMBOL {
DWORD SizeOfStruct;
DWORD NumberOfDups;
PIMAGEHLP_SYMBOL Symbol;
DWORD SelectedSymbol;
} IMAGEHLP_DUPLICATE_SYMBOL,*PIMAGEHLP_DUPLICATE_SYMBOL;
#endif
typedef struct _SYMSRV_INDEX_INFO {
DWORD sizeofstruct;
CHAR file[MAX_PATH +1];
WINBOOL stripped;
DWORD timestamp;
DWORD size;
CHAR dbgfile[MAX_PATH +1];
CHAR pdbfile[MAX_PATH + 1];
GUID guid;
DWORD sig;
DWORD age;
} SYMSRV_INDEX_INFO, *PSYMSRV_INDEX_INFO;
typedef struct _SYMSRV_INDEX_INFOW {
DWORD sizeofstruct;
WCHAR file[MAX_PATH +1];
WINBOOL stripped;
DWORD timestamp;
DWORD size;
WCHAR dbgfile[MAX_PATH +1];
WCHAR pdbfile[MAX_PATH + 1];
GUID guid;
DWORD sig;
DWORD age;
} SYMSRV_INDEX_INFOW, *PSYMSRV_INDEX_INFOW;
WINBOOL IMAGEAPI SymSetParentWindow(HWND hwnd);
PCHAR IMAGEAPI SymSetHomeDirectory(HANDLE hProcess,PCSTR dir);
PCHAR IMAGEAPI SymSetHomeDirectoryW(HANDLE hProcess,PCWSTR dir);
PCHAR IMAGEAPI SymGetHomeDirectory(DWORD type,PSTR dir,size_t size);
PWCHAR IMAGEAPI SymGetHomeDirectoryW(DWORD type,PWSTR dir,size_t size);
#define hdBase 0
#define hdSym 1
#define hdSrc 2
#define hdMax 3
#define SYMOPT_CASE_INSENSITIVE 0x00000001
#define SYMOPT_UNDNAME 0x00000002
#define SYMOPT_DEFERRED_LOADS 0x00000004
#define SYMOPT_NO_CPP 0x00000008
#define SYMOPT_LOAD_LINES 0x00000010
#define SYMOPT_OMAP_FIND_NEAREST 0x00000020
#define SYMOPT_LOAD_ANYTHING 0x00000040
#define SYMOPT_IGNORE_CVREC 0x00000080
#define SYMOPT_NO_UNQUALIFIED_LOADS 0x00000100
#define SYMOPT_FAIL_CRITICAL_ERRORS 0x00000200
#define SYMOPT_EXACT_SYMBOLS 0x00000400
#define SYMOPT_ALLOW_ABSOLUTE_SYMBOLS 0x00000800
#define SYMOPT_IGNORE_NT_SYMPATH 0x00001000
#define SYMOPT_INCLUDE_32BIT_MODULES 0x00002000
#define SYMOPT_PUBLICS_ONLY 0x00004000
#define SYMOPT_NO_PUBLICS 0x00008000
#define SYMOPT_AUTO_PUBLICS 0x00010000
#define SYMOPT_NO_IMAGE_SEARCH 0x00020000
#define SYMOPT_SECURE 0x00040000
#define SYMOPT_NO_PROMPTS 0x00080000
#define SYMOPT_ALLOW_ZERO_ADDRESS 0x01000000
#define SYMOPT_DISABLE_SYMSRV_AUTODETECT 0x02000000
#define SYMOPT_FAVOR_COMPRESSED 0x00800000
#define SYMOPT_FLAT_DIRECTORY 0x00400000
#define SYMOPT_IGNORE_IMAGEDIR 0x00200000
#define SYMOPT_OVERWRITE 0x00100000
#define SYMOPT_DEBUG 0x80000000
DWORD IMAGEAPI SymSetOptions(DWORD SymOptions);
DWORD IMAGEAPI SymGetOptions(VOID);
WINBOOL IMAGEAPI SymCleanup(HANDLE hProcess);
WINBOOL IMAGEAPI SymMatchString(PCSTR string,PCSTR expression,WINBOOL fCase);
WINBOOL IMAGEAPI SymMatchStringW(PCWSTR string,PCWSTR expression,WINBOOL fCase);
typedef WINBOOL (CALLBACK *PSYM_ENUMSOURCEFILES_CALLBACK)(PSOURCEFILE pSourceFile,PVOID UserContext);
typedef WINBOOL (CALLBACK *PSYM_ENUMSOURCEFILES_CALLBACKW)(PSOURCEFILEW pSourceFile,PVOID UserContext);
#define PSYM_ENUMSOURCFILES_CALLBACK PSYM_ENUMSOURCEFILES_CALLBACK
WINBOOL IMAGEAPI SymEnumSourceFiles(HANDLE hProcess,ULONG64 ModBase,PCSTR Mask,PSYM_ENUMSOURCEFILES_CALLBACK cbSrcFiles,PVOID UserContext);
WINBOOL IMAGEAPI SymEnumSourceFilesW(HANDLE hProcess,ULONG64 ModBase,PCWSTR Mask,PSYM_ENUMSOURCEFILES_CALLBACKW cbSrcFiles,PVOID UserContext);
WINBOOL IMAGEAPI SymEnumerateModules64(HANDLE hProcess,PSYM_ENUMMODULES_CALLBACK64 EnumModulesCallback,PVOID UserContext);
WINBOOL IMAGEAPI SymEnumerateModulesW64(HANDLE hProcess,PSYM_ENUMMODULES_CALLBACKW64 EnumModulesCallback,PVOID UserContext);
#ifdef _IMAGEHLP64
#define SymEnumerateModules SymEnumerateModules64
#else
WINBOOL IMAGEAPI SymEnumerateModules(HANDLE hProcess,PSYM_ENUMMODULES_CALLBACK EnumModulesCallback,PVOID UserContext);
#endif
WINBOOL IMAGEAPI SymEnumerateSymbols64(HANDLE hProcess,DWORD64 BaseOfDll,PSYM_ENUMSYMBOLS_CALLBACK64 EnumSymbolsCallback,PVOID UserContext);
WINBOOL IMAGEAPI SymEnumerateSymbolsW64(HANDLE hProcess,DWORD64 BaseOfDll,PSYM_ENUMSYMBOLS_CALLBACK64W EnumSymbolsCallback,PVOID UserContext);
#ifdef _IMAGEHLP64
#define SymEnumerateSymbols SymEnumerateSymbols64
#define SymEnumerateSymbolsW SymEnumerateSymbolsW64
#else
WINBOOL IMAGEAPI SymEnumerateSymbols(HANDLE hProcess,DWORD BaseOfDll,PSYM_ENUMSYMBOLS_CALLBACK EnumSymbolsCallback,PVOID UserContext);
WINBOOL IMAGEAPI SymEnumerateSymbolsW(HANDLE hProcess,DWORD BaseOfDll,PSYM_ENUMSYMBOLS_CALLBACKW EnumSymbolsCallback,PVOID UserContext);
#endif
WINBOOL IMAGEAPI EnumerateLoadedModules64(HANDLE hProcess,PENUMLOADED_MODULES_CALLBACK64 EnumLoadedModulesCallback,PVOID UserContext);
WINBOOL IMAGEAPI EnumerateLoadedModulesW64(HANDLE hProcess,PENUMLOADED_MODULES_CALLBACKW64 EnumLoadedModulesCallback,PVOID UserContext);
#ifdef DBGHELP_TRANSLATE_TCHAR
#define EnumerateLoadedModules64 EnumerateLoadedModulesW64
#endif
#ifdef _IMAGEHLP64
#define EnumerateLoadedModules EnumerateLoadedModules64
#else
WINBOOL IMAGEAPI EnumerateLoadedModules(HANDLE hProcess,PENUMLOADED_MODULES_CALLBACK EnumLoadedModulesCallback,PVOID UserContext);
#endif
PVOID IMAGEAPI SymFunctionTableAccess64(HANDLE hProcess,DWORD64 AddrBase);
#ifdef _IMAGEHLP64
#define SymFunctionTableAccess SymFunctionTableAccess64
#else
PVOID IMAGEAPI SymFunctionTableAccess(HANDLE hProcess,DWORD AddrBase);
#endif
WINBOOL IMAGEAPI SymGetModuleInfo64(HANDLE hProcess,DWORD64 qwAddr,PIMAGEHLP_MODULE64 ModuleInfo);
WINBOOL IMAGEAPI SymGetModuleInfoW64(HANDLE hProcess,DWORD64 qwAddr,PIMAGEHLP_MODULEW64 ModuleInfo);
#ifdef _IMAGEHLP64
#define SymGetModuleInfo SymGetModuleInfo64
#define SymGetModuleInfoW SymGetModuleInfoW64
#else
WINBOOL IMAGEAPI SymGetModuleInfo(HANDLE hProcess,DWORD dwAddr,PIMAGEHLP_MODULE ModuleInfo);
WINBOOL IMAGEAPI SymGetModuleInfoW(HANDLE hProcess,DWORD dwAddr,PIMAGEHLP_MODULEW ModuleInfo);
#endif
DWORD64 IMAGEAPI SymGetModuleBase64(HANDLE hProcess,DWORD64 qwAddr);
#ifdef _IMAGEHLP64
#define SymGetModuleBase SymGetModuleBase64
#else
DWORD IMAGEAPI SymGetModuleBase(HANDLE hProcess,DWORD dwAddr);
#endif
WINBOOL IMAGEAPI SymGetSymNext64(HANDLE hProcess,PIMAGEHLP_SYMBOL64 Symbol);
#ifdef _IMAGEHLP64
#define SymGetSymNext SymGetSymNext64
#else
WINBOOL IMAGEAPI SymGetSymNext(HANDLE hProcess,PIMAGEHLP_SYMBOL Symbol);
#endif
WINBOOL IMAGEAPI SymGetSymPrev64(HANDLE hProcess,PIMAGEHLP_SYMBOL64 Symbol);
#ifdef _IMAGEHLP64
#define SymGetSymPrev SymGetSymPrev64
#else
WINBOOL IMAGEAPI SymGetSymPrev(HANDLE hProcess,PIMAGEHLP_SYMBOL Symbol);
#endif
typedef struct _SRCCODEINFO {
DWORD SizeOfStruct;
PVOID Key;
DWORD64 ModBase;
CHAR Obj[MAX_PATH + 1];
CHAR FileName[MAX_PATH + 1];
DWORD LineNumber;
DWORD64 Address;
} SRCCODEINFO,*PSRCCODEINFO;
typedef struct _SRCCODEINFOW {
DWORD SizeOfStruct;
PVOID Key;
DWORD64 ModBase;
WCHAR Obj[MAX_PATH + 1];
WCHAR FileName[MAX_PATH + 1];
DWORD LineNumber;
DWORD64 Address;
} SRCCODEINFOW,*PSRCCODEINFOW;
typedef WINBOOL (CALLBACK *PSYM_ENUMLINES_CALLBACK)(PSRCCODEINFO LineInfo,PVOID UserContext);
typedef WINBOOL (CALLBACK *PSYM_ENUMLINES_CALLBACKW)(PSRCCODEINFOW LineInfo,PVOID UserContext);
WINBOOL IMAGEAPI SymEnumLines(HANDLE hProcess,ULONG64 Base,PCSTR Obj,PCSTR File,PSYM_ENUMLINES_CALLBACK EnumLinesCallback,PVOID UserContext);
WINBOOL IMAGEAPI SymEnumLinesW(HANDLE hProcess,ULONG64 Base,PCWSTR Obj,PCSTR File,PSYM_ENUMLINES_CALLBACKW EnumLinesCallback,PVOID UserContext);
WINBOOL IMAGEAPI SymGetLineFromAddr64(HANDLE hProcess,DWORD64 qwAddr,PDWORD pdwDisplacement,PIMAGEHLP_LINE64 Line64);
WINBOOL IMAGEAPI SymGetLineFromAddrW64(HANDLE hProcess,DWORD64 qwAddr,PDWORD pdwDisplacement,PIMAGEHLP_LINEW64 Line64);
#ifdef _IMAGEHLP64
#define SymGetLineFromAddr SymGetLineFromAddr64
#else
WINBOOL IMAGEAPI SymGetLineFromAddr(HANDLE hProcess,DWORD dwAddr,PDWORD pdwDisplacement,PIMAGEHLP_LINE Line);
#endif
WINBOOL IMAGEAPI SymGetLineFromName64(HANDLE hProcess,PCSTR ModuleName,PCSTR FileName,DWORD dwLineNumber,PLONG plDisplacement,PIMAGEHLP_LINE64 Line);
WINBOOL IMAGEAPI SymGetLineFromNameW64(HANDLE hProcess,PCWSTR ModuleName,PCWSTR FileName,DWORD dwLineNumber,PLONG plDisplacement,PIMAGEHLP_LINEW64 Line);
#ifdef _IMAGEHLP64
#define SymGetLineFromName SymGetLineFromName64
#else
WINBOOL IMAGEAPI SymGetLineFromName(HANDLE hProcess,PCSTR ModuleName,PCSTR FileName,DWORD dwLineNumber,PLONG plDisplacement,PIMAGEHLP_LINE Line);
#endif
WINBOOL IMAGEAPI SymGetLineNext64(HANDLE hProcess,PIMAGEHLP_LINE64 Line);
WINBOOL IMAGEAPI SymGetLineNextW64(HANDLE hProcess,PIMAGEHLP_LINEW64 Line);
#ifdef _IMAGEHLP64
#define SymGetLineNext SymGetLineNext64
#else
WINBOOL IMAGEAPI SymGetLineNext(HANDLE hProcess,PIMAGEHLP_LINE Line);
#endif
WINBOOL IMAGEAPI SymGetLinePrev64(HANDLE hProcess,PIMAGEHLP_LINE64 Line);
WINBOOL IMAGEAPI SymGetLinePrevW64(HANDLE hProcess,PIMAGEHLP_LINEW64 Line);
#ifdef _IMAGEHLP64
#define SymGetLinePrev SymGetLinePrev64
#else
WINBOOL IMAGEAPI SymGetLinePrev(HANDLE hProcess,PIMAGEHLP_LINE Line);
#endif
WINBOOL IMAGEAPI SymMatchFileName(PCSTR FileName,PCSTR Match,PSTR *FileNameStop,PSTR *MatchStop);
WINBOOL IMAGEAPI SymMatchFileNameW(PCWSTR FileName,PCWSTR Match,PWSTR *FileNameStop,PWSTR *MatchStop);
WINBOOL IMAGEAPI SymInitialize(HANDLE hProcess,PCSTR UserSearchPath,WINBOOL fInvadeProcess);
WINBOOL IMAGEAPI SymInitializeW(HANDLE hProcess,PCWSTR UserSearchPath,WINBOOL fInvadeProcess);
WINBOOL IMAGEAPI SymGetSearchPath(HANDLE hProcess,PSTR SearchPath,DWORD SearchPathLength);
WINBOOL IMAGEAPI SymGetSearchPathW(HANDLE hProcess,PWSTR SearchPath,DWORD SearchPathLength);
WINBOOL IMAGEAPI SymSetSearchPath(HANDLE hProcess,PCSTR SearchPath);
WINBOOL IMAGEAPI SymSetSearchPathW(HANDLE hProcess,PCWSTR SearchPath);
DWORD64 IMAGEAPI SymLoadModule64(HANDLE hProcess,HANDLE hFile,PCSTR ImageName,PCSTR ModuleName,DWORD64 BaseOfDll,DWORD SizeOfDll);
#define SLMFLAG_VIRTUAL 0x1
DWORD64 IMAGEAPI SymLoadModuleEx(HANDLE hProcess,HANDLE hFile,PCSTR ImageName,PCSTR ModuleName,DWORD64 BaseOfDll,DWORD DllSize,PMODLOAD_DATA Data,DWORD Flags);
DWORD64 IMAGEAPI SymLoadModuleExW(HANDLE hProcess,HANDLE hFile,PCWSTR ImageName,PCWSTR ModuleName,DWORD64 BaseOfDll,DWORD DllSize,PMODLOAD_DATA Data,DWORD Flags);
#ifdef _IMAGEHLP64
#define SymLoadModule SymLoadModule64
#else
DWORD IMAGEAPI SymLoadModule(HANDLE hProcess,HANDLE hFile,PCSTR ImageName,PCSTR ModuleName,DWORD BaseOfDll,DWORD SizeOfDll);
#endif
WINBOOL IMAGEAPI SymUnloadModule64(HANDLE hProcess,DWORD64 BaseOfDll);
#ifdef _IMAGEHLP64
#define SymUnloadModule SymUnloadModule64
#else
WINBOOL IMAGEAPI SymUnloadModule(HANDLE hProcess,DWORD BaseOfDll);
#endif
WINBOOL IMAGEAPI SymUnDName64(PIMAGEHLP_SYMBOL64 sym,PSTR UnDecName,DWORD UnDecNameLength);
#ifdef _IMAGEHLP64
#define SymUnDName SymUnDName64
#else
WINBOOL IMAGEAPI SymUnDName(PIMAGEHLP_SYMBOL sym,PSTR UnDecName,DWORD UnDecNameLength);
#endif
WINBOOL IMAGEAPI SymRegisterCallback64(HANDLE hProcess,PSYMBOL_REGISTERED_CALLBACK64 CallbackFunction,ULONG64 UserContext);
WINBOOL IMAGEAPI SymRegisterCallback64W(HANDLE hProcess,PSYMBOL_REGISTERED_CALLBACK64 CallbackFunction,ULONG64 UserContext);
WINBOOL IMAGEAPI SymRegisterFunctionEntryCallback64(HANDLE hProcess,PSYMBOL_FUNCENTRY_CALLBACK64 CallbackFunction,ULONG64 UserContext);
#ifdef _IMAGEHLP64
#define SymRegisterCallback SymRegisterCallback64
#define SymRegisterFunctionEntryCallback SymRegisterFunctionEntryCallback64
#else
WINBOOL IMAGEAPI SymRegisterCallback(HANDLE hProcess,PSYMBOL_REGISTERED_CALLBACK CallbackFunction,PVOID UserContext);
WINBOOL IMAGEAPI SymRegisterFunctionEntryCallback(HANDLE hProcess,PSYMBOL_FUNCENTRY_CALLBACK CallbackFunction,PVOID UserContext);
#endif
typedef struct _IMAGEHLP_SYMBOL_SRC {
DWORD sizeofstruct;
DWORD type;
char file[MAX_PATH];
} IMAGEHLP_SYMBOL_SRC,*PIMAGEHLP_SYMBOL_SRC;
typedef struct _MODULE_TYPE_INFO {
USHORT dataLength;
USHORT leaf;
BYTE data[1];
} MODULE_TYPE_INFO,*PMODULE_TYPE_INFO;
typedef struct _SYMBOL_INFO {
ULONG SizeOfStruct;
ULONG TypeIndex;
ULONG64 Reserved[2];
ULONG info;
ULONG Size;
ULONG64 ModBase;
ULONG Flags;
ULONG64 Value;
ULONG64 Address;
ULONG Register;
ULONG Scope;
ULONG Tag;
ULONG NameLen;
ULONG MaxNameLen;
CHAR Name[1];
} SYMBOL_INFO,*PSYMBOL_INFO;
typedef struct _SYMBOL_INFOW {
ULONG SizeOfStruct;
ULONG TypeIndex;
ULONG64 Reserved[2];
ULONG info;
ULONG Size;
ULONG64 ModBase;
ULONG Flags;
ULONG64 Value;
ULONG64 Address;
ULONG Register;
ULONG Scope;
ULONG Tag;
ULONG NameLen;
ULONG MaxNameLen;
WCHAR Name[1];
} SYMBOL_INFOW,*PSYMBOL_INFOW;
#define SYMFLAG_CLR_TOKEN 0x00040000
#define SYMFLAG_CONSTANT 0x00000100
#define SYMFLAG_EXPORT 0x00000200
#define SYMFLAG_FORWARDER 0x00000400
#define SYMFLAG_FRAMEREL 0x00000020
#define SYMFLAG_FUNCTION 0x00000800
#define SYMFLAG_ILREL 0x00010000
#define SYMFLAG_LOCAL 0x00000080
#define SYMFLAG_METADATA 0x00020000
#define SYMFLAG_PARAMETER 0x00000040
#define SYMFLAG_REGISTER 0x00000008
#define SYMFLAG_REGREL 0x00000010
#define SYMFLAG_SLOT 0x00008000
#define SYMFLAG_THUNK 0x00002000
#define SYMFLAG_TLSREL 0x00004000
#define SYMFLAG_VALUEPRESENT 0x00000001
#define SYMFLAG_VIRTUAL 0x00001000
typedef struct _SYMBOL_INFO_PACKAGE {
SYMBOL_INFO si;
CHAR name[MAX_SYM_NAME + 1];
} SYMBOL_INFO_PACKAGE,*PSYMBOL_INFO_PACKAGE;
typedef struct _IMAGEHLP_STACK_FRAME {
ULONG64 InstructionOffset;
ULONG64 ReturnOffset;
ULONG64 FrameOffset;
ULONG64 StackOffset;
ULONG64 BackingStoreOffset;
ULONG64 FuncTableEntry;
ULONG64 Params[4];
ULONG64 Reserved[5];
WINBOOL Virtual;
ULONG Reserved2;
} IMAGEHLP_STACK_FRAME,*PIMAGEHLP_STACK_FRAME;
typedef VOID IMAGEHLP_CONTEXT,*PIMAGEHLP_CONTEXT;
WINBOOL IMAGEAPI SymSetContext(HANDLE hProcess,PIMAGEHLP_STACK_FRAME StackFrame,PIMAGEHLP_CONTEXT Context);
WINBOOL IMAGEAPI SymFromAddr(HANDLE hProcess,DWORD64 Address,PDWORD64 Displacement,PSYMBOL_INFO Symbol);
WINBOOL IMAGEAPI SymFromAddrW(HANDLE hProcess,DWORD64 Address,PDWORD64 Displacement,PSYMBOL_INFOW Symbol);
WINBOOL IMAGEAPI SymFromToken(HANDLE hProcess,DWORD64 Base,DWORD Token,PSYMBOL_INFO Symbol);
WINBOOL IMAGEAPI SymFromTokenW(HANDLE hProcess,DWORD64 Base,DWORD Token,PSYMBOL_INFOW Symbol);
WINBOOL IMAGEAPI SymFromName(HANDLE hProcess,PCSTR Name,PSYMBOL_INFO Symbol);
WINBOOL IMAGEAPI SymFromNameW(HANDLE hProcess,PCWSTR Name,PSYMBOL_INFOW Symbol);
typedef WINBOOL (CALLBACK *PSYM_ENUMERATESYMBOLS_CALLBACK)(PSYMBOL_INFO pSymInfo,ULONG SymbolSize,PVOID UserContext);
typedef WINBOOL (CALLBACK *PSYM_ENUMERATESYMBOLS_CALLBACKW)(PSYMBOL_INFOW pSymInfo,ULONG SymbolSize,PVOID UserContext);
WINBOOL IMAGEAPI SymEnumSymbols(HANDLE hProcess,ULONG64 BaseOfDll,PCSTR Mask,PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,PVOID UserContext);
WINBOOL IMAGEAPI SymEnumSymbolsW(HANDLE hProcess,ULONG64 BaseOfDll,PCWSTR Mask,PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback,PVOID UserContext);
WINBOOL IMAGEAPI SymEnumSymbolsForAddr(HANDLE hProcess,DWORD64 Address,PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,PVOID UserContext);
WINBOOL IMAGEAPI SymEnumSymbolsForAddrW(HANDLE hProcess,DWORD64 Address,PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback,PVOID UserContext);
#define SYMENUMFLAG_FULLSRCH 1
#define SYMENUMFLAG_SPEEDSRCH 2
typedef enum _IMAGEHLP_SYMBOL_TYPE_INFO {
TI_GET_SYMTAG,
TI_GET_SYMNAME,
TI_GET_LENGTH,
TI_GET_TYPE,
TI_GET_TYPEID,
TI_GET_BASETYPE,
TI_GET_ARRAYINDEXTYPEID,
TI_FINDCHILDREN,
TI_GET_DATAKIND,
TI_GET_ADDRESSOFFSET,
TI_GET_OFFSET,
TI_GET_VALUE,
TI_GET_COUNT,
TI_GET_CHILDRENCOUNT,
TI_GET_BITPOSITION,
TI_GET_VIRTUALBASECLASS,
TI_GET_VIRTUALTABLESHAPEID,
TI_GET_VIRTUALBASEPOINTEROFFSET,
TI_GET_CLASSPARENTID,
TI_GET_NESTED,
TI_GET_SYMINDEX,
TI_GET_LEXICALPARENT,
TI_GET_ADDRESS,
TI_GET_THISADJUST,
TI_GET_UDTKIND,
TI_IS_EQUIV_TO,
TI_GET_CALLING_CONVENTION
} IMAGEHLP_SYMBOL_TYPE_INFO;
typedef struct _TI_FINDCHILDREN_PARAMS {
ULONG Count;
ULONG Start;
ULONG ChildId[1];
} TI_FINDCHILDREN_PARAMS;
WINBOOL IMAGEAPI SymGetTypeInfo(HANDLE hProcess,DWORD64 ModBase,ULONG TypeId,IMAGEHLP_SYMBOL_TYPE_INFO GetType,PVOID pInfo);
WINBOOL IMAGEAPI SymEnumTypes(HANDLE hProcess,ULONG64 BaseOfDll,PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,PVOID UserContext);
WINBOOL IMAGEAPI SymEnumTypesW(HANDLE hProcess,ULONG64 BaseOfDll,PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback,PVOID UserContext);
WINBOOL IMAGEAPI SymGetTypeFromName(HANDLE hProcess,ULONG64 BaseOfDll,PCSTR Name,PSYMBOL_INFO Symbol);
WINBOOL IMAGEAPI SymGetTypeFromNameW(HANDLE hProcess,ULONG64 BaseOfDll,PCWSTR Name,PSYMBOL_INFOW Symbol);
WINBOOL IMAGEAPI SymAddSymbol(HANDLE hProcess,ULONG64 BaseOfDll,PCSTR Name,DWORD64 Address,DWORD Size,DWORD Flags);
WINBOOL IMAGEAPI SymAddSymbolW(HANDLE hProcess,ULONG64 BaseOfDll,PCWSTR Name,DWORD64 Address,DWORD Size,DWORD Flags);
WINBOOL IMAGEAPI SymDeleteSymbol(HANDLE hProcess,ULONG64 BaseOfDll,PCSTR Name,DWORD64 Address,DWORD Flags);
WINBOOL IMAGEAPI SymDeleteSymbolW(HANDLE hProcess,ULONG64 BaseOfDll,PCWSTR Name,DWORD64 Address,DWORD Flags);
typedef WINBOOL (WINAPI *PDBGHELP_CREATE_USER_DUMP_CALLBACK)(DWORD DataType,PVOID *Data,LPDWORD DataLength,PVOID UserData);
WINBOOL WINAPI DbgHelpCreateUserDump(LPCSTR FileName,PDBGHELP_CREATE_USER_DUMP_CALLBACK Callback,PVOID UserData);
WINBOOL WINAPI DbgHelpCreateUserDumpW(LPCWSTR FileName,PDBGHELP_CREATE_USER_DUMP_CALLBACK Callback,PVOID UserData);
WINBOOL IMAGEAPI SymGetSymFromAddr64(HANDLE hProcess,DWORD64 qwAddr,PDWORD64 pdwDisplacement,PIMAGEHLP_SYMBOL64 Symbol);
#ifdef _IMAGEHLP64
#define SymGetSymFromAddr SymGetSymFromAddr64
#else
WINBOOL IMAGEAPI SymGetSymFromAddr(HANDLE hProcess,DWORD dwAddr,PDWORD pdwDisplacement,PIMAGEHLP_SYMBOL Symbol);
#endif
WINBOOL IMAGEAPI SymGetSymFromName64(HANDLE hProcess,PCSTR Name,PIMAGEHLP_SYMBOL64 Symbol);
#ifdef _IMAGEHLP64
#define SymGetSymFromName SymGetSymFromName64
#else
WINBOOL IMAGEAPI SymGetSymFromName(HANDLE hProcess,PCSTR Name,PIMAGEHLP_SYMBOL Symbol);
#endif
DBHLP_DEPRECIATED WINBOOL IMAGEAPI FindFileInPath(HANDLE hprocess,PCSTR SearchPath,PCSTR FileName,PVOID id,DWORD two,DWORD three,DWORD flags,PSTR FilePath);
DBHLP_DEPRECIATED WINBOOL IMAGEAPI FindFileInSearchPath(HANDLE hprocess,PCSTR SearchPath,PCSTR FileName,DWORD one,DWORD two,DWORD three,PSTR FilePath);
DBHLP_DEPRECIATED WINBOOL IMAGEAPI SymEnumSym(HANDLE hProcess,ULONG64 BaseOfDll,PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,PVOID UserContext);
#ifdef __cplusplus
}
#endif
#define SYMF_OMAP_GENERATED 0x00000001
#define SYMF_OMAP_MODIFIED 0x00000002
#define SYMF_REGISTER 0x00000008
#define SYMF_REGREL 0x00000010
#define SYMF_FRAMEREL 0x00000020
#define SYMF_PARAMETER 0x00000040
#define SYMF_LOCAL 0x00000080
#define SYMF_CONSTANT 0x00000100
#define SYMF_EXPORT 0x00000200
#define SYMF_FORWARDER 0x00000400
#define SYMF_FUNCTION 0x00000800
#define SYMF_VIRTUAL 0x00001000
#define SYMF_THUNK 0x00002000
#define SYMF_TLSREL 0x00004000
#define IMAGEHLP_SYMBOL_INFO_VALUEPRESENT 1
#define IMAGEHLP_SYMBOL_INFO_REGISTER SYMF_REGISTER
#define IMAGEHLP_SYMBOL_INFO_REGRELATIVE SYMF_REGREL
#define IMAGEHLP_SYMBOL_INFO_FRAMERELATIVE SYMF_FRAMEREL
#define IMAGEHLP_SYMBOL_INFO_PARAMETER SYMF_PARAMETER
#define IMAGEHLP_SYMBOL_INFO_LOCAL SYMF_LOCAL
#define IMAGEHLP_SYMBOL_INFO_CONSTANT SYMF_CONSTANT
#define IMAGEHLP_SYMBOL_FUNCTION SYMF_FUNCTION
#define IMAGEHLP_SYMBOL_VIRTUAL SYMF_VIRTUAL
#define IMAGEHLP_SYMBOL_THUNK SYMF_THUNK
#define IMAGEHLP_SYMBOL_INFO_TLSRELATIVE SYMF_TLSREL
#include <pshpack4.h>
#define MINIDUMP_SIGNATURE ('PMDM')
#define MINIDUMP_VERSION (42899)
typedef DWORD RVA;
typedef ULONG64 RVA64;
typedef struct _MINIDUMP_LOCATION_DESCRIPTOR {
ULONG32 DataSize;
RVA Rva;
} MINIDUMP_LOCATION_DESCRIPTOR;
typedef struct _MINIDUMP_LOCATION_DESCRIPTOR64 {
ULONG64 DataSize;
RVA64 Rva;
} MINIDUMP_LOCATION_DESCRIPTOR64;
typedef struct _MINIDUMP_MEMORY_DESCRIPTOR {
ULONG64 StartOfMemoryRange;
MINIDUMP_LOCATION_DESCRIPTOR Memory;
} MINIDUMP_MEMORY_DESCRIPTOR,*PMINIDUMP_MEMORY_DESCRIPTOR;
typedef struct _MINIDUMP_MEMORY_DESCRIPTOR64 {
ULONG64 StartOfMemoryRange;
ULONG64 DataSize;
} MINIDUMP_MEMORY_DESCRIPTOR64,*PMINIDUMP_MEMORY_DESCRIPTOR64;
typedef struct _MINIDUMP_HEADER {
ULONG32 Signature;
ULONG32 Version;
ULONG32 NumberOfStreams;
RVA StreamDirectoryRva;
ULONG32 CheckSum;
__C89_NAMELESS union {
ULONG32 Reserved;
ULONG32 TimeDateStamp;
};
ULONG64 Flags;
} MINIDUMP_HEADER,*PMINIDUMP_HEADER;
typedef struct _MINIDUMP_DIRECTORY {
ULONG32 StreamType;
MINIDUMP_LOCATION_DESCRIPTOR Location;
} MINIDUMP_DIRECTORY,*PMINIDUMP_DIRECTORY;
typedef struct _MINIDUMP_STRING {
ULONG32 Length;
WCHAR Buffer[0];
} MINIDUMP_STRING,*PMINIDUMP_STRING;
typedef enum _MINIDUMP_STREAM_TYPE {
UnusedStream = 0,
ReservedStream0 = 1,
ReservedStream1 = 2,
ThreadListStream = 3,
ModuleListStream = 4,
MemoryListStream = 5,
ExceptionStream = 6,
SystemInfoStream = 7,
ThreadExListStream = 8,
Memory64ListStream = 9,
CommentStreamA = 10,
CommentStreamW = 11,
HandleDataStream = 12,
FunctionTableStream = 13,
UnloadedModuleListStream = 14,
MiscInfoStream = 15,
MemoryInfoListStream = 16,
ThreadInfoListStream = 17,
HandleOperationListStream = 18,
TokenStream = 19,
ceStreamNull = 0x8000,
ceStreamSystemInfo = 0x8001,
ceStreamException = 0x8002,
ceStreamModuleList = 0x8003,
ceStreamProcessList = 0x8004,
ceStreamThreadList = 0x8005,
ceStreamThreadContextList = 0x8006,
ceStreamThreadCallStackList = 0x8007,
ceStreamMemoryVirtualList = 0x8008,
ceStreamMemoryPhysicalList = 0x8009,
ceStreamBucketParameters = 0x800a,
ceStreamProcessModuleMap = 0x800b,
ceStreamDiagnosisList = 0x800c,
LastReservedStream = 0xffff
} MINIDUMP_STREAM_TYPE;
typedef union _CPU_INFORMATION {
struct {
ULONG32 VendorId[3];
ULONG32 VersionInformation;
ULONG32 FeatureInformation;
ULONG32 AMDExtendedCpuFeatures;
} X86CpuInfo;
struct {
ULONG64 ProcessorFeatures[2];
} OtherCpuInfo;
} CPU_INFORMATION,*PCPU_INFORMATION;
typedef struct _MINIDUMP_SYSTEM_INFO {
USHORT ProcessorArchitecture;
USHORT ProcessorLevel;
USHORT ProcessorRevision;
__C89_NAMELESS union {
USHORT Reserved0;
__C89_NAMELESS struct {
UCHAR NumberOfProcessors;
UCHAR ProductType;
};
};
ULONG32 MajorVersion;
ULONG32 MinorVersion;
ULONG32 BuildNumber;
ULONG32 PlatformId;
RVA CSDVersionRva;
__C89_NAMELESS union {
ULONG32 Reserved1;
__C89_NAMELESS struct {
USHORT SuiteMask;
USHORT Reserved2;
};
};
CPU_INFORMATION Cpu;
} MINIDUMP_SYSTEM_INFO,*PMINIDUMP_SYSTEM_INFO;
C_ASSERT(sizeof(((PPROCESS_INFORMATION)0)->dwThreadId)==4);
typedef struct _MINIDUMP_THREAD {
ULONG32 ThreadId;
ULONG32 SuspendCount;
ULONG32 PriorityClass;
ULONG32 Priority;
ULONG64 Teb;
MINIDUMP_MEMORY_DESCRIPTOR Stack;
MINIDUMP_LOCATION_DESCRIPTOR ThreadContext;
} MINIDUMP_THREAD,*PMINIDUMP_THREAD;
typedef struct _MINIDUMP_THREAD_LIST {
ULONG32 NumberOfThreads;
MINIDUMP_THREAD Threads[0];
} MINIDUMP_THREAD_LIST,*PMINIDUMP_THREAD_LIST;
typedef struct _MINIDUMP_THREAD_EX {
ULONG32 ThreadId;
ULONG32 SuspendCount;
ULONG32 PriorityClass;
ULONG32 Priority;
ULONG64 Teb;
MINIDUMP_MEMORY_DESCRIPTOR Stack;
MINIDUMP_LOCATION_DESCRIPTOR ThreadContext;
MINIDUMP_MEMORY_DESCRIPTOR BackingStore;
} MINIDUMP_THREAD_EX,*PMINIDUMP_THREAD_EX;
typedef struct _MINIDUMP_THREAD_EX_LIST {
ULONG32 NumberOfThreads;
MINIDUMP_THREAD_EX Threads[0];
} MINIDUMP_THREAD_EX_LIST,*PMINIDUMP_THREAD_EX_LIST;
typedef struct _MINIDUMP_EXCEPTION {
ULONG32 ExceptionCode;
ULONG32 ExceptionFlags;
ULONG64 ExceptionRecord;
ULONG64 ExceptionAddress;
ULONG32 NumberParameters;
ULONG32 __unusedAlignment;
ULONG64 ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];
} MINIDUMP_EXCEPTION,*PMINIDUMP_EXCEPTION;
typedef struct MINIDUMP_EXCEPTION_STREAM {
ULONG32 ThreadId;
ULONG32 __alignment;
MINIDUMP_EXCEPTION ExceptionRecord;
MINIDUMP_LOCATION_DESCRIPTOR ThreadContext;
} MINIDUMP_EXCEPTION_STREAM,*PMINIDUMP_EXCEPTION_STREAM;
typedef struct _MINIDUMP_MODULE {
ULONG64 BaseOfImage;
ULONG32 SizeOfImage;
ULONG32 CheckSum;
ULONG32 TimeDateStamp;
RVA ModuleNameRva;
VS_FIXEDFILEINFO VersionInfo;
MINIDUMP_LOCATION_DESCRIPTOR CvRecord;
MINIDUMP_LOCATION_DESCRIPTOR MiscRecord;
ULONG64 Reserved0;
ULONG64 Reserved1;
} MINIDUMP_MODULE,*PMINIDUMP_MODULE;
typedef struct _MINIDUMP_MODULE_LIST {
ULONG32 NumberOfModules;
MINIDUMP_MODULE Modules[0];
} MINIDUMP_MODULE_LIST,*PMINIDUMP_MODULE_LIST;
typedef struct _MINIDUMP_MEMORY_LIST {
ULONG32 NumberOfMemoryRanges;
MINIDUMP_MEMORY_DESCRIPTOR MemoryRanges[0];
} MINIDUMP_MEMORY_LIST,*PMINIDUMP_MEMORY_LIST;
typedef struct _MINIDUMP_MEMORY64_LIST {
ULONG64 NumberOfMemoryRanges;
RVA64 BaseRva;
MINIDUMP_MEMORY_DESCRIPTOR64 MemoryRanges[0];
} MINIDUMP_MEMORY64_LIST,*PMINIDUMP_MEMORY64_LIST;
typedef struct _MINIDUMP_EXCEPTION_INFORMATION {
DWORD ThreadId;
PEXCEPTION_POINTERS ExceptionPointers;
WINBOOL ClientPointers;
} MINIDUMP_EXCEPTION_INFORMATION,*PMINIDUMP_EXCEPTION_INFORMATION;
typedef struct _MINIDUMP_EXCEPTION_INFORMATION64 {
DWORD ThreadId;
ULONG64 ExceptionRecord;
ULONG64 ContextRecord;
WINBOOL ClientPointers;
} MINIDUMP_EXCEPTION_INFORMATION64,*PMINIDUMP_EXCEPTION_INFORMATION64;
typedef struct _MINIDUMP_HANDLE_DESCRIPTOR {
ULONG64 Handle;
RVA TypeNameRva;
RVA ObjectNameRva;
ULONG32 Attributes;
ULONG32 GrantedAccess;
ULONG32 HandleCount;
ULONG32 PointerCount;
} MINIDUMP_HANDLE_DESCRIPTOR,*PMINIDUMP_HANDLE_DESCRIPTOR;
typedef struct _MINIDUMP_HANDLE_DATA_STREAM {
ULONG32 SizeOfHeader;
ULONG32 SizeOfDescriptor;
ULONG32 NumberOfDescriptors;
ULONG32 Reserved;
} MINIDUMP_HANDLE_DATA_STREAM,*PMINIDUMP_HANDLE_DATA_STREAM;
typedef struct _MINIDUMP_FUNCTION_TABLE_DESCRIPTOR {
ULONG64 MinimumAddress;
ULONG64 MaximumAddress;
ULONG64 BaseAddress;
ULONG32 EntryCount;
ULONG32 SizeOfAlignPad;
} MINIDUMP_FUNCTION_TABLE_DESCRIPTOR,*PMINIDUMP_FUNCTION_TABLE_DESCRIPTOR;
typedef struct _MINIDUMP_FUNCTION_TABLE_STREAM {
ULONG32 SizeOfHeader;
ULONG32 SizeOfDescriptor;
ULONG32 SizeOfNativeDescriptor;
ULONG32 SizeOfFunctionEntry;
ULONG32 NumberOfDescriptors;
ULONG32 SizeOfAlignPad;
} MINIDUMP_FUNCTION_TABLE_STREAM,*PMINIDUMP_FUNCTION_TABLE_STREAM;
typedef struct _MINIDUMP_UNLOADED_MODULE {
ULONG64 BaseOfImage;
ULONG32 SizeOfImage;
ULONG32 CheckSum;
ULONG32 TimeDateStamp;
RVA ModuleNameRva;
} MINIDUMP_UNLOADED_MODULE,*PMINIDUMP_UNLOADED_MODULE;
typedef struct _MINIDUMP_UNLOADED_MODULE_LIST {
ULONG32 SizeOfHeader;
ULONG32 SizeOfEntry;
ULONG32 NumberOfEntries;
} MINIDUMP_UNLOADED_MODULE_LIST,*PMINIDUMP_UNLOADED_MODULE_LIST;
#define MINIDUMP_MISC1_PROCESS_ID 0x00000001
#define MINIDUMP_MISC1_PROCESS_TIMES 0x00000002
#define MINIDUMP_MISC1_PROCESSOR_POWER_INFO 0x00000004
typedef struct _MINIDUMP_MISC_INFO {
ULONG32 SizeOfInfo;
ULONG32 Flags1;
ULONG32 ProcessId;
ULONG32 ProcessCreateTime;
ULONG32 ProcessUserTime;
ULONG32 ProcessKernelTime;
} MINIDUMP_MISC_INFO,*PMINIDUMP_MISC_INFO;
typedef struct _MINIDUMP_USER_RECORD {
ULONG32 Type;
MINIDUMP_LOCATION_DESCRIPTOR Memory;
} MINIDUMP_USER_RECORD,*PMINIDUMP_USER_RECORD;
typedef struct _MINIDUMP_USER_STREAM {
ULONG32 Type;
ULONG BufferSize;
PVOID Buffer;
} MINIDUMP_USER_STREAM,*PMINIDUMP_USER_STREAM;
typedef struct _MINIDUMP_USER_STREAM_INFORMATION {
ULONG UserStreamCount;
PMINIDUMP_USER_STREAM UserStreamArray;
} MINIDUMP_USER_STREAM_INFORMATION,*PMINIDUMP_USER_STREAM_INFORMATION;
typedef enum _MINIDUMP_CALLBACK_TYPE {
ModuleCallback,
ThreadCallback,
ThreadExCallback,
IncludeThreadCallback,
IncludeModuleCallback,
MemoryCallback,
CancelCallback,
WriteKernelMinidumpCallback,
KernelMinidumpStatusCallback,
RemoveMemoryCallback,
IncludeVmRegionCallback,
IoStartCallback,
IoWriteAllCallback,
IoFinishCallback,
ReadMemoryFailureCallback,
SecondaryFlagsCallback
} MINIDUMP_CALLBACK_TYPE;
typedef struct _MINIDUMP_THREAD_CALLBACK {
ULONG ThreadId;
HANDLE ThreadHandle;
CONTEXT Context;
ULONG SizeOfContext;
ULONG64 StackBase;
ULONG64 StackEnd;
} MINIDUMP_THREAD_CALLBACK,*PMINIDUMP_THREAD_CALLBACK;
typedef struct _MINIDUMP_THREAD_EX_CALLBACK {
ULONG ThreadId;
HANDLE ThreadHandle;
CONTEXT Context;
ULONG SizeOfContext;
ULONG64 StackBase;
ULONG64 StackEnd;
ULONG64 BackingStoreBase;
ULONG64 BackingStoreEnd;
} MINIDUMP_THREAD_EX_CALLBACK,*PMINIDUMP_THREAD_EX_CALLBACK;
typedef struct _MINIDUMP_INCLUDE_THREAD_CALLBACK {
ULONG ThreadId;
} MINIDUMP_INCLUDE_THREAD_CALLBACK,*PMINIDUMP_INCLUDE_THREAD_CALLBACK;
typedef enum _THREAD_WRITE_FLAGS {
ThreadWriteThread = 0x0001,
ThreadWriteStack = 0x0002,
ThreadWriteContext = 0x0004,
ThreadWriteBackingStore = 0x0008,
ThreadWriteInstructionWindow = 0x0010,
ThreadWriteThreadData = 0x0020,
ThreadWriteThreadInfo = 0x0040
} THREAD_WRITE_FLAGS;
typedef struct _MINIDUMP_MODULE_CALLBACK {
PWCHAR FullPath;
ULONG64 BaseOfImage;
ULONG SizeOfImage;
ULONG CheckSum;
ULONG TimeDateStamp;
VS_FIXEDFILEINFO VersionInfo;
PVOID CvRecord;
ULONG SizeOfCvRecord;
PVOID MiscRecord;
ULONG SizeOfMiscRecord;
} MINIDUMP_MODULE_CALLBACK,*PMINIDUMP_MODULE_CALLBACK;
typedef struct _MINIDUMP_INCLUDE_MODULE_CALLBACK {
ULONG64 BaseOfImage;
} MINIDUMP_INCLUDE_MODULE_CALLBACK,*PMINIDUMP_INCLUDE_MODULE_CALLBACK;
typedef enum _MODULE_WRITE_FLAGS {
ModuleWriteModule = 0x0001,
ModuleWriteDataSeg = 0x0002,
ModuleWriteMiscRecord = 0x0004,
ModuleWriteCvRecord = 0x0008,
ModuleReferencedByMemory = 0x0010,
ModuleWriteTlsData = 0x0020,
ModuleWriteCodeSegs = 0x0040
} MODULE_WRITE_FLAGS;
typedef enum _MINIDUMP_SECONDARY_FLAGS {
MiniSecondaryWithoutPowerInfo = 0x00000001
} MINIDUMP_SECONDARY_FLAGS;
typedef struct _MINIDUMP_CALLBACK_INPUT {
ULONG ProcessId;
HANDLE ProcessHandle;
ULONG CallbackType;
__C89_NAMELESS union {
MINIDUMP_THREAD_CALLBACK Thread;
MINIDUMP_THREAD_EX_CALLBACK ThreadEx;
MINIDUMP_MODULE_CALLBACK Module;
MINIDUMP_INCLUDE_THREAD_CALLBACK IncludeThread;
MINIDUMP_INCLUDE_MODULE_CALLBACK IncludeModule;
};
} MINIDUMP_CALLBACK_INPUT,*PMINIDUMP_CALLBACK_INPUT;
typedef struct _MINIDUMP_MEMORY_INFO {
ULONG64 BaseAddress;
ULONG64 AllocationBase;
ULONG32 AllocationProtect;
ULONG32 __alignment1;
ULONG64 RegionSize;
ULONG32 State;
ULONG32 Protect;
ULONG32 Type;
ULONG32 __alignment2;
} MINIDUMP_MEMORY_INFO, *PMINIDUMP_MEMORY_INFO;
typedef struct _MINIDUMP_MISC_INFO_2 {
ULONG32 SizeOfInfo;
ULONG32 Flags1;
ULONG32 ProcessId;
ULONG32 ProcessCreateTime;
ULONG32 ProcessUserTime;
ULONG32 ProcessKernelTime;
ULONG32 ProcessorMaxMhz;
ULONG32 ProcessorCurrentMhz;
ULONG32 ProcessorMhzLimit;
ULONG32 ProcessorMaxIdleState;
ULONG32 ProcessorCurrentIdleState;
} MINIDUMP_MISC_INFO_2, *PMINIDUMP_MISC_INFO_2;
typedef struct _MINIDUMP_MEMORY_INFO_LIST {
ULONG SizeOfHeader;
ULONG SizeOfEntry;
ULONG64 NumberOfEntries;
} MINIDUMP_MEMORY_INFO_LIST, *PMINIDUMP_MEMORY_INFO_LIST;
typedef struct _MINIDUMP_CALLBACK_OUTPUT {
__C89_NAMELESS union {
ULONG ModuleWriteFlags;
ULONG ThreadWriteFlags;
ULONG SecondaryFlags;
__C89_NAMELESS struct {
ULONG64 MemoryBase;
ULONG MemorySize;
};
__C89_NAMELESS struct {
WINBOOL CheckCancel;
WINBOOL Cancel;
};
HANDLE Handle;
};
__C89_NAMELESS struct {
MINIDUMP_MEMORY_INFO VmRegion;
WINBOOL Continue;
};
HRESULT Status;
} MINIDUMP_CALLBACK_OUTPUT, *PMINIDUMP_CALLBACK_OUTPUT;
typedef enum _MINIDUMP_TYPE {
MiniDumpNormal = 0x00000000,
MiniDumpWithDataSegs = 0x00000001,
MiniDumpWithFullMemory = 0x00000002,
MiniDumpWithHandleData = 0x00000004,
MiniDumpFilterMemory = 0x00000008,
MiniDumpScanMemory = 0x00000010,
MiniDumpWithUnloadedModules = 0x00000020,
MiniDumpWithIndirectlyReferencedMemory = 0x00000040,
MiniDumpFilterModulePaths = 0x00000080,
MiniDumpWithProcessThreadData = 0x00000100,
MiniDumpWithPrivateReadWriteMemory = 0x00000200,
MiniDumpWithoutOptionalData = 0x00000400,
MiniDumpWithFullMemoryInfo = 0x00000800,
MiniDumpWithThreadInfo = 0x00001000,
MiniDumpWithCodeSegs = 0x00002000,
MiniDumpWithoutAuxiliaryState = 0x00004000,
MiniDumpWithFullAuxiliaryState = 0x00008000,
MiniDumpWithPrivateWriteCopyMemory = 0x00010000,
MiniDumpIgnoreInaccessibleMemory = 0x00020000,
MiniDumpWithTokenInformation = 0x00040000
} MINIDUMP_TYPE;
#define MINIDUMP_THREAD_INFO_ERROR_THREAD 0x00000001
#define MINIDUMP_THREAD_INFO_WRITING_THREAD 0x00000002
#define MINIDUMP_THREAD_INFO_EXITED_THREAD 0x00000004
#define MINIDUMP_THREAD_INFO_INVALID_INFO 0x00000008
#define MINIDUMP_THREAD_INFO_INVALID_CONTEXT 0x00000010
#define MINIDUMP_THREAD_INFO_INVALID_TEB 0x00000020
typedef struct _MINIDUMP_THREAD_INFO {
ULONG32 ThreadId;
ULONG32 DumpFlags;
ULONG32 DumpError;
ULONG32 ExitStatus;
ULONG64 CreateTime;
ULONG64 ExitTime;
ULONG64 KernelTime;
ULONG64 UserTime;
ULONG64 StartAddress;
ULONG64 Affinity;
} MINIDUMP_THREAD_INFO, *PMINIDUMP_THREAD_INFO;
typedef struct _MINIDUMP_THREAD_INFO_LIST {
ULONG SizeOfHeader;
ULONG SizeOfEntry;
ULONG NumberOfEntries;
} MINIDUMP_THREAD_INFO_LIST, *PMINIDUMP_THREAD_INFO_LIST;
typedef struct _MINIDUMP_HANDLE_OPERATION_LIST {
ULONG32 SizeOfHeader;
ULONG32 SizeOfEntry;
ULONG32 NumberOfEntries;
ULONG32 Reserved;
} MINIDUMP_HANDLE_OPERATION_LIST, *PMINIDUMP_HANDLE_OPERATION_LIST;
#ifdef __cplusplus
extern "C" {
#endif
typedef WINBOOL (WINAPI *MINIDUMP_CALLBACK_ROUTINE)(PVOID CallbackParam,CONST PMINIDUMP_CALLBACK_INPUT CallbackInput,PMINIDUMP_CALLBACK_OUTPUT CallbackOutput);
typedef struct _MINIDUMP_CALLBACK_INFORMATION {
MINIDUMP_CALLBACK_ROUTINE CallbackRoutine;
PVOID CallbackParam;
} MINIDUMP_CALLBACK_INFORMATION,*PMINIDUMP_CALLBACK_INFORMATION;
#define RVA_TO_ADDR(Mapping,Rva) ((PVOID)(((ULONG_PTR) (Mapping)) + (Rva)))
WINBOOL WINAPI MiniDumpWriteDump(HANDLE hProcess,DWORD ProcessId,HANDLE hFile,MINIDUMP_TYPE DumpType,CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam);
WINBOOL WINAPI MiniDumpReadDumpStream(PVOID BaseOfDump,ULONG StreamNumber,PMINIDUMP_DIRECTORY *Dir,PVOID *StreamPointer,ULONG *StreamSize);
WINBOOL WINAPI EnumerateLoadedModulesEx(
HANDLE hProcess,
PENUMLOADED_MODULES_CALLBACK64 EnumLoadedModulesCallback,
PVOID UserContext
);
WINBOOL WINAPI EnumerateLoadedModulesExW(
HANDLE hProcess,
PENUMLOADED_MODULES_CALLBACKW64 EnumLoadedModulesCallback,
PVOID UserContext
);
WINBOOL WINAPI SymAddSourceStream(
HANDLE hProcess,
ULONG64 Base,
PCSTR StreamFile,
PBYTE Buffer,
size_t Size
);
WINBOOL WINAPI SymAddSourceStreamW(
HANDLE hProcess,
ULONG64 Base,
PCWSTR StreamFile,
PBYTE Buffer,
size_t Size
);
WINBOOL WINAPI SymEnumSourceLines(
HANDLE hProcess,
ULONG64 Base,
PCSTR Obj,
PCSTR File,
DWORD Line,
DWORD Flags,
PSYM_ENUMLINES_CALLBACK EnumLinesCallback,
PVOID UserContext
);
WINBOOL WINAPI SymEnumSourceLinesW(
HANDLE hProcess,
ULONG64 Base,
PCWSTR Obj,
PCWSTR File,
DWORD Line,
DWORD Flags,
PSYM_ENUMLINES_CALLBACKW EnumLinesCallback,
PVOID UserContext
);
WINBOOL WINAPI SymEnumTypesByName(
HANDLE hProcess,
ULONG64 BaseOfDll,
PCSTR mask,
PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,
PVOID UserContext
);
WINBOOL WINAPI SymEnumTypesByNameW(
HANDLE hProcess,
ULONG64 BaseOfDll,
PCSTR mask,
PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback,
PVOID UserContext
);
HANDLE WINAPI SymFindDebugInfoFile(
HANDLE hProcess,
PCSTR FileName,
PSTR DebugFilePath,
PFIND_DEBUG_FILE_CALLBACK Callback,
PVOID CallerData
);
HANDLE WINAPI SymFindDebugInfoFileW(
HANDLE hProcess,
PCWSTR FileName,
PWSTR DebugFilePath,
PFIND_DEBUG_FILE_CALLBACKW Callback,
PVOID CallerData
);
HANDLE WINAPI SymFindExecutableImage(
HANDLE hProcess,
PCSTR FileName,
PSTR ImageFilePath,
PFIND_EXE_FILE_CALLBACK Callback,
PVOID CallerData
);
HANDLE WINAPI SymFindExecutableImageW(
HANDLE hProcess,
PCWSTR FileName,
PWSTR ImageFilePath,
PFIND_EXE_FILE_CALLBACKW Callback,
PVOID CallerData
);
WINBOOL WINAPI SymFromIndex(
HANDLE hProcess,
ULONG64 BaseOfDll,
DWORD Index,
PSYMBOL_INFO Symbol
);
WINBOOL WINAPI SymFromIndexW(
HANDLE hProcess,
ULONG64 BaseOfDll,
DWORD Index,
PSYMBOL_INFOW Symbol
);
WINBOOL WINAPI SymGetScope(
HANDLE hProcess,
ULONG64 BaseOfDll,
DWORD Index,
PSYMBOL_INFO Symbol
);
WINBOOL WINAPI SymGetScopeW(
HANDLE hProcess,
ULONG64 BaseOfDll,
DWORD Index,
PSYMBOL_INFOW Symbol
);
WINBOOL WINAPI SymGetSourceFileFromToken(
HANDLE hProcess,
PVOID Token,
PCSTR Params,
PSTR FilePath,
DWORD Size
);
WINBOOL WINAPI SymGetSourceFileFromTokenW(
HANDLE hProcess,
PVOID Token,
PCWSTR Params,
PWSTR FilePath,
DWORD Size
);
WINBOOL WINAPI SymGetSourceFileToken(
HANDLE hProcess,
ULONG64 Base,
PCSTR FileSpec,
PVOID *Token,
DWORD *Size
);
WINBOOL WINAPI SymGetSourceFileTokenW(
HANDLE hProcess,
ULONG64 Base,
PCWSTR FileSpec,
PVOID *Token,
DWORD *Size
);
WINBOOL WINAPI SymGetSourceFile(
HANDLE hProcess,
ULONG64 Base,
PCSTR Params,
PCSTR FileSpec,
PSTR FilePath,
DWORD Size
);
WINBOOL WINAPI SymGetSourceFileW(
HANDLE hProcess,
ULONG64 Base,
PCWSTR Params,
PCWSTR FileSpec,
PWSTR FilePath,
DWORD Size
);
WINBOOL WINAPI SymGetSourceVarFromToken(
HANDLE hProcess,
PVOID Token,
PCSTR Params,
PCSTR VarName,
PSTR Value,
DWORD Size
);
WINBOOL WINAPI SymGetSourceVarFromTokenW(
HANDLE hProcess,
PVOID Token,
PCWSTR Params,
PCWSTR VarName,
PWSTR Value,
DWORD Size
);
WINBOOL WINAPI SymGetSymbolFile(
HANDLE hProcess,
PCSTR SymPath,
PCSTR ImageFile,
DWORD Type,
PSTR SymbolFile,
size_t cSymbolFile,
PSTR DbgFile,
size_t cDbgFile
);
WINBOOL WINAPI SymGetSymbolFileW(
HANDLE hProcess,
PCWSTR SymPath,
PCWSTR ImageFile,
DWORD Type,
PWSTR SymbolFile,
size_t cSymbolFile,
PWSTR DbgFile,
size_t cDbgFile
);
WINBOOL WINAPI SymNext(
HANDLE hProcess,
PSYMBOL_INFO Symbol
);
WINBOOL WINAPI SymNextW(
HANDLE hProcess,
PSYMBOL_INFOW Symbol
);
WINBOOL WINAPI SymPrev(
HANDLE hProcess,
PSYMBOL_INFO Symbol
);
WINBOOL WINAPI SymPrevW(
HANDLE hProcess,
PSYMBOL_INFOW Symbol
);
WINBOOL WINAPI SymRefreshModuleList(
HANDLE hProcess
);
#define SYMSEARCH_MASKOBJS 0x01
#define SYMSEARCH_RECURSE 0x02
#define SYMSEARCH_GLOBALSONLY 0x04
#define SYMSEARCH_ALLITEMS 0x08
WINBOOL WINAPI SymSearch(
HANDLE hProcess,
ULONG64 BaseOfDll,
DWORD Index,
DWORD SymTag,
PCSTR Mask,
DWORD64 Address,
PSYM_ENUMERATESYMBOLS_CALLBACK EnumSymbolsCallback,
PVOID UserContext,
DWORD Options
);
WINBOOL WINAPI SymSearchW(
HANDLE hProcess,
ULONG64 BaseOfDll,
DWORD Index,
DWORD SymTag,
PCWSTR Mask,
DWORD64 Address,
PSYM_ENUMERATESYMBOLS_CALLBACKW EnumSymbolsCallback,
PVOID UserContext,
DWORD Options
);
WINBOOL WINAPI SymSrvGetFileIndexString(
HANDLE hProcess,
PCSTR SrvPath,
PCSTR File,
PSTR Index,
size_t Size,
DWORD Flags
);
WINBOOL WINAPI SymSrvGetFileIndexStringW(
HANDLE hProcess,
PCWSTR SrvPath,
PCWSTR File,
PWSTR Index,
size_t Size,
DWORD Flags
);
#ifdef DBGHELP_TRANSLATE_TCHAR
#define SymSrvGetFileIndexString SymSrvGetFileIndexStringW
#endif
WINBOOL WINAPI SymSrvGetFileIndexInfo(
PCSTR File,
PSYMSRV_INDEX_INFO Info,
DWORD Flags
);
WINBOOL WINAPI SymSrvGetFileIndexInfoW(
PCWSTR File,
PSYMSRV_INDEX_INFOW Info,
DWORD Flags
);
#ifdef DBGHELP_TRANSLATE_TCHAR
#define SymSrvGetFileIndexInfo SymSrvGetFileIndexInfoW
#endif
WINBOOL WINAPI SymSrvGetFileIndexes(
PCTSTR File,
GUID *Id,
DWORD *Val1,
DWORD *Val2,
DWORD Flags
);
WINBOOL WINAPI SymSrvGetFileIndexesW(
PCWSTR File,
GUID *Id,
DWORD *Val1,
DWORD *Val2,
DWORD Flags
);
#ifdef DBGHELP_TRANSLATE_TCHAR
#define SymSrvGetFileIndexes SymSrvGetFileIndexesW
#endif
PCSTR WINAPI SymSrvGetSupplement(
HANDLE hProcess,
PCSTR SymPath,
PCSTR Node,
PCSTR File
);
PCWSTR WINAPI SymSrvGetSupplementW(
HANDLE hProcess,
PCWSTR SymPath,
PCWSTR Node,
PCWSTR File
);
#ifdef DBGHELP_TRANSLATE_TCHAR
#define SymSrvGetSupplement SymSrvGetSupplementW
#endif
WINBOOL WINAPI SymSrvIsStore(
HANDLE hProcess,
PCSTR path
);
WINBOOL WINAPI SymSrvIsStoreW(
HANDLE hProcess,
PCWSTR path
);
#ifdef DBGHELP_TRANSLATE_TCHAR
#define SymSrvIsStore SymSrvIsStoreW
#endif
PCSTR WINAPI SymSrvStoreFile(
HANDLE hProcess,
PCSTR SrvPath,
PCSTR File,
DWORD Flags
);
PCWSTR WINAPI SymSrvStoreFileW(
HANDLE hProcess,
PCWSTR SrvPath,
PCWSTR File,
DWORD Flags
);
#define SYMSTOREOPT_COMPRESS 0x01
#define SYMSTOREOPT_OVERWRITE 0x02
#define SYMSTOREOPT_RETURNINDEX 0x04
#define SYMSTOREOPT_POINTER 0x08
#define SYMSTOREOPT_PASS_IF_EXISTS 0x40
#ifdef DBGHELP_TRANSLATE_TCHAR
#define SymSrvStoreFile SymSrvStoreFileW
#endif
PCSTR WINAPI SymSrvStoreSupplement(
HANDLE hProcess,
const PCTSTR SymPath,
PCSTR Node,
PCSTR File,
DWORD Flags
);
PCWSTR WINAPI SymSrvStoreSupplementW(
HANDLE hProcess,
const PCWSTR SymPath,
PCWSTR Node,
PCWSTR File,
DWORD Flags
);
#ifdef DBGHELP_TRANSLATE_TCHAR
#define SymSrvStoreSupplement SymSrvStoreSupplementW
#endif
PCSTR WINAPI SymSrvDeltaName(
HANDLE hProcess,
PCSTR SymPath,
PCSTR Type,
PCSTR File1,
PCSTR File2
);
PCWSTR WINAPI SymSrvDeltaNameW(
HANDLE hProcess,
PCWSTR SymPath,
PCWSTR Type,
PCWSTR File1,
PCWSTR File2
);
#ifdef DBGHELP_TRANSLATE_TCHAR
#define SymSrvDeltaName SymSrvDeltaNameW
#endif
#include <poppack.h>
#ifdef __cplusplus
}
#endif
|
zig-lang/zig
|
lib/libc/include/any-windows-any/psdk_inc/_dbg_common.h
|
C
|
mit
| 63,999
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ILMergeHelper - FAKE - F# Make</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull">
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script src="http://code.jquery.com/ui/1.8.23/jquery-ui.js"></script>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" />
<script type="text/javascript" src="http://fsharp.github.io/FAKE/content/tips.js"></script>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li><a href="http://fsharp.org">fsharp.org</a></li>
<li><a href="http://github.com/fsharp/fake">github page</a></li>
</ul>
<h3 class="muted">FAKE - F# Make</h3>
</div>
<hr />
<div class="row">
<div class="span9" id="main">
<h1>ILMergeHelper</h1>
<div class="xmldoc">
<p>Contains task a task which allows to merge .NET assemblies with <a href="http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx">ILMerge</a>.</p>
</div>
<!-- Render nested types and modules, if there are any -->
<h2>Nested types and modules</h2>
<div>
<table class="table table-bordered type-list">
<thead>
<tr><td>Type</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="type-name">
<a href="fake-ilmergehelper-allowduplicatetypes.html">AllowDuplicateTypes</a>
</td>
<td class="xmldoc"><p>Option type to configure ILMerge's processing of duplicate types.</p>
</td>
</tr>
<tr>
<td class="type-name">
<a href="fake-ilmergehelper-ilmergeparams.html">ILMergeParams</a>
</td>
<td class="xmldoc"><p>Parameter type for ILMerge</p>
</td>
</tr>
<tr>
<td class="type-name">
<a href="fake-ilmergehelper-internalizetypes.html">InternalizeTypes</a>
</td>
<td class="xmldoc"><p>Option type to configure ILMerge's processing of internal types.</p>
</td>
</tr>
<tr>
<td class="type-name">
<a href="fake-ilmergehelper-targetkind.html">TargetKind</a>
</td>
<td class="xmldoc"><p>Option type to configure ILMerge's target output.</p>
</td>
</tr>
</tbody>
</table>
</div>
<h3>Functions and values</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>Function or value</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '267', 267)" onmouseover="showTip(event, '267', 267)">
ILMerge (...)
</code>
<div class="tip" id="267">
<strong>Signature:</strong>setParams:(ILMergeParams -> ILMergeParams) -> outputFile:string -> primaryAssembly:string -> unit<br />
</div>
</td>
<td class="xmldoc">
<p>Uses ILMerge to merge .NET assemblies.</p>
<h2>Parameters</h2>
<ul>
<li><code>setParams</code> - Function used to create an ILMergeParams value with your required settings. Called with an ILMergeParams value configured with the defaults.</li>
<li><code>outputFile</code> - Output file path for the merged assembly.</li>
<li><code>primaryAssembly</code> - The assembly you want ILMerge to consider as the primary.</li>
</ul>
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/ILMergeHelper.fs#L143-143" class="github-link">Go to GitHub source</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '268', 268)" onmouseover="showTip(event, '268', 268)">
ILMergeDefaults
</code>
<div class="tip" id="268">
<strong>Signature:</strong>ILMergeParams<br />
</div>
</td>
<td class="xmldoc">
<p>ILMerge default parameters. Tries to automatically locate ilmerge.exe in a subfolder.</p>
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/ILMergeHelper.fs#L68-68" class="github-link">Go to GitHub source</a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="span3">
<img src="http://fsharp.github.io/FAKE/pics/logo.png" alt="FAKE - F# Make" style="width:150px;margin-left: 20px;" />
<ul class="nav nav-list" id="menu" style="margin-top: 20px;">
<li class="nav-header">FAKE - F# Make</li>
<li><a href="http://fsharp.github.io/FAKE/index.html">Home page</a></li>
<li class="divider"></li>
<li><a href="https://nuget.org/packages/Fake">Get FAKE via NuGet</a></li>
<li><a href="http://github.com/fsharp/fake">Source Code on GitHub</a></li>
<li><a href="https://github.com/fsharp/FAKE/blob/develop/License.txt">License (MS-PL)</a></li>
<li><a href="http://fsharp.github.io/FAKE/users.html">Who is using FAKE?</a></li>
<li><a href="http://fsharp.github.io/FAKE/RELEASE_NOTES.html">Release Notes</a></li>
<li><a href="http://fsharp.github.io/FAKE/contributing.html">Contributing to FAKE</a></li>
<li><a href="http://stackoverflow.com/questions/tagged/f%23-fake">Ask a question</a></li>
<li class="nav-header">Articles</li>
<li><a href="http://fsharp.github.io/FAKE/gettingstarted.html">Getting started</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/nuget.html">NuGet package restore</a></li>
<li><a href="http://fsharp.github.io/FAKE/fxcop.html">Using FxCop in a build</a></li>
<li><a href="http://fsharp.github.io/FAKE/assemblyinfo.html">Generating AssemblyInfo</a></li>
<li><a href="http://fsharp.github.io/FAKE/create-nuget-package.html">Create NuGet packages</a></li>
<li><a href="http://fsharp.github.io/FAKE/specifictargets.html">Running specific targets</a></li>
<li><a href="http://fsharp.github.io/FAKE/commandline.html">Running FAKE from command line</a></li>
<li><a href="http://fsharp.github.io/FAKE/customtasks.html">Creating custom tasks</a></li>
<li><a href="http://fsharp.github.io/FAKE/teamcity.html">TeamCity integration</a></li>
<li><a href="http://fsharp.github.io/FAKE/canopy.html">Running canopy tests</a></li>
<li><a href="http://fsharp.github.io/FAKE/octopusdeploy.html">Octopus Deploy</a></li>
<li><a href="http://fsharp.github.io/FAKE/typescript.html">TypeScript support</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/deploy.html">Fake.Deploy</a></li>
<li class="nav-header">Documentation</li>
<li><a href="http://fsharp.github.io/FAKE/apidocs/index.html">API Reference</a></li>
</ul>
</div>
</div>
</div>
<a href="http://github.com/fsharp/fake"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
</body>
</html>
|
TeaDrivenDev/Graphology
|
packages/FAKE/docs/apidocs/fake-ilmergehelper.html
|
HTML
|
mit
| 7,987
|
// import path from 'path';
// import {isCI} from '../lib/ci';
module.exports = {
// // - - - - CHIMP - - - -
// watch: false,
// watchTags: '@watch,@focus',
// domainSteps: null,
// e2eSteps: null,
// fullDomain: false,
// domainOnly: false,
// e2eTags: '@e2e',
// watchWithPolling: false,
// server: false,
// serverPort: 8060,
// serverHost: 'localhost',
// sync: true,
// offline: false,
// showXolvioMessages: true,
// // - - - - CUCUMBER - - - -
path: 'tests/end-to-end',
// format: 'pretty',
// tags: '~@ignore',
// singleSnippetPerFile: true,
// recommendedFilenameSeparator: '_',
// chai: false,
// screenshotsOnError: isCI(),
// screenshotsPath: '.screenshots',
// captureAllStepScreenshots: false,
// saveScreenshotsToDisk: true,
// // Note: With a large viewport size and captureAllStepScreenshots enabled,
// // you may run out of memory. Use browser.setViewportSize to make the
// // viewport size smaller.
// saveScreenshotsToReport: false,
// jsonOutput: null,
// compiler: 'js:' + path.resolve(__dirname, '../lib/babel-register.js'),
// conditionOutput: true,
// // - - - - SELENIUM - - - -
// browser: null,
// platform: 'ANY',
// name: '',
// user: '',
// key: '',
// port: null,
// host: null,
// // deviceName: null,
// // - - - - WEBDRIVER-IO - - - -
// webdriverio: {
// desiredCapabilities: {},
// logLevel: 'silent',
// // logOutput: null,
// host: '127.0.0.1',
// port: 4444,
// path: '/wd/hub',
// baseUrl: null,
// coloredLogs: true,
// screenshotPath: null,
// waitforTimeout: 500,
// waitforInterval: 250,
// },
// // - - - - SELENIUM-STANDALONE
// seleniumStandaloneOptions: {
// // check for more recent versions of selenium here:
// // http://selenium-release.storage.googleapis.com/index.html
// version: '2.53.1',
// baseURL: 'https://selenium-release.storage.googleapis.com',
// drivers: {
// chrome: {
// // check for more recent versions of chrome driver here:
// // http://chromedriver.storage.googleapis.com/index.html
// version: '2.25',
// arch: process.arch,
// baseURL: 'https://chromedriver.storage.googleapis.com'
// },
// ie: {
// // check for more recent versions of internet explorer driver here:
// // http://selenium-release.storage.googleapis.com/index.html
// version: '2.50.0',
// arch: 'ia32',
// baseURL: 'https://selenium-release.storage.googleapis.com'
// },
// firefox: {
// // check for more recent versions of gecko driver here:
// // https://github.com/mozilla/geckodriver/releases
// version: '0.11.1',
// arch: process.arch,
// baseURL: 'https://github.com/mozilla/geckodriver/releases/download'
// }
// }
// },
// // - - - - SESSION-MANAGER - - - -
// noSessionReuse: false,
// // - - - - SIMIAN - - - -
// simianResultEndPoint: 'api.simian.io/v1.0/result',
// simianAccessToken: false,
// simianResultBranch: null,
// simianRepositoryId: null,
// // - - - - MOCHA - - - -
mocha: true,
mochaCommandLineOptions: ['--color'],
mochaConfig: {
// tags and grep only work when watch mode is false
tags: '',
grep: null,
timeout: 40000,
reporter: 'min',
slow: 100,
retries: 3,
bail: false // bail after first test failure
},
// // - - - - JASMINE - - - -
// jasmine: false,
// jasmineConfig: {
// specDir: '.',
// specFiles: [
// '**/*@(_spec|-spec|Spec).@(js|jsx)',
// ],
// helpers: [
// 'support/**/*.@(js|jsx)',
// ],
// stopSpecOnExpectationFailure: false,
// random: false,
// },
// jasmineReporterConfig: {
// // This options are passed to jasmine.configureDefaultReporter(...)
// // See: http://jasmine.github.io/2.4/node.html#section-Reporters
// },
// // - - - - METEOR - - - -
ddp: 'http://localhost:3000'
// serverExecuteTimeout: 10000,
// // - - - - PHANTOM - - - -
// phantom_w: 1280,
// phantom_h: 1024,
// phantom_ignoreSSLErrors: false,
// // - - - - DEBUGGING - - - -
// log: 'info',
// debug: false,
// seleniumDebug: null,
// debugCucumber: null,
// debugBrkCucumber: null,
// debugMocha: null,
// debugBrkMocha: null,
};
|
wtsarchive/Rocket.Chat
|
tests/chimp-config.js
|
JavaScript
|
mit
| 4,154
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.