<commit_before>/**
 *
 */
$(document).ready(function() {
	tagid = $('#tagid').val();

	$.getJSON('/api/tag/' + tagid +"?nameonly=true", function(data) {
		$('.breadcrumb').append(''+
		  '
 '+
		  data.tagtext+
		  '
');
	});

	$.getJSON('/api/tag/' + tagid , function(data) {
		console.log(data);
		for ( var i = 0; i < data.length; i++) {
			$('#widget-tagged-as-results').append(''+
		'
'+
		'
'+
		'		'+
		'
'+
		'
'+data[i].name+'
'+
		'
'+data[i].description+'
'+
		'
'+
		'				Read more >>>'+
		'
'+
		'
'+
		'
'+
		'
');
		}

	});

});
<commit_msg>Use correct REST calls for tags API<commit_after>/**
 *
 */
$(document).ready(function() {
	tagid = $('#tagid').val();

	$.getJSON('/api/tag/' + tagid, function(data) {
		$('.breadcrumb').append(''+
		  '
 '+
		  data.tagtext+
		  '
');
	});

	$.getJSON('/api/tag/' + tagid +"/widgets", function(data) {
		console.log(data);
		for ( var i = 0; i < data.length; i++) {
			$('#widget-tagged-as-results').append(''+
		'
'+
		'
'+
		'		'+
		'
'+
		'
'+data[i].name+'
'+
		'
'+data[i].description+'
'+
		'
'+
		'				Read more >>>'+
		'
'+
		'
'+
		'
'+
		'
');
		}

	});

});
<|endoftext|>


<commit_before>import { fetchURL, removePrefix } from './utils'
import { baseURL } from '@/utils/constants'
import store from '@/store'

export async function fetch (url) {
  url = removePrefix(url)

  const res = await fetchURL(`/api/resources${url}`, {})

  if (res.status === 200) {
    let data = await res.json()
    data.url = `/files${url}`

    if (data.isDir) {
      if (!data.url.endsWith('/')) data.url += '/'
      data.items = data.items.map((item, index) => {
        item.index = index
        item.url = `${data.url}${encodeURIComponent(item.name)}`

        if (item.isDir) {
          item.url += '/'
        }

        return item
      })
    }

    return data
  } else {
    throw new Error(res.status)
  }
}

async function resourceAction (url, method, content) {
  url = removePrefix(url)

  let opts = { method }

  if (content) {
    opts.body = content
  }

  const res = await fetchURL(`/api/resources${url}`, opts)

  if (res.status !== 200) {
    throw new Error(await res.text())
  } else {
    return res
  }
}

export async function remove (url) {
  return resourceAction(url, 'DELETE')
}

export async function put (url, content = '') {
  return resourceAction(url, 'PUT', content)
}

export function download (format, ...files) {
  let url = `${baseURL}/api/raw`

  if (files.length === 1) {
    url += removePrefix(files[0]) + '?'
  } else {
    let arg = ''

    for (let file of files) {
      arg += removePrefix(file) + ','
    }

    arg = arg.substring(0, arg.length - 1)
    arg = encodeURIComponent(arg)
    url += `/?files=${arg}&`
  }

  if (format !== null) {
    url += `algo=${format}&`
  }

  url += `auth=${store.state.jwt}`
  window.open(url)
}

export async function post (url, content = '', overwrite = false, onupload) {
  url = removePrefix(url)

  return new Promise((resolve, reject) => {
    let request = new XMLHttpRequest()
    request.open('POST', `${baseURL}/api/resources${url}?override=${overwrite}`, true)
    request.setRequestHeader('X-Auth', store.state.jwt)

    if (typeof onupload === 'function') {
      request.upload.onprogress = onupload
    }

    request.onload = () => {
      if (request.status === 200) {
        resolve(request.responseText)
      } else if (request.status === 409) {
        reject(request.status)
      } else {
        reject(request.responseText)
      }
    }

    request.onerror = (error) => {
      reject(error)
    }

    request.send(content)
  })
}

function moveCopy (items, copy = false, overwrite = false, rename = false) {
  let promises = []

  for (let item of items) {
    const from = removePrefix(item.from)
    const to = encodeURIComponent(removePrefix(item.to))
    const url = `${from}?action=${copy ? 'copy' : 'rename'}&destination=${to}&override=${overwrite}&rename=${rename}`
    promises.push(resourceAction(url, 'PATCH'))
  }

  return Promise.all(promises)
}

export function move (items, overwrite = false, rename = false) {
  return moveCopy(items, false, overwrite, rename)
}

export function copy (items, overwrite = false, rename = false) {
  return moveCopy(items, true, overwrite, rename)
}

export async function checksum (url, algo) {
  const data = await resourceAction(`${url}?checksum=${algo}`, 'GET')
  return (await data.json()).checksums[algo]
}
<commit_msg>feat: support WKWebview custom protocol (#1113)<commit_after>import { fetchURL, removePrefix } from './utils'
import { baseURL } from '@/utils/constants'
import store from '@/store'

export async function fetch (url) {
  url = removePrefix(url)

  const res = await fetchURL(`/api/resources${url}`, {})

  if (res.status === 200) {
    let data = await res.json()
    data.url = `/files${url}`

    if (data.isDir) {
      if (!data.url.endsWith('/')) data.url += '/'
      data.items = data.items.map((item, index) => {
        item.index = index
        item.url = `${data.url}${encodeURIComponent(item.name)}`

        if (item.isDir) {
          item.url += '/'
        }

        return item
      })
    }

    return data
  } else {
    throw new Error(res.status)
  }
}

async function resourceAction (url, method, content) {
  url = removePrefix(url)

  let opts = { method }

  if (content) {
    opts.body = content
  }

  const res = await fetchURL(`/api/resources${url}`, opts)

  if (res.status !== 200) {
    throw new Error(await res.text())
  } else {
    return res
  }
}

export async function remove (url) {
  return resourceAction(url, 'DELETE')
}

export async function put (url, content = '') {
  return resourceAction(url, 'PUT', content)
}

export function download (format, ...files) {
  let url = `${baseURL}/api/raw`

  if (files.length === 1) {
    url += removePrefix(files[0]) + '?'
  } else {
    let arg = ''

    for (let file of files) {
      arg += removePrefix(file) + ','
    }

    arg = arg.substring(0, arg.length - 1)
    arg = encodeURIComponent(arg)
    url += `/?files=${arg}&`
  }

  if (format !== null) {
    url += `algo=${format}&`
  }

  url += `auth=${store.state.jwt}`
  window.open(url)
}

export async function post (url, content = '', overwrite = false, onupload) {
  url = removePrefix(url)

  let bufferContent
  if (content instanceof Blob && !['http:', 'https:'].includes(window.location.protocol)) {
    bufferContent = await new Response(content).arrayBuffer()
  }

  return new Promise((resolve, reject) => {
    let request = new XMLHttpRequest()
    request.open('POST', `${baseURL}/api/resources${url}?override=${overwrite}`, true)
    request.setRequestHeader('X-Auth', store.state.jwt)

    if (typeof onupload === 'function') {
      request.upload.onprogress = onupload
    }

    request.onload = () => {
      if (request.status === 200) {
        resolve(request.responseText)
      } else if (request.status === 409) {
        reject(request.status)
      } else {
        reject(request.responseText)
      }
    }

    request.onerror = (error) => {
      reject(error)
    }

    request.send(bufferContent || content)
  })
}

function moveCopy (items, copy = false, overwrite = false, rename = false) {
  let promises = []

  for (let item of items) {
    const from = removePrefix(item.from)
    const to = encodeURIComponent(removePrefix(item.to))
    const url = `${from}?action=${copy ? 'copy' : 'rename'}&destination=${to}&override=${overwrite}&rename=${rename}`
    promises.push(resourceAction(url, 'PATCH'))
  }

  return Promise.all(promises)
}

export function move (items, overwrite = false, rename = false) {
  return moveCopy(items, false, overwrite, rename)
}

export function copy (items, overwrite = false, rename = false) {
  return moveCopy(items, true, overwrite, rename)
}

export async function checksum (url, algo) {
  const data = await resourceAction(`${url}?checksum=${algo}`, 'GET')
  return (await data.json()).checksums[algo]
}
<|endoftext|>


<commit_before><commit_msg>Infinite Scrolling<commit_after><|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var shell = require('shelljs');
var semver = require('semver');
var _ = require('lodash');

var currentPackage, previousVersions, cdnVersion, gitRepoInfo;

/**
 * Load information about this project from the package.json
 * @return {Object} The package information
 */
var getPackage = function() {
  // Search up the folder hierarchy for the first package.json
  var packageFolder = path.resolve('.');
  while (!fs.existsSync(path.join(packageFolder, 'package.json'))) {
    var parent = path.dirname(packageFolder);
    if (parent === packageFolder) { break; }
    packageFolder = parent;
  }
  return JSON.parse(fs.readFileSync(path.join(packageFolder,'package.json'), 'UTF-8'));
};

/**
 * Parse the github URL for useful information
 * @return {Object} An object containing the github owner and repository name
 */
var getGitRepoInfo = function() {
  var GITURL_REGEX = /^https:\/\/github.com\/([^\/]+)\/(.+).git$/;
  var match = GITURL_REGEX.exec(currentPackage.repository.url);
  var git = {
    owner: match[1],
    repo: match[2]
  };
  return git;
};

/**
 * Extract the code name from the tagged commit's message - it should contain the text of the form:
 * "codename(some-code-name)"
 * @param  {String} tagName Name of the tag to look in for the codename
 * @return {String}         The codename if found, otherwise null/undefined
 */
var getCodeName = function(tagName) {
  var gitCatOutput = shell.exec('git cat-file -p ' + tagName, {silent:true}).output;
  var tagMessage = gitCatOutput.match(/^.*codename.*$/mg)[0];
  var codeName = tagMessage && tagMessage.match(/codename\((.*)\)/)[1];
  if (!codeName) {
    throw new Error("Could not extract release code name. The message of tag " + tagName +
      " must match '*codename(some release name)*'");
  }
  return codeName;
};

/**
 * Compute a build segment for the version, from the Jenkins build number and current commit SHA
 * @return {String} The build segment of the version
 */
function getBuild() {
  var hash = shell.exec('git rev-parse --short HEAD', {silent: true}).output.replace('\n', '');
  return 'sha.' + hash;
}

/**
 * If the current commit is tagged as a version get that version
 * @return {SemVer} The version or null
 */
var getTaggedVersion = function() {
  var gitTagResult = shell.exec('git describe --exact-match', {silent:true});

  if (gitTagResult.code === 0) {
    var tag = gitTagResult.output.trim();
    var version = semver.parse(tag);

    if (version && semver.satisfies(version, currentPackage.branchVersion)) {
      version.codeName = getCodeName(tag);
      version.full = version.version;
      version.branch = 'v' + currentPackage.branchPattern.replace('*', 'x');
      return version;
    }
  }

  return null;
};

/**
 * Get a collection of all the previous versions sorted by semantic version
 * @return {Array.<SemVer>} The collection of previous versions
 */
var getPreviousVersions =  function() {
  // always use the remote tags as the local clone might
  // not contain all commits when cloned with git clone --depth=...
  // Needed e.g. for Travis
  var repo_url = currentPackage.repository.url;
  var tagResults = shell.exec('git ls-remote --tags ' + repo_url,
                              {silent: true});
  if (tagResults.code === 0) {
    return _(tagResults.output.match(/v[0-9].*[0-9]$/mg))
      .map(function(tag) {
        var version = semver.parse(tag);
        return version;
      })
      .filter()
      .map(function(version) {
        version.docsUrl = 'http://code.angularjs.org/' + version.version + '/docs';
        // Versions before 1.0.2 had a different docs folder name
        if (version.major < 1 || (version.major === 1 && version.minor === 0 && version.dot < 2)) {
          version.docsUrl += '-' + version.version;
        }
        return version;
      })
      .sort(semver.compare)
      .value();
  } else {
    return [];
  }
};

var getCdnVersion = function() {
  return _(previousVersions)
    .filter(function(tag) {
      return semver.satisfies(tag, currentPackage.branchVersion);
    })
    .reverse()
    .reduce(function(cdnVersion, version) {
      if (!cdnVersion) {
        // Note: need to use shell.exec and curl here
        // as version-infos returns its result synchronously...
        var cdnResult = shell.exec('curl http://ajax.googleapis.com/ajax/libs/angularjs/' + version + '/angular.min.js ' +
                  '--head --write-out "%{http_code}" -o /dev/null -silent',
                                    {silent: false});
        if (cdnResult.code === 0) {
          var statusCode = cdnResult.output.trim();
          if (statusCode === '200') {
            cdnVersion = version;
          }
        }
      }
      return cdnVersion;
    }, null);
};

/**
 * Get the unstable snapshot version
 * @return {SemVer} The snapshot version
 */
var getSnapshotVersion = function() {
  var version = _(previousVersions)
    .filter(function(tag) {
      return semver.satisfies(tag, currentPackage.branchVersion);
    })
    .last();

  if (!version) {
    // a snapshot version before the first tag on the branch
    version = semver(currentPackage.branchPattern.replace('*','0-beta.1'));
  }

  // We need to clone to ensure that we are not modifying another version
  version = semver(version.raw);

  var jenkinsBuild = process.env.TRAVIS_BUILD_NUMBER || process.env.BUILD_NUMBER;
  if (!version.prerelease || !version.prerelease.length) {
    // last release was a non beta release. Increment the patch level to
    // indicate the next release that we will be doing.
    // E.g. last release was 1.3.0, then the snapshot will be
    // 1.3.1-build.1, which is lesser than 1.3.1 accorind the semver!

    // If the last release was a beta release we don't update the
    // beta number by purpose, as otherwise the semver comparison
    // does not work any more when the next beta is released.
    // E.g. don't generate 1.3.0-beta.2.build.1
    // as this is bigger than 1.3.0-beta.2 according to semver
    version.patch++;
  }
  version.prerelease = jenkinsBuild ? ['build', jenkinsBuild] : ['local'];
  version.build = getBuild();
  version.codeName = 'snapshot';
  version.isSnapshot = true;
  version.format();
  version.full = version.version + '+' + version.build;
  version.branch = 'master';

  return version;
};

exports.currentPackage = currentPackage = getPackage();
exports.gitRepoInfo = gitRepoInfo = getGitRepoInfo();
exports.previousVersions = previousVersions = getPreviousVersions();
exports.cdnVersion = cdnVersion = getCdnVersion();
exports.currentVersion = getTaggedVersion() || getSnapshotVersion();
<commit_msg>chore(version-info): silence the HTTP curl to get the cdn version<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var shell = require('shelljs');
var semver = require('semver');
var _ = require('lodash');

var currentPackage, previousVersions, cdnVersion, gitRepoInfo;

/**
 * Load information about this project from the package.json
 * @return {Object} The package information
 */
var getPackage = function() {
  // Search up the folder hierarchy for the first package.json
  var packageFolder = path.resolve('.');
  while (!fs.existsSync(path.join(packageFolder, 'package.json'))) {
    var parent = path.dirname(packageFolder);
    if (parent === packageFolder) { break; }
    packageFolder = parent;
  }
  return JSON.parse(fs.readFileSync(path.join(packageFolder,'package.json'), 'UTF-8'));
};

/**
 * Parse the github URL for useful information
 * @return {Object} An object containing the github owner and repository name
 */
var getGitRepoInfo = function() {
  var GITURL_REGEX = /^https:\/\/github.com\/([^\/]+)\/(.+).git$/;
  var match = GITURL_REGEX.exec(currentPackage.repository.url);
  var git = {
    owner: match[1],
    repo: match[2]
  };
  return git;
};

/**
 * Extract the code name from the tagged commit's message - it should contain the text of the form:
 * "codename(some-code-name)"
 * @param  {String} tagName Name of the tag to look in for the codename
 * @return {String}         The codename if found, otherwise null/undefined
 */
var getCodeName = function(tagName) {
  var gitCatOutput = shell.exec('git cat-file -p ' + tagName, {silent:true}).output;
  var tagMessage = gitCatOutput.match(/^.*codename.*$/mg)[0];
  var codeName = tagMessage && tagMessage.match(/codename\((.*)\)/)[1];
  if (!codeName) {
    throw new Error("Could not extract release code name. The message of tag " + tagName +
      " must match '*codename(some release name)*'");
  }
  return codeName;
};

/**
 * Compute a build segment for the version, from the Jenkins build number and current commit SHA
 * @return {String} The build segment of the version
 */
function getBuild() {
  var hash = shell.exec('git rev-parse --short HEAD', {silent: true}).output.replace('\n', '');
  return 'sha.' + hash;
}

/**
 * If the current commit is tagged as a version get that version
 * @return {SemVer} The version or null
 */
var getTaggedVersion = function() {
  var gitTagResult = shell.exec('git describe --exact-match', {silent:true});

  if (gitTagResult.code === 0) {
    var tag = gitTagResult.output.trim();
    var version = semver.parse(tag);

    if (version && semver.satisfies(version, currentPackage.branchVersion)) {
      version.codeName = getCodeName(tag);
      version.full = version.version;
      version.branch = 'v' + currentPackage.branchPattern.replace('*', 'x');
      return version;
    }
  }

  return null;
};

/**
 * Get a collection of all the previous versions sorted by semantic version
 * @return {Array.<SemVer>} The collection of previous versions
 */
var getPreviousVersions =  function() {
  // always use the remote tags as the local clone might
  // not contain all commits when cloned with git clone --depth=...
  // Needed e.g. for Travis
  var repo_url = currentPackage.repository.url;
  var tagResults = shell.exec('git ls-remote --tags ' + repo_url,
                              {silent: true});
  if (tagResults.code === 0) {
    return _(tagResults.output.match(/v[0-9].*[0-9]$/mg))
      .map(function(tag) {
        var version = semver.parse(tag);
        return version;
      })
      .filter()
      .map(function(version) {
        version.docsUrl = 'http://code.angularjs.org/' + version.version + '/docs';
        // Versions before 1.0.2 had a different docs folder name
        if (version.major < 1 || (version.major === 1 && version.minor === 0 && version.dot < 2)) {
          version.docsUrl += '-' + version.version;
        }
        return version;
      })
      .sort(semver.compare)
      .value();
  } else {
    return [];
  }
};

var getCdnVersion = function() {
  return _(previousVersions)
    .filter(function(tag) {
      return semver.satisfies(tag, currentPackage.branchVersion);
    })
    .reverse()
    .reduce(function(cdnVersion, version) {
      if (!cdnVersion) {
        // Note: need to use shell.exec and curl here
        // as version-infos returns its result synchronously...
        var cdnResult = shell.exec('curl http://ajax.googleapis.com/ajax/libs/angularjs/' + version + '/angular.min.js ' +
                  '--head --write-out "%{http_code}" -o /dev/null -silent',
                                    {silent: true});
        if (cdnResult.code === 0) {
          var statusCode = cdnResult.output.trim();
          if (statusCode === '200') {
            cdnVersion = version;
          }
        }
      }
      return cdnVersion;
    }, null);
};

/**
 * Get the unstable snapshot version
 * @return {SemVer} The snapshot version
 */
var getSnapshotVersion = function() {
  var version = _(previousVersions)
    .filter(function(tag) {
      return semver.satisfies(tag, currentPackage.branchVersion);
    })
    .last();

  if (!version) {
    // a snapshot version before the first tag on the branch
    version = semver(currentPackage.branchPattern.replace('*','0-beta.1'));
  }

  // We need to clone to ensure that we are not modifying another version
  version = semver(version.raw);

  var jenkinsBuild = process.env.TRAVIS_BUILD_NUMBER || process.env.BUILD_NUMBER;
  if (!version.prerelease || !version.prerelease.length) {
    // last release was a non beta release. Increment the patch level to
    // indicate the next release that we will be doing.
    // E.g. last release was 1.3.0, then the snapshot will be
    // 1.3.1-build.1, which is lesser than 1.3.1 accorind the semver!

    // If the last release was a beta release we don't update the
    // beta number by purpose, as otherwise the semver comparison
    // does not work any more when the next beta is released.
    // E.g. don't generate 1.3.0-beta.2.build.1
    // as this is bigger than 1.3.0-beta.2 according to semver
    version.patch++;
  }
  version.prerelease = jenkinsBuild ? ['build', jenkinsBuild] : ['local'];
  version.build = getBuild();
  version.codeName = 'snapshot';
  version.isSnapshot = true;
  version.format();
  version.full = version.version + '+' + version.build;
  version.branch = 'master';

  return version;
};

exports.currentPackage = currentPackage = getPackage();
exports.gitRepoInfo = gitRepoInfo = getGitRepoInfo();
exports.previousVersions = previousVersions = getPreviousVersions();
exports.cdnVersion = cdnVersion = getCdnVersion();
exports.currentVersion = getTaggedVersion() || getSnapshotVersion();
<|endoftext|>


<commit_before><commit_msg>Use ES6 template literals for dashboard messages<commit_after><|endoftext|>


<commit_before>const getTier = (query, tiers) => {

  if (!tiers || tiers.length === 0)
    return null;

  // We order the tiers by start range DESC
  tiers.sort((a,b) => {
    return a.range[0] < b.range[0];
  });

  // We get the first tier for which the totalDonations is higher than the minimum amount for that tier
  const tier = tiers.find((tier) => {
    if (query.interval && query.interval !== tier.interval) return false;
    if (query.amount && query.amount >= tier.range[0] && query.amount <= tier.range[1]) return true;
    return false;
  });

  return tier;
};

module.exports = { getTier };<commit_msg>making sure we only return a tier if it matches the amount (#389)<commit_after>const getTier = (query, tiers) => {

  if (!tiers || tiers.length === 0)
    return null;

  // We order the tiers by start range DESC
  tiers.sort((a,b) => {
    return a.range[0] < b.range[0];
  });

  // We get the first tier for which the totalDonations is higher than the minimum amount for that tier
  const tier = tiers.find((tier) => {
    if (query.interval && query.interval !== tier.interval) return false;
    if (query.amount && parseInt(query.amount, 10) === parseInt(tier.amount,10)) return true;
    return false;
  });

  return tier;
};

module.exports = { getTier };<|endoftext|>


<commit_before><commit_msg>Created utilities to get US timezones, and manual 'top' US list #651<commit_after><|endoftext|>


<commit_before>YUI.add('moodle-core-dragdrop', function(Y) {
    var MOVEICON = {'pix':"i/move_2d",'component':'moodle'};

   /*
    * General DRAGDROP class, this should not be used directly,
    * it is supposed to be extended by your class
    */
    var DRAGDROP = function() {
        DRAGDROP.superclass.constructor.apply(this, arguments);
    };

    Y.extend(DRAGDROP, Y.Base, {
        goingup : null,
        lasty   : null,
        samenodeclass : null,
        parentnodeclass : null,
        groups : [],
        lastdroptarget : null,
        initializer : function(params) {
            // Listen for all drag:start events
            Y.DD.DDM.on('drag:start', this.global_drag_start, this);
            // Listen for all drag:end events
            Y.DD.DDM.on('drag:end', this.global_drag_end, this);
            // Listen for all drag:drag events
            Y.DD.DDM.on('drag:drag', this.global_drag_drag, this);
            // Listen for all drop:over events
            Y.DD.DDM.on('drop:over', this.global_drop_over, this);
            // Listen for all drop:hit events
            Y.DD.DDM.on('drop:hit', this.global_drop_hit, this);
            // Listen for all drop:miss events
            Y.DD.DDM.on('drag:dropmiss', this.global_drag_dropmiss, this);
        },

        get_drag_handle: function(title, classname, iconclass) {
            var dragicon = Y.Node.create('')
                .setStyle('cursor', 'move')
                .setAttrs({
                    'src' : M.util.image_url(MOVEICON.pix, MOVEICON.component),
                    'alt' : title,
                    'title' : M.str.moodle.move
                });
            if (iconclass) {
                dragicon.addClass(iconclass);
            }

            var dragelement = Y.Node.create('')
                .addClass(classname)
                .setAttribute('title', title)
            dragelement.appendChild(dragicon);
            return dragelement;
        },

        lock_drag_handle: function(drag, classname) {
            // Disable dragging
            drag.removeHandle('.'+classname);
        },

        unlock_drag_handle: function(drag, classname) {
            // Enable dragging
            drag.addHandle('.'+classname);
        },

        ajax_failure: function(response) {
            var e = {
                name : response.status+' '+response.statusText,
                message : response.responseText
            };
            return new M.core.exception(e);
        },

        in_group: function(target) {
            var ret = false;
            Y.each(this.groups, function(v, k) {
                if (target._groups[v]) {
                    ret = true;
                }
            }, this);
            return ret;
        },
        /*
         * Drag-dropping related functions
         */
        global_drag_start : function(e) {
            // Get our drag object
            var drag = e.target;
            // Check that drag object belongs to correct group
            if (!this.in_group(drag)) {
                return;
            }
            // Set some general styles here
            drag.get('node').setStyle('opacity', '.25');
            drag.get('dragNode').setStyles({
                opacity: '.75',
                borderColor: drag.get('node').getStyle('borderColor'),
                backgroundColor: drag.get('node').getStyle('backgroundColor')
            });
            drag.get('dragNode').empty();
            this.drag_start(e);
        },

        global_drag_end : function(e) {
            var drag = e.target;
            // Check that drag object belongs to correct group
            if (!this.in_group(drag)) {
                return;
            }
            //Put our general styles back
            drag.get('node').setStyles({
                visibility: '',
                opacity: '1'
            });
            this.drag_end(e);
        },

        global_drag_drag : function(e) {
            var drag = e.target;
            // Check that drag object belongs to correct group
            if (!this.in_group(drag)) {
                return;
            }
            //Get the last y point
            var y = drag.lastXY[1];
            //is it greater than the lasty var?
            if (y < this.lasty) {
                //We are going up
                this.goingup = true;
            } else {
                //We are going down.
                this.goingup = false;
            }
            //Cache for next check
            this.lasty = y;
            this.drag_drag(e);
        },

        global_drop_over : function(e) {
            // Check that drop object belong to correct group
            if (!e.drop || !e.drop.inGroup(this.groups)) {
                return;
            }
            //Get a reference to our drag and drop nodes
            var drag = e.drag.get('node');
            var drop = e.drop.get('node');
            // Save last drop target for the case of missed target processing
            this.lastdroptarget = e.drop;
            //Are we dropping on the same node?
            if (drop.hasClass(this.samenodeclass)) {
                //Are we not going up?
                if (!this.goingup) {
                    drop = drop.next('.'+this.samenodeclass);
                }
                //Add the node
                e.drop.get('node').ancestor().insertBefore(drag, drop);
            } else if (drop.hasClass(this.parentnodeclass) && !drop.contains(drag)) {
                // We are dropping on parent node and it is empty
                if (this.goingup) {
                    drop.append(drag);
                } else {
                    drop.prepend(drag);
                }
            }
            this.drop_over(e);
        },

        global_drag_dropmiss : function(e) {
            // drag:dropmiss does not have e.drag and e.drop properties
            // we substitute them for the ease of use. For e.drop we use,
            // this.lastdroptarget (ghost node we use for indicating where to drop)
            e.drag = e.target;
            // Check that drop object belong to correct group
            if (!e.drop || !e.drop.inGroup(this.groups)) {
                return;
            }
            e.drop = this.lastdroptarget;
            this.drag_dropmiss(e);
        },

        global_drop_hit : function(e) {
            // Check that drop object belong to correct group
            if (!e.drop || !e.drop.inGroup(this.groups)) {
                return;
            }
            this.drop_hit(e);
        },

        /*
         * Abstract functions definitions
         */
        drag_start : function(e) {},
        drag_end : function(e) {},
        drag_drag : function(e) {},
        drag_dropmiss : function(e) {},
        drop_over : function(e) {},
        drop_hit : function(e) {}
    }, {
        NAME : 'dragdrop',
        ATTRS : {}
    });

M.core = M.core || {};
M.core.dragdrop = DRAGDROP;

}, '@VERSION@', {requires:['base', 'node', 'io', 'dom', 'dd', 'moodle-core-notification']});
<commit_msg>MDL-34328 Correct usage of e.drop when catching missed drag/drop events<commit_after>YUI.add('moodle-core-dragdrop', function(Y) {
    var MOVEICON = {'pix':"i/move_2d",'component':'moodle'};

   /*
    * General DRAGDROP class, this should not be used directly,
    * it is supposed to be extended by your class
    */
    var DRAGDROP = function() {
        DRAGDROP.superclass.constructor.apply(this, arguments);
    };

    Y.extend(DRAGDROP, Y.Base, {
        goingup : null,
        lasty   : null,
        samenodeclass : null,
        parentnodeclass : null,
        groups : [],
        lastdroptarget : null,
        initializer : function(params) {
            // Listen for all drag:start events
            Y.DD.DDM.on('drag:start', this.global_drag_start, this);
            // Listen for all drag:end events
            Y.DD.DDM.on('drag:end', this.global_drag_end, this);
            // Listen for all drag:drag events
            Y.DD.DDM.on('drag:drag', this.global_drag_drag, this);
            // Listen for all drop:over events
            Y.DD.DDM.on('drop:over', this.global_drop_over, this);
            // Listen for all drop:hit events
            Y.DD.DDM.on('drop:hit', this.global_drop_hit, this);
            // Listen for all drop:miss events
            Y.DD.DDM.on('drag:dropmiss', this.global_drag_dropmiss, this);
        },

        get_drag_handle: function(title, classname, iconclass) {
            var dragicon = Y.Node.create('')
                .setStyle('cursor', 'move')
                .setAttrs({
                    'src' : M.util.image_url(MOVEICON.pix, MOVEICON.component),
                    'alt' : title,
                    'title' : M.str.moodle.move
                });
            if (iconclass) {
                dragicon.addClass(iconclass);
            }

            var dragelement = Y.Node.create('')
                .addClass(classname)
                .setAttribute('title', title)
            dragelement.appendChild(dragicon);
            return dragelement;
        },

        lock_drag_handle: function(drag, classname) {
            // Disable dragging
            drag.removeHandle('.'+classname);
        },

        unlock_drag_handle: function(drag, classname) {
            // Enable dragging
            drag.addHandle('.'+classname);
        },

        ajax_failure: function(response) {
            var e = {
                name : response.status+' '+response.statusText,
                message : response.responseText
            };
            return new M.core.exception(e);
        },

        in_group: function(target) {
            var ret = false;
            Y.each(this.groups, function(v, k) {
                if (target._groups[v]) {
                    ret = true;
                }
            }, this);
            return ret;
        },
        /*
         * Drag-dropping related functions
         */
        global_drag_start : function(e) {
            // Get our drag object
            var drag = e.target;
            // Check that drag object belongs to correct group
            if (!this.in_group(drag)) {
                return;
            }
            // Set some general styles here
            drag.get('node').setStyle('opacity', '.25');
            drag.get('dragNode').setStyles({
                opacity: '.75',
                borderColor: drag.get('node').getStyle('borderColor'),
                backgroundColor: drag.get('node').getStyle('backgroundColor')
            });
            drag.get('dragNode').empty();
            this.drag_start(e);
        },

        global_drag_end : function(e) {
            var drag = e.target;
            // Check that drag object belongs to correct group
            if (!this.in_group(drag)) {
                return;
            }
            //Put our general styles back
            drag.get('node').setStyles({
                visibility: '',
                opacity: '1'
            });
            this.drag_end(e);
        },

        global_drag_drag : function(e) {
            var drag = e.target;
            // Check that drag object belongs to correct group
            if (!this.in_group(drag)) {
                return;
            }
            //Get the last y point
            var y = drag.lastXY[1];
            //is it greater than the lasty var?
            if (y < this.lasty) {
                //We are going up
                this.goingup = true;
            } else {
                //We are going down.
                this.goingup = false;
            }
            //Cache for next check
            this.lasty = y;
            this.drag_drag(e);
        },

        global_drop_over : function(e) {
            // Check that drop object belong to correct group
            if (!e.drop || !e.drop.inGroup(this.groups)) {
                return;
            }
            //Get a reference to our drag and drop nodes
            var drag = e.drag.get('node');
            var drop = e.drop.get('node');
            // Save last drop target for the case of missed target processing
            this.lastdroptarget = e.drop;
            //Are we dropping on the same node?
            if (drop.hasClass(this.samenodeclass)) {
                //Are we not going up?
                if (!this.goingup) {
                    drop = drop.next('.'+this.samenodeclass);
                }
                //Add the node
                e.drop.get('node').ancestor().insertBefore(drag, drop);
            } else if (drop.hasClass(this.parentnodeclass) && !drop.contains(drag)) {
                // We are dropping on parent node and it is empty
                if (this.goingup) {
                    drop.append(drag);
                } else {
                    drop.prepend(drag);
                }
            }
            this.drop_over(e);
        },

        global_drag_dropmiss : function(e) {
            // drag:dropmiss does not have e.drag and e.drop properties
            // we substitute them for the ease of use. For e.drop we use,
            // this.lastdroptarget (ghost node we use for indicating where to drop)
            e.drag = e.target;
            e.drop = this.lastdroptarget;
            // Check that drop object belong to correct group
            if (!e.drop || !e.drop.inGroup(this.groups)) {
                return;
            }
            this.drag_dropmiss(e);
        },

        global_drop_hit : function(e) {
            // Check that drop object belong to correct group
            if (!e.drop || !e.drop.inGroup(this.groups)) {
                return;
            }
            this.drop_hit(e);
        },

        /*
         * Abstract functions definitions
         */
        drag_start : function(e) {},
        drag_end : function(e) {},
        drag_drag : function(e) {},
        drag_dropmiss : function(e) {},
        drop_over : function(e) {},
        drop_hit : function(e) {}
    }, {
        NAME : 'dragdrop',
        ATTRS : {}
    });

M.core = M.core || {};
M.core.dragdrop = DRAGDROP;

}, '@VERSION@', {requires:['base', 'node', 'io', 'dom', 'dd', 'moodle-core-notification']});
<|endoftext|>


<commit_before>/**
 * @file Test script to test Bastion's successful booting
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

const Tesseract = xrequire('tesseract');

const configurations = xrequire('./settings/config_example.json');
const credentials = xrequire('./settings/credentials_example.json');
configurations.prefix = [ '!', '*' ];
credentials.token = 'MxjfutRSdOfjOPvxbvTladhT.XTalmy.xStT_kjfuOTladfjOPvxbvtRSdx';

const BASTION = new Tesseract.Client({
  configurations,
  credentials,
  disabledEvents: [
    'USER_NOTE_UPDATE',
    'TYPING_START',
    'RELATIONSHIP_ADD',
    'RELATIONSHIP_REMOVE'
  ]
});

BASTION.package = xrequire('./package.json');
BASTION.Constants = Tesseract.Constants;
BASTION.colors = Tesseract.Constants.Colors;
BASTION.permissions = Tesseract.Permissions.FLAGS;

// xrequire('./prototypes/Array.prototype');
xrequire('./prototypes/String.prototype');
xrequire('./prototypes/Number.prototype');

const WebhookHandler = xrequire('./handlers/webhookHandler.js');
BASTION.webhook = new WebhookHandler(BASTION.credentials.webhooks);
BASTION.log = xrequire('./handlers/logHandler');
BASTION.methods = xrequire('./handlers/methodHandler');

const StringHandler = xrequire('./handlers/stringHandler');
BASTION.i18n = new StringHandler();

const Sequelize = xrequire('sequelize');
BASTION.database = new Sequelize(BASTION.credentials.database.URI, {
  operatorsAliases: false,
  logging: false
});
BASTION.database.authenticate().then(() => {
  // Populate Database/Implement model definitions
  xrequire('./utils/models')(Sequelize, BASTION.database);

  // Load Bastion Events
  xrequire('./handlers/eventHandler')(BASTION);

  // Load Bastion Modules
  const Modules = xrequire('./handlers/moduleHandler');
  BASTION.commands = Modules.commands;
  BASTION.aliases = Modules.aliases;

  if (BASTION.commands && BASTION.aliases) {
    BASTION.log.info(`Successfully loaded ${BASTION.commands.size} commands`);
  }
  else {
    BASTION.log.error('Failed to load commands.');
    process.exit(1);
  }
}).catch(e => {
  BASTION.log.error(e.stack);
  process.exit(1);
});
<commit_msg>tests: use settingsDirectory Tesseract option in boot test<commit_after>/**
 * @file Test script to test Bastion's successful booting
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

const Tesseract = xrequire('tesseract');
const BASTION = new Tesseract.Client({
  settingsDirectory: './settings',
  disabledEvents: [
    'USER_NOTE_UPDATE',
    'TYPING_START',
    'RELATIONSHIP_ADD',
    'RELATIONSHIP_REMOVE'
  ]
});

BASTION.package = xrequire('./package.json');
BASTION.Constants = Tesseract.Constants;
BASTION.colors = Tesseract.Constants.Colors;
BASTION.permissions = Tesseract.Permissions.FLAGS;

// xrequire('./prototypes/Array.prototype');
xrequire('./prototypes/String.prototype');
xrequire('./prototypes/Number.prototype');

const WebhookHandler = xrequire('./handlers/webhookHandler.js');
BASTION.webhook = new WebhookHandler(BASTION.credentials.webhooks);
BASTION.log = xrequire('./handlers/logHandler');
BASTION.methods = xrequire('./handlers/methodHandler');

const StringHandler = xrequire('./handlers/stringHandler');
BASTION.i18n = new StringHandler();

const Sequelize = xrequire('sequelize');
BASTION.database = new Sequelize(BASTION.credentials.database.URI, {
  operatorsAliases: false,
  logging: false
});
BASTION.database.authenticate().then(() => {
  // Populate Database/Implement model definitions
  xrequire('./utils/models')(Sequelize, BASTION.database);

  // Load Bastion Events
  xrequire('./handlers/eventHandler')(BASTION);

  // Load Bastion Modules
  const Modules = xrequire('./handlers/moduleHandler');
  BASTION.commands = Modules.commands;
  BASTION.aliases = Modules.aliases;

  if (BASTION.commands && BASTION.aliases) {
    BASTION.log.info(`Successfully loaded ${BASTION.commands.size} commands`);
  }
  else {
    BASTION.log.error('Failed to load commands.');
    process.exit(1);
  }
}).catch(e => {
  BASTION.log.error(e.stack);
  process.exit(1);
});
<|endoftext|>


<commit_before>import Mn from 'backbone.marionette';

var OverlayView = Mn.ItemView.extend({
  className: 'overlay-view hide',

  // The OverlayView doesn't need a template: it's simply an element
  // that covers up the entirety of the application
  template: false,

  // Convert click DOM events into BB Events
  events: {
    click: '_handleClick'
  },

  // Shows the overlay. Then, when it's clicked, close it.
  display() {
    this.$el.removeClass('hide');
    this.once('click', this.hide);
  },

  hide() {
    // Ensure that the click event has been unregistered
    this.off('click');
    this.$el.addClass('hide');
    this.trigger('hide');
  },

  // Emit the `click` event if the overlay is clicked directly.
  // Otherwise, emit a `click:child` event.
  _handleClick(e) {
    var clickedSelf = e.target === e.currentTarget;
    var eventName = self ? 'click' : 'click:child';
    this.trigger(eventName);
  }
});

export default OverlayView;
<commit_msg>Attach to Mn<commit_after>import Mn from 'backbone.marionette';

var OverlayView = Mn.ItemView.extend({
  className: 'overlay-view hide',

  // The OverlayView doesn't need a template: it's simply an element
  // that covers up the entirety of the application
  template: false,

  // Convert click DOM events into BB Events
  events: {
    click: '_handleClick'
  },

  // Shows the overlay. Then, when it's clicked, close it.
  display() {
    this.$el.removeClass('hide');
    this.once('click', this.hide);
  },

  hide() {
    // Ensure that the click event has been unregistered
    this.off('click');
    this.$el.addClass('hide');
    this.trigger('hide');
  },

  // Emit the `click` event if the overlay is clicked directly.
  // Otherwise, emit a `click:child` event.
  _handleClick(e) {
    var clickedSelf = e.target === e.currentTarget;
    var eventName = self ? 'click' : 'click:child';
    this.trigger(eventName);
  }
});

Mn.OverlayView = OverlayView;

export default OverlayView;
<|endoftext|>


<commit_before>const { createCore/*, ALL*/ } = require(`../dist/core.umd.cjs`);

const createModuleMock = () => {
    const module = {
        started: 0,
        stopped: 0,
    };
    return Object.assign(module, {
        start() {
            module.started += 1;
        },
        stop() {
            module.stopped += 1;
        },
    });
};

let core;
describe(`Testing Core`, function () {

    beforeEach(function () {
        core = createCore();
    });

    afterEach(function () {
    });

    it(`should call start of that module`, async function () {
        const module = createModuleMock();
        await core.start(module);

        expect(module.started).toBe(1);
    });

    it(`should fail if start is undefined`, async function () {
        const module = createModuleMock();
        delete module[`start`];

        await expectAsync(
            core.start(module),
        ).toBeRejected();
    });

    it(`should call stop of that module`, async function () {
        const module = createModuleMock();
        const id = await core.start(module);
        await core.stop(id);

        expect(module.stopped).toBe(1);
    });

    it(`should not fail if stop is undefined`, async function () {
        const module = createModuleMock();
        delete module[`stop`];
        const id = await core.start(module);
        await core.stop(id);

        expect(module.started).toBe(1);
    });

    it(`should use the name as id if it was provided`, async function () {
        const name = `myName`;
        const module = createModuleMock();
        const id = await core.start(module, { name });

        expect(id).toBe(name);
    });

    it(`should allow multiple instances start`, async function () {
        const module = createModuleMock();
        await core.start(module);
        await core.start(module);

        expect(module.started).toBe(2);
    });

    it(`start multiple instances with the same name should throw`, async function () {
        const name = `myName`;
        const module = createModuleMock();
        await core.start(module, { name });

        await expectAsync(
            core.start(module, { name }),
        ).toBeRejected();
    });

    it(`should silently proceed if stop is called on something already stopped`, async function () {
        const module = createModuleMock();
        const id = await core.start(module);
        await core.stop(id);
        await core.stop(id);

        expect(module.stopped).toBe(1);
    });

    it(`stop should receive as first argument the return of the start`, async function () {
        const x = Symbol();
        const module = {
            start() {
                return x;
            },
            stop(arg1) {
                expect(arg1).toBe(x);
            },
        };
        const id = await core.start(module);
        await core.stop(id);
    });

    it(`start should receive an emitter to be able to communcicate with other modules`, async function () {
        const module = {
            start(emitter) {
                expect(emitter.on).toBeDefined();
                expect(emitter.off).toBeDefined();
                expect(emitter.emit).toBeDefined();
            },
        };
        await core.start(module);
    });

    it(`get state should return what the module returns`, async function () {
        const x = Symbol();
        const module = {
            start() {
            },
            getState() {
                return x;
            },
        };
        const name = `test`;
        await core.start(module, {name});
        const result = await core.getState(name);
        expect(result).toBe(x);
    });

    it(`get state should return empty object if not defined`, async function () {
        const name = `test`;
        await core.start(createModuleMock(), {name});
        const result = await core.getState(name);
        expect(result).toBeInstanceOf(Object);
    });

    it(`getAllStates should return an object with key values similar to getState`, async function () {
        const x = Symbol();
        const y = Symbol();
        const module1 = {
            start() {
            },
            getState() {
                return x;
            },
        };
        const module2 = {
            start() {
            },
            getState() {
                return y;
            },
        };
        const name1 = `test`;
        const name2 = `tes2`;
        await core.start(module1, {name: name1});
        await core.start(module2, {name: name2});
        const result = await core.getAllStates();
        expect(result[name1]).toBe(x);
        expect(result[name2]).toBe(y);
    });
});
<commit_msg>create test to prove issue<commit_after>const { createCore/*, ALL*/ } = require(`../dist/core.umd.cjs`);

const createModuleMock = () => {
    const module = {
        started: 0,
        stopped: 0,
    };
    return Object.assign(module, {
        start() {
            module.started += 1;
        },
        stop() {
            module.stopped += 1;
        },
    });
};

let core;
describe(`Testing Core`, function () {

    beforeEach(function () {
        core = createCore();
    });

    afterEach(function () {
    });

    it(`should call start of that module`, async function () {
        const module = createModuleMock();
        await core.start(module);

        expect(module.started).toBe(1);
    });

    it(`should fail if start is undefined`, async function () {
        const module = createModuleMock();
        delete module[`start`];

        await expectAsync(
            core.start(module),
        ).toBeRejected();
    });

    it(`should call stop of that module`, async function () {
        const module = createModuleMock();
        const id = await core.start(module);
        await core.stop(id);

        expect(module.stopped).toBe(1);
    });

    it(`should not fail if stop is undefined`, async function () {
        const module = createModuleMock();
        delete module[`stop`];
        const id = await core.start(module);
        await core.stop(id);

        expect(module.started).toBe(1);
    });

    it(`should use the name as id if it was provided`, async function () {
        const name = `myName`;
        const module = createModuleMock();
        const id = await core.start(module, { name });

        expect(id).toBe(name);
    });

    it(`should allow multiple instances start`, async function () {
        const module = createModuleMock();
        await core.start(module);
        await core.start(module);

        expect(module.started).toBe(2);
    });

    it(`start multiple instances with the same name should throw`, async function () {
        const name = `myName`;
        const module = createModuleMock();
        await core.start(module, { name });

        await expectAsync(
            core.start(module, { name }),
        ).toBeRejected();
    });

    it(`start multiple instances with the same name should throw without a-waiting`, async function () {
        const name = `myName`;
        const module = createModuleMock();
        core.start(module, { name });

        await expectAsync(
            core.start(module, { name }),
        ).toBeRejected();
    });

    it(`should silently proceed if stop is called on something already stopped`, async function () {
        const module = createModuleMock();
        const id = await core.start(module);
        await core.stop(id);
        await core.stop(id);

        expect(module.stopped).toBe(1);
    });

    it(`stop should receive as first argument the return of the start`, async function () {
        const x = Symbol();
        const module = {
            start() {
                return x;
            },
            stop(arg1) {
                expect(arg1).toBe(x);
            },
        };
        const id = await core.start(module);
        await core.stop(id);
    });

    it(`start should receive an emitter to be able to communcicate with other modules`, async function () {
        const module = {
            start(emitter) {
                expect(emitter.on).toBeDefined();
                expect(emitter.off).toBeDefined();
                expect(emitter.emit).toBeDefined();
            },
        };
        await core.start(module);
    });

    it(`get state should return what the module returns`, async function () {
        const x = Symbol();
        const module = {
            start() {
            },
            getState() {
                return x;
            },
        };
        const name = `test`;
        await core.start(module, {name});
        const result = await core.getState(name);
        expect(result).toBe(x);
    });

    it(`get state should return empty object if not defined`, async function () {
        const name = `test`;
        await core.start(createModuleMock(), {name});
        const result = await core.getState(name);
        expect(result).toBeInstanceOf(Object);
    });

    it(`getAllStates should return an object with key values similar to getState`, async function () {
        const x = Symbol();
        const y = Symbol();
        const module1 = {
            start() {
            },
            getState() {
                return x;
            },
        };
        const module2 = {
            start() {
            },
            getState() {
                return y;
            },
        };
        const name1 = `test`;
        const name2 = `tes2`;
        await core.start(module1, {name: name1});
        await core.start(module2, {name: name2});
        const result = await core.getAllStates();
        expect(result[name1]).toBe(x);
        expect(result[name2]).toBe(y);
    });
});
<|endoftext|>


<commit_before>'use strict';

define(['superagent', 'uri/URI'], function (superagent, URI) {
    class Printer {
        constructor(url) {
            this.url = new URI(url).normalize().href();
        }

        async print(format, data) {
            const url = new URI(this.url).segment('print').href();
            return (await superagent
                .post(url)
                .send({
                    format, data
                })).body;
        }

        async ports() {
            const url = new URI(this.url).segment('ports').href();
            return await getData(url);
        }

        async deleteFormat(format) {
            const url = new URI(this.url).segment('db/format').segmentCoded(format).href();
            return (await superagent.del(url)).body;
        }

        async saveFormat(key, value) {
            const url = new URI(this.url).segment('db/format').href();
            return (await superagent.put(url).send({key, value})).body;
        }

        async getFormat(format) {
            const url = new URI(this.url).segment('db/format').segmentCoded(format).href();
            return await getData(url);
        }

        async getAllFormats() {
            return getFormats();
        }

        async getFormats(kind) {
            if(!kind) {
                const url = new URI(this.url).segment('db/format').href();
                return (await superagent.get(url)).body;
            } else {
                const url = new URI(this.url).segment('db/format').segmentCoded(kind).href();
                return await getData(url);
            }
        }

        async getFormatNames(kind) {
            if(kind) {
                const url = new URI(this.url).segment('db/format/names').href();
                return await getData(url);
            } else {
                const url = new URI(this.url).segment('db/format').segmentCoded(kind).segment('names').href();
                return await getData(url);
            }
        }
    }

    async function getData(url) {
        return (await superagent.get(url)).body;
    }

    return Printer;
});
<commit_msg>update Printer<commit_after>'use strict';

define(['superagent', 'uri/URI'], function (superagent, URI) {
    class Printer {
        constructor(url) {
            this.url = new URI(url).normalize().href();
        }

        async print(format, data) {
            const url = new URI(this.url).segment('print').href();
            return (await superagent
                .post(url)
                .send({
                    format, data
                })).body;
        }

        async ports() {
            const url = new URI(this.url).segment('ports').href();
            return await getData(url);
        }

        async deleteFormat(format) {
            const url = new URI(this.url).segment('db/format').segmentCoded(format).href();
            return (await superagent.del(url)).body;
        }

        async saveFormat(key, value) {
            const url = new URI(this.url).segment('db/format').href();
            return (await superagent.put(url).send({key, value})).body;
        }

        async getFormat(format) {
            const url = new URI(this.url).segment('db/format').segmentCoded(format).href();
            return await getData(url);
        }

        async getAllFormats() {
            return getFormats();
        }

        async getFormats(kind) {
            if(!kind) {
                const url = new URI(this.url).segment('db/format').href();
                return (await superagent.get(url)).body;
            } else {
                const url = new URI(this.url).segment('db/format/kind').segmentCoded(kind).href();
                return await getData(url);
            }
        }

        async getFormatNames(kind) {
            if(kind) {
                const url = new URI(this.url).segment('db/format/names').href();
                return await getData(url);
            } else {
                const url = new URI(this.url).segment('db/format/kind').segmentCoded(kind).segment('names').href();
                return await getData(url);
            }
        }
    }

    async function getData(url) {
        return (await superagent.get(url)).body;
    }

    return Printer;
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jslint nomen:true*/

var test = require('tap').test,
    log = require('../log'),
    main = require('../');

// buffer log msgs instead of outputing them
log.pause();

function reset(t) {
    if (t) {
        t.same(log.record, log._buffer, 'records & buffer are same');
        t.ok(log.record.length, 'have records buffered');
    }
    log.record = log._buffer = [];
}

test('extra params err', function(t) {
    function cb(err) {
        t.equal(err, 'Unknown extra parameters.');
    }
    t.plan(1);
    main([1,2,3,4], {}, {}, cb);
});

test('no mojito err', function(t) {
    function cb(err) {
        t.equal(err, 'Cannot find mojito.');
    }
    t.plan(1);
    main([], {}, {}, cb);
});

test('no mojito schema err', function(t) {
    var meta = {mojito: {path: __dirname}};

    function cb(err) {
        t.equal(err, 'Cannot find mojito configuration schemas.');
    }

    t.plan(1);
    main([], {}, meta, cb);
});

test('mojito validate (someapp cwd)', function (t) {
    t.plan(2);
    reset();

    var oldcwd = process.cwd(),
        cwd = __dirname + '/fixtures/someapp',
        ymlFile = cwd + "/mojits/testMojit/definition.yaml",
        errors = [],
        warns = [],
        expectedWarnings = ["{ config: 'context[0] -> actionTimeout',\n  message: 'Instance is not a required type' }",
            "JS-YAML: missed comma between flow collection entries in \"" +
                ymlFile + "\" at line 3, column 20:\n            \"settings\" : [ \"master\" ],\n                       ^",
            "{ config: 'context[0] -> debugger',\n  message: 'Additional properties are not allowed' }",
            "{ config: 'context[0] -> search-advanced-page -> verbs[2]',\n  message: 'Instance is not one of the possible values: get,post,put,delete,GET,POST,PUT,DELETE' }",
            "Parse error on line 3:\n...\"master\" ]        \"config\": {        \n---------------------^\nExpecting 'EOF', '}', ',', ']', got 'STRING'"
            ],
        meta = {"mojito" : {
            "path": cwd + "/node_modules/mojito"
        }};

    log.on('log.error', function (m) {
        errors.push(m.message);
    });

    log.on('log.warn', function (m) {
        warns.push(m.message);
    });

    function cb(msg) {
        console.log(msg);
    }

    process.chdir(cwd);
    main([], null, meta, cb);
    setTimeout(function () {
        t.equals(errors.length, 4);
        t.same(warns, expectedWarnings);
        process.chdir(oldcwd);
    }, 3000);
});

test('mojito validate (someapp-ok cwd)', function (t) {
    t.plan(2);
    reset();

    var oldcwd = process.cwd(),
        cwd = __dirname + '/fixtures/someapp-ok',
        ymlFile = cwd + "/mojits/testMojit/definition.yaml",
        errors = [],
        warns = [],
        expectedWarnings = [],
        meta = {"mojito" : {
            "path": cwd + "/node_modules/mojito"
        }};

    log.on('log.error', function (m) {
        errors.push(m.message);
    });

    log.on('log.warn', function (m) {
        warns.push(m.message);
    });

    function cb(msg, zz) {
        console.log(msg, zz);
    }

    process.chdir(cwd);
    main([], null, meta, cb);
    setTimeout(function () {
        t.equals(errors.length, 0);
        t.same(warns, expectedWarnings);
        process.chdir(oldcwd);
    }, 3000);
});
<commit_msg>fix UT error<commit_after>/*
 * Copyright (c) 2011-2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jslint nomen:true*/

var test = require('tap').test,
    log = require('../log'),
    main = require('../');

// buffer log msgs instead of outputing them
log.pause();

function reset(t) {
    if (t) {
        t.same(log.record, log._buffer, 'records & buffer are same');
        t.ok(log.record.length, 'have records buffered');
    }
    log.record = log._buffer = [];
}

test('extra params err', function (t) {
    function cb(err) {
        t.equal(err, 'Unknown extra parameters.');
    }
    t.plan(1);
    main([1, 2, 3, 4], {}, {}, cb);
});

test('no mojito err', function (t) {
    function cb(err) {
        t.equal(err, 'Cannot find mojito.');
    }
    t.plan(1);
    main([], {}, {}, cb);
});

test('no mojito schema err', function (t) {
    var meta = {mojito: {path: __dirname}};

    function cb(err) {
        t.equal(err, 'Cannot find mojito configuration schemas.');
    }

    t.plan(1);
    main([], {}, meta, cb);
});

test('mojito validate (someapp cwd)', function (t) {
    t.plan(7);
    reset();

    var oldcwd = process.cwd(),
        cwd = __dirname + '/fixtures/someapp',
        ymlFile = cwd + "/mojits/testMojit/definition.yaml",
        errors = [],
        warns = [],
        expectedWarnings = ["{ config: 'context[0] -> actionTimeout',\n  message: 'Instance is not a required type' }",
            "JS-YAML: missed comma between flow collection entries in \"" +
                ymlFile + "\" at line 3, column 20:\n            \"settings\" : [ \"master\" ],\n                       ^",
            "{ config: 'context[0] -> debugger',\n  message: 'Additional properties are not allowed' }",
            "{ config: 'context[0] -> search-advanced-page -> verbs[2]',\n  message: 'Instance is not one of the possible values: get,post,put,delete,GET,POST,PUT,DELETE' }",
            "Parse error on line 3:\n...\"master\" ]        \"config\": {        \n---------------------^\nExpecting 'EOF', '}', ',', ']', got 'STRING'"
            ],
        meta = {"mojito" : {
            "path": cwd + "/node_modules/mojito"
        }};

    log.on('log.error', function (m) {
        errors.push(m.message);
    });

    log.on('log.warn', function (m) {
        warns.push(m.message);
    });

    function cb(msg) {
        console.log(msg);
    }

    process.chdir(cwd);
    main([], null, meta, cb);
    setTimeout(function () {
        var i = 0;
        t.equals(errors.length, 4);
        t.equals(warns.length, expectedWarnings.length);
        for (i = 0; i < warns.length; i = i + 1) {
            t.ok((expectedWarnings.indexOf(warns[i]) >= 0), "catch validation error successfully");
        }
        process.chdir(oldcwd);
    }, 3000);
});

test('mojito validate (someapp-ok cwd)', function (t) {
    t.plan(2);
    reset();

    var oldcwd = process.cwd(),
        cwd = __dirname + '/fixtures/someapp-ok',
        ymlFile = cwd + "/mojits/testMojit/definition.yaml",
        errors = [],
        warns = [],
        expectedWarnings = [],
        meta = {"mojito" : {
            "path": cwd + "/node_modules/mojito"
        }};

    log.on('log.error', function (m) {
        errors.push(m.message);
    });

    log.on('log.warn', function (m) {
        warns.push(m.message);
    });

    function cb(msg, zz) {
        console.log(msg, zz);
    }

    process.chdir(cwd);
    main([], null, meta, cb);
    setTimeout(function () {
        t.equals(errors.length, 0);
        t.same(warns, expectedWarnings);
        process.chdir(oldcwd);
    }, 3000);
});
<|endoftext|>


<commit_before>define('views/settings',
    ['forms', 'log', 'notification', 'requests', 'urls', 'user', 'z'],
    function(forms, log, notification, requests, urls, user, z) {

    var console = log('settings');

    function handleProfileUpdate(changes) {
        user.update_settings(changes);
        z.page.trigger('reload_chrome');
        require('views').reload().done(function() {
            notification.notification({message: gettext('Your settings have been saved')});
        });
    };
    function updateProfile($this) {
        forms.toggleSubmitFormState($this, false);

        var newUsername = $this.find('[name=username]').val();

        requests.put(urls.api.url('user.profile'), {
            username: newUsername
        }).done(function(data) {
            handleProfileUpdate(newData);
        }).fail(function(data) {
            // TODO: Show specific error messages for common error cases (ie. email already in use)
            console.error('Failed to update settings! Error:', data.response);
            notification.notification({message: gettext('Failed to update settings')});
            forms.toggleSubmitFormState($this, true);
        });
    };

    z.body.on('submit', 'form.edit-profile', function(e) {
        e.preventDefault();
        updateProfile($(this));
    });

    return function(builder, args) {
        builder.start('settings.html').done(function() {
        });

        builder.z('type', 'leaf settings');
        builder.z('title', gettext('Settings'));
    };
});
<commit_msg>Fixed a silly refactoring bug in settings.js<commit_after>define('views/settings',
    ['forms', 'log', 'notification', 'requests', 'urls', 'user', 'z'],
    function(forms, log, notification, requests, urls, user, z) {

    var console = log('settings');

    function handleProfileUpdate(changes) {
        user.update_settings(changes);
        z.page.trigger('reload_chrome');
        require('views').reload().done(function() {
            notification.notification({message: gettext('Your settings have been saved')});
        });
    };
    function updateProfile($this) {
        forms.toggleSubmitFormState($this, false);

        var newUsername = $this.find('[name=username]').val();
        var newData = {
            username: newUsername
        };

        requests.put(urls.api.url('user.profile'), newData).done(function(data) {
            handleProfileUpdate(newData);
        }).fail(function(data) {
            // TODO: Show specific error messages for common error cases (ie. email already in use)
            console.error('Failed to update settings! Error:', data.response);
            notification.notification({message: gettext('Failed to update settings')});
            forms.toggleSubmitFormState($this, true);
        });
    };

    z.body.on('submit', 'form.edit-profile', function(e) {
        e.preventDefault();
        updateProfile($(this));
    });

    return function(builder, args) {
        builder.start('settings.html').done(function() {
        });

        builder.z('type', 'leaf settings');
        builder.z('title', gettext('Settings'));
    };
});
<|endoftext|>


<commit_before>module.exports.sentry = {
    active: true,
    dsn: process.env.SENTRY_DSN,
    level: 'error'
};
<commit_msg>Trailing comma<commit_after>module.exports.sentry = {
    active: true,
    dsn: process.env.SENTRY_DSN,
    level: 'error',
};
<|endoftext|>


<commit_before>var Ajax;
if (Ajax && (Ajax != null)) {
	Ajax.Responders.register({
	  onCreate: function() {
        if($('spinner') && Ajax.activeRequestCount>0)
          Effect.Appear('spinner',{duration:0.5,queue:'end'});
	  },
	  onComplete: function() {
        if($('spinner') && Ajax.activeRequestCount==0)
          Effect.Fade('spinner',{duration:0.5,queue:'end'});
	  }
	});
}
<commit_msg>Added default argument support for javascript<commit_after>var Ajax;
if (Ajax && (Ajax != null)) {
	Ajax.Responders.register({
	  onCreate: function() {
        if($('spinner') && Ajax.activeRequestCount>0)
          Effect.Appear('spinner',{duration:0.5,queue:'end'});
	  },
	  onComplete: function() {
        if($('spinner') && Ajax.activeRequestCount==0)
          Effect.Fade('spinner',{duration:0.5,queue:'end'});
	  }
	});
}

Function.prototype.defaults = function()
{
  var _f = this;
  var _a = Array(_f.length-arguments.length).concat(
           Array.prototype.slice.apply(arguments));
  return function()
  {
    return _f.apply(_f, Array.prototype.slice.apply(arguments).concat(
      _a.slice(arguments.length, _a.length)));
  }
}
<|endoftext|>


<commit_before>function get(v, defaultValue) {
	return (typeof v === "undefined") ? defaultValue : v;
}

function initUI(io) {
	io.on('remove', function(data) {
		console.log(data.name + " removed!");
		$("#" + data.name + "_wrapper").remove();
	});

	var notifyChangeValue = function(key, value) {
			io.emit('change', {name: param.name, value: ui.value});
		},
		createLabel = function(text, isRight) {
			return $('
' + text + '
').button({disabled: true}).css({height: 25, fontSize: "80%"})
		}

	function createSlider(param, $main) {
		var min = get(param.option.min, 0),
			max = get(param.option.max, 1),
			initial = get(param.option.initial, 0.5);
		var $ui = $('

'),
			$wrapper = $('

'),
			$label = createLabel(param.name),
			$value = createLabel(initial, true);

		$wrapper
			.append($label)
			.append($ui)
			.append($value);

		$main.append($wrapper);

		var setValue = function(event, ui) {
			$value.button({label: ui.value});
			sendSocket(param.name, ui.value);
		}
		$ui.slider({
			min: min,
			max: max,
			value: initial,
			step: (max - min) / 256.0,
			start: setValue,
			slide: setValue,
			change: setValue,
			stop: setValue
		});
	}

	function createButton(param, $main) {

	}

	function createTextBox(param, $main) {

	}

	function createTextArea(param, $main) {

	}

	function createToggle(param, $main) {
		var initial = param.option.initial;

		var $ui = $('<input type="checkbox" id="' + param.name + '">' + param.name + ''),
			$wrapper = $('

'),
			$label = createLabel(param.name),
			$value = createLabel(initial, true);

		$wrapper
			.append($label)
			.append($ui)
			.append($value);
		$main.append($wrapper);

		$ui.button({height: 25, fontSize: "80%"});

		var setValue = function(event) {
			var selected = this.id.substr(this.id.length - 1);
			$value.button({label: "" + selected});

			notifyChangeValue(param.name, selected);
		};
		$ui.change(setValue);
	}

	function createFlags(param, $main) {

	}

	function createSelectOption(param, $main) {
   		var labels = param.option.labels || ["undefined"],
   			initial = param.option.initial || 0,
			htmlFragment = '
';
		for(var i = 0; i < labels.length; i++) {
			var checked = (i == initial) ? ' checked="checked"' : '';
			htmlFragment	+=	'<input type="radio" id=' + param.name + '_' + i + ' name="' + param.name + '"' + checked + '>'
							+	'' + labels[i] + '';
		}
		htmlFragment += '
';
		var $ui      = $(htmlFragment),
			$wrapper = $('

"'),
			$label = createLabel(param.name),
			$value = createLabel(initial, true);

		$wrapper
			.append($label)
			.append($ui)
			.append($value);
		$main.append($wrapper);

		$ui.buttonset().find("label").css({width: 360 / labels.length, height: 25, fontSize: "80%"});

		var setValue = function(event) {
			var selected = this.id.substr(this.id.length - 1);
			$value.button({label: "" + selected});

			notifyChangeValue(param.name, selected);
		};
		$ui.find('input[type=radio]').change(setValue);
	}

	function createColor(param, $main) {

	}

	return (function(UI) {
		UI.addParts = {
			slider:   createSlider,
			button:   createButton,
			text:     createTextBox,
			longText: createTextArea,
			toggle:   createToggle,
			flags:    createFlags,
			select:   createSelectOption,
			color:    createColor
		};
		UI.create = function(parameters, $main) {
			for(var i = 0; i < parameters.length; i++) {
				// console.log(parameters[i]);
				UI.addParts[parameters[i].type](parameters[i], $main);
			}
		};
		return UI;
	})({io: io});
}<commit_msg>fix fuckin mistake<commit_after>function get(v, defaultValue) {
	return (typeof v === "undefined") ? defaultValue : v;
}

function initUI(io) {
	io.on('remove', function(data) {
		console.log(data.name + " removed!");
		$("#" + data.name + "_wrapper").remove();
	});

	var notifyChangeValue = function(key, value) {
			io.emit('change', {name: key, value: value});
		},
		createLabel = function(text, isRight) {
			return $('
' + text + '
').button({disabled: true}).css({height: 25, fontSize: "80%"})
		}

	function createSlider(param, $main) {
		var min = get(param.option.min, 0),
			max = get(param.option.max, 1),
			initial = get(param.option.initial, 0.5);
		var $ui = $('

'),
			$wrapper = $('

'),
			$label = createLabel(param.name),
			$value = createLabel(initial, true);

		$wrapper
			.append($label)
			.append($ui)
			.append($value);

		$main.append($wrapper);

		var setValue = function(event, ui) {
			$value.button({label: ui.value});
			notifyChangeValue(param.name, ui.value);
		}
		$ui.slider({
			min: min,
			max: max,
			value: initial,
			step: (max - min) / 256.0,
			start: setValue,
			slide: setValue,
			change: setValue,
			stop: setValue
		});
	}

	function createButton(param, $main) {

	}

	function createTextBox(param, $main) {

	}

	function createTextArea(param, $main) {

	}

	function createToggle(param, $main) {
		var initial = param.option.initial;

		var $ui = $('<input type="checkbox" id="' + param.name + '">' + param.name + ''),
			$wrapper = $('

'),
			$label = createLabel(param.name),
			$value = createLabel(initial, true);

		$wrapper
			.append($label)
			.append($ui)
			.append($value);
		$main.append($wrapper);

		$ui.button({height: 25, fontSize: "80%"});

		var setValue = function(event) {
			var selected = this.id.substr(this.id.length - 1);
			$value.button({label: "" + selected});

			notifyChangeValue(param.name, selected);
		};
		$ui.change(setValue);
	}

	function createFlags(param, $main) {

	}

	function createSelectOption(param, $main) {
   		var labels = param.option.labels || ["undefined"],
   			initial = param.option.initial || 0,
			htmlFragment = '
';
		for(var i = 0; i < labels.length; i++) {
			var checked = (i == initial) ? ' checked="checked"' : '';
			htmlFragment	+=	'<input type="radio" id=' + param.name + '_' + i + ' name="' + param.name + '"' + checked + '>'
							+	'' + labels[i] + '';
		}
		htmlFragment += '
';
		var $ui      = $(htmlFragment),
			$wrapper = $('

"'),
			$label = createLabel(param.name),
			$value = createLabel(initial, true);

		$wrapper
			.append($label)
			.append($ui)
			.append($value);
		$main.append($wrapper);

		$ui.buttonset().find("label").css({width: 360 / labels.length, height: 25, fontSize: "80%"});

		var setValue = function(event) {
			var selected = this.id.substr(this.id.length - 1);
			$value.button({label: "" + selected});

			notifyChangeValue(param.name, selected);
		};
		$ui.find('input[type=radio]').change(setValue);
	}

	function createColor(param, $main) {

	}

	return (function(UI) {
		UI.addParts = {
			slider:   createSlider,
			button:   createButton,
			text:     createTextBox,
			longText: createTextArea,
			toggle:   createToggle,
			flags:    createFlags,
			select:   createSelectOption,
			color:    createColor
		};
		UI.create = function(parameters, $main) {
			for(var i = 0; i < parameters.length; i++) {
				// console.log(parameters[i]);
				UI.addParts[parameters[i].type](parameters[i], $main);
			}
		};
		return UI;
	})({io: io});
}<|endoftext|>


<commit_before>const keyMirror = require('keymirror');

const Actions = keyMirror({
  DISCORD_READY: null,
  DISCORD_FOUND_CORRECT_SERVER: null,
  DISCORD_FOUND_VOICE_CHANNEL: null,
  DISCORD_JOINED_VOICE_CHANNEL: null,

  START_MUSIC_PLAYBACK: null,
  ICY_CONNECTED: null,
  ICY_METADATA: null,

  SET_AUDIO_VOLUME: null,

  NOW_PLAYING_SONG: null,
  NEXT_SONG: null,
  PREVIOUS_SONG: null,
  PAUSE_SONG: null,
  RESUME_SONG: null,
  PLAY_PLAYLIST_POSITION: null,
  DISPLAY_PLAYLIST: null,

  QUEUE_DISPLAY_NOW_PLAYING: null,
  QUEUE_DISPLAY_PLAYLIST: null,
  QUEUE_ITEM: null,
  QUEUE_SKIP: null,
  QUEUE_DONE_ITEM: null,

  NICEHASH_DISPLAY: null,

  STATUS_SYS_INFO: null,
  STATUS_USER_INFO: null,
});

module.exports = Actions;
<commit_msg>actions: remove actions for transitioned modules<commit_after>const keyMirror = require('keymirror');

const Actions = keyMirror({
  DISCORD_READY: null,
  DISCORD_FOUND_CORRECT_SERVER: null,
  DISCORD_FOUND_VOICE_CHANNEL: null,
  DISCORD_JOINED_VOICE_CHANNEL: null,

  START_MUSIC_PLAYBACK: null,
  ICY_CONNECTED: null,
  ICY_METADATA: null,

  STATUS_SYS_INFO: null,
  STATUS_USER_INFO: null,
});

module.exports = Actions;
<|endoftext|>