language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class Collection {
/**
* Creates the collection instance and initializes the value buffer.
*
* @param {Number} size - The number of values to buffer.
* @access public
*/
constructor(size) {
this.values = new NanoBuffer(size);
this.min = null;
this.max = null;
this.avg = null;
}
/**
* Adds a value to the collection and recomputes the minimum, maximum, and average.
*
* @param {Number} value - The value to add to the collection.
* @returns {Collection}
* @access public
*/
add(value) {
if (typeof value !== 'number' || isNaN(value)) {
throw TypeError('Expected value to be a number');
}
this.values.push(value);
if (this.values.size === 1) {
this.min = this.max = this.avg = value;
} else {
let total = 0;
for (const counter of this.values) {
total += counter;
if (counter < this.min) {
this.min = counter;
}
if (counter > this.max) {
this.max = counter;
}
}
this.avg = total / this.values.size;
}
return this;
}
/**
* Returns a snapshot of the contents of this collection.
*
* @returns {Object}
* @access public
*/
get stats() {
return {
values: Array.from(this.values),
min: this.min,
max: this.max,
avg: this.avg
};
}
} |
JavaScript | class AvatarView extends BaseUpdateView {
/**
* @param {ViewModel} value view model with {avatarUrl, avatarColorNumber, avatarTitle, avatarLetter}
* @param {Number} size
*/
constructor(value, size) {
super(value);
this._root = null;
this._avatarUrl = null;
this._avatarTitle = null;
this._avatarLetter = null;
this._size = size;
}
_avatarUrlChanged() {
if (this.value.avatarUrl(this._size) !== this._avatarUrl) {
this._avatarUrl = this.value.avatarUrl(this._size);
return true;
}
return false;
}
_avatarTitleChanged() {
if (this.value.avatarTitle !== this._avatarTitle) {
this._avatarTitle = this.value.avatarTitle;
return true;
}
return false;
}
_avatarLetterChanged() {
if (this.value.avatarLetter !== this._avatarLetter) {
this._avatarLetter = this.value.avatarLetter;
return true;
}
return false;
}
mount(options) {
this._avatarUrlChanged();
this._avatarLetterChanged();
this._avatarTitleChanged();
this._root = renderStaticAvatar(this.value, this._size);
// takes care of update being called when needed
super.mount(options);
return this._root;
}
root() {
return this._root;
}
update(vm) {
// important to always call _...changed for every prop
if (this._avatarUrlChanged()) {
// avatarColorNumber won't change, it's based on room/user id
const bgColorClass = `usercolor${vm.avatarColorNumber}`;
if (vm.avatarUrl(this._size)) {
this._root.replaceChild(renderImg(vm, this._size), this._root.firstChild);
this._root.classList.remove(bgColorClass);
} else {
this._root.textContent = vm.avatarLetter;
this._root.classList.add(bgColorClass);
}
}
const hasAvatar = !!vm.avatarUrl(this._size);
if (this._avatarTitleChanged() && hasAvatar) {
const element = this._root.firstChild;
if (element.tagName === "IMG") {
element.setAttribute("title", vm.avatarTitle);
}
}
if (this._avatarLetterChanged() && !hasAvatar) {
this._root.textContent = vm.avatarLetter;
}
}
} |
JavaScript | class ContactList extends Component {
render() {
let {contactList} = this.props;
return (
<div className="row top-buffer" id="contacts">
<div className="col-xs-12" id="contacts-header">
<h4>Contacts</h4>
</div>
<div className="col-xs-12 top-buffer-small">
<table className="table table table-bordered table-hover table-striped" id="contacts-table">
<thead>
<tr>
<th>Name</th>
<th>Phone Number</th>
</tr>
</thead>
<tbody>
{contactList.map(({phone_number, name = "Unknown"}) => {
return(
<tr key={name} onClick={() => this.props.onNumberSelect(phone_number)}>
<td>{name}</td>
<td>{phone_number}</td>
</tr>
)
})}
</tbody>
</table>
</div>
</div>
)
}
} |
JavaScript | class Coins {
constructor(coins) {
this.coins = coins
this.total = this.calculateTotal(coins)
}
/**
* Set item stock
* @param {Object} coins - new coin stock
* @return {number} total - value of coins
*/
set(coins) {
this.coins = coins
this.total = this.calculateTotal(coins)
return this.total
}
/**
* Get item stock
* @param {Object} coins - coin stock
*/
get() {
return this.coins
}
/**
* Get coin value
* @param {string} coin - coin type
* @return {number} value - coin value
*/
getValue(coin) {
return COINS.find(([coinName]) => coinName === coin)[1]
}
/**
* Refill coin stock
* @param {Object} coins - coin quantities
* @return {number} total - updated coin stock value
*/
refill(coins) {
this.set(
Object.keys(coins).reduce((acc, coin) => {
if (acc[coin] && acc[coin] > 0) {
return (acc[coin] = acc[coin] + coins[coin])
} else {
return {...acc, [coin]: coins[coin]}
}
}, this.coins),
)
return this.total
}
/**
* Find largest in stock coin
* @param {number} amount - coin quantity
* @param {Object} coins - coin quantities
* @return {string} coin - coin type
*/
findLargestCoin(amount, coins) {
const largestCoin = COINS.find(([coin, value]) => {
const inStock = coins[coin] > 0
return inStock && amount - value >= 0
})
if (!largestCoin) throw new Error('COINS_OUT_OF_STOCK')
return largestCoin[0]
}
/**
* Process purchase coins
* @param {number} amount - purchase value
* @param {Object} coins - coin quantities
* @param {Object} change - change coin quantities
*/
purchase(amount, coins) {
const coinsValue = this.calculateTotal(coins)
const changeAmount = coinsValue - amount
if (changeAmount < 0) throw new Error('LOW_PAYMENT')
let remainingChange = changeAmount
let coinStock = {...this.coins}
// include purchase coins in coin stock
coinStock = Object.keys(coins).reduce((acc, coin) => {
if (acc[coin] && acc[coin] > 0) {
return {...acc, [coin]: acc[coin] + coins[coin]}
} else {
return {...acc, [coin]: coins[coin]}
}
}, coinStock)
const change = {}
while (remainingChange > 0.03) {
const nextCoin = this.findLargestCoin(
remainingChange,
coinStock,
)
// update coin stock copy
coinStock[nextCoin] -= 1
// update change obj
if (change[nextCoin]) change[nextCoin]++
else change[nextCoin] = 1
remainingChange -= this.getValue(nextCoin)
}
this.set(coinStock)
return change
}
/**
* Calculate total value of coins
* @param {Object} coins - coin quantities
* @return {number} total - total coin value
*/
calculateTotal(coins) {
// TODO: cache and return on shallow object compare
return Object.keys(coins).reduce((total, coin) => {
switch (coin) {
case 'TWO_DOLLAR':
return total + coins[coin] * 2
case 'DOLLAR':
return total + coins[coin] * 1
case 'QUARTER':
return total + coins[coin] * 0.25
case 'DIME':
return total + coins[coin] * 0.1
case 'NICKEL':
return total + coins[coin] * 0.05
default:
return total
}
}, 0)
}
} |
JavaScript | class Model {
/**
*
* @param {*} pymodel the Python model.
*/
constructor(pymodel) {
this.pymodel = pymodel;
}
/**
* Compile the model.
* @param {object} opts
* @param {string} opts.optimizer
* @param {*} opts.loss
* @param {*} opts.metrics
*/
compile(opts) {
return this.pymodel.compile(boa.kwargs(opts));
}
/**
* Train the model with tensor x and y.
* @param {*} x
* @param {*} y
* @param {*} opts
* @param {*} opts.epochs
*/
fit(x, y, opts) {
return this.pymodel.fit(x, y, boa.kwargs(opts));
}
/**
* Evaluate the model.
* @param {*} x
* @param {*} y
* @param {*} opts
* @param {number} opts.verbose
*/
evaluate(x, y, opts) {
return this.pymodel.fit(x, y, boa.kwargs(opts));
}
/**
* Generates output predictions for the input samples.
* @param {*} x
* @param {*} opts
*/
predict(x, opts) {
return this.pymodel.predict(x, boa.kwargs(opts));
}
/**
* Save the model.
* @param {*} path
*/
save(pathname) {
return this.pymodel.save(pathname);
}
/**
* Output the summary of this model.
*/
summary() {
return this.pymodel.summary();
}
/**
* set the current model if trainable.
*/
setTrainable(val) {
this.pymodel.trainable = !!val;
}
/**
* Returns a JSON/YAML string containing the network configuration.
* @param {*} format
*/
toString(format = 'json') {
if (format === 'yaml') {
return this.pymodel.to_yaml();
} else {
return this.pymodel.to_json();
}
}
} |
JavaScript | class Tool {
static registry = {}
/** Default values that we don't want to bury in the code. */
static defaults = {
RUNNER_TEMP: process.env.RUNNER_TEMP ?? "/tmp/runner",
}
get defaults() {
return this.constructor.defaults
}
/** Accessors for the statics declared on subclasses. */
get tool() {
return this.constructor.tool
}
get toolVersion() {
return (
this.constructor.toolVersion ?? `${this.constructor.tool} --version`
)
}
get envVar() {
return this.constructor.envVar
}
get envPaths() {
const paths = this.constructor.envPaths ?? ["bin"]
return Array.isArray(paths) ? paths : [paths]
}
get installer() {
return this.constructor.installer
}
get installerPath() {
return this.constructor.installerPath ?? `.${this.installer}`
}
get installerVersion() {
return (
this.constructor.installerVersion ?? `${this.installer} --version`
)
}
/**
* Make a new Tool instance.
* @param {string} name - Tool name passed from subclass.
*/
constructor(name) {
this.name = name
const required = ["tool", "envVar", "installer"]
for (const member of required) {
if ((this.constructor[member] ?? null) == null) {
throw new Error(
`${this.constructor.name}: missing required member '${member}'`,
)
}
}
// Create logger wrapper functions for this tool
const loggers = ["debug", "info", "warning", "notice", "error"]
loggers.forEach((logger) => {
this[logger] = (...msg) => this.log(logger, msg)
})
}
// Log a message using method from core and msg prepended with the name
log(method, msg) {
if (Array.isArray(msg)) {
if (this.name) msg = `[${this.name}]\t${msg.join(" ")}`
else msg = msg.join(" ")
}
core[method](msg)
}
// determines the desired version of the tool (e.g. terraform) that is being requested.
// if the desired version presented to the action is present, that version is
// honored rather than the version presented in the version file (e.g. .terraform-version)
// that can be optionally present in the checked out repo itself.
// Second value returned indicates whether or not the version returned has overridden
// the version from the repositories tool version file.
getVersion(actionDesiredVersion, repoToolVersionFilename) {
this.debug(`getVersion: ${repoToolVersionFilename}`)
// Check if we have any version passed in to the action (can be null/empty string)
if (actionDesiredVersion) return [actionDesiredVersion, true]
if (fs.existsSync(repoToolVersionFilename)) {
let textRead = fs.readFileSync(repoToolVersionFilename, {
encoding: "utf8",
flag: "r",
})
const readToolVersionNumber = textRead ? textRead.trim() : textRead
this.debug(
`Found version ${readToolVersionNumber} in ${repoToolVersionFilename}`,
)
if (readToolVersionNumber && readToolVersionNumber.length > 0)
return [readToolVersionNumber, false]
}
// No version has been specified
return [null, null]
}
/**
* Return an array of the found version strings in `text`.
* @param {string} text - Text to parse looking for versions.
* @returns {Array} - Found version strings.
*/
versionParser(text) {
return findVersions(text, { loose: true })
}
/**
* Run `cmd` with environment `env` and resolves the promise with any
* parsable version strings in an array. provide true for
* useLooseVersionFinding when the expected version string contains
* non-version appearing values such as go1.16.8.
* @param {string} cmd - Command to run to find version output.
* @param {boolean} soft - Set to a truthy value to skip hard failure.
* @returns {string} - The version string that was found.
*/
async version(cmd, soft) {
silly(`version cmd: ${cmd}`)
let check = this.subprocessShell(cmd, { silent: true })
.then((proc) => {
if (proc.stdout) {
let stdoutVersions = this.versionParser(proc.stdout)
if (stdoutVersions) return stdoutVersions
}
if (proc.stderr) {
return this.versionParser(proc.stderr)
}
this.debug("version: no output parsed")
return []
})
.then((versions) => {
if (!versions || versions.length < 1) {
throw new Error(`${cmd}: no version found`)
}
this.info(`${cmd}: ${versions[0]}`)
return versions[0]
})
// This is a hard check and will fail the action
if (!soft) {
return check.catch(this.logAndExit(`failed to get version: ${cmd}`))
}
return check.catch((err) => {
silly(`version error: ${err}`)
// Return a soft/empty version here
if (/Unable to locate executable file:/.test(err.message)) {
return null
}
// Otherwise re-throw
throw err
})
}
// validateVersion returns the found current version from a subprocess which
// is compared against the expected value given
async validateVersion(expected) {
const command = this.toolVersion
this.debug(`validateVersion: ${expected}: ${command}`)
let version = await this.version(command)
if (expected != version) {
this.debug(`found command ${io.which(command.split(" ")[0])}`)
// this.debug(process.env.PATH)
this.logAndExit(`version mismatch ${expected} != ${version}`)(
new Error("version mismatch"),
)
}
return version
}
/**
* Return true if `version` is not empty.
*
* @param {string} version
* @returns
*/
async haveVersion(version) {
if (!version || version.length < 1) {
this.debug("skipping setup, no version found")
return false
}
this.info(`Desired version: ${version}`)
if (process.env.IGNORE_INSTALLED) {
this.info(" not checking for installed tools")
return true
}
this.debug("checking for installed version")
const found = await this.version(this.toolVersion, true).catch(
(err) => {
if (
/^subprocess exited with non-zero code:/.test(err.message)
) {
// This can happen if there's no default version, so we
// don't want to hard error here
return null
}
throw err
},
)
// this.debug(`found version: ${found}`)
if (!found) return true
// Just export the environment blindly if we have a version
this.setEnv()
const semantic = `^${version.replace(/\.\d+$/, ".x")}`
const ok = semver.satisfies(found, semantic)
if (!ok) {
this.info(
`Installed tool version ${found} does not satisfy ` +
`${semantic}...`,
)
return true
}
this.info(
`Found installed tool version ${found} that satisfies ${semantic},` +
` skipping setup...`,
)
return false
}
/**
* Invokes `cmd` with environment `env` and resolves the promise with
* an object containing the output and any error that was caught
* @param {string} cmd - Command to run.
* @param {Object} opts - Subprocess options.
*/
async subprocess(cmd, opts = { silent: false }) {
let proc = {
stdout: "",
stderr: "",
err: null,
exitCode: 0,
}
silly(`subprocess env exists?: ${!!opts.env}`)
// Always merge the passed environment on top of the process environment so
// we don't lose execution context
// opts.env = opts.env ?? { ...process.env, ...(await this.getEnv()) }
// opts.env = opts.env ?? { ...process.env }
// this.debug("subprocess got env")
// This lets us inspect the process output, otherwise an error is thrown
// and it is lost
opts.ignoreReturnCode = opts.ignoreReturnCode ?? true
// this.debug(`subprocess cmd: ${cmd}`)
// let args = shellQuote.parse(cmd)
let args = this.tokenizeArgs(cmd)
// this.debug(`subprocess args: ${args}`)
cmd = args.shift()
return new Promise((resolve, reject) => {
getExecOutput(cmd, args, opts)
.then((result) => {
if (result.exitCode > 0) {
let err = new Error(
`subprocess exited with non-zero code: ${cmd}`,
)
err.exitCode = result.exitCode
err.stdout = result.stdout
err.stderr = result.stderr
err.env = { ...opts.env }
reject(err)
return
}
proc.exitCode = result.exitCode
proc.stdout = result.stdout
proc.stderr = result.stderr
proc.env = { ...opts.env }
resolve(proc)
})
.catch((err) => {
if (/^Unable to locate executable file/.test(err.message)) {
this.debug(`'${cmd.split(" ")[0]}' not on PATH`)
silly(`PATH = ${opts.env.PATH}`)
}
reject(err)
})
})
}
/**
* Run `cmd` with options `opts` in a bash subshell to ensure the PATH
* environment is set.
* @param {String} cmd - Command to run.
* @param {Object} opts - Subprocess options.
* @returns
*/
async subprocessShell(cmd, opts) {
opts = opts ?? {}
const escaped = cmd.replace(/"/g, '\\"')
const cmdName = this.tokenizeArgs(cmd).shift()
const shell = `bash -c "` + escaped + `"`
const name = opts.check ? "\tcheckExecutableExists" : "subprocessShell"
silly(`${name} running: ${cmd}`)
silly(`${name} env exists? ${!!opts.env}`)
opts.env = opts.env ?? { ...process.env, ...(await this.getEnv()) }
if (process.env.SILLY_LOGGING) {
let paths = opts.env.PATH.split(":").filter((i) =>
i.includes(this.installer),
)
if (!paths) silly(`${name} no matching PATH`)
else silly(`${name} matching PATH=`)
paths.forEach((p) => silly(`${name} \t${p}`))
}
let cmdExists
if (!opts.check) {
silly(`subprocessShell: ${shell}`)
const checkOpts = { ...opts, silent: true, check: true }
cmdExists = await this.subprocessShell(
`command -v ${cmdName}`,
checkOpts,
)
.then((proc) => {
silly(`\tcommand exists: ${proc.stdout.trim()}`)
return true
})
.catch(() => {
silly(`\tcommand does not exist: ${cmdName}}`)
return false
})
} else {
silly(`${name} checking: ${shell}`)
}
delete opts.check
const proc = await this.subprocess(shell, opts).catch((err) => {
silly(`${name} caught error: ${err}`)
if (
/^subprocess exited with non-zero code: bash/.test(err.message)
) {
if (cmdExists) {
silly(`${name} command exists: ${cmd}, but failed`)
silly(`\t${err.stderr}`)
err.message = `subprocess exited with non-zero code: ${cmd}`
// this.debug(`subprocessShell error: ${err.stderr}`)
} else {
silly(`${name} command does not exist`)
err.message = `Unable to locate executable file: ${cmdName}`
}
}
silly(`${name} throwing...`)
throw err
})
return proc
}
/**
* Return `cmd` split into arguments using basic quoting.
*
* This has only limited token parsing powers, so full Bash quoting and
* variables and newlines or line continuations will break things.
*
* @param {string} cmd
* @returns
*/
tokenizeArgs(cmd) {
let last = 0
let peek = last
const tokens = []
let escaped = false
let quoted = null
let quote = 0
const tokenize = () => {
// Empty string, skip it
if (last == peek) return
// Grab the token
let token = cmd.slice(last, peek)
// Replace escaped whitespace with a space
token = token.replace(/\\ /g, " ")
tokens.push(token)
}
while (peek < cmd.length) {
let char = cmd[peek]
// this.debug(` ${char} ${!!quoted}\t${escaped}`)
switch (char) {
case "'":
case '"':
// Escaped quotes aren't handled lexographically
if (escaped && quoted != char) break
else if (escaped) {
// If it's escaped and the char we're escaping is the
// same as our quote, remove the escaping since it won't
// be needed in the final token
cmd =
cmd.slice(0, peek - 1) + cmd.slice(peek, cmd.length)
peek--
break
}
// If we have an open quote and we're hitting the same one,
// and we're not escaped, that will close the quote and the
// next whitespace character will signify the token end
if (quoted && quoted == char) {
// Here we have to strip the quotes from the original
// string(!) so they are processed correctly
// (e.g. "foo"bar"baz" -> foo"bar"baz)
cmd =
cmd.slice(0, quote) +
cmd.slice(quote + 1, peek) +
cmd.slice(peek + 1, cmd.length)
peek -= 2 // Removed quote length
quoted = null
quote = 0
} else if (!quoted) {
quoted = char
quote = peek
}
break
case "`":
// Backticks are handled separately because they should not
// be removed from the tokens
if (escaped) break
if (quoted && quoted == char) {
quoted = null
quote = 0
} else if (!quoted) {
quoted = char
quote = peek
}
break
case `\\`:
escaped = true
peek++
continue
case `\n`:
case ` `:
if (quoted) break
if (escaped) break
// If we're not quoting or escaping this whitespace, then we
// found a token
tokenize()
last = peek + 1
break
}
escaped = false
peek++
}
tokenize()
return tokens
}
// logAndExit logs the error message from a subprocess and sets the failure
// message for the Action and exits the process entirely
logAndExit(msg) {
return (err) => {
if (err) this.error(err)
core.setFailed(msg)
throw err
}
}
/**
* This checks if the installer tool, e.g. nodenv, is present and
* functional, otherwise it will run the install() method to install it.
*/
async findInstaller() {
this.info(`Finding installer: ${this.installerVersion}`)
const found = await this.version(this.installerVersion, true)
if (found) {
this.info("Installer found, setting environment")
await this.setEnv()
return
}
this.info("Installer not found... attempting to install")
let root = await this.findRoot()
root = await this.install(root)
this.info("Install finished, setting environment")
await this.setEnv(root)
this.info("Checking version")
return this.version(this.installerVersion).catch((err) => {
this.debug(`version check failed: ${err.exitCode}`)
this.debug(` stdout: ${err.stdout}`)
this.debug(` stderr: ${err.stderr}`)
throw err
})
}
/**
* Return a temporary directory suitable for installing our tool within.
* @returns {string} - Temporary directory path.
*/
get tempRoot() {
if (this._tempRoot) return this._tempRoot
this._tempRoot = this.constructor.tempRoot()
return this._tempRoot
}
/**
* Create and return a new temporary directory for installing our tool.
* @returns {string} - Temporary directory path.
*/
static tempRoot() {
const root = path.join(
this.defaults.RUNNER_TEMP,
this.tool,
crypto.randomUUID(),
this.installerPath ?? `.${this.installer}`,
)
core.debug(`[${this.tool}]\tCreating temp root: ${root}`)
fs.mkdirSync(root, { recursive: true })
return root
}
/**
* Return the default root path to where the tool likes to be installed.
*/
get defaultRoot() {
return path.join(os.homedir(), this.installerPath)
}
/**
* Return the path to the tool installation directory, if found, otherwise
* return the default path to the tool.
*
* @returns {String} - Path to the root folder of the tool.
*/
async findRoot() {
const tool = this.installer
const toolEnv = this.envVar
let toolPath = process.env[toolEnv]
// Return whatever's currently set if we have it
if (toolPath) {
this.debug(`${toolEnv} set from environment: ${toolPath}`)
if (!fs.existsSync(toolPath)) {
throw new Error(
`${toolEnv} misconfigured: ${toolPath} does not exist`,
)
}
return toolPath
}
// Default path is ~/.<dir>/ since that's what our CI uses and most of
// the tools install there too
const defaultPath = this.defaultRoot
// Use a subshell get the command path or function name and
// differentiate in a sane way
const defaultEnv = {
...process.env,
...(await this.getEnv(defaultPath)),
}
const check = `sh -c "command -v ${tool}"`
const proc = await this.subprocess(check, {
env: defaultEnv,
silent: true,
}).catch(() => {
this.debug("command -v failed, using default path")
return { stdout: defaultPath }
})
toolPath = proc.stdout ? proc.stdout.trim() : ""
if (toolPath == tool) {
// This means it's a function from the subshell profile
// somewhere, so we just have to use the default
this.debug("Found tool path as function name")
return defaultPath
}
if (!fs.existsSync(toolPath)) {
// This is a weird error case
this.debug(`tool root does not exist: ${toolPath}`)
this.debug(`using temp root: ${this.tempRoot}`)
return this.tempRoot
}
// Walk down symbolic links until we find the real path
while (toolPath) {
const stat = await fsPromises.lstat(toolPath).catch((err) => {
this.error(err)
return defaultPath
})
if (!stat.isSymbolicLink()) break
let link = await fsPromises.readlink(toolPath).catch((err) => {
this.error(err)
return defaultPath
})
// Make sure we can resolve relative symlinks which Homebrew uses
toolPath = path.resolve(path.dirname(toolPath), link)
}
const re = new RegExp(`/(bin|libexec)/${tool}$`)
toolPath = toolPath.replace(re, "")
if (fs.existsSync(toolPath)) return toolPath
let err = `${toolEnv} misconfigured: ${toolPath} does not exist`
this.error(err)
throw new Error(err)
}
/**
* Subclasses should implement install to install our installer tools.
* @param {string} root - The root install directory for the tool.
*/
async install(root) {
const err = "install not implemented"
this.debug(`attempting to install to ${root}`)
this.error(err)
throw new Error(err)
}
/**
* Downloads a url and optionally untars it
* @param {string} url - The url to download.
* @param {(string|{dest: string, strip: number})} tar - Path to extract
* tarball to, or tar options.
* @returns {string} The path to the downloaded or extracted file.
*/
async downloadTool(url, tar) {
this.debug(`downloadTool: ${url}`)
// This is really only used to support the test environment...
if (!process.env.RUNNER_TEMP) {
this.debug(
"RUNNER_TEMP required by tool-cache, setting a sane default",
)
process.env.RUNNER_TEMP = this.defaults.RUNNER_TEMP
}
const download = await toolCache.downloadTool(url)
// Straightforward download to temp directory
if (!tar) return download
// Extract the downloaded tarball
tar = tar ?? {}
// Allow simple destination extract string
if (typeof tar === "string") tar = { dest: tar }
// Match default args for tool-cache
tar.args = tar.args ?? ["-xz"]
// Allow stripping directories
if (tar.strip) tar.args.push(`--strip-components=${tar.strip}`)
// Extract the tarball
const dir = await toolCache.extractTar(download, tar.dest, tar.args)
// Try to remove the downloaded file now that we have extracted it, but
// allow it to happen async and in the background, and we don't care if
// it fails
await fsPromises.rm(download, { recursive: true }).catch(() => {})
// Return the extracted directory
return dir
}
/**
* Build and return an environment object suitable for calling subprocesses
* consistently.
* @param {string} root - Root directory of this tool.
* @returns {Object} - Environment object for use in subprocesses.
*/
async getEnv(root) {
silly(`getEnv: ${root}`)
root = root ?? (await this.findRoot())
const env = {}
let envPath = process.env.PATH ?? ""
const testPath = `:${envPath}:`
for (let dir of this.envPaths) {
dir = path.join(root, dir)
if (testPath.includes(`:${dir}:`)) continue
envPath = this.addPath(dir, envPath)
}
env.PATH = envPath
env[this.envVar] = root
return env
}
/**
* Export the environment settings for this tool to work correctly.
* @param {string} root - The root installer directory for our tool.
*/
async setEnv(root) {
root = root ?? (await this.findRoot())
core.exportVariable(this.envVar, root)
for (const dir of this.envPaths) {
core.addPath(path.join(root, dir))
}
}
/**
* Modifies and de-duplicates PATH strings.
* @param {string} newPath - Path to add to exising PATH.
* @param {string} path - PATH string from environment.
* @returns {string} - New PATH value.
*/
addPath(newPath, path = process.env.PATH) {
path = path.split(":").filter((p) => p != "")
path.push(newPath)
path = [...new Set(path)]
path = path.join(":")
return path
}
// register adds name : subclass to the tool registry
static register() {
this.registry[this.tool] = this
}
// all returns an array of objects containing the tool name and the bound
// setup function of a tool instance
static all() {
return Object.keys(this.registry).map((k) => {
let tool = new this.registry[k]()
return { name: k, setup: tool.setup.bind(tool) }
})
}
} |
JavaScript | class AppService {
/**
* Method to know is admin role
*/
isAdmin() {
let valid = false;
try {
const dataSession = VueContext.getDataInSession();
if (CommonsUtils.isNotNull(dataSession)) {
const roles = dataSession["roles"];
if (CommonsUtils.arrayNotNull(roles)) {
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "ADMIN") {
valid = true;
break;
}
}
}
}
} catch (ex) {
console.log(ex);
}
return valid;
}
/**
* Method for get nick form user
* @returns nick from user
*/
getNickUser() {
let nick = "";
try {
const dataSession = VueContext.getDataInSession();
if (CommonsUtils.isNotNull(dataSession)) {
nick = dataSession["nick"];
}
} catch (ex) {
console.log(ex);
}
return nick;
}
/**
* Method for get user id
* @returns number id from user
*/
getUserId() {
let userId = -999;
try {
const dataSession = VueContext.getDataInSession();
if (CommonsUtils.isNotNull(dataSession)) {
userId = dataSession["userId"];
}
} catch (ex) {
console.log(ex);
}
return userId;
}
} |
JavaScript | class CacheableResponse extends Response {
/**
* Constructs a new Response instance
*
* @constructor
* @param {Buffer} body
* @param {Object} [init]
*/
constructor(body, init) {
super(body, init);
const headers = new Headers(init.headers);
this[INTERNALS] = {
headers,
bufferedBody: body,
};
}
get headers() {
return this[INTERNALS].headers;
}
set headers(headers) {
if (headers instanceof Headers) {
this[INTERNALS].headers = headers;
} else {
throw new TypeError('instance of Headers expected');
}
}
get body() {
return Readable.from(this[INTERNALS].bufferedBody);
}
// eslint-disable-next-line class-methods-use-this
get bodyUsed() {
return false;
}
async buffer() {
return this[INTERNALS].bufferedBody;
}
async arrayBuffer() {
return toArrayBuffer(this[INTERNALS].bufferedBody);
}
async text() {
return this[INTERNALS].bufferedBody.toString();
}
async json() {
return JSON.parse(await this.text());
}
clone() {
const {
url, status, statusText, headers, httpVersion, counter,
} = this;
return new CacheableResponse(
this[INTERNALS].bufferedBody,
{
url, status, statusText, headers, httpVersion, counter,
},
);
}
get [Symbol.toStringTag]() {
return this.constructor.name;
}
} |
JavaScript | class DownloadTask extends FileTask {
/**
* Initializes a new instance of the class.
* @param {object} [options] An object specifying values used to initialize this instance.
*/
constructor(options = {}) {
super(options);
/**
* The pattern indicating the target path of the downloaded files (e.g. `path/to/i18n/{{locale}}.json`).
* @type {string}
*/
this.filePattern = typeof options.filePattern == 'string' ? options.filePattern : '';
/**
* The list of locales to be downloaded.
* @type {string[]}
*/
this.locales = Array.isArray(options.locales) ? options.locales : [];
/**
* The download parameters.
* @type {object}
*/
this._params = {};
if (typeof options.includeOriginalStrings == 'boolean') this.includeOriginalStrings = options.includeOriginalStrings;
if (typeof options.retrievalType == 'string') this.retrievalType = options.retrievalType;
}
/**
* Value indicating whether to return the original string or an empty string when no translation is available.
* @type {boolean}
*/
get includeOriginalStrings() {
return this._params.includeOriginalStrings == 'true';
}
/**
* The desired format for the download.
* @type {string}
*/
get retrievalType() {
return typeof this._params.retrievalType == 'string' ? this._params.retrievalType : RetrievalType.PUBLISHED;
}
/**
* Sets a value indicating whether to return the original string or an empty string when no translation is available.
* @param {boolean} value `true` to return the original string when no translation is available, otherwise `false`.
*/
set includeOriginalStrings(value) {
this._params.includeOriginalStrings = value ? 'true' : 'false';
}
/**
* Sets the desired format for the download.
* @param {string} value The desired format for the download.
*/
set retrievalType(value) {
this._params.retrievalType = value;
}
/**
* Downloads the message translations from the Smartling server.
* @return {Promise} Completes when the message translations have been downloaded.
*/
run() {
let fileApi = new SmartlingSdk(SmartlingSdk.API_BASE_URLS.LIVE, this.apiKey, this.projectId);
return Promise.all(this.locales.map(locale => fileApi.get(this.fileURI, this.filePattern.replace('{{locale}}', locale), Object.assign({
locale: Locale.getSpecificLocale(locale)
}, this._params))));
}
} |
JavaScript | class SeparatorType {
constructor(label) {
this.label = label;
}
} |
JavaScript | class CalleeInfoContainerStatic extends Component {
_renderContent(){
const _colorScheme = {'features/base/color-scheme':{}};
const _largeVideoStyles = ColorSchemeRegistry.get(_colorScheme, 'LargeVideo');
const _toolBoxStyles = ColorSchemeRegistry.get(_colorScheme, 'Toolbox');
return (
<>
<LargeAvatarStatic
_participantId={null}
_styles={_largeVideoStyles}
onClick={() => false}
{...this.props}
/>
<SafeAreaView
pointerEvents = 'box-none'
style = {styles.toolboxAndFilmstripContainer}>
<CalleeInfoNew {...this.props}/>
<ToolboxStatic
_styles={_toolBoxStyles}
_visible={true}
{...this.props}
/>
</SafeAreaView>
<SafeAreaView
pointerEvents = 'box-none'
style = {styles.navBarSafeView}>
<NavigationBarStatic {...this.props} toolBoxStyles={_toolBoxStyles} />
</SafeAreaView>
</>
);
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
return (
<Container style={fixAndroidViewClipping({
alignSelf: 'stretch',
backgroundColor: ColorPalette.appBackground,
flex: 1
})}>
<StatusBar
barStyle = 'light-content'
hidden = { true }
translucent = { true } />
{ this._renderContent() }
</Container>
);
}
} |
JavaScript | class SingleProduct extends Component {
constructor(props) {
super(props);
this.state = {
showEdit: false,
}
this.addToCart = this.addToCart.bind(this)
}
async componentDidMount() {
await this.props.fetch(this.props.match.params.id);
}
async addToCart() {
if(this.props.isLoggedIn) {
await this.props.addToCarts(
[this.props.userId, this.props.product, 'increment']
)
} else {
let existingCart = await JSON.parse(localStorage.getItem('guestCart'))
const currentProduct = this.props.product
let truthyValue;
if (!existingCart) {
existingCart = []
localStorage.setItem('guestCart', JSON.stringify(existingCart))
} else {
//here it maps through the elements in the ucrrent cart, if it finds one it iterates the quantity
existingCart.map(mapproduct => {
if(mapproduct.id === currentProduct.id) {
mapproduct.quantity++
truthyValue = true
return truthyValue
}
})
}
if(!truthyValue) {
//if theres no truthy value (truthy is false,), the current item needs to be added onto the existing cart
currentProduct.quantity = 1
existingCart.push(currentProduct)
}
localStorage.setItem('guestCart', JSON.stringify(existingCart))
}
}
render() {
const product = this.props.product || [];
const { isAdmin } = this.props;
return (
<div className="singleProductContainer">
<h3 id="singleMushroomHeader">{product.name} mushrooms</h3>
<div className="singleProductView" key={product.id}>
<img src={product.imageUrl} id="singleProductViewImage" />
<div className="singleMushroomText">
<p id="singleMushroomName">{product.name}</p>
<p>{product.description && product.description.length > 3
? product.description
: ""}</p>
<p id="singleProductPrice">{product.price}/lb</p>
<div className="singleMushroomButton">
<button className = "singleMushroomButtons" onClick={this.addToCart}>add to cart</button>
{isAdmin &&
<button
className = "singleMushroomButtons"
onClick={() => {this.setState({showEdit: !this.state.showEdit})}}
>edit</button>}
{isAdmin &&
<button
className = "singleMushroomButtons"
onClick={
() => {
if (window.confirm('Are you sure you wish to delete this item?')) {
this.props.delete(product.id);
}
}
}
>remove</button>}
</div>
</div>
</div>
{this.state.showEdit &&
<div className="singleProductEdit">
<a
onClick={() => {this.setState({showEdit: false})}}
className="remove-form"
>
✖
</a>
<EditProduct />
</div> }
</div>
);
}
} |
JavaScript | class NotFoundHttpException extends HttpException {
constructor(message) {
super(HttpStatus.NOT_FOUND['code'], message || "Not found.", errors);
}
} |
JavaScript | class AdminUsers extends React.Component {
constructor(props) {
super(props);
this.state = {
recentUsersPageNum: 0,
recentUsers: [],
searchUsersPageNum: 0,
searchUsers: []
};
}
componentDidMount() {
this.loadRecentUsers((_, json) => this.setState({
recentUsers: dottie.get(json, 'users', [])
}));
}
loadRecentUsers(cb) {
const {loading} = this.props;
const {recentUsersPageNum} = this.state;
loading((done) => request.post({
url: context.uris.RecentUsersURI,
json: {
/* eslint-disable camelcase */
page_num: recentUsersPageNum,
num_per_page: 10
/* eslint-enable camelcase */
}
}, (err, resp, json) => {
cb(err, json);
return done();
}));
}
handleLoadMoreRecentUsers(evt) {
evt.preventDefault();
const {recentUsers, recentUsersPageNum} = this.state;
this.setState({
recentUsersPageNum: recentUsersPageNum + 1
}, () => {
this.loadRecentUsers((err, moreUsers) => {
if (err || !dottie.get(moreUsers, 'users', [null]).length) {
// Reset the page number to the existing (non-incremented) index.
return this.setState({recentUsersPageNum});
}
return this.setState({
recentUsers: recentUsers.concat(moreUsers.users)
});
});
});
}
handleAddUserClick(evt) {
evt.preventDefault();
this.userAddModal.component.modal.showModal();
}
doUserSearch(username, cb) {
const {searchUsersPageNum} = this.state;
if (this.inFlightSearchRequest) {
this.inFlightSearchRequest.abort();
}
this.inFlightSearchRequest = request.post({
url: context.uris.UserSearchURI,
json: {
/* eslint-disable camelcase */
username,
page_num: searchUsersPageNum,
num_per_page: 10
/* eslint-enable camelcase */
}
}, (err, resp, json) => cb(err, json));
}
handleUserSearch(evt) {
const username = evt.target.value;
if (!username) {
return this.setState({searchUsers: []});
}
return this.setState({
searchUsersPageNum: 0
}, () => this.doUserSearch(username, (err, json = {}) => {
if (!err) {
this.setState({searchUsers: json.users || []});
}
}));
}
isSearching() {
return this.searchField ? this.searchField.getValue().length > 0 : false;
}
render() {
const {recentUsers, searchUsers} = this.state;
return (
<div className="margin-huge--bottom">
<p className="text--section-header">USERS</p>
<p className="text--section-caption">
These are all registered users.
</p>
<TextField
ref={(elem) => {
this.searchField = elem;
}}
className="search-bar sans-serif margin-small--bottom"
placeholder="Search for users..."
onChange={this.handleUserSearch.bind(this)}
icon={<Search />}
iconSpacing="25px"
/>
<Table
className="sans-serif text-gray-60 iota margin-small--top"
headerClassName="sans-serif bold"
header={[
'USERNAME',
'SIGNUP IP',
'ADMIN',
'SIGNUP TIME'
]}
entries={(this.isSearching() ? searchUsers : recentUsers).map((user) => [
user.username,
user.signup_ip,
user.is_admin ? 'Yes' : 'No',
humanize.date('F j, Y g:i A', user.signup_time)
])}
/>
<Button
className="sans-serif bold iota text-white margin-small--top"
text="Load more..."
onClick={this.handleLoadMoreRecentUsers.bind(this)}
/>
<Button
className="sans-serif bold iota text-white margin--left margin-small--top"
text="Add user"
onClick={this.handleAddUserClick.bind(this)}
/>
<UserAddModal
ref={(elem) => {
this.userAddModal = elem;
}}
/>
</div>
);
}
} |
JavaScript | class Orders extends WHMCS {
/**
* @param {Object} config Object containing your API credentials.
* @param {string} config.serverUrl URL to your installation. Remember to point to /includes/api.php
* @param {string} [config.username]
* @param {string} [config.password]
* @param {string} [config.identifier]
* @param {string} [config.secret]
*/
constructor (config) {
super(config)
}
/**
* Retrieve Order Status and number in those statuses - https://developers.whmcs.com/api-reference/getorderstatuses/
* @param {Object} opts
*/
getOrderStatuses (opts) {
const options = {
action: 'GetOrderStatuses',
...opts
}
return this.callApi(options)
}
/**
* NOTE: This API method is designed to be used in the building of custom order
forms. As a result, only custom fields that have the ‘Show on Order Form’
setting enabled will be returned for a given product. - https://developers.whmcs.com/api-reference/getproducts/
* @param {Object} opts
* @param {Number} [opts.pid] string
* @param {Number} [opts.gid] Retrieve products in a specific group id
* @param {String} [opts.module] Retrieve products utilising a specific module
*/
getProducts (opts) {
const options = {
action: 'GetProducts',
...opts
}
return this.callApi(options)
}
/**
* Accepts a pending order - https://developers.whmcs.com/api-reference/acceptorder/
* @param {Object} opts
* @param {Number} opts.orderid The order id to be accepted
* @param {Number} [opts.serverid] The specific server to assign to products within the order
* @param {String} [opts.serviceusername] The specific username to assign to products within the order
* @param {String} [opts.servicepassword] The specific password to assign to products within the order
* @param {String} [opts.registrar] The specific registrar to assign to domains within the order
* @param {Boolean} [opts.sendregistrar] Send the request to the registrar to register the domain.
* @param {Boolean} [opts.autosetup] Send the request to the product module to activate the service. This can override the product configuration.
* @param {Boolean} [opts.sendemail] Send any automatic emails. This can be Product Welcome, Domain Renewal, Domain Transfer etc.
*/
acceptOrder (opts) {
const options = {
action: 'AcceptOrder',
...opts
}
return this.callApi(options)
}
/**
* Sets an order, and all associated order items to Pending status - https://developers.whmcs.com/api-reference/pendingorder/
* @param {Object} opts
* @param {Number} opts.orderid The order id to be accepted
*/
pendingOrder (opts) {
const options = {
action: 'PendingOrder',
...opts
}
return this.callApi(options)
}
/**
* Marks an order as fraudulent. - https://developers.whmcs.com/api-reference/fraudorder/
* @param {Object} opts
* @param {Number} opts.orderid The Order ID to set as fraud
* @param {Boolean} [opts.cancelsub] Pass as true to cancel any PayPal Subscription(s) associated with the products & services that belong to the given order.
*/
fraudOrder (opts) {
const options = {
action: 'FraudOrder',
...opts
}
return this.callApi(options)
}
/**
* Cancel a Pending Order - https://developers.whmcs.com/api-reference/cancelorder/
* @param {Object} opts
* @param {Number} opts.orderid The ID of the pending order
* @param {Boolean} [opts.cancelsub] Attempt to cancel the subscription associated with the products
* @param {Boolean} [opts.noemail] Set to true to stop the invoice payment email being sent if the invoice becomes paid
*/
cancelOrder (opts) {
const options = {
action: 'CancelOrder',
...opts
}
return this.callApi(options)
}
/**
* Adds an order to a client. - https://developers.whmcs.com/api-reference/addorder/
* @param {Object} opts
* @param {Number} opts.clientid
* @param {String} opts.paymentmethod The payment method for the order in the system format. eg. paypal, mailin
* @param {Array.<Number>} [opts.pid] The array of product ids to add the order for
* @param {Array.<String>} [opts.domain] The array of domain names associated with the products/domains
* @param {Array.<String>} [opts.billingcycle] The array of billing cycles for the products
* @param {Array.<String>} [opts.domaintype] For domain registrations, an array of register or transfer values
* @param {Array.<Number>} [opts.regperiod] For domain registrations, the registration periods for the domains in the order
* @param {Array.<String>} [opts.eppcode] For domain transfers. The epp codes for the domains being transferred in the order
* @param {String} [opts.nameserver1] The first nameserver to apply to all domains in the order
* @param {String} [opts.nameserver2] The second nameserver to apply to all domains in the order
* @param {String} [opts.nameserver3] The third nameserver to apply to all domains in the order
* @param {String} [opts.nameserver4] The fourth nameserver to apply to all domains in the order
* @param {String} [opts.nameserver5] The fifth nameserver to apply to all domains in the order
* @param {Array.<String>} [opts.customfields] an array of base64 encoded serialized array of product custom field values
* @param {Array.<String>} [opts.configoptions] an array of base64 encoded serialized array of product configurable options values
* @param {Array.<Number>} [opts.priceoverride] Override the price of the product being ordered
* @param {String} [opts.promocode] The promotion code to apply to the order
* @param {Boolean} [opts.promooverride] Should the promotion apply to the order even without matching promotional products
* @param {Number} [opts.affid] The affiliate id to associate with the order
* @param {Boolean} [opts.noinvoice] Set to true to suppress the invoice generating for the whole order
* @param {Boolean} [opts.noinvoiceemail] Set to true to suppress the Invoice Created email being sent for the order
* @param {Boolean} [opts.noemail] Set to true to suppress the Order Confirmation email being sent
* @param {Array.<String>} [opts.addons] A comma separated list of addons to create on order with the products
* @param {Array.<String>} [opts.hostname] The hostname of the server for VPS/Dedicated Server orders
* @param {Array.<String>} [opts.ns1prefix] The first nameserver prefix for the VPS/Dedicated server. Eg. ns1 in ns1.hostname.com
* @param {Array.<String>} [opts.ns2prefix] The second nameserver prefix for the VPS/Dedicated server. Eg. ns2 in ns2.hostname.com
* @param {Array.<String>} [opts.rootpw] The desired root password for the VPS/Dedicated server.
* @param {Number} [opts.contactid] The id of the contact, associated with the client, that should apply to all domains in the order
* @param {Array.<Boolean>} [opts.dnsmanagement] Add DNS Management to the Domain Order
* @param {Array.<String>} [opts.domainfields] an array of base64 encoded serialized array of TLD Specific Field Values
* @param {Array.<Boolean>} [opts.emailforwarding] Add Email Forwarding to the Domain Order
* @param {Array.<Boolean>} [opts.idprotection] Add ID Protection to the Domain Order
* @param {Array.<Number>} [opts.domainpriceoverride] Override the price of the registration price on the domain being ordered
* @param {Array.<Number>} [opts.domainrenewoverride] Override the price of the renewal price on the domain being ordered
* @param {Array} [opts.domainrenewals] A name -> value array of $domainName -> $renewalPeriod renewals to add an order for
* @param {String} [opts.clientip] The ip address to associate with the order
* @param {Number} [opts.addonid] The Addon ID for an Addon Only Order
* @param {Number} [opts.serviceid] The service ID for the addon only order
* @param {Array.<Number>} [opts.addonids] An Array of addon ids for an Addon Only Order
* @param {Array.<Number>} [opts.serviceids] An array of service ids to associate the addons for an Addon Only order
*/
addOrder (opts) {
const options = {
action: 'AddOrder',
...opts
}
return this.callApi(options)
}
/**
* Obtain orders matching the passed criteria - https://developers.whmcs.com/api-reference/getorders/
* @param {Object} opts
* @param {Number} [opts.limitstart] The offset for the returned order data (default: 0)
* @param {Number} [opts.limitnum] The number of records to return (default: 25)
* @param {Number} [opts.id] Find orders for a specific id
* @param {Number} [opts.userid] Find orders for a specific client id
* @param {String} [opts.status] Find orders for a specific status
*/
getOrders (opts) {
const options = {
action: 'GetOrders',
...opts
}
return this.callApi(options)
}
/**
* Run a fraud check on a passed Order ID - https://developers.whmcs.com/api-reference/orderfraudcheck/
* @param {Object} opts
* @param {Number} opts.orderid The order id to complete the fraud check on
* @param {String} [opts.ipaddress] To override the IP address on the fraud check
*/
orderFraudCheck (opts) {
const options = {
action: 'OrderFraudCheck',
...opts
}
return this.callApi(options)
}
/**
* Obtain promotions matching the passed criteria - https://developers.whmcs.com/api-reference/getpromotions/
* @param {Object} opts
* @param {String} [opts.code] Retrieve a specific promotion code. Do not pass to retrieve all
*/
getPromotions (opts) {
const options = {
action: 'GetPromotions',
...opts
}
return this.callApi(options)
}
/**
* Removes an order from the system. This cannot be undone. This will remove all items associated with the order (services, addons, domains, invoices etc) - https://developers.whmcs.com/api-reference/deleteorder/
* @param {Object} opts
* @param {Number} opts.orderid The order to be deleted
*/
deleteOrder (opts) {
const options = {
action: 'DeleteOrder',
...opts
}
return this.callApi(options)
}
} |
JavaScript | class NetworkQualitySignaling extends EventEmitter {
/**
* Construct a {@link NetworkQualitySignaling}.
* @param {MediaSignalingTransport} mediaSignalingTransport
*/
constructor(mediaSignalingTransport) {
super();
Object.defineProperties(this, {
_level: {
value: null,
writable: true
},
_levels: {
value: null,
writable: true
},
_mediaSignalingTransport: {
value: mediaSignalingTransport
},
_networkQualityInputs: {
value: new AsyncVar()
}
});
mediaSignalingTransport.on('message', message => {
switch (message.type) {
case 'network_quality':
this._handleNetworkQualityMessage(message);
break;
default:
break;
}
});
this._sendNetworkQualityInputs();
}
/**
* Get the current {@link NetworkQualityLevel}, if any.
* @returns {?NetworkQualityLevel} level - initially null
*/
get level() {
return this._level;
}
/**
* Get the current {@link NetworkQualityLevels}, if any.
* @deprecated - the decomposed levels are only used for debugging and will be
* removed as soon as we are confident in our implementation
* @returns {?NetworkQualityLevels} levels - initially null
*/
get levels() {
return this._levels;
}
/**
* Check to see if the {@link NetworkQualityLevel} is new, and raise an
* event if necessary.
* @private
* @param {object} message
* @returns {void}
*/
_handleNetworkQualityMessage(message) {
let level = null;
const local = message ? message.local : null;
if (typeof local === 'number') {
// NOTE(mroberts): In prod, we plan to only send the level.
level = local;
this._levels = null;
} else if (typeof local === 'object' && local) {
// NOTE(mroberts): In dev, we plan to send the decomposed levels. An early
// VMS version does not compute `level` for us, so we fallback to taking
// the minimum ourselves.
this._levels = local;
level = typeof local.level === 'number'
? local.level
: Math.min(
local.audio.send,
local.audio.recv,
local.video.send,
local.video.recv);
}
if (level !== null && this.level !== level) {
this._level = level;
this.emit('updated');
}
setTimeout(() => this._sendNetworkQualityInputs(), 1000);
}
/**
* Start sending {@link NetworkQualityInputs}.
* @private
* @returns {Promise<void>}
*/
_sendNetworkQualityInputs() {
return this._networkQualityInputs.take().then(networkQualityInputs => {
this._mediaSignalingTransport.publish(createNetworkQualityInputsMessage(networkQualityInputs));
});
}
/**
* Put {@link NetworkQualityInputs} to be used for computing
* {@link NetworkQualityLevel}.
* @param {NetworkQualityInputs} networkQualityInputs
* @returns {void}
*/
put(networkQualityInputs) {
this._networkQualityInputs.put(networkQualityInputs);
}
} |
JavaScript | class PanelModule extends Module {
constructor (store, api, config) {
super(store, api, config)
// Create the mount point as the last child of the page's body
const el = document.createElement('div')
let mountEl = document.querySelector(this.config.mountInto)
if (!mountEl) {
mountEl = document.body
}
const viEl = mountEl.appendChild(el)
store.registerModule(this.constructor.moduleName, this.constructor.store(this))
const component = this.config.platform.isDesktop ? LargePanel : CompactPanel
const VueComponentClass = Vue.extend(component)
this._vi = new VueComponentClass({
parent: this.constructor.rootVi,
data: () => {
return {
// Make module configuration directly accessible by the module's Vue instance as a data prop
moduleConfig: this.config
}
}
})
this._vi.$mount(viEl)
Platform.evt.ORIENTATION_CHANGE.sub(() => {
this._vi.$store.commit('panel/setOrientation', this.config.platform.simpleOrientation)
})
}
} |
JavaScript | class Webcam extends React.Component {
constructor(props){
super(props);
this.state = {
imgData: '',
webcamEnabled: false,
}
}
handleImageRequest = async (obj) => {
return await superagent.post(`${obj.url}/${obj.resource}`)
.field('username', obj.data.username)
.field('imageObj', obj.data.imgData)
.field('image', 'user image');
}
handleWebcam = (img) => {
this.setState({
webcamEnabled: !this.state.webcamEnabled,
imgData: img
})
this.handleImageRequest({
url:process.env.REACT_APP_API_URL,
resource:'pic',
data: {
username: this.props.user,
imgData: img
}
})
.then(result => this.props.setData(result.body))
}
controlWebcam = () => {
this.setState({ webcamEnabled: !this.state.webcamEnabled });
}
render(){
const { webcamEnabled, imgData } = this.state;
let content = webcamEnabled && !imgData ? (
<>
<p id="web-msg">Let's take your pic!</p>
<WebcamCapture handler={this.handleWebcam} setImgData={this.props.setImgData} setURL={this.props.setURL}/>
</>
) : imgData && !webcamEnabled ?
(
<React.Fragment>
<h3>Things</h3>
</React.Fragment>
)
: (
<React.Fragment>
<Zoom>
<img height="420" width="350" src={require('../images/btn.gif')} onClick={this.controlWebcam} />
</Zoom>
</React.Fragment>
)
return (
<React.Fragment>
{content}
</React.Fragment>
)
}
} |
JavaScript | class FireInsurancePolicyFilter extends BaseModel {
/**
* @constructor
* @param {Object} obj The object passed to constructor
*/
constructor(obj) {
super(obj);
if (obj === undefined || obj === null) return;
this.insurancePolicyType = this.constructor.getValue(obj.insurancePolicyType);
this.insuranceExtraCoverageIds = this.constructor.getValue(obj.insuranceExtraCoverageIds);
this.valuePerSquareMeterCoverageRateId =
this.constructor.getValue(obj.valuePerSquareMeterCoverageRateId);
this.valueOfAppliancesFurnishing =
this.constructor.getValue(obj.valueOfAppliancesFurnishing);
this.cityId = this.constructor.getValue(obj.cityId);
this.skeletonTypeId = this.constructor.getValue(obj.skeletonTypeId);
this.buildingTypeId = this.constructor.getValue(obj.buildingTypeId);
this.buildingArea = this.constructor.getValue(obj.buildingArea);
this.onlyAppliancesFurnishings = this.constructor.getValue(obj.onlyAppliancesFurnishings);
this.policyTermId = this.constructor.getValue(obj.policyTermId);
this.insuranceCentreSubDomainName =
this.constructor.getValue(obj.insuranceCentreSubDomainName);
this.insuranceCentreId = this.constructor.getValue(obj.insuranceCentreId);
this.insuranceCompanyId = this.constructor.getValue(obj.insuranceCompanyId);
this.giftCode = this.constructor.getValue(obj.giftCode);
this.customerUserId = this.constructor.getValue(obj.customerUserId);
}
/**
* Function containing information about the fields of this model
* @return {array} Array of objects containing information about the fields
*/
static mappingInfo() {
return super.mappingInfo().concat([
{ name: 'insurancePolicyType', realName: 'insurancePolicyType' },
{ name: 'insuranceExtraCoverageIds', realName: 'insuranceExtraCoverageIds' },
{
name: 'valuePerSquareMeterCoverageRateId',
realName: 'valuePerSquareMeterCoverageRateId',
},
{ name: 'valueOfAppliancesFurnishing', realName: 'valueOfAppliancesFurnishing' },
{ name: 'cityId', realName: 'cityId' },
{ name: 'skeletonTypeId', realName: 'skeletonTypeId' },
{ name: 'buildingTypeId', realName: 'buildingTypeId' },
{ name: 'buildingArea', realName: 'buildingArea' },
{ name: 'onlyAppliancesFurnishings', realName: 'onlyAppliancesFurnishings' },
{ name: 'policyTermId', realName: 'policyTermId' },
{ name: 'insuranceCentreSubDomainName', realName: 'insuranceCentreSubDomainName' },
{ name: 'insuranceCentreId', realName: 'insuranceCentreId' },
{ name: 'insuranceCompanyId', realName: 'insuranceCompanyId' },
{ name: 'giftCode', realName: 'giftCode' },
{ name: 'customerUserId', realName: 'customerUserId' },
]);
}
/**
* Function containing information about discriminator values
* mapped with their corresponding model class names
*
* @return {object} Object containing Key-Value pairs mapping discriminator
* values with their corresponding model classes
*/
static discriminatorMap() {
return {};
}
} |
JavaScript | class Person {
// conventionally a class name uses PascalCase
// public field
// these can be directly accessed outsied the class
name;
// private fields
// cannot be accessed outside without getters or setters
#hairColor;
#eyeColor;
// a constructor is a special function that can be used with new to
// create an object that is an intance of this class
constructor(name, hairColor = "brown", eyeColor = "blue") {
this.name = name;
this.#hairColor = hairColor;
this.#eyeColor = eyeColor;
}
// getters can be used to expose private fields
// this allows reading but not writing to the fields.
get hairColor() {
return this.#hairColor;
}
get eyeColor() {
return this.#eyeColor;
}
} |
JavaScript | class child extends Person {
#age = 5;
constructor(
name = new Person().name,
hairColor = new Person().hairColor,
eyeColor = new Person().eyeColor
) {
// a subclass MUST use the super constructor.
super(name, hairColor, eyeColor);
}
ageUp() {
this.#age++;
}
get age() {
return this.#age;
}
} |
JavaScript | class Interpreter {
constructor() {
this.code = []
this.grid = []
this.input = [] // must be an array of bits
}
parse(value) {
this.code = value.split`
`
// first three lines are train data, input and output, in that order.
// train data is [x,y,dx,dy]
// input and output points are given as x,y pairs. They must be lazy points.
// may add a flag later to accomodate string input converted to a byte stream.
try {
this.tD = JSON.parse(this.code[0])
this.iP = JSON.parse(this.code[1]).map(x=>x.reverse()) // input points
this.pP = JSON.parse(this.code[2]).map(x=>[x[1],x[0],x[2]]) // preset points
this.oP = JSON.parse(this.code[3]).map(x=>x.reverse()) // output points
} catch (e) {
console.log("input/output invalid")
return
}
[this.tC,this.tR,this.dC,this.dR] = this.tD
// Pad each line to hte longest length
let lAL = Math.max(...this.code.slice(2).map(x=>x.length))
// Make rows of chars
this.grid = this.code.slice(3).map(l => Array.from(l.padEnd(lAL - l.length, " ")))
if(!this.tD)console.log("No train given")
console.log(this.tRow,this.tCol)
console.log(this.dRow,this.dCol)
console.log(this.grid)
}
/*
Track specification:
Track symbol: '#'
Train symbol: 'T'
*/
step(display) { // Main stepping function
const g = JSON.parse(JSON.stringify(this.grid))
g[this.tR][this.tC] = '<span style="color:red">T</span>';
display.innerHTML = g.map(x=>x.join``).join`
`.replace(/([PS])/g,'<span class="$1color">$1</span>')
this.tR += this.dR
this.tC += this.dC
console.log(this.tR,this.tC,this.dR,this.dC)
let vn = [[0,1],[1,0],[0,-1],[-1,0]].filter(d=>d!=[-this.dR,-this.dC].toString())
let ps = vn.filter(d=>'#' == (this.grid[this.tR+d[0]]||[])[this.tC+d[1]])
let ss = vn.filter(d=>'S' == (this.grid[this.tR+d[0]]||[])[this.tC+d[1]])
let sw = vn.filter(d=>'P' == (this.grid[this.tR+d[0]]||[])[this.tC+d[1]])
if(ss[0] && ss[0] != [-this.dR,-this.dC]){
[this.dR,this.dC] = ss[0]
} else if(ps[0]) {
[this.dR,this.dC] = ps[0]
} else if(sw[0]){
[this.dR,this.dC] = sw[0]
this.grid[this.tR+this.dR][this.tC+this.dC] = '#'
this.grid[this.tR+2*this.dR][this.tC+2*this.dC] = 'P'
} else {
return 0 // stop on a falsy value
}
console.log(this.grid)
if(this.tR == this.tD[1] && this.tC == this.tD[0]){
return 0 // end at original position
}
return this.grid
}
async run(display, output) {
while(this.step(display))await new Promise(resolve => setTimeout(resolve, 500)) // JS's awful hack of a delaying method.
let aPs = {} // all point data
for(let i=0; i<this.iP.length; i++) {
let [r,c] = this.iP[i]
let b = this.input[i]
aPs[this.iP[i]] = this.grid[r][c] == 'P' ? b : !b
}
for(let i=0; i<this.pP.length; i++) {
let [r,c,b] = this.pP[i]
aPs[this.pP[i].slice(0,2)] = this.grid[r][c] == 'P' ? b : !b
}
output.innerText = this.oP.map(x => +aPs[x]).join``
}
let interp = new Interpreter() |
JavaScript | class Columns extends Component {
constructor(props, ...args){
super(props, ...args);
// Bind context to methods
this.makeInnerChildren = this.makeInnerChildren.bind(this);
}
render(){
return (
h('div', {
class: "cell container-fluid",
id: this.props.id,
"data-cell-id": this.props.id,
"data-cell-type": "Columns",
style: this.props.extraData.divStyle
}, [
h('div', {class: "row flex-nowrap"}, this.makeInnerChildren())
])
);
}
makeInnerChildren(){
return this.getReplacementElementsFor('c').map(replElement => {
return (
h('div', {
class: "col-sm"
}, [replElement])
);
});
}
} |
JavaScript | class Queue {
/*
size = 0;
element_count = 0;
container;
head_idx = 0;
tail_idx = 0;
get = this.dequeue;
*/
/**
* Builds a queue.
* @constructor
* @param {number} [queue_size = 1000] The initial queue capacity.
*/
constructor(queue_size = 1000) {
this.size = queue_size;
this.container = [];
this.container.length = queue_size;
this.head_idx = 0;
this.tail_idx = 0;
this.element_count = 0;
this.get = this.dequeue;
}
/**
* Find the index of the next element in the queue.
* TODO: Make this a private method when support increases.
* @param {number} pos The current position in the queue.
* @returns {number} The next position in the queue.
*/
inc_queue_ptr(pos) {
return((pos + 1) % this.size);
}
/**
* Find out if the queue is full.
* @returns {boolean} True if the queue is full.
*/
is_full() {
return(this.size == this.element_count);
}
/**
* Double the capacity of the queue.
*/
resize() {
let prefix = []
let suffix = []
if (this.head_idx <= this.tail_idx) {
prefix = this.container.slice(this.tail_idx, this.container.length);
suffix = this.container.slice(0, this.head_idx);
}
else {
prefix = this.container.slice(this.tail_idx, this.head_idx + 1);
}
this.container = prefix.concat(suffix);
this.head_idx = this.container.length;
this.tail_idx = 0;
this.container.length = 2 * this.size;
this.size = 2 * this.size;
}
/**
* Find out if the queue is empty.
* @returns {boolean} True if the queue is empty.
*/
is_empty() {
return(this.element_count == 0);
}
/**
* Add an element to the queue.
* @param {*} element The element to insert into the queue.
*/
enqueue(element) {
if (this.is_full()) {
this.resize()
}
this.element_count++;
this.container[this.head_idx] = element;
this.head_idx = this.inc_queue_ptr(this.head_idx);
}
/**
* Remove an element from the queue.
* @returns {*} The element removed from the queue.
*/
dequeue() {
if (this.is_empty()) {
throw new Error("Queue is empty");
}
this.element_count--;
let element = this.container[this.tail_idx];
this.tail_idx = this.inc_queue_ptr(this.tail_idx);
return(element);
}
/**
* Add multiple elements to the queue.
* @param {Iterable} elements As an iterable, the collection of elements to add to the queue.
*/
put(elements) {
let element;
for (element of elements) {
this.enqueue(element)
}
}
} |
JavaScript | class MapModal extends React.Component {
constructor(props, context) {
super(props, context);
this.handleShow = this.handleShow.bind(this);
this.handleClose = this.handleClose.bind(this);
this.state = {
show: false
};
}
handleClose() {
this.setState({ show: false });
}
handleShow() {
this.setState({ show: true });
}
render() {
return (
<div>
<Button bsStyle="danger" bsSize="large" onClick={this.handleShow} id="modal-btn">
Create a Project!
</Button>
<Modal show={this.state.show} onHide={this.handleClose}>
<Modal.Header closeButton>
<Modal.Title>
<div className="text-center">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="text-danger">Create a Project</h1>
</div>
</Modal.Title>
</Modal.Header>
<Modal.Body>
<CreateProjectForm
handleClose={this.handleClose}
userID={this.props.userID}
username={this.props.username}
/>
</Modal.Body>
<Modal.Footer></Modal.Footer>
</Modal>
</div>
);
}
} |
JavaScript | class NexmoClientError {
constructor(errorInput) {
const error = NexmoClientErrorTypes[errorInput];
// for other errors (libs/browser APIs) re-use the Client error
// to forward it but don't throw it away
if (error) {
// if error type exists in our list keep consistency
decorateError(this, error);
}
else {
// if the structure is not as expected, f/w as much as we can get
this.message = errorInput && errorInput.message ? errorInput.message : errorInput;
this.stack = errorInput && errorInput.stack ? errorInput.stack : new Error().stack;
}
// make sure the error.name matches the class name
this.name = 'NexmoClientError';
if (typeof global.NXMbugsnagClient !== 'undefined') {
global.NXMbugsnagClient.notify(this, {
severity: 'info'
});
}
}
} |
JavaScript | class NexmoApiError {
constructor(error) {
decorateError(this, error);
// make sure the error.name matches the class name
this.name = 'NexmoApiError';
if (typeof global.NXMbugsnagClient !== 'undefined') {
global.NXMbugsnagClient.notify(this, {
severity: 'info',
metaData: {
'API trace': error.__metadata,
rid: error.rid
}
});
}
}
} |
JavaScript | class User {
/**
* If the user has set the account to have limited access to functions when the class was constructed.
* @type boolean
* @private
*/
_initLimited;
/**
* The Users cookie, CANNOT be changed once class is initialized. Used for limited
* @type string
* @private
*/
_cookie;
/**
* A list of the users previous names, to view it, run the {@link previousNames} method.
* @type string[]
* @private
*/
_previousNames;
/**
* The roblox user's roblox avatar url's
* @type {import('../../typings/index').AvatarObject}
* @private
*/
_avatar;
/**
* The roblox user's roblox ID
* @type string
* @public
* @readonly
*/
userId;
/**
* The date when the account was created
* @type Date
* @public
* @readonly
*/
createdAt;
/**
* The roblox user's roblox username
* @type string
* @public
* @readonly
*/
username;
/**
* The roblox user's roblox display name - to change it (requires limited access - see {@link limitedAccess}) run the {@link changeUsername} method
* @type string
* @public
* @readonly
*/
displayName;
/**
* If the roblox user has premium.
* @type boolean
* @public
* @readonly
*/
hasPremium;
/**
* If the roblox user is banned.
* @type boolean
* @public
* @readonly
*/
banned;
/**
* The roblox user's roblox description
* @type string
* @public
* @readonly
*/
description;
/**
* Construct the User class
* @param {boolean} limitedAccess If the user has limited access to functions
* @param {import('../../typings/index').UserConstructor} info The Cookie of the account to log in with
*/
constructor(limitedAccess, info) {
this._initLimited = limitedAccess;
this._cookie = info._cookie;
this.userId = info.userId;
this.createdAt = info.createdAt;
this.username = info.username;
this.displayName = info.displayName;
this.hasPremium = info.hasPremium;
this.banned = info.banned;
this.description = info.description;
}
/**
* Reloads the Avatars currently in the User Class
* @returns {Promise<void>}}
* @public
*/
async reloadAvatar() {
const avatarThumbnail = await avatarThumbnails.getAvatar([this.userId], false)
const avatarBust = await avatarThumbnails.getBust([this.userId], false)
const avatarHeadshot = await avatarThumbnails.getHeadshot([this.userId], false)
this._avatar = {}
this._avatar.thumbnail = avatarThumbnail[0].imageUrl
this._avatar.bust = avatarBust[0].imageUrl
this._avatar.headshot = avatarHeadshot[0].imageUrl
}
/**
* If the cookie (assuming given) for this roblox user class seems to be valid*
*
* ***Note**: This is not a guarantee that the cookie is valid, it is a basic check to see if the cookie *seems* valid
* @returns {boolean}
* @public
*/
cookieValid() {
if (!this._cookie) return false;
if (!this._cookie.toUpperCase().includes('_|WARNING:-DO-NOT-SHARE-THIS.')) {
throw new Error('No ROBLOX warning was found in the provided cookie. Ensure that you include the entire .ROBLOSECURITY warning!')
} else return true;
}
/**
* If this roblox user class will have limited functions available
* @returns {boolean}
* @public
*/
limitedAccess() {
if (!this._initLimited || (this._cookie && this.cookieValid())) {
return true;
} else return false;
}
/**
* If this roblox user class will have limited functions available
* @returns {string | false}
* @public
*/
avatarUrl(avatarType) {
this.reloadAvatar();
if (this._avatar && this._avatar[avatarType]) {
return this._avatar[avatarType];
} else return false;
}
/**
* desc
* @returns {Promise<string[] | null>}
* @public
*/
async getPreviousNames() {
/**
* @type {import('../../typings/response').v1_users_username_history}
*/
let names = await request.get({
url: `${routes.v1.bases.usersApi()}${routes.v1.usernameHistory(this.userId)}`
})
this._previousNames = [];
names.data.data.forEach((prevName) => {
this._previousNames.push(prevName.name)
})
return this._previousNames;
}
changeUsername(newUsername) {}
changeDescription(newDescription) {}
} |
JavaScript | class QueryKey {
/**
* If defined in extending class, will omit all parameters where values
* match that of the default query
*
* @type {?Object}
*/
static DEFAULT_QUERY = null;
/**
* If defined in extending class as true, will omit all null values from
* stringified or parsed query objects
*
* @type {Boolean}
*/
static OMIT_NULL_VALUES = false;
/**
* Given a query object, determines which values of query are included in
* stringification or parsed return value. The base class will omit only
* undefined values, but can be extended to omit null values or values
* matching those in a default query.
*
* @param {Object} query Query object
* @return {Object} Pruned query object
*/
static omit( query ) {
const { OMIT_NULL_VALUES, DEFAULT_QUERY } = this;
if ( ! OMIT_NULL_VALUES && ! DEFAULT_QUERY ) {
return query;
}
return omitBy( query, ( value, key ) => {
if ( OMIT_NULL_VALUES && null === value ) {
return true;
}
if ( DEFAULT_QUERY && DEFAULT_QUERY[ key ] === value ) {
return true;
}
return false;
} );
}
/**
* Returns a serialized query, given a query object
*
* @param {Object} query Query object
* @return {String} Serialized query
*/
static stringify( query ) {
const prunedQuery = this.omit( query );
// A stable query is one which produces the same result regardless of
// key ordering in the original object, to ensure that:
//
// QueryKey.stringify( { a: 1, b: 2 } ) === QueryKey.stringify( { b: 2, a: 1 } )
const stableQuery = sortBy( toPairs( prunedQuery ), pair => pair[ 0 ] );
return JSON.stringify( stableQuery );
}
/**
* Returns a query object, given a serialized query
*
* @param {String} key Serialized query
* @return {Object} Query object
*/
static parse( key ) {
return this.omit( fromPairs( JSON.parse( key ) ) );
}
} |
JavaScript | class InputData extends React.Component {
// Data collection point.
constructor(props) {
super(props);
this.validation = new validator();
// We retrieve field map from dataFieldList
const fieldMap = getFields({
proportions_or_means: props.proportions_or_means,
number_of_samples: props.number_of_samples
});
this.state = {
fields: fieldMap.fields
};
}
handleChange = event => {
// Find field by id in local state and update its value property via this.setState()
const { type, value, id } = event.target;
// If input type is number, parse value to actual number type
const val = type === 'number' ? parseFloat(value) : value;
const updatedFields = this.state.fields.map(field => {
if (field.id === id) {
field.value = val;
// Reset error state
if (field.error) {
field.error = false;
field.helperText = field.hadHelperText;
}
}
return field;
});
this.setState({ fields: updatedFields });
};
onSubmit = e => {
e.preventDefault();
let isDataValid = true;
const validatedFields = this.state.fields.map(field => {
const isFieldValid = this.validation.validate(field);
// console.log('validation is: ', isFieldValid);
if (!isFieldValid) {
isDataValid = false;
field.error = true;
field.hadHelperText = field.helperText;
field.helperText = field.validation.errorMessage;
}
return field;
});
return isDataValid ? this.onDataValid() : this.setState({ fields: validatedFields });
};
onDataValid() {
// TODO: 1. Update calculator data in store. 2. Route to next page
//console.log('data is valid! Lets go to next page ho.');
// Save local fields data to central redux store.
let data = {
samples: [{}, {}],
hypothetical_mean: null,
hypothetical_proportion: null
};
const sampleKeys = ['number_of_units', 'mean', 'variance', 'proportion'];
for (let i = 0; i < this.state.fields.length; i++) {
const field = this.state.fields[i];
if (sampleKeys.includes(field.name)) {
data.samples[field.column][field.name] = field.value;
} else {
data[field.name] = field.value;
}
}
this.props.setCalculationData(data);
this.props.setStepCompleted({ name: 'data' });
this.makeCalculation(data).then(results => {
this.props.setResults(results);
this.props.setStepCompleted({ name: 'options' });
changeCalculatorStep('t-test', 'results');
});
}
makeCalculation(data) {
return calculate({
number_of_samples: this.props.number_of_samples,
proportions_or_means: this.props.proportions_or_means,
options: this.props.options,
data: data
});
}
renderField(field) {
// Render TextField
return <DataInput key={field.id} {...field} onChange={this.handleChange}></DataInput>;
}
getField(name, column) {
return this.state.fields.find(field => field.name === name && field.column == column);
}
render() {
return (
<Container maxWidth="sm">
<form noValidate autoComplete="off" onSubmit={this.onSubmit}>
<Grid container spacing={3}>
<Grid item sm={6}>
<Typography variant="body1">Prvi vzorec</Typography>
{this.state.fields.map(field => (field.column === 0 ? this.renderField(field) : null))}
</Grid>
<Grid item sm={6}>
<Typography variant="body1">
{this.props.number_of_samples === 2 ? 'Drugi vzorec' : 'Hipotetična vrednost'}
</Typography>
{this.state.fields.map(field => (field.column === 1 ? this.renderField(field) : null))}
</Grid>
</Grid>
<PageControls
nextText="naprej"
previousPage="nazaj"
nextClickHandler={this.nextClickHandler}
previousClickHandler={() => changeCalculatorStep('t-test', 'subject')}
nextButtonType="submit"
></PageControls>
</form>
</Container>
);
}
} |
JavaScript | class OAuth{
/**
* @param {Object} opts
* @param {Object} opts.consumer Consumer token (required)
* @param {string} opts.consumer.public Consumer key (public key)
* @param {string} opts.consumer.private Consumer secret
* @param {number} [opts.nonce_length=32] Length of nonce (oauth_nonce)
* @param {string} [opts.signature_method="HMAC-SHA1"] Signing algorithm
* Supported algorithm:
* - `HMAC-SHA1`
* - `PLAINTEXT`
* - `HMAC-SHA256`
*
* Note that `HMAC-256` is non-standard.
* @param {string} [opts.version=1.0] OAuth version (oauth_version)
* @param {boolean} [opts.last_ampersand=true] Whether to append trailing
* ampersand to signing key
*/
constructor(opts){
opts = opts || {}
if(!opts.consumer) {
throw new Error('consumer option is required');
}
this._opts = Object.assign({
nonce_length: 32,
signature_method: 'HMAC-SHA1',
version: '1.0',
last_ampersand: true,
parameter_seperator: ', ',
}, opts);
}
/**
* Sign a string with key
* @private
* @param {string} str String to sign
* @param {string} key HMAC key
* @return {string} Signed string in base64 format
*/
_sign(str, key){
if(!this._signer){
// Cache the signer
this._signer = this._getSigner(this._opts.signature_method);
}
return this._signer(str, key);
}
/**
* Retrieve a signing algorithm by algorithm name
* @private
* @param {string} type Algorithm name
* @throws {Error} Algorithm is not supported
* @return {Function} Algorithm implementation
*/
_getSigner(type){
if(Signer[type]){
return Signer[type];
}else{
let supported = JSON.stringify(Object.keys(Signer));
throw new Error(`Hash type ${type} not supported. Supported: ${supported}`);
}
}
/**
* Create OAuth signing data for attaching to request body
* @param {Object} request
* @param {string} request.method HTTP Method name (eg. `GET`, `POST`, `PUT`)
* @param {string} request.url URL
* @param {Object} request.data Post data as a key, value map
*
* @param {Object} [token={}] User token
* @param {string} [token.key] Token public key
* @param {string} [token.secret] Token secret key
*
* @return {Object} OAuth signing data. You probably want to put this in your POST body
*
* @example
* let request = {
* method: 'POST',
* url: 'https://api.twitter.com/1.1/statuses/update.json',
* data: {
* status: 'Hello, world!'
* }
* };
* let token = {
* public: '<user token>',
* private: '<user token secret>'
* };
* let oauth_data = oauth.authorize(request, token);
* console.log(oauth_data);
*
* @example <caption>Example response</caption>
* {
* "oauth_consumer_key": "xvz1evFS4wEEPTGEFPHBog",
* "oauth_nonce": "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",
* "oauth_signature_method": "HMAC-SHA1",
* "oauth_timestamp": 1318622958,
* "oauth_version": "1.0",
* "oauth_token": "370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb",
* "oauth_signature": "tnnArxj06cWHq44gCs1OSKk/jLY="
* }
*/
authorize(request, token){
token = token || {};
let oauth_data = this._getOAuthData(token);
oauth_data.oauth_signature = this.getSignature(request, token.secret, oauth_data);
return oauth_data;
}
/**
* Create OAuth Authorization header
* @param {Object} request
* @param {string} request.method HTTP Method name (eg. `GET`, `POST`, `PUT`)
* @param {string} request.url URL
* @param {Object} request.data Post data as a key, value map
*
* @param {Object} [token={}] User token
* @param {string} [token.key] Token public key
* @param {string} [token.secret] Token secret key
*
* @return {string} Authorization header value
*/
getHeader(request, token){
let oauth_data = this.authorize(request, token);
return Utils.toHeader(oauth_data, this._opts.parameter_seperator);
}
/**
* Format OAuth signing data for sending via HTTP Header
* @param {Object} oauth_data OAuth signing data as returned from
* {@link OAuth#authorize}
* @return {Object} Headers required to sign the request
* @deprecated This method is preserved for backward compatibility with
* oauth-1.0a. New implementors should use {@link OAuth#getHeader} instead.
*/
toHeader(oauth_data){
return {
Authorization: Utils.toHeader(oauth_data, this._opts.parameter_seperator)
};
}
/**
* Create oauth_signature from request. Usually you probably want to use
* {@link OAuth#authorize} instead.
* @param {Object} request
* @param {string} request.method HTTP Method name (eg. `GET`, `POST`, `PUT`)
* @param {string} request.url URL
* @param {Object} request.data Post data as a key, value map
*
* @param {Object} [token={}] User token
* @param {string} [token.key] Token public key
* @param {string} [token.secret] Token secret key
*
* @param {Object} oauth_data
* @param {string} oauth_data.oauth_consumer_key Consumer key
* @param {string} oauth_data.oauth_nonce Nonce string
* @param {string} oauth_data.oauth_signature_method Signing algorithm name
* (only for building signing string, the actual signing algorithm is set by
* class {@link OAuth#constructor} arguments)
* @param {number} oauth_data.oauth_timestamp Current time in seconds
* @param {string} oauth_data.oauth_version OAuth version (should be 1.0)
*
* @return {string} Value of oauth_signature field
*/
getSignature(request, token, oauth_data){
return this._sign(
this._getBaseString(request, oauth_data),
this._getSigningKey(token)
);
}
/**
* Create new OAuth data
* @private
* @param {Object} [token] User token
* @param {string} token.public Token public key
* @return {Object} OAuth data without oauth_signature
*
* @example <caption>Example response</caption>
* {
* "oauth_consumer_key": "xvz1evFS4wEEPTGEFPHBog",
* "oauth_nonce": "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",
* "oauth_signature_method": "HMAC-SHA1",
* "oauth_timestamp": 1318622958,
* "oauth_version": "1.0",
* "oauth_token": "370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb",
* }
*/
_getOAuthData(token){
let oauth_data = {
oauth_consumer_key: this._opts.consumer.public,
oauth_nonce: this._getNonce(),
oauth_signature_method: this._opts.signature_method,
oauth_timestamp: this._getTimeStamp(),
oauth_version: this._opts.version
};
if(token && token.public){
oauth_data.oauth_token = token.public;
}
return oauth_data;
}
/**
* Build authorization string to sign.
*
* An authorization string composes of HTTP method name, base URL and
* parameters (both request parameters and OAuth data)
* @private
* @param {Object} request Request object
* @param {Object} oauth_data OAuth parameters
* @return {string} Authorization string
*/
_getBaseString(request, oauth_data){
let out = [
request.method.toUpperCase(),
Utils.getBaseUrl(request.url),
Utils.getParameterString(request, oauth_data)
];
return out.map(item => Utils.percentEncode(item))
.join('&');
}
/**
* Build a query string similar to {@link querystring.encode}, but
* escape things correctly per OAuth spec
*
* @param {Object} data Object to encode as query string
* @return {string} Query string object
*/
buildQueryString(data){
data = Utils.toSortedMap(data);
return Utils.stringifyQueryMap(data, '&', '=', {
encodeURIComponent: Utils.percentEncode
});
}
/**
* Build signing key.
*
* A signing key composes of consumer secret and,
* optionally, user token secret.
*
* This method will append trailing ampersand when `token_secret` is unset
* if `last_ampersand` constructor option is set.
*
* @private
* @param {string} [token_secret] User token secret
* @return {string} Signing Key
*/
_getSigningKey(token_secret){
let out = [
this._opts.consumer.secret
];
if(this._opts.last_ampersand || token_secret){
out.push(token_secret || '');
}
return out.map(item => Utils.percentEncode(item))
.join('&');
}
/**
* Create nonce.
*
* Nonce is a random string to prevent replaying of requests.
*
* Default nonce length is 32 characters, and can be specified by
* `nonce_length` constructor option.
*
* @private
* @return {string} Nonce string
*/
_getNonce(){
return randomstring.generate({
length: this._opts.nonce_length || 32,
charset: 'alphanumeric'
});
}
/**
* Create timestamp from current time
* @private
* @return {number} Current time in seconds
*/
_getTimeStamp(){
return parseInt(new Date().getTime()/1000, 10);
}
} |
JavaScript | class SecretItem {
/**
* Create a SecretItem.
* @member {string} [id] Secret identifier.
* @member {object} [attributes] The secret management attributes.
* @member {string} [attributes.recoveryLevel] Reflects the deletion recovery
* level currently in effect for secrets in the current vault. If it contains
* 'Purgeable', the secret can be permanently deleted by a privileged user;
* otherwise, only the system can purge the secret, at the end of the
* retention interval. Possible values include: 'Purgeable',
* 'Recoverable+Purgeable', 'Recoverable',
* 'Recoverable+ProtectedSubscription'
* @member {object} [tags] Application specific metadata in the form of
* key-value pairs.
* @member {string} [contentType] Type of the secret value such as a
* password.
* @member {boolean} [managed] True if the secret's lifetime is managed by
* key vault. If this is a key backing a certificate, then managed will be
* true.
*/
constructor() {
}
/**
* Defines the metadata of SecretItem
*
* @returns {object} metadata of SecretItem
*
*/
mapper() {
return {
required: false,
serializedName: 'SecretItem',
type: {
name: 'Composite',
className: 'SecretItem',
modelProperties: {
id: {
required: false,
serializedName: 'id',
type: {
name: 'String'
}
},
attributes: {
required: false,
serializedName: 'attributes',
type: {
name: 'Composite',
className: 'SecretAttributes'
}
},
tags: {
required: false,
serializedName: 'tags',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
contentType: {
required: false,
serializedName: 'contentType',
type: {
name: 'String'
}
},
managed: {
required: false,
readOnly: true,
serializedName: 'managed',
type: {
name: 'Boolean'
}
}
}
}
};
}
} |
JavaScript | class SignatureMessageFragment {
/* @internal */
constructor(trytes) {
this._trytes = trytes;
}
/**
* Create signature fragment from trytes.
* @param signatureMessageFragment The trytes to create the signature fragment from.
* @returns An instance of SignatureMessageFragment.
*/
static fromTrytes(signatureMessageFragment) {
if (!objectHelper_1.ObjectHelper.isType(signatureMessageFragment, trytes_1.Trytes)) {
throw new dataError_1.DataError("The signatureMessageFragment should be a valid Trytes object");
}
const length = signatureMessageFragment.length();
if (length !== SignatureMessageFragment.LENGTH) {
throw new dataError_1.DataError(`The signatureMessageFragment should be ${SignatureMessageFragment.LENGTH} characters in length`, { length });
}
return new SignatureMessageFragment(signatureMessageFragment);
}
/**
* Convert the signature fragment to trytes.
* @returns Trytes version of the signature fragment.
*/
toTrytes() {
return this._trytes;
}
/**
* Get the string view of the object.
* @returns string of the trytes.
*/
toString() {
return this._trytes.toString();
}
} |
JavaScript | class Ascii {
/**
* Constructor
*
* @param {String|Ascii} value
*/
constructor(value) {
if (value instanceof Ascii) {
this[P_VALUE] = value.toString();
} else {
this[P_VALUE] = Ascii.validate(value);
}
}
/**
* Validates an ascii string.
*
* @param {String} value
* @return {String}
*/
static validate(value) {
if (value.length === 0) {
return value;
}
for (let pos = 0; pos < value.length; pos++) {
if (value.charCodeAt(pos) < 32 || value.charCodeAt(pos) > 126) {
throw new Error(`Invalid ascii - character ${value[pos]} not allowed at position ${pos}`);
}
}
return value;
}
/**
* Gets the string value itself.
*
* @returns {String}
*/
toString() {
return this[P_VALUE];
}
/**
* Gets an escaped string representation for EPasa usage.
*
* @returns {*}
*/
toStringEscaped() {
return this[P_VALUE].replace(new RegExp(REGEX_TO_ESCAPE, 'gm'), '\\$1');
}
/**
* Gets a value indicating whether the current char c1 is an escape modifier
* and the second is in the list of chars to escape.
*
* @param {String} c1
* @param {String} c2
* @returns {boolean}
*/
static isEscape(c1, c2) {
return c1 === '\\' && CHARS_TO_ESCAPE.indexOf(c2) > -1;
}
} |
JavaScript | class CentrelineDAO {
// SEGMENTS
/**
*
* @param {Array<number>} centrelineIds
* @returns {Promise<Array<CentrelineLocation>>}
*/
static async segmentsByIds(centrelineIds) {
if (centrelineIds.length === 0) {
return [];
}
const sql = `
SELECT
cm.aadt,
cm."centrelineId",
cm."centrelineType",
lsc."description",
cm."featureCode",
ST_AsGeoJSON(cm.geom)::json AS geom,
cm.lat,
cm.lng,
cm."roadId"
FROM centreline.midblocks cm
JOIN location_search.centreline lsc USING ("centrelineType", "centrelineId")
WHERE "centrelineId" IN ($(centrelineIds:csv))`;
return db.manyOrNone(sql, { centrelineIds });
}
/**
*
* @param {number} intersectionId
* @returns {Promise<Array<CentrelineLocation>>}
*/
static async segmentsIncidentTo(intersectionId) {
const sql = `
SELECT
cm.aadt,
cm."centrelineId",
cm."centrelineType",
lsc."description",
cm."featureCode",
ST_AsGeoJSON(cm.geom)::json AS geom,
cm.lat,
cm.lng,
cm."roadId"
FROM centreline.midblocks cm
JOIN location_search.centreline lsc USING ("centrelineType", "centrelineId")
WHERE fnode = $(intersectionId) OR tnode = $(intersectionId)`;
return db.manyOrNone(sql, { intersectionId });
}
// INTERSECTIONS
/**
*
* @param {Array<number>} centrelineIds
* @returns {Promise<Array<CentrelineLocation>>}
*/
static async intersectionsByIds(centrelineIds) {
if (centrelineIds.length === 0) {
return [];
}
const sql = `
SELECT
"centrelineId",
"centrelineType",
classification,
description,
"featureCode",
ST_AsGeoJSON(geom)::json AS geom,
lat,
lng
FROM centreline.intersections
WHERE "centrelineId" IN ($(centrelineIds:csv))`;
return db.manyOrNone(sql, { centrelineIds });
}
/**
*
* @param {number} segmentId
* @returns {Promise<Array<CentrelineLocation>>}
*/
static async intersectionsIncidentTo(segmentId) {
const sql = `
SELECT
ci."centrelineId",
ci."centrelineType",
ci.classification,
ci.description,
ci."featureCode",
ST_AsGeoJSON(ci.geom)::json AS geom,
ci.lat,
ci.lng
FROM centreline.intersections ci
JOIN centreline.midblocks cm ON ci."centrelineId" IN (cm.fnode, cm.tnode)
WHERE cm."centrelineId" = $(segmentId)`;
return db.manyOrNone(sql, { segmentId });
}
// COMBINED METHODS
/**
*
* @param {CentrelineFeature} feature
* @returns {Promise<CentrelineLocation?>}
*/
static async byFeature(feature) {
const locations = await CentrelineDAO.byFeatures([feature]);
const [location] = locations;
return location;
}
/**
*
* @param {Array<CentrelineFeature>} features
* @returns {Promise<Array<CentrelineLocation?>>}
*/
static async byFeatures(features) {
const segmentIds = new Set();
const intersectionIds = new Set();
features.forEach(({ centrelineId, centrelineType }) => {
if (centrelineType === CentrelineType.SEGMENT) {
segmentIds.add(centrelineId);
} else if (centrelineType === CentrelineType.INTERSECTION) {
intersectionIds.add(centrelineId);
} else {
throw new InvalidCentrelineTypeError(centrelineType);
}
});
const [rowsSegments, rowsIntersections] = await Promise.all([
CentrelineDAO.segmentsByIds([...segmentIds]),
CentrelineDAO.intersectionsByIds([...intersectionIds]),
]);
const locationMap = new Map();
rowsSegments.forEach((segment) => {
const { centrelineId } = segment;
const feature = { centrelineId, centrelineType: CentrelineType.SEGMENT };
const key = centrelineKey(feature);
locationMap.set(key, segment);
});
rowsIntersections.forEach((intersection) => {
const { centrelineId } = intersection;
const feature = { centrelineId, centrelineType: CentrelineType.INTERSECTION };
const key = centrelineKey(feature);
locationMap.set(key, intersection);
});
return features.map((feature) => {
const key = centrelineKey(feature);
const location = locationMap.get(key);
if (location === undefined) {
return null;
}
return location;
});
}
/**
* Returns the centreline features that are incident to the given feature.
* For intersections, these are the intersection legs. For segments, these
* are the segment endpoints.
*
* Note that this is *NOT* the same as *adjacent* (vertices connected by an
* edge). To understand the difference: suppose `u`, `v` are two vertices
* connected by an edge `e`. Then `e` is incident to `u`, `v` but `u`, `v`
* themselves are adjacent.
*
* @param {CentrelineType} centrelineType - type of centreline feature
* @param {number} centrelineId - ID of centreline feature
* @returns {Promise<Array<CentrelineLocation>>} incident features
*/
static async featuresIncidentTo(centrelineType, centrelineId) {
if (centrelineType === CentrelineType.SEGMENT) {
return CentrelineDAO.intersectionsIncidentTo(centrelineId);
}
if (centrelineType === CentrelineType.INTERSECTION) {
return CentrelineDAO.segmentsIncidentTo(centrelineId);
}
throw new InvalidCentrelineTypeError(centrelineType);
}
} |
JavaScript | class MuuriDirective {
constructor() {
this.restrict = 'A';
}
link(scope, element, attributes, controller) {
const node = element[0];
if (window.matchMedia('print').matches) {
node.classList.add('printable');
return;
}
const onBeforePrint = () => {
if (element.muuri) {
element.muuri.destroy();
}
node.classList.add('printable');
};
window.addEventListener('beforeprint', onBeforePrint);
scope.$on('lastItem', (slide) => {
// console.log('MuuriDirective.lastItem', slide);
this.onMuuri(scope, element, attributes);
});
scope.$on('lazyImage', (slide) => {
// console.log('lazyImage', element.muuri);
return;
if (element.muuri) {
const node = element[0];
const items = Array.from(node.querySelectorAll('.listing__item'));
element.muuri.refreshItems(items).layout();
}
});
scope.$on('$destroy', () => {
window.removeEventListener('beforeprint', onBeforePrint);
if (element.muuri) {
element.muuri.destroy();
}
});
setTimeout(() => {
this.onMuuri(scope, element, attributes);
}, 1);
}
onMuuri(scope, element, attributes) {
if (element.muuri) {
const node = element[0];
// const items = scope.$eval(attributes.muuri);
const previousItems = element.muuri.getItems().map(x => x.getElement());
// console.log('MuuriDirective.previousItems', previousItems);
const items = Array.from(node.querySelectorAll('.listing__item'));
// console.log('MuuriDirective.newItems', items);
const newItems = items.filter(x => previousItems.indexOf(x) === -1);
const removeItems = previousItems.filter(x => items.indexOf(x) === -1);
element.muuri.remove(removeItems);
element.muuri.add(newItems);
// element.muuri.refreshItems(items).layout();
} else {
element.muuri = new Muuri(element[0], {
layoutDuration: 0, // 400,
layoutEasing: 'ease',
layout: {
fillGaps: true,
horizontal: false,
alignRight: false,
alignBottom: false,
rounding: false
}
});
element.addClass('muuri-init');
scope.$emit('onMuuri');
}
}
static factory() {
return new MuuriDirective();
}
} |
JavaScript | class Main extends React.Component {
constructor() {
super();
this.state = {
stateData: toDoData,
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(id) {
// Update state so that the item with the given id flips `completed` from false to true (or vise versa)s
// console.log(`This id was clicked ${todo.id}`);
// Remember not to modify prevState directly, but instead to return a new version of state with the change you want included in that update. (Think how you might use the `.map` method to do this)
this.setState((prevState) => {
const updatedState = prevState.stateData.map((todo) => {
if (todo.id === id) {
// Old way
// todo.completed = !todo.completed;
//* Instead of modifying the previous state we will return an object that will replace todo in new array and modifying the completed property rather than modifying the old object directly
return {
...todo,
completed: !todo.completed,
};
}
return todo;
});
return {
stateData: updatedState,
};
});
}
render() {
const ToDos = this.state.stateData.map((todo) => (
<TodoItem
key={todo.id}
taskID={todo.id}
task={todo.text}
progress={todo.completed}
handleChange={this.handleChange}
/>
));
return (
<div className="App">
<div className="todo-list App">
<h1>To do list</h1>
{ToDos}
</div>
</div>
);
}
} |
JavaScript | class OtpauthInvalidURL extends Error {
/** @param {number} errorType */
constructor(errorType) {
super()
this.name = 'OtpauthInvalidURL'
this.errorType = errorType
for (const type in ErrorType)
if (ErrorType[type] === errorType)
this.message =
'Given otpauth:// URL is invalid. (Error ' + type + ')'
}
} |
JavaScript | class Parser {
/**
* Parses a character as content, without any delimiters. The current position must be that of the character, which may be an escape sequence. The new
* position will be that immediately after the character.
* <p>
* This method always allows the delimiter to be escaped.
* </p>
* @param reader The reader the contents of which to be parsed.
* @param delimiter The char code of the delimiter that surrounds the character and which should be escaped.
* @return The code point parsed from the reader, or `-1` if the unescaped delimiter was encountered.
* @throws ParseError if a control character was represented, if the character is not escaped correctly, or the reader has no more characters before the
* current character is completely parsed.
*/
parseCharacterCodePoint(reader, delimiter) {
let c = reader.readRequired; //read a character
//TODO check for and prevent control characters
if (c == delimiter) {
return -1;
} else if (c == SPEC.CHARACTER_ESCAPE) { //if this is an escape character
c = reader.readRequired; //read another a character
switch (c) { //see what the next character
case SPEC.CHARACTER_ESCAPE: //\\
case SPEC.SOLIDUS_CHAR: //\/
break; //use the escaped escape character unmodified
case SPEC.ESCAPED_BACKSPACE: //\b backspace
c = SPEC.BACKSPACE_CHAR;
break;
case SPEC.ESCAPED_FORM_FEED: //\f
c = SPEC.FORM_FEED_CHAR;
break;
case SPEC.ESCAPED_LINE_FEED: //\n
c = SPEC.LINE_FEED_CHAR;
break;
case SPEC.ESCAPED_CARRIAGE_RETURN: //\r
c = SPEC.CARRIAGE_RETURN_CHAR;
break;
case SPEC.ESCAPED_TAB: //\t
c = SPEC.CHARACTER_TABULATION_CHAR;
break;
case SPEC.ESCAPED_VERTICAL_TAB: //\v
c = SPEC.LINE_TABULATION_CHAR;
break;
case SPEC.ESCAPED_UNICODE: //u Unicode
{
const unicodeString = reader.readRequiredCount(4); //read the four Unicode code point hex characters
c = Number.parseInt(unicodeString, 16); //parse the hex characters and use the resulting code point
if (Number.isNaN(c)) { //if the hex integer was not in the correct format
throw new ParseError(`Invalid Unicode escape sequence ${unicodeString}.`);
}
if (c >= 0xD800 && c <= 0xDBFF) { //if this is a high surrogate, expect another Unicode escape sequence TODO create isHighSurrogate() method
reader.check(SPEC.CHARACTER_ESCAPE); //\
reader.check(SPEC.ESCAPED_UNICODE); //u
const unicodeString2 = reader.readRequiredCount(4);
const c2 = Number.parseInt(unicodeString2, 16);
if (Number.isNaN(c2)) { //if the hex integer was not in the correct format
throw new ParseError(`Invalid Unicode escape sequence ${unicodeString2}.`);
}
/*TODO; see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
if(!Character.isLowSurrogate(c2)) {
throw new ParseIOException(reader, "Unicode high surrogate character " + Characters.getLabel(c)
+ " must be followed by low surrogate character; found " + Characters.getLabel(c2));
}
*/
return (c - 0xD800) * 0x400 + c2 - 0xDC00 + 0x10000;
}
/*TODO
if(Character.isLowSurrogate(c)) {
throw new ParseIOException(reader, "Unicode character escape sequence cannot begin with low surrogate character " + Characters.getLabel(c));
}
*/
}
break;
default: //if another character was escaped
if (c != delimiter) { //if this is not the delimiter that was escaped
throw new ParseError(reader, `Unknown escaped character: ${c}`); //TODO use character label
}
break;
}
} else if (c >= 0xD800 && c <= 0xDBFF) { //if this is a high surrogate, expect another character TODO create isHighSurrogate() method
const c2 = reader.readRequired; //read another character
/*TODO fix
if(!Character.isLowSurrogate(c2)) {
throw new ParseIOException(reader,
"Unicode high surrogate character " + Characters.getLabel(c) + " must be followed by low surrogate character; found " + Characters.getLabel(c2));
}
*/
return (c - 0xD800) * 0x400 + c2 - 0xDC00 + 0x10000; //short-circuit and return the surrogate pair code point
/*TODO fix
} else if(Character.isLowSurrogate(c)) {
throw new ParseIOException(reader, "Unicode character cannot begin with low surrogate character " + Characters.getLabel(c));
*/
}
return c;
}
} |
JavaScript | class Serializer {
/**
* Serializes a resource graph to a string.
* <p>
* This method discovers resource references to that aliases may be generated as needed. This record of resource references is reset after serialization, but
* any generated aliases remain. This allows the same serializer to be used multiple times for the same graph, with the same aliases being used.
* </p>
* <p>
* This is a convenience method that delegates to {@link #serializeRoot(appendable, root)}.
* </p>
* @param root The root resource, or `null` if there is no resource to serialize.
* @return A serialized string representation of the given resource graph.
*/
serialize(root) {
//TODO discoverResourceReferences(root);
try {
const writer = new StringBuffer();
this.serializeRoot(writer, root);
return writer.toString();
} finally {
//TODO fix resourceHasReferenceMap.clear();
}
}
/**
* Serializes a resource graph to some appendable destination.
* <p>
* All references to the resources in the graph must have already been discovered if aliases need to be generated.
* </p>
* @param appendable The appendable to which serialized data should be appended.
* @param root The root resource, or `null` if there is no resource to serialize.
*/
serializeRoot(appendable, root) {
if (root == null) {
return;
}
this.serializeResource(appendable, root);
}
/**
* Serializes a resource to some appendable destination.
* <p>
* All references to the resources in the graph must have already been discovered if aliases need to be generated.
* </p>
* @param appendable The appendable to which serialized data should be appended.
* @param resource The resource to serialize.
*/
serializeResource(appendable, resource) {
//TODO
if (resource === "") {
appendable.append("\"\"");
return;
}
throw new Error(`Serialization of value ${JSON.stringify(resource)} not yet supported.`);
}
} |
JavaScript | class Participants extends events_1.EventEmitter {
constructor(conversation, services, participants) {
super();
this.services = services;
this.conversation = conversation;
this.participants = participants;
}
async unsubscribe() {
if (this.rosterEntityPromise) {
let entity = await this.rosterEntityPromise;
entity.close();
this.rosterEntityPromise = null;
}
}
subscribe(rosterObjectName) {
return this.rosterEntityPromise = this.rosterEntityPromise
|| this.services.syncClient.map({ id: rosterObjectName, mode: 'open_existing' })
.then(rosterMap => {
rosterMap.on('itemAdded', args => {
log.debug(this.conversation.sid + ' itemAdded: ' + args.item.key);
this.upsertParticipant(args.item.key, args.item.data)
.then(participant => {
this.emit('participantJoined', participant);
});
});
rosterMap.on('itemRemoved', args => {
log.debug(this.conversation.sid + ' itemRemoved: ' + args.key);
let participantSid = args.key;
if (!this.participants.has(participantSid)) {
return;
}
let leftParticipant = this.participants.get(participantSid);
this.participants.delete(participantSid);
this.emit('participantLeft', leftParticipant);
});
rosterMap.on('itemUpdated', args => {
log.debug(this.conversation.sid + ' itemUpdated: ' + args.item.key);
this.upsertParticipant(args.item.key, args.item.data);
});
let participantsPromises = [];
let that = this;
const rosterMapHandler = function (paginator) {
paginator.items.forEach(item => { participantsPromises.push(that.upsertParticipant(item.key, item.data)); });
return paginator.hasNextPage ? paginator.nextPage().then(rosterMapHandler) : null;
};
return rosterMap
.getItems()
.then(rosterMapHandler)
.then(() => Promise.all(participantsPromises))
.then(() => rosterMap);
})
.catch(err => {
this.rosterEntityPromise = null;
if (this.services.syncClient.connectionState != 'disconnected') {
log.error('Failed to get roster object for conversation', this.conversation.sid, err);
}
log.debug('ERROR: Failed to get roster object for conversation', this.conversation.sid, err);
throw err;
});
}
async upsertParticipant(participantSid, data) {
let participant = this.participants.get(participantSid);
if (participant) {
return participant._update(data);
}
participant = new participant_1.Participant(this.services, this.conversation, data, participantSid);
this.participants.set(participantSid, participant);
participant.on('updated', (args) => this.emit('participantUpdated', args));
return participant;
}
/**
* @returns {Promise<Array<Participant>>} returns list of participants {@see Participant}
*/
getParticipants() {
return this.rosterEntityPromise.then(() => {
let participants = [];
this.participants.forEach(participant => participants.push(participant));
return participants;
});
}
/**
* Get participant by SID from conversation
* @returns {Promise<Participant>}
*/
async getParticipantBySid(participantSid) {
return this.rosterEntityPromise.then(() => {
let participant = this.participants.get(participantSid);
if (!participant) {
throw new Error('Participant with SID ' + participantSid + ' was not found');
}
return participant;
});
}
/**
* Get participant by identity from conversation
* @returns {Promise<Participant>}
*/
async getParticipantByIdentity(identity) {
let foundParticipant = null;
return this.rosterEntityPromise.then(() => {
this.participants.forEach(participant => {
if (participant.identity === identity) {
foundParticipant = participant;
}
});
if (!foundParticipant) {
throw new Error('Participant with identity ' + identity + ' was not found');
}
return foundParticipant;
});
}
/**
* Add a chat participant to the conversation
* @returns {Promise<any>}
*/
add(identity, attributes) {
return this.services.session.addCommand('addMemberV2', {
channelSid: this.conversation.sid,
attributes: JSON.stringify(attributes),
username: identity
});
}
/**
* Add a non-chat participant to the conversation.
*
* @param proxyAddress
* @param address
* @param attributes
* @returns {Promise<any>}
*/
addNonChatParticipant(proxyAddress, address, attributes = {}) {
return this.services.session.addCommand('addNonChatParticipant', {
conversationSid: this.conversation.sid,
proxyAddress,
attributes: JSON.stringify(attributes),
address
});
}
/**
* Invites user to the conversation
* User can choose either to join or not
* @returns {Promise<any>}
*/
invite(identity) {
return this.services.session.addCommand('inviteMember', {
channelSid: this.conversation.sid,
username: identity
});
}
/**
* Remove participant from conversation by Identity
* @returns {Promise<any>}
*/
removeByIdentity(identity) {
return this.services.session.addCommand('removeMember', {
channelSid: this.conversation.sid,
username: identity
});
}
/**
* Remove participant from conversation by sid
* @returns {Promise<any>}
*/
removeBySid(sid) {
return this.services.session.addCommand('removeMember', {
channelSid: this.conversation.sid,
memberSid: sid
});
}
} |
JavaScript | class FeatureDiscoveryPrompt extends Component {
constructor (props) {
super(props);
this.promptRef = React.createRef()
}
componentDidMount () {
this.portal = document.createElement('div')
document.body.appendChild(this.portal)
this.portal.style.position = 'fixed'
this.portal.style.zIndex = 1
this.portal.style.top = 0
this.portal.style.left = 0
}
componentWillUnmount () {
unmountComponentAtNode(this.portal)
this.portal = null
}
render () {
const { theme, children, open, color, innerColor, description, title, onClose } = this.props;
const child = React.Children.only(children);
let ref;
if (!!this.promptRef.current) {
if (isElement(this.promptRef.current)) {
ref = this.promptRef.current;
} else {
if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
console.warn('material-ui-feature-discovery-prompt: the child of a FeatureDiscoveryPrompt needs to be a DOM element.')
}
}
}
const styles = {}
if (open) {
styles.opacity = 0
}
return (
<div>
{React.cloneElement(child, {ref: this.promptRef, style:styles})}
{
!!open && !!ref &&
<Portal container={this.portal}>
<Circles
backgroundColor={theme.palette[color].main}
innerColor={innerColor}
description={description}
element={ref}
onClose={onClose}
open={open}
title={title}
>
{
React.cloneElement(child, {
onClick: e => {onClose();child.props.onClick(e)},
style: {...child.props.style, position: 'relative', top:0 , left:0, right:0, bottom:0},
id: child.props.id ? `cloneOf-${child.props.id}` : null,
name: child.props.name ? `cloneOf-${child.props.name}` : null,
key: child.props.key ? `cloneOf-${child.props.key}` : null,
})
}
</Circles>
</Portal>
}
</div>
)
}
} |
JavaScript | class Service {
/**
* Configure Fee Settings.
* @static
* @param {Request} req - Request object.
* @memberof Service
* { Promise< Object | Error | Null > } A promise that resolves or rejects
*/
static async feeConfiguration(body) {
const { FeeConfigurationSpec } = body;
const newArr = [];
const array = FeeConfigurationSpec.split('\n');
array.forEach(el => {
const index = el.indexOf(':');
const arr = [el.slice(0, index), el.slice(index + 1)];
const arr1 = arr[0].trim().split(' ');
const arr2 = arr[1].trim().split(' ');
const [fee_id, fee_currency, fee_locale, entity] = arr1;
const [_, fee_type, fee_value] = arr2;
const [fee_entity, entity_property] = entity.split('(');
const obj = {
fee_id,
fee_currency,
fee_locale,
fee_entity,
entity_property: entity_property.replace(')', ''),
fee_type,
fee_value,
};
newArr.push(obj);
});
await client.set('setup', JSON.stringify(newArr));
}
/**
* Get Filter value.
* @static
* @param {Request} req - Request object.
* @memberof Service
* @returns {Object} - An Object response.
*/
static filterEntityProperty(item, body) {
switch (item.entity_property) {
case (body.ID):
return true;
case (body.Issuer):
return true;
case (body.Brand):
return true;
case (body.Number):
return true;
case (body.SixID):
return true;
default:
return (item.entity_property === '*');
}
}
/**
* Get Fee value.
* @static
* @param {Request} req - Request object.
* @memberof Service
* @returns {Integer} - An Integer response.
*/
static getFeeValue(data, amount) {
let fee;
let flat_value;
let perc_value;
switch (data.fee_type) {
case ('FLAT'):
fee = Number(data.fee_value);
break;
case ('PERC'):
fee = (Number(data.fee_value) / 100) * amount;
break;
case ('FLAT_PERC'):
[flat_value, perc_value] = data.fee_value.split(':');
fee = Number(flat_value) + (Number(perc_value) / 100) * amount;
break;
default:
break;
}
return fee;
}
/**
* Compute transaction fee.
* @static
* @param {Request} req - Request object.
* @memberof Service
* { Promise< Object | Error | Null > } A promise that resolves or rejects
*/
static async feeComputation(body) {
const { CurrencyCountry, PaymentEntity, Customer, Amount } = body;
const { Type, Country } = PaymentEntity;
const locale = (CurrencyCountry === Country) ? 'LOCL' : 'INTL';
let setup = await client.get('setup');
setup = JSON.parse(setup);
let result = setup.filter((el) => ((el.fee_locale === locale) ? true : (el.fee_locale === '*'))).sort((a, b) => (a.fee_locale > b.fee_locale ? -1 : 1));
result = result.filter((el) => ((el.fee_entity === Type) ? true : (el.fee_entity === '*'))).sort((a, b) => (a.fee_entity > b.fee_entity ? -1 : 1));
[result] = result.filter((el) => this.filterEntityProperty(el, PaymentEntity)).sort((a, b) => (a.entity_property > b.entity_property ? -1 : 1));
let computedFee = this.getFeeValue(result, Amount);
computedFee = Math.round(computedFee);
const fee = (Customer.BearsFee === true) ? (computedFee + Amount) : Amount;
return {
AppliedFeeID: result.fee_id,
AppliedFeeValue: computedFee,
ChargeAmount: fee,
SettlementAmount: (fee - computedFee)
};
}
} |
JavaScript | class AccordionGroup extends React.Component {
static defaultProps = {
isToggle: true, //says if the accordion should be toggleable
allowMultiple: false, //says if more than one accordion can be expanded at once.
callback: (DC, isOpen) => {}, // is run every time an accordion is expanded or collapsed
toggleClassName: "open", // the CSS for when the element is toggled
className: "accordionGroup", // className for the accordion group
style: {} // style for the accordion groupe
};
static Accordion = AccordionElement; // can be used instead of importing Accordion. <AccordionGroup.Accordion {..props}>panel content</AccordionGroup.Accordion>
constructor(props) {
super(props);
this.uniqueId = `Accordion-component-number${new Date().getUTCMilliseconds()}`;
this.group = `group-${this.uniqueId}`; // you can not have a single accordion placed in a group without a group element
this.accordionObj = {}; //filled below and used in the componentDidMount
this.accordionElements = []; // filled below and used in the componentDidMount
if (!this.props.children) {
throw new Error("AccordionGroup requires <Tab> components as children.");
} else {
const accordionArray = React.Children.toArray(this.props.children);
this.accordionElements = accordionArray.map(child => {
const uniqueId = `${child.props.title}-${this.uniqueId}`.replace(
/\s+/g,
"_"
); // the replace replaces spaces with _ because spaces don't work in ids very well.
this.accordionObj[`${child.props.title}-${uniqueId}`] = (
<React.Fragment>{child.props.children}</React.Fragment>
); // This is what is passed into the componentDidMount function into AccDC
return (
<React.Fragment key={uniqueId}>
{React.createElement(
child.props.triggeringElement,
{
className: child.props.className,
style: child.props.style,
"data-controls": `${child.props.title}-${uniqueId}`,
"data-insert": `content-${uniqueId}`,
"data-defaultopen": child.props.defaultOpen,
"data-accordiongroup": this.group,
id: uniqueId
},
child.props.title
)}
<div id={`content-${uniqueId}`} />
</React.Fragment>
);
});
}
}
componentDidMount() {
strap.setAccordion(this, this.accordionObj, {
callback: this.props.callback,
isToggle: this.props.isToggle,
allowMultiple: this.props.allowMultiple,
overrides: {
toggleClassName: this.props.toggleClassName
}
});
}
render() {
return (
<div
id={this.uniqueId}
className={this.props.className}
style={this.props.style}
>
{this.accordionElements}
</div>
);
}
} |
JavaScript | class AsyncForEach {
/**
* Creates an AsyncForEach instance
* with the given iterable
* @param {Iterable} iterable
*/
constructor(iterable) {
/**
* @ignore
*/
this.iterable = iterable;
}
/**
* Initiate iteration of items from the iterable
* @param {Function} scope
* @returns {Promise}
*/
do(scope) {
let prev;
// eslint-disable-next-line no-restricted-syntax
for (const item of this.iterable) {
if (typeof prev === 'undefined') {
prev = defer(item, scope);
} else {
prev = prev.then(() => defer(item, scope));
}
}
return resolve(prev);
}
} |
JavaScript | class User {
/**
* @description The User logged in.
*
* @param {MakerBot} client - The MakerBot client
* @returns {Object}
*
*/
constructor (client) {
/**
* The MakerBot Client
* @type {MakerBot}
*/
this.client = client;
/**
* The id
* @type {String|number}
*/
this.id = null;
/**
* The name/username
* @type {String|null}
*/
this.username = null;
/**
* The first name
* @type {String}
*/
this.first_name = null;
/**
* The last name
* @type {String}
*/
this.last_name = null;
/**
* The image id of the user
* @type {String|number}
*/
this.image_id = null;
/**
* The indrustry the user is from
* @type {String|null}
*/
this.industry = null;
/**
* Is an admin (Might be Makerbot Internal var)
* @type {Boolean}
* @default false
*/
this.is_admin = null;
/**
* Is an creator (Might be Makerbot Internal var)
* @type {Boolean}
* @default false
*/
this.is_curator = null;
/**
* Is an creator (Might be Makerbot Internal var)
* @type {Boolean}
* @default false
*/
this.is_moderator = null;
/**
* Can the user signin with sso?
* @type {Boolean}
* @default false
*/
this.has_active_sso = null;
/**
* Does the user have a password?
* @type {Boolean}
* @default true
*/
this.has_basic_auth = null;
/**
* The country the user is from
* @type {String}
* @default 'US'
*/
this.country = null;
/**
* Was the user forced to change their password?
* @type {Boolean}
* @default false
*/
this.forced_pass_reset = null;
// this.user_attributes = null;
/**
* The Users full name
* @type {String}
*/
this.full_name = null;
/**
* The Users username
* @type {String}
*/
this.name = null;
/**
* The Users email address
* @type {String}
*/
this.email = null;
// this.tokens = null;
/**
* The Users Profile Image
* @type {URL|String}
*/
this.thumbnail = null;
/**
* The Users Notification Settings
* @type {Object}
* @param {Boolean} notificationSetting.isNotificationEnabled
* @param {Boolean} notificationSetting.isOnlyOwnPrintJobs
*/
this.notificationSetting = {
isNotificationEnabled: true,
isOnlyOwnPrintJobs: true
};
// this.registrationInfo;
/**
* The basic Info Of the User
* @type {TeamUser}
*/
this.teamsUser = null;
// this.teams;
// this.generalSettings
this.client.emit('debug', `Loading User`);
return this.getUser();
}
getUser () {
if (this.client.options.debug) this.client.emit('debug', `Getting User`);
return new Promise((resolve, reject) => {
this.client.http.get('/user').then(response => {
if (response.status !== 200) throw new Error(`User.getUser() - ${response.statusCode} - ${response.statusMessage}`);
Object.keys(response.data).forEach(key => {
if (!Object.keys(this).includes(key)) return;
if (key === 'teamsUser') {
this.teamsUser = new TeamUser(this.client, response.data[key]);
} else this[key] = response.data[key];
});
if (this.client.options.debug) this.client.emit('debug', `User Loaded: ${this.full_name}`);
return resolve(this);
}).catch(error => {
if (this.client.debug) this.client.emit('debug', "Login failed: " + error.message);
this.client.emit('error', error);
throw error;
})
});
}
} |
JavaScript | class InlineObject118 {
/**
* Constructs a new <code>InlineObject118</code>.
* @alias module:model/InlineObject118
* @param state {module:model/InlineObject118.StateEnum} The state of the status. Can be one of `error`, `failure`, `pending`, or `success`.
*/
constructor(state) {
InlineObject118.initialize(this, state);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj, state) {
obj['state'] = state;
}
/**
* Constructs a <code>InlineObject118</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/InlineObject118} obj Optional instance to populate.
* @return {module:model/InlineObject118} The populated <code>InlineObject118</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new InlineObject118();
if (data.hasOwnProperty('context')) {
obj['context'] = ApiClient.convertToType(data['context'], 'String');
}
if (data.hasOwnProperty('description')) {
obj['description'] = ApiClient.convertToType(data['description'], 'String');
}
if (data.hasOwnProperty('state')) {
obj['state'] = ApiClient.convertToType(data['state'], 'String');
}
if (data.hasOwnProperty('target_url')) {
obj['target_url'] = ApiClient.convertToType(data['target_url'], 'String');
}
}
return obj;
}
} |
JavaScript | class Node {
constructor(val) {
this.value = val;
this.prev = null;
this.next = null;
}
} |
JavaScript | class App extends React.Component {
render() {
return (
<AppWrapper>
<Helmet
titleTemplate="%s | React Quickstart"
defaultTitle="React Quickstart"
>
<meta
name="description"
content="React starter kit for single page web applications development."
/>
</Helmet>
<Header />
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/counter" component={ManageCounterPage} />
<Route component={NotFoundPage} />
</Switch>
</AppWrapper>
);
}
} |
JavaScript | class HomePage extends Component {
constructor() {
super();
this.state = {
books: [
// {
// title: 'Early Transcendentals',
// author: 'Stewart',
// image: 'https://images-na.ssl-images-amazon.com/images/I/51xUmFAz%2BVL._SX258_BO1,204,203,200_.jpg',
// id: '596fea7c734d1d6202a70d1f'
// },
// {
// title: 'Calculus',
// author: 'Anton, Bivens, Davis',
// image: 'https://prodimage.images-bn.com/pimages/9780470647691_p0_v2_s192x300.jpg',
// id: '2'
// }
],
open: false,
explore: false
};
}
componentDidMount() {
axios.post('http://localhost:3000/', {
id: this.props.user.id
}, {
headers: {
'Authorization': 'Bearer ' + this.props.token
}
})
.then((res) => {
if (res.data.success) {
this.setState({
books: res.data.books
});
console.log('BOOKS', this.state.books);
}
})
.catch((err) => {
console.log('ERR', err);
})
}
onLogout() {
this.props.logout();
}
onExplore() {
this.setState({
explore: true
})
}
onNav(e) {
// This prevents ghost click.
e.preventDefault();
this.setState({
open: true,
anchorEl: e.currentTarget
});
};
handleRequestClose = () => {
this.setState({
open: false,
});
};
render() {
if (!this.props.token) {
return <Redirect to='/login' />;
}
if (this.state.explore) {
return <Redirect to='/explore' />;
}
return (
<div>
<div className={CSSstyles.nav}>
<RaisedButton
onClick={(e) => this.onNav(e)}
label="Navigate"
/>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}
onRequestClose={this.handleRequestClose}
animation={PopoverAnimationVertical}
>
<Menu>
<MenuItem primaryText="Explore" onClick={() => {this.onExplore()}}/>
<MenuItem primaryText="Logout" onClick={() => {this.onLogout()}}/>
</Menu>
</Popover>
</div>
<div className={styles.container}>
<img src='./visuals/logo-small.png'/>
</div>
<div className= {styles.bookStream}>
<BookStream books={this.state.books}/>
</div>
</div>
);
}
} |
JavaScript | class RenderableInstance {
/**
* @constructor
* @param {Defiant.Plugin.Theme.Renderable} renderable
* The Renderable that this is an instance of.
* @param {Object} setup
* The configuration object.
* @param {Defiant.Context} context
* The request context.
* @returns {Defiant.Plugin.Theme.RenderableInstance}
* The instantiation of the RenderableInstance.
*/
constructor(renderable, setup, context) {
/**
* @member {Defiant.Plugin.Theme.RenderableInstance} Defiant.Plugin.Theme.RenderableInstance#parent
* The "parent" of this Renderable, if applicable. Mostly useful with
* [CollectionInstances]{@link Defiant.Plugin.Theme.CollectionInstance}.
*/
this.parent = undefined;
/**
* @member {Defiant.Plugin.Theme.Renderable} Defiant.Plugin.Theme.RenderableInstance#renderable
* The Renderable that created this instance.
*/
this.renderable = renderable;
[
/**
* @member {String} Defiant.Plugin.Theme.RenderableInstance#id
* The id of the Renderable.
*/
'id',
/**
* @member {String} Defiant.Plugin.Theme.RenderableInstance#name
* The name of this instance. You may wish for the name to be unique
* within a single request. This name is the unique identifier used by
* the [CollectionInstance]{@link Defiant.Plugin.Theme.CollectionInstance}.
*/
'name',
/**
* @member {number} Defiant.Plugin.Theme.RenderableInstance#weight
* The weight of this instance (helpful when putting Renderables into a
* [Collection]{@link Defiant.Plugin.Theme.Collection}).
*/
'weight'].map(key => this[key] = setup[key] ? setup[key] : this.constructor[key]);
/**
* @member {Object} Defiant.Plugin.Theme.RenderableInstance#data
* The setup data.
*/
this.data = clone(setup.data || {});
/**
* @member {Defiant.Context} Defiant.Plugin.Theme.RenderableInstance#context
* The request context.
*/
this.context = context;
}
/**
* Perform any initialization needed, and in particular, async operations.
*
* When this function is finished, then the renderable should be ready to
* be rendered as a string.
* @function
* @async
* @param {Object} [data={}]
* The initialization data.
*/
async init(data={}) {
this.data = merge(this.data, data);
}
/**
* Take all data that was passed in via the constructor as well as any work
* done by the [init()]{@link Defiant.Plugin.Theme.RenderableInstance#init},
* and compile it using the
* [Renderable.templateFunction]{@link Defiant.Plugin.Theme.Renderable#templateFunction}.
* @function
* @async
* @returns {String}
* The final string that should be provided to the user.
*/
async commit() {
return this.renderable.templateFunction(this.data);
}
/**
* Helper function to return the RenderableInstance that is at the root of a
* tree-like structure. A tree-like structure is common with
* [Collections]{@link Defiant.Plugin.Theme.Collection}.
* @function
* @returns {Defiant.Plugin.Theme.Renderable.RenderableInstance}
* If the Renderables are in a tree structure, return the root of the tree.
*/
getTopmostParent() {
return this.parent ? this.parent.getTopmostParent() : this;
}
} |
JavaScript | class TypingIndicatorContainer extends Component {
static propTypes = {
client: PropTypes.object,
conversationId: PropTypes.string,
}
// Necessary in order to grab client out of the context.
// TODO: May want to rename to layerClient to avoid conflicts.
static contextTypes = {
client: PropTypes.object,
}
constructor(props, context) {
super(props, context);
this.client = props.client || context.client;
this.state = {
typing: [],
paused: [],
};
}
componentWillMount() {
this.client.on('typing-indicator-change', this.onTypingIndicatorChange);
}
onTypingIndicatorChange = ({ conversationId, typing, paused }) => {
if (conversationId === this.props.conversationId) {
this.setState({
typing,
paused,
});
}
}
componentWillReceiveProps(nextProps) {
if (this.props.conversationId !== nextProps.conversationId) {
this.setState({
typing: [],
paused: [],
});
}
}
render() {
return <ComposedComponent {...this.props} {...this.state} />;
}
componentWillUnmount() {
this.client.off('typing-indicator-change', this.onTypingIndicatorChange);
}
} |
JavaScript | class AbstractTravianScanner extends TravianScannerInterface {
constructor(travianDocumentScanner) {
super();
this.travianDocumentScanner = travianDocumentScanner;
}
r() {
return this.travianDocumentScanner.r();
}
// Get element by id
g(aID) {
return this.travianDocumentScanner.g(aID);
}
// Get element by name
gn(aID) {
return this.travianDocumentScanner.gn(aID);
}
// Get element by tag name
gt(tagName, root = undefined) {
return this.travianDocumentScanner.gt(tagName, root);
}
// Get element by class name
gc(className, root = undefined) {
return this.travianDocumentScanner.gc(className, root);
}
// Get events that can be occurred while scanning
getEvents() {
return {};
}
} |
JavaScript | class Manager extends Employee{
constructor(name, id, email, officeNumber){
super(name, id, email);
if (typeof officeNumber !== "number" || isNaN(officeNumber) || officeNumber <= 0) {
throw new Error("Expected parameter 'officeNumber' to be a non-empty number");
}
// Add officeNumber attribute
this.officeNumber = officeNumber;
}
// add getOfficeNumber method
getOfficeNumber(){
return this.officeNumber;
}
// Add get role method, hard coded as "Manager"
getRole(){
return "Manager"
}
} |
JavaScript | class MapWithDeprecations {
constructor(options) {
this._map = new Map();
}
copy() {
(true && !(false) && Ember.deprecate('Calling `.copy()` on a map generated by ember-data is deprecated, please migrate to using native Map functionality only.', false, { id: 'ember-data.map.copy', until: '3.5.0' }));
// can't just pass `this._map` here because IE11 doesn't accept
// constructor args with its `Map`
var newMap = new MapWithDeprecations();
this._map.forEach(function (value, key) {
newMap.set(key, value);
});
return newMap;
}
isEmpty() {
(true && !(false) && Ember.deprecate('Calling `.isEmpty()` on a map generated by ember-data is deprecated, please migrate to using native Map functionality only.', false, { id: 'ember-data.map.isEmpty', until: '3.5.0' }));
return this.size === 0;
}
// proxy all normal Map methods to the underlying Map
get size() {
return this._map.size;
}
clear() {
return this._map.clear(...arguments);
}
delete() {
return this._map.delete(...arguments);
}
entries() {
return this._map.entries(...arguments);
}
forEach() {
return this._map.forEach(...arguments);
}
get() {
return this._map.get(...arguments);
}
has() {
return this._map.has(...arguments);
}
keys() {
return this._map.keys(...arguments);
}
set() {
return this._map.set(...arguments);
}
values() {
return this._map.values(...arguments);
}
} |
JavaScript | class RecordReference extends Reference {
constructor(store, internalModel) {
super(store, internalModel);
this.type = internalModel.modelName;
this._id = internalModel.id;
}
/**
The `id` of the record that this reference refers to.
Together, the `type` and `id` properties form a composite key for
the identity map.
Example
```javascript
let userRef = store.getReference('user', 1);
userRef.id(); // '1'
```
@method id
@return {String} The id of the record.
*/
id() {
return this._id;
}
/**
How the reference will be looked up when it is loaded: Currently
this always return `identity` to signifying that a record will be
loaded by the `type` and `id`.
Example
```javascript
const userRef = store.getReference('user', 1);
userRef.remoteType(); // 'identity'
```
@method remoteType
@return {String} 'identity'
*/
remoteType() {
return 'identity';
}
/**
This API allows you to provide a reference with new data. The
simplest usage of this API is similar to `store.push`: you provide a
normalized hash of data and the object represented by the reference
will update.
If you pass a promise to `push`, Ember Data will not ask the adapter
for the data if another attempt to fetch it is made in the
interim. When the promise resolves, the underlying object is updated
with the new data, and the promise returned by *this function* is resolved
with that object.
For example, `recordReference.push(promise)` will be resolved with a
record.
Example
```javascript
let userRef = store.getReference('user', 1);
// provide data for reference
userRef.push({ data: { id: 1, username: "@user" }}).then(function(user) {
userRef.value() === user;
});
```
@method push
@param objectOrPromise {Promise|Object}
@return Promise<record> a promise for the value (record or relationship)
*/
push(objectOrPromise) {
return Ember.RSVP.resolve(objectOrPromise).then(data => {
return this.store.push(data);
});
}
/**
If the entity referred to by the reference is already loaded, it is
present as `reference.value`. Otherwise the value returned by this function
is `null`.
Example
```javascript
let userRef = store.getReference('user', 1);
userRef.value(); // user
```
@method value
@return {DS.Model} the record for this RecordReference
*/
value() {
if (this.internalModel.hasRecord) {
return this.internalModel.getRecord();
}
return null;
}
/**
Triggers a fetch for the backing entity based on its `remoteType`
(see `remoteType` definitions per reference type).
Example
```javascript
let userRef = store.getReference('user', 1);
// load user (via store.find)
userRef.load().then(...)
```
@method load
@return {Promise<record>} the record for this RecordReference
*/
load() {
return this.store.findRecord(this.type, this._id);
}
/**
Reloads the record if it is already loaded. If the record is not
loaded it will load the record via `store.findRecord`
Example
```javascript
let userRef = store.getReference('user', 1);
// or trigger a reload
userRef.reload().then(...)
```
@method reload
@return {Promise<record>} the record for this RecordReference
*/
reload() {
var record = this.value();
if (record) {
return record.reload();
}
return this.load();
}
} |
JavaScript | class BelongsToReference extends Reference {
constructor(store, parentInternalModel, belongsToRelationship) {
super(store, parentInternalModel);
this.belongsToRelationship = belongsToRelationship;
this.type = belongsToRelationship.relationshipMeta.type;
this.parent = parentInternalModel.recordReference;
// TODO inverse
}
/**
This returns a string that represents how the reference will be
looked up when it is loaded. If the relationship has a link it will
use the "link" otherwise it defaults to "id".
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
});
let userRef = blog.belongsTo('user');
// get the identifier of the reference
if (userRef.remoteType() === "id") {
let id = userRef.id();
} else if (userRef.remoteType() === "link") {
let link = userRef.link();
}
```
@method remoteType
@return {String} The name of the remote type. This should either be "link" or "id"
*/
remoteType() {
if (this.belongsToRelationship.link) {
return 'link';
}
return 'id';
}
/**
The `id` of the record that this reference refers to. Together, the
`type()` and `id()` methods form a composite key for the identity
map. This can be used to access the id of an async relationship
without triggering a fetch that would normally happen if you
attempted to use `record.get('relationship.id')`.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
}
});
let userRef = blog.belongsTo('user');
// get the identifier of the reference
if (userRef.remoteType() === "id") {
let id = userRef.id();
}
```
@method id
@return {String} The id of the record in this belongsTo relationship.
*/
id() {
var inverseInternalModel = this.belongsToRelationship.inverseInternalModel;
return inverseInternalModel && inverseInternalModel.id;
}
/**
The link Ember Data will use to fetch or reload this belongs-to
relationship.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
links: {
related: '/articles/1/author'
}
}
}
}
});
let userRef = blog.belongsTo('user');
// get the identifier of the reference
if (userRef.remoteType() === "link") {
let link = userRef.link();
}
```
@method link
@return {String} The link Ember Data will use to fetch or reload this belongs-to relationship.
*/
link() {
return this.belongsToRelationship.link;
}
/**
The meta data for the belongs-to relationship.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
links: {
related: {
href: '/articles/1/author',
meta: {
lastUpdated: 1458014400000
}
}
}
}
}
}
});
let userRef = blog.belongsTo('user');
userRef.meta() // { lastUpdated: 1458014400000 }
```
@method meta
@return {Object} The meta information for the belongs-to relationship.
*/
meta() {
return this.belongsToRelationship.meta;
}
/**
`push` can be used to update the data in the relationship and Ember
Data will treat the new data as the conanical value of this
relationship on the backend.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
}
});
let userRef = blog.belongsTo('user');
// provide data for reference
userRef.push({
data: {
type: 'user',
id: 1,
attributes: {
username: "@user"
}
}
}).then(function(user) {
userRef.value() === user;
});
```
@method push
@param {Object|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship.
@return {Promise<record>} A promise that resolves with the new value in this belongs-to relationship.
*/
push(objectOrPromise) {
return Ember.RSVP.resolve(objectOrPromise).then(data => {
var record = void 0;
if (data instanceof Model) {
record = data;
} else {
record = this.store.push(data);
}
Debug.assertPolymorphicType(this.internalModel, this.belongsToRelationship.relationshipMeta, record._internalModel, this.store);
this.belongsToRelationship.setCanonicalInternalModel(record._internalModel);
return record;
});
}
/**
`value()` synchronously returns the current value of the belongs-to
relationship. Unlike `record.get('relationshipName')`, calling
`value()` on a reference does not trigger a fetch if the async
relationship is not yet loaded. If the relationship is not loaded
it will always return `null`.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
}
});
let userRef = blog.belongsTo('user');
userRef.value(); // null
// provide data for reference
userRef.push({
data: {
type: 'user',
id: 1,
attributes: {
username: "@user"
}
}
}).then(function(user) {
userRef.value(); // user
});
```
@method value
@return {DS.Model} the record in this relationship
*/
value() {
var inverseInternalModel = this.belongsToRelationship.inverseInternalModel;
if (inverseInternalModel && inverseInternalModel.isLoaded()) {
return inverseInternalModel.getRecord();
}
return null;
}
/**
Loads a record in a belongs to-relationship if it is not already
loaded. If the relationship is already loaded this method does not
trigger a new load.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
}
});
let userRef = blog.belongsTo('user');
userRef.value(); // null
userRef.load().then(function(user) {
userRef.value() === user
});
```
You may also pass in an options object whose properties will be
fed forward. This enables you to pass `adapterOptions` into the
request given to the adapter via the reference.
Example
```javascript
userRef.load({ adapterOptions: { isPrivate: true } }).then(function(user) {
userRef.value() === user;
});
```
```app/adapters/user.js
export default ApplicationAdapter.extend({
findRecord(store, type, id, snapshot) {
// In the adapter you will have access to adapterOptions.
let adapterOptions = snapshot.adapterOptions;
}
});
```
@method load
@param {Object} options the options to pass in.
@return {Promise} a promise that resolves with the record in this belongs-to relationship.
*/
load(options) {
var rel = this.belongsToRelationship;
rel.getData(options);
if (rel.fetchPromise !== null) {
return rel.fetchPromise.then(() => {
return this.value();
});
}
return Ember.RSVP.resolve(this.value());
}
/**
Triggers a reload of the value in this relationship. If the
remoteType is `"link"` Ember Data will use the relationship link to
reload the relationship. Otherwise, it will reload the record by its
id.
Example
```javascript
// models/blog.js
export default DS.Model.extend({
user: DS.belongsTo({ async: true })
});
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
}
});
let userRef = blog.belongsTo('user');
userRef.reload().then(function(user) {
userRef.value() === user
});
```
You may also pass in an options object whose properties will be
fed forward. This enables you to pass `adapterOptions` into the
request given to the adapter via the reference. A full example
can be found in the `load` method.
Example
```javascript
userRef.reload({ adapterOptions: { isPrivate: true } })
```
@method reload
@param {Object} options the options to pass in.
@return {Promise} a promise that resolves with the record in this belongs-to relationship after the reload has completed.
*/
reload(options) {
return this.belongsToRelationship.reload(options).then(internalModel => {
return this.value();
});
}
} |
JavaScript | class HasManyReference extends Reference {
constructor(store, parentInternalModel, hasManyRelationship) {
super(store, parentInternalModel);
this.hasManyRelationship = hasManyRelationship;
this.type = hasManyRelationship.relationshipMeta.type;
this.parent = parentInternalModel.recordReference;
// TODO inverse
}
/**
This returns a string that represents how the reference will be
looked up when it is loaded. If the relationship has a link it will
use the "link" otherwise it defaults to "id".
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
data: [{ type: 'comment', id: 1 }]
}
}
}
});
let commentsRef = post.hasMany('comments');
// get the identifier of the reference
if (commentsRef.remoteType() === "ids") {
let ids = commentsRef.ids();
} else if (commentsRef.remoteType() === "link") {
let link = commentsRef.link();
}
```
@method remoteType
@return {String} The name of the remote type. This should either be "link" or "ids"
*/
remoteType() {
if (this.hasManyRelationship.link) {
return 'link';
}
return 'ids';
}
/**
The link Ember Data will use to fetch or reload this has-many
relationship.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
links: {
related: '/posts/1/comments'
}
}
}
}
});
let commentsRef = post.hasMany('comments');
commentsRef.link(); // '/posts/1/comments'
```
@method link
@return {String} The link Ember Data will use to fetch or reload this has-many relationship.
*/
link() {
return this.hasManyRelationship.link;
}
/**
`ids()` returns an array of the record IDs in this relationship.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
data: [{ type: 'comment', id: 1 }]
}
}
}
});
let commentsRef = post.hasMany('comments');
commentsRef.ids(); // ['1']
```
@method ids
@return {Array} The ids in this has-many relationship
*/
ids() {
var members = this.hasManyRelationship.members.toArray();
return members.map(function (internalModel) {
return internalModel.id;
});
}
/**
The metadata for the has-many relationship.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
links: {
related: {
href: '/posts/1/comments',
meta: {
count: 10
}
}
}
}
}
}
});
let commentsRef = post.hasMany('comments');
commentsRef.meta(); // { count: 10 }
```
@method meta
@return {Object} The meta information for the has-many relationship.
*/
meta() {
return this.hasManyRelationship.meta;
}
/**
`push` can be used to update the data in the relationship and Ember
Data will treat the new data as the canonical value of this
relationship on the backend.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
data: [{ type: 'comment', id: 1 }]
}
}
}
});
let commentsRef = post.hasMany('comments');
commentsRef.ids(); // ['1']
commentsRef.push([
[{ type: 'comment', id: 2 }],
[{ type: 'comment', id: 3 }],
])
commentsRef.ids(); // ['2', '3']
```
@method push
@param {Array|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship.
@return {DS.ManyArray}
*/
push(objectOrPromise) {
return Ember.RSVP.resolve(objectOrPromise).then(payload => {
var array = payload;
if (typeof payload === 'object' && payload.data) {
array = payload.data;
}
var internalModels = void 0;
internalModels = array.map(obj => {
var record = this.store.push(obj);
{
var relationshipMeta = this.hasManyRelationship.relationshipMeta;
Debug.assertPolymorphicType(this.internalModel, relationshipMeta, record._internalModel, this.store);
}
return record._internalModel;
});
this.hasManyRelationship.computeChanges(internalModels);
return this.hasManyRelationship.manyArray;
});
}
_isLoaded() {
var hasRelationshipDataProperty = Ember.get(this.hasManyRelationship, 'hasAnyRelationshipData');
if (!hasRelationshipDataProperty) {
return false;
}
var members = this.hasManyRelationship.members.toArray();
return members.every(function (internalModel) {
return internalModel.isLoaded() === true;
});
}
/**
`value()` synchronously returns the current value of the has-many
relationship. Unlike `record.get('relationshipName')`, calling
`value()` on a reference does not trigger a fetch if the async
relationship is not yet loaded. If the relationship is not loaded
it will always return `null`.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
data: [{ type: 'comment', id: 1 }]
}
}
}
});
let commentsRef = post.hasMany('comments');
post.get('comments').then(function(comments) {
commentsRef.value() === comments
})
```
@method value
@return {DS.ManyArray}
*/
value() {
if (this._isLoaded()) {
return this.hasManyRelationship.manyArray;
}
return null;
}
/**
Loads the relationship if it is not already loaded. If the
relationship is already loaded this method does not trigger a new
load.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
data: [{ type: 'comment', id: 1 }]
}
}
}
});
let commentsRef = post.hasMany('comments');
commentsRef.load().then(function(comments) {
//...
});
```
You may also pass in an options object whose properties will be
fed forward. This enables you to pass `adapterOptions` into the
request given to the adapter via the reference.
Example
```javascript
commentsRef.load({ adapterOptions: { isPrivate: true } })
.then(function(comments) {
//...
});
```
```app/adapters/comment.js
export default ApplicationAdapter.extend({
findMany(store, type, id, snapshots) {
// In the adapter you will have access to adapterOptions.
let adapterOptions = snapshots[0].adapterOptions;
}
});
```
@method load
@param {Object} options the options to pass in.
@return {Promise} a promise that resolves with the ManyArray in
this has-many relationship.
*/
load(options) {
// TODO this can be simplified
if (!this._isLoaded()) {
return this.hasManyRelationship.getData(options);
}
return Ember.RSVP.resolve(this.hasManyRelationship.manyArray);
}
/**
Reloads this has-many relationship.
Example
```app/models/post.js
export default DS.Model.extend({
comments: DS.hasMany({ async: true })
});
```
```javascript
let post = store.push({
data: {
type: 'post',
id: 1,
relationships: {
comments: {
data: [{ type: 'comment', id: 1 }]
}
}
}
});
let commentsRef = post.hasMany('comments');
commentsRef.reload().then(function(comments) {
//...
});
```
You may also pass in an options object whose properties will be
fed forward. This enables you to pass `adapterOptions` into the
request given to the adapter via the reference. A full example
can be found in the `load` method.
Example
```javascript
commentsRef.reload({ adapterOptions: { isPrivate: true } })
```
@method reload
@param {Object} options the options to pass in.
@return {Promise} a promise that resolves with the ManyArray in this has-many relationship.
*/
reload(options) {
return this.hasManyRelationship.reload(options);
}
} |
JavaScript | class InternalModel {
constructor(modelName, id, store, data) {
this.id = id;
// this ensure ordered set can quickly identify this as unique
this[Ember.GUID_KEY] = InternalModelReferenceId++ + 'internal-model';
this.store = store;
this.modelName = modelName;
this._promiseProxy = null;
this._record = null;
this._isDestroyed = false;
this.isError = false;
this._pendingRecordArrayManagerFlush = false; // used by the recordArrayManager
// During dematerialization we don't want to rematerialize the record. The
// reason this might happen is that dematerialization removes records from
// record arrays, and Ember arrays will always `objectAt(0)` and
// `objectAt(len - 1)` to test whether or not `firstObject` or `lastObject`
// have changed.
this._isDematerializing = false;
this._scheduledDestroy = null;
this.resetRecord();
if (data) {
this.__data = data;
}
// caches for lazy getters
this._modelClass = null;
this.__deferredTriggers = null;
this.__recordArrays = null;
this._references = null;
this._recordReference = null;
this.__relationships = null;
this.__implicitRelationships = null;
// Used during the mark phase of unloading to avoid checking the same internal
// model twice in the same scan
this._bfsId = 0;
}
get modelClass() {
return this._modelClass || (this._modelClass = this.store.modelFor(this.modelName));
}
get type() {
return this.modelClass;
}
get recordReference() {
if (this._recordReference === null) {
this._recordReference = new RecordReference(this.store, this);
}
return this._recordReference;
}
get _recordArrays() {
if (this.__recordArrays === null) {
this.__recordArrays = new EmberDataOrderedSet();
}
return this.__recordArrays;
}
get references() {
if (this._references === null) {
this._references = Object.create(null);
}
return this._references;
}
get _deferredTriggers() {
if (this.__deferredTriggers === null) {
this.__deferredTriggers = [];
}
return this.__deferredTriggers;
}
get _attributes() {
if (this.__attributes === null) {
this.__attributes = Object.create(null);
}
return this.__attributes;
}
set _attributes(v) {
this.__attributes = v;
}
get _relationships() {
if (this.__relationships === null) {
this.__relationships = new Relationships(this);
}
return this.__relationships;
}
get _inFlightAttributes() {
if (this.__inFlightAttributes === null) {
this.__inFlightAttributes = Object.create(null);
}
return this.__inFlightAttributes;
}
set _inFlightAttributes(v) {
this.__inFlightAttributes = v;
}
get _data() {
if (this.__data === null) {
this.__data = Object.create(null);
}
return this.__data;
}
set _data(v) {
this.__data = v;
}
/*
implicit relationships are relationship which have not been declared but the inverse side exists on
another record somewhere
For example if there was
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr()
})
```
but there is also
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr(),
comments: DS.hasMany('comment')
})
```
would have a implicit post relationship in order to be do things like remove ourselves from the post
when we are deleted
*/
get _implicitRelationships() {
if (this.__implicitRelationships === null) {
this.__implicitRelationships = Object.create(null);
}
return this.__implicitRelationships;
}
isHiddenFromRecordArrays() {
// During dematerialization we don't want to rematerialize the record.
// recordWasDeleted can cause other records to rematerialize because it
// removes the internal model from the array and Ember arrays will always
// `objectAt(0)` and `objectAt(len -1)` to check whether `firstObject` or
// `lastObject` have changed. When this happens we don't want those
// models to rematerialize their records.
return this._isDematerializing || this.hasScheduledDestroy() || this.isDestroyed || this.currentState.stateName === 'root.deleted.saved' || this.isEmpty();
}
isEmpty() {
return this.currentState.isEmpty;
}
isLoading() {
return this.currentState.isLoading;
}
isLoaded() {
return this.currentState.isLoaded;
}
hasDirtyAttributes() {
return this.currentState.hasDirtyAttributes;
}
isSaving() {
return this.currentState.isSaving;
}
isDeleted() {
return this.currentState.isDeleted;
}
isNew() {
return this.currentState.isNew;
}
isValid() {
return this.currentState.isValid;
}
dirtyType() {
return this.currentState.dirtyType;
}
getRecord(properties) {
if (!this._record && !this._isDematerializing) {
// lookupFactory should really return an object that creates
// instances with the injections applied
var createOptions = {
store: this.store,
_internalModel: this,
currentState: this.currentState,
isError: this.isError,
adapterError: this.error
};
if (properties !== undefined) {
(true && !(typeof properties === 'object' && properties !== null) && Ember.assert(`You passed '${properties}' as properties for record creation instead of an object.`, typeof properties === 'object' && properties !== null));
var classFields = this.getFields();
var relationships = this._relationships;
var propertyNames = Object.keys(properties);
for (var i = 0; i < propertyNames.length; i++) {
var name = propertyNames[i];
var fieldType = classFields.get(name);
var propertyValue = properties[name];
if (name === 'id') {
this.setId(propertyValue);
continue;
}
switch (fieldType) {
case 'attribute':
this.setDirtyAttribute(name, propertyValue);
break;
case 'belongsTo':
this.setDirtyBelongsTo(name, propertyValue);
relationships.get(name).setHasAnyRelationshipData(true);
relationships.get(name).setRelationshipIsEmpty(false);
break;
case 'hasMany':
this.setDirtyHasMany(name, propertyValue);
relationships.get(name).setHasAnyRelationshipData(true);
relationships.get(name).setRelationshipIsEmpty(false);
break;
default:
createOptions[name] = propertyValue;
}
}
}
if (Ember.setOwner) {
// ensure that `getOwner(this)` works inside a model instance
Ember.setOwner(createOptions, getOwner(this.store));
} else {
createOptions.container = this.store.container;
}
this._record = this.store._modelFactoryFor(this.modelName).create(createOptions);
this._triggerDeferredTriggers();
}
return this._record;
}
getFields() {
return Ember.get(this.modelClass, 'fields');
}
resetRecord() {
this._record = null;
this.isReloading = false;
this.error = null;
this.currentState = RootState$1.empty;
this.__attributes = null;
this.__inFlightAttributes = null;
this._data = null;
}
dematerializeRecord() {
this._isDematerializing = true;
if (this._record) {
this._record.destroy();
}
// move to an empty never-loaded state
this.destroyRelationships();
this.resetRecord();
this.updateRecordArrays();
}
deleteRecord() {
this.send('deleteRecord');
}
save(options) {
var promiseLabel = 'DS: Model#save ' + this;
var resolver = Ember.RSVP.defer(promiseLabel);
this.store.scheduleSave(this, resolver, options);
return resolver.promise;
}
startedReloading() {
this.isReloading = true;
if (this.hasRecord) {
Ember.set(this._record, 'isReloading', true);
}
}
finishedReloading() {
this.isReloading = false;
if (this.hasRecord) {
Ember.set(this._record, 'isReloading', false);
}
}
reload(options) {
this.startedReloading();
var internalModel = this;
var promiseLabel = 'DS: Model#reload of ' + this;
return new Ember.RSVP.Promise(function (resolve) {
internalModel.send('reloadRecord', { resolve, options });
}, promiseLabel).then(function () {
internalModel.didCleanError();
return internalModel;
}, function (error) {
internalModel.didError(error);
throw error;
}, 'DS: Model#reload complete, update flags').finally(function () {
internalModel.finishedReloading();
internalModel.updateRecordArrays();
});
}
/*
Computes the set of internal models reachable from `this` across exactly one
relationship.
@return {Array} An array containing the internal models that `this` belongs
to or has many.
*/
_directlyRelatedInternalModels() {
var array = [];
this._relationships.forEach((name, rel) => {
array = array.concat(rel.members.list, rel.canonicalMembers.list);
});
return array;
}
/*
Computes the set of internal models reachable from this internal model.
Reachability is determined over the relationship graph (ie a graph where
nodes are internal models and edges are belongs to or has many
relationships).
@return {Array} An array including `this` and all internal models reachable
from `this`.
*/
_allRelatedInternalModels() {
var array = [];
var queue = [];
var bfsId = nextBfsId++;
queue.push(this);
this._bfsId = bfsId;
while (queue.length > 0) {
var node = queue.shift();
array.push(node);
var related = node._directlyRelatedInternalModels();
for (var i = 0; i < related.length; ++i) {
var internalModel = related[i];
(true && !(internalModel._bfsId <= bfsId) && Ember.assert('Internal Error: seen a future bfs iteration', internalModel._bfsId <= bfsId));
if (internalModel._bfsId < bfsId) {
queue.push(internalModel);
internalModel._bfsId = bfsId;
}
}
}
return array;
}
/*
Unload the record for this internal model. This will cause the record to be
destroyed and freed up for garbage collection. It will also do a check
for cleaning up internal models.
This check is performed by first computing the set of related internal
models. If all records in this set are unloaded, then the entire set is
destroyed. Otherwise, nothing in the set is destroyed.
This means that this internal model will be freed up for garbage collection
once all models that refer to it via some relationship are also unloaded.
*/
unloadRecord() {
if (this.isDestroyed) {
return;
}
this.send('unloadRecord');
this.dematerializeRecord();
if (this._scheduledDestroy === null) {
this._scheduledDestroy = Ember.run.backburner.schedule('destroy', this, '_checkForOrphanedInternalModels');
}
}
hasScheduledDestroy() {
return !!this._scheduledDestroy;
}
cancelDestroy() {
(true && !(!this.isDestroyed) && Ember.assert(`You cannot cancel the destruction of an InternalModel once it has already been destroyed`, !this.isDestroyed));
this._isDematerializing = false;
Ember.run.cancel(this._scheduledDestroy);
this._scheduledDestroy = null;
}
// typically, we prefer to async destroy this lets us batch cleanup work.
// Unfortunately, some scenarios where that is not possible. Such as:
//
// ```js
// const record = store.find(‘record’, 1);
// record.unloadRecord();
// store.createRecord(‘record’, 1);
// ```
//
// In those scenarios, we make that model's cleanup work, sync.
//
destroySync() {
if (this._isDematerializing) {
this.cancelDestroy();
}
this._checkForOrphanedInternalModels();
if (this.isDestroyed || this.isDestroying) {
return;
}
// just in-case we are not one of the orphaned, we should still
// still destroy ourselves
this.destroy();
}
_checkForOrphanedInternalModels() {
this._isDematerializing = false;
this._scheduledDestroy = null;
if (this.isDestroyed) {
return;
}
this._cleanupOrphanedInternalModels();
}
_cleanupOrphanedInternalModels() {
var relatedInternalModels = this._allRelatedInternalModels();
if (areAllModelsUnloaded(relatedInternalModels)) {
for (var i = 0; i < relatedInternalModels.length; ++i) {
var internalModel = relatedInternalModels[i];
if (!internalModel.isDestroyed) {
internalModel.destroy();
}
}
}
}
eachRelationship(callback, binding) {
return this.modelClass.eachRelationship(callback, binding);
}
destroy() {
(true && !(!this._record || this._record.get('isDestroyed') || this._record.get('isDestroying')) && Ember.assert('Cannot destroy an internalModel while its record is materialized', !this._record || this._record.get('isDestroyed') || this._record.get('isDestroying')));
this.isDestroying = true;
this.store._internalModelDestroyed(this);
this._relationships.forEach((name, rel) => rel.destroy());
this._isDestroyed = true;
}
eachAttribute(callback, binding) {
return this.modelClass.eachAttribute(callback, binding);
}
inverseFor(key) {
return this.modelClass.inverseFor(key);
}
setupData(data) {
this.store._internalModelDidReceiveRelationshipData(this.modelName, this.id, data.relationships);
var changedKeys = void 0;
if (this.hasRecord) {
changedKeys = this._changedKeys(data.attributes);
}
Ember.assign(this._data, data.attributes);
this.pushedData();
if (this.hasRecord) {
this._record._notifyProperties(changedKeys);
}
}
getAttributeValue(key) {
if (key in this._attributes) {
return this._attributes[key];
} else if (key in this._inFlightAttributes) {
return this._inFlightAttributes[key];
} else {
return this._data[key];
}
}
setDirtyHasMany(key, records) {
(true && !(isArrayLike(records)) && Ember.assert(`You must pass an array of records to set a hasMany relationship`, isArrayLike(records)));
(true && !(function () {
return Ember.A(records).every(record => record.hasOwnProperty('_internalModel') === true);
}()) && Ember.assert(`All elements of a hasMany relationship must be instances of DS.Model, you passed ${Ember.inspect(records)}`, function () {
return Ember.A(records).every(record => record.hasOwnProperty('_internalModel') === true);
}()));
var relationship = this._relationships.get(key);
relationship.clear();
relationship.addInternalModels(records.map(record => Ember.get(record, '_internalModel')));
}
setDirtyBelongsTo(key, value) {
if (value === undefined) {
value = null;
}
if (value && value.then) {
this._relationships.get(key).setRecordPromise(value);
} else if (value) {
this._relationships.get(key).setInternalModel(value._internalModel);
} else {
this._relationships.get(key).setInternalModel(value);
}
}
setDirtyAttribute(key, value) {
if (this.isDeleted()) {
throw new Ember.Error(`Attempted to set '${key}' to '${value}' on the deleted record ${this}`);
}
var oldValue = this.getAttributeValue(key);
var originalValue = void 0;
if (value !== oldValue) {
// Add the new value to the changed attributes hash; it will get deleted by
// the 'didSetProperty' handler if it is no different from the original value
this._attributes[key] = value;
if (key in this._inFlightAttributes) {
originalValue = this._inFlightAttributes[key];
} else {
originalValue = this._data[key];
}
this.send('didSetProperty', {
name: key,
oldValue: oldValue,
originalValue: originalValue,
value: value
});
}
return value;
}
get isDestroyed() {
return this._isDestroyed;
}
get hasRecord() {
return !!this._record;
}
/*
@method createSnapshot
@private
*/
createSnapshot(options) {
return new Snapshot(this, options);
}
/*
@method loadingData
@private
@param {Promise} promise
*/
loadingData(promise) {
this.send('loadingData', promise);
}
/*
@method loadedData
@private
*/
loadedData() {
this.send('loadedData');
}
/*
@method notFound
@private
*/
notFound() {
this.send('notFound');
}
/*
@method pushedData
@private
*/
pushedData() {
this.send('pushedData');
}
flushChangedAttributes() {
this._inFlightAttributes = this._attributes;
this._attributes = null;
}
hasChangedAttributes() {
return this.__attributes !== null && Object.keys(this.__attributes).length > 0;
}
/*
Checks if the attributes which are considered as changed are still
different to the state which is acknowledged by the server.
This method is needed when data for the internal model is pushed and the
pushed data might acknowledge dirty attributes as confirmed.
@method updateChangedAttributes
@private
*/
updateChangedAttributes() {
var changedAttributes = this.changedAttributes();
var changedAttributeNames = Object.keys(changedAttributes);
var attrs = this._attributes;
for (var i = 0, length = changedAttributeNames.length; i < length; i++) {
var attribute = changedAttributeNames[i];
var data = changedAttributes[attribute];
var oldData = data[0];
var newData = data[1];
if (oldData === newData) {
delete attrs[attribute];
}
}
}
/*
Returns an object, whose keys are changed properties, and value is an
[oldProp, newProp] array.
@method changedAttributes
@private
*/
changedAttributes() {
var oldData = this._data;
var currentData = this._attributes;
var inFlightData = this._inFlightAttributes;
var newData = Ember.assign({}, inFlightData, currentData);
var diffData = Object.create(null);
var newDataKeys = Object.keys(newData);
for (var i = 0, length = newDataKeys.length; i < length; i++) {
var key = newDataKeys[i];
diffData[key] = [oldData[key], newData[key]];
}
return diffData;
}
/*
@method adapterWillCommit
@private
*/
adapterWillCommit() {
this.send('willCommit');
}
/*
@method adapterDidDirty
@private
*/
adapterDidDirty() {
this.send('becomeDirty');
this.updateRecordArrays();
}
/*
@method send
@private
@param {String} name
@param {Object} context
*/
send(name, context) {
var currentState = this.currentState;
if (!currentState[name]) {
this._unhandledEvent(currentState, name, context);
}
return currentState[name](this, context);
}
notifyHasManyAdded(key, record, idx) {
if (this.hasRecord) {
this._record.notifyHasManyAdded(key, record, idx);
}
}
notifyBelongsToChange(key, record) {
if (this.hasRecord) {
this._record.notifyBelongsToChange(key, record);
}
}
notifyPropertyChange(key) {
if (this.hasRecord) {
this._record.notifyPropertyChange(key);
}
}
rollbackAttributes() {
var dirtyKeys = void 0;
if (this.hasChangedAttributes()) {
dirtyKeys = Object.keys(this._attributes);
this._attributes = null;
}
if (Ember.get(this, 'isError')) {
this._inFlightAttributes = null;
this.didCleanError();
}
if (this.isNew()) {
this.removeFromInverseRelationships();
}
if (this.isValid()) {
this._inFlightAttributes = null;
}
this.send('rolledBack');
if (dirtyKeys && dirtyKeys.length > 0) {
this._record._notifyProperties(dirtyKeys);
}
}
/*
@method transitionTo
@private
@param {String} name
*/
transitionTo(name) {
// POSSIBLE TODO: Remove this code and replace with
// always having direct reference to state objects
var pivotName = extractPivotName(name);
var state = this.currentState;
var transitionMapId = `${state.stateName}->${name}`;
do {
if (state.exit) {
state.exit(this);
}
state = state.parentState;
} while (!state[pivotName]);
var setups = void 0;
var enters = void 0;
var i = void 0;
var l = void 0;
var map = TransitionChainMap[transitionMapId];
if (map) {
setups = map.setups;
enters = map.enters;
state = map.state;
} else {
setups = [];
enters = [];
var path = splitOnDot(name);
for (i = 0, l = path.length; i < l; i++) {
state = state[path[i]];
if (state.enter) {
enters.push(state);
}
if (state.setup) {
setups.push(state);
}
}
TransitionChainMap[transitionMapId] = { setups, enters, state };
}
for (i = 0, l = enters.length; i < l; i++) {
enters[i].enter(this);
}
this.currentState = state;
if (this.hasRecord) {
Ember.set(this._record, 'currentState', state);
}
for (i = 0, l = setups.length; i < l; i++) {
setups[i].setup(this);
}
this.updateRecordArrays();
}
_unhandledEvent(state, name, context) {
var errorMessage = 'Attempted to handle event `' + name + '` ';
errorMessage += 'on ' + String(this) + ' while in state ';
errorMessage += state.stateName + '. ';
if (context !== undefined) {
errorMessage += 'Called with ' + Ember.inspect(context) + '.';
}
throw new Ember.Error(errorMessage);
}
triggerLater(...args) {
if (this._deferredTriggers.push(args) !== 1) {
return;
}
this.store._updateInternalModel(this);
}
_triggerDeferredTriggers() {
//TODO: Before 1.0 we want to remove all the events that happen on the pre materialized record,
//but for now, we queue up all the events triggered before the record was materialized, and flush
//them once we have the record
if (!this.hasRecord) {
return;
}
var triggers = this._deferredTriggers;
var record = this._record;
var trigger = record.trigger;
for (var i = 0, l = triggers.length; i < l; i++) {
trigger.apply(record, triggers[i]);
}
triggers.length = 0;
}
/*
This method should only be called by records in the `isNew()` state OR once the record
has been deleted and that deletion has been persisted.
It will remove this record from any associated relationships.
@method removeFromInverseRelationships
@private
*/
removeFromInverseRelationships() {
this._relationships.forEach((name, rel) => {
rel.removeCompletelyFromInverse();
rel.clear();
});
var implicitRelationships = this._implicitRelationships;
this.__implicitRelationships = null;
Object.keys(implicitRelationships).forEach(key => {
var rel = implicitRelationships[key];
rel.removeCompletelyFromInverse();
rel.clear();
});
}
/*
Notify all inverses that this internalModel has been dematerialized
and destroys any ManyArrays.
*/
destroyRelationships() {
var relationships = this._relationships;
relationships.forEach((name, rel) => destroyRelationship(rel));
var implicitRelationships = this._implicitRelationships;
this.__implicitRelationships = null;
Object.keys(implicitRelationships).forEach(key => {
var rel = implicitRelationships[key];
destroyRelationship(rel);
});
}
/*
When a find request is triggered on the store, the user can optionally pass in
attributes and relationships to be preloaded. These are meant to behave as if they
came back from the server, except the user obtained them out of band and is informing
the store of their existence. The most common use case is for supporting client side
nested URLs, such as `/posts/1/comments/2` so the user can do
`store.findRecord('comment', 2, { preload: { post: 1 } })` without having to fetch the post.
Preloaded data can be attributes and relationships passed in either as IDs or as actual
models.
@method preloadData
@private
@param {Object} preload
*/
preloadData(preload) {
//TODO(Igor) consider the polymorphic case
Object.keys(preload).forEach(key => {
var preloadValue = Ember.get(preload, key);
var relationshipMeta = this.modelClass.metaForProperty(key);
if (relationshipMeta.isRelationship) {
this._preloadRelationship(key, preloadValue);
} else {
this._data[key] = preloadValue;
}
});
}
_preloadRelationship(key, preloadValue) {
var relationshipMeta = this.modelClass.metaForProperty(key);
var modelClass = relationshipMeta.type;
if (relationshipMeta.kind === 'hasMany') {
this._preloadHasMany(key, preloadValue, modelClass);
} else {
this._preloadBelongsTo(key, preloadValue, modelClass);
}
}
_preloadHasMany(key, preloadValue, modelClass) {
(true && !(Array.isArray(preloadValue)) && Ember.assert('You need to pass in an array to set a hasMany property on a record', Array.isArray(preloadValue)));
var recordsToSet = new Array(preloadValue.length);
for (var i = 0; i < preloadValue.length; i++) {
var recordToPush = preloadValue[i];
recordsToSet[i] = this._convertStringOrNumberIntoInternalModel(recordToPush, modelClass);
}
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships.get(key).updateInternalModelsFromAdapter(recordsToSet);
}
_preloadBelongsTo(key, preloadValue, modelClass) {
var internalModelToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, modelClass);
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships.get(key).setInternalModel(internalModelToSet);
}
_convertStringOrNumberIntoInternalModel(value, modelClass) {
if (typeof value === 'string' || typeof value === 'number') {
return this.store._internalModelForId(modelClass, value);
}
if (value._internalModel) {
return value._internalModel;
}
return value;
}
/*
Used to notify the store to update FilteredRecordArray membership.
@method updateRecordArrays
@private
*/
updateRecordArrays() {
this.store.recordArrayManager.recordDidChange(this);
}
setId(id) {
(true && !(this.id === null || this.id === id || this.isNew()) && Ember.assert("A record's id cannot be changed once it is in the loaded state", this.id === null || this.id === id || this.isNew()));
var didChange = id !== this.id;
this.id = id;
if (didChange && this.hasRecord) {
this._record.notifyPropertyChange('id');
}
}
didError(error) {
this.error = error;
this.isError = true;
if (this.hasRecord) {
this._record.setProperties({
isError: true,
adapterError: error
});
}
}
didCleanError() {
this.error = null;
this.isError = false;
if (this.hasRecord) {
this._record.setProperties({
isError: false,
adapterError: null
});
}
}
/*
If the adapter did not return a hash in response to a commit,
merge the changed attributes and relationships into the existing
saved data.
@method adapterDidCommit
*/
adapterDidCommit(data) {
if (data) {
this.store._internalModelDidReceiveRelationshipData(this.modelName, this.id, data.relationships);
data = data.attributes;
}
this.didCleanError();
var changedKeys = this._changedKeys(data);
Ember.assign(this._data, this._inFlightAttributes);
if (data) {
Ember.assign(this._data, data);
}
this._inFlightAttributes = null;
this.send('didCommit');
this.updateRecordArrays();
if (!data) {
return;
}
this._record._notifyProperties(changedKeys);
}
addErrorMessageToAttribute(attribute, message) {
Ember.get(this.getRecord(), 'errors')._add(attribute, message);
}
removeErrorMessageFromAttribute(attribute) {
Ember.get(this.getRecord(), 'errors')._remove(attribute);
}
clearErrorMessages() {
Ember.get(this.getRecord(), 'errors')._clear();
}
hasErrors() {
var errors = Ember.get(this.getRecord(), 'errors');
return errors.get('length') > 0;
}
// FOR USE DURING COMMIT PROCESS
/*
@method adapterDidInvalidate
@private
*/
adapterDidInvalidate(errors) {
var attribute = void 0;
for (attribute in errors) {
if (errors.hasOwnProperty(attribute)) {
this.addErrorMessageToAttribute(attribute, errors[attribute]);
}
}
this.send('becameInvalid');
this._saveWasRejected();
}
/*
@method adapterDidError
@private
*/
adapterDidError(error) {
this.send('becameError');
this.didError(error);
this._saveWasRejected();
}
_saveWasRejected() {
var keys = Object.keys(this._inFlightAttributes);
if (keys.length > 0) {
var attrs = this._attributes;
for (var i = 0; i < keys.length; i++) {
if (attrs[keys[i]] === undefined) {
attrs[keys[i]] = this._inFlightAttributes[keys[i]];
}
}
}
this._inFlightAttributes = null;
}
/*
Ember Data has 3 buckets for storing the value of an attribute on an internalModel.
`_data` holds all of the attributes that have been acknowledged by
a backend via the adapter. When rollbackAttributes is called on a model all
attributes will revert to the record's state in `_data`.
`_attributes` holds any change the user has made to an attribute
that has not been acknowledged by the adapter. Any values in
`_attributes` are have priority over values in `_data`.
`_inFlightAttributes`. When a record is being synced with the
backend the values in `_attributes` are copied to
`_inFlightAttributes`. This way if the backend acknowledges the
save but does not return the new state Ember Data can copy the
values from `_inFlightAttributes` to `_data`. Without having to
worry about changes made to `_attributes` while the save was
happenign.
Changed keys builds a list of all of the values that may have been
changed by the backend after a successful save.
It does this by iterating over each key, value pair in the payload
returned from the server after a save. If the `key` is found in
`_attributes` then the user has a local changed to the attribute
that has not been synced with the server and the key is not
included in the list of changed keys.
If the value, for a key differs from the value in what Ember Data
believes to be the truth about the backend state (A merger of the
`_data` and `_inFlightAttributes` objects where
`_inFlightAttributes` has priority) then that means the backend
has updated the value and the key is added to the list of changed
keys.
@method _changedKeys
@private
*/
_changedKeys(updates) {
var changedKeys = [];
if (updates) {
var original = void 0,
i = void 0,
value = void 0,
key = void 0;
var keys = Object.keys(updates);
var length = keys.length;
var hasAttrs = this.hasChangedAttributes();
var attrs = void 0;
if (hasAttrs) {
attrs = this._attributes;
}
original = Object.create(null);
Ember.assign(original, this._data, this._inFlightAttributes);
for (i = 0; i < length; i++) {
key = keys[i];
value = updates[key];
// A value in _attributes means the user has a local change to
// this attributes. We never override this value when merging
// updates from the backend so we should not sent a change
// notification if the server value differs from the original.
if (hasAttrs === true && attrs[key] !== undefined) {
continue;
}
if (!Ember.isEqual(original[key], value)) {
changedKeys.push(key);
}
}
}
return changedKeys;
}
toString() {
return `<${this.modelName}:${this.id}>`;
}
referenceFor(kind, name) {
var reference = this.references[name];
if (!reference) {
var relationship = this._relationships.get(name);
{
var modelName = this.modelName;
(true && !(relationship) && Ember.assert(`There is no ${kind} relationship named '${name}' on a model of modelClass '${modelName}'`, relationship));
var actualRelationshipKind = relationship.relationshipMeta.kind;
(true && !(actualRelationshipKind === kind) && Ember.assert(`You tried to get the '${name}' relationship on a '${modelName}' via record.${kind}('${name}'), but the relationship is of kind '${actualRelationshipKind}'. Use record.${actualRelationshipKind}('${name}') instead.`, actualRelationshipKind === kind));
}
if (kind === 'belongsTo') {
reference = new BelongsToReference(this.store, this, relationship);
} else if (kind === 'hasMany') {
reference = new HasManyReference(this.store, this, relationship);
}
this.references[name] = reference;
}
return reference;
}
} |
JavaScript | class InternalModelMap {
constructor(modelName) {
this.modelName = modelName;
this._idToModel = Object.create(null);
this._models = [];
this._metadata = null;
}
/**
* @method get
* @param id {String}
* @return {InternalModel}
*/
get(id) {
return this._idToModel[id];
}
has(id) {
return !!this._idToModel[id];
}
get length() {
return this._models.length;
}
set(id, internalModel) {
(true && !(id) && Ember.assert(`You cannot index an internalModel by an empty id'`, id));
(true && !(internalModel instanceof InternalModel) && Ember.assert(`You cannot set an index for an internalModel to something other than an internalModel`, internalModel instanceof InternalModel));
(true && !(this.contains(internalModel)) && Ember.assert(`You cannot set an index for an internalModel that is not in the InternalModelMap`, this.contains(internalModel)));
(true && !(!this.has(id) || this.get(id) === internalModel) && Ember.assert(`You cannot update the id index of an InternalModel once set. Attempted to update ${id}.`, !this.has(id) || this.get(id) === internalModel));
this._idToModel[id] = internalModel;
}
add(internalModel, id) {
(true && !(!this.contains(internalModel)) && Ember.assert(`You cannot re-add an already present InternalModel to the InternalModelMap.`, !this.contains(internalModel)));
if (id) {
(true && !(!this.has(id) || this.get(id) === internalModel) && Ember.assert(`Duplicate InternalModel for ${this.modelName}:${id} detected.`, !this.has(id) || this.get(id) === internalModel));
this._idToModel[id] = internalModel;
}
this._models.push(internalModel);
}
remove(internalModel, id) {
delete this._idToModel[id];
var loc = this._models.indexOf(internalModel);
if (loc !== -1) {
this._models.splice(loc, 1);
}
}
contains(internalModel) {
return this._models.indexOf(internalModel) !== -1;
}
/**
An array of all models of this modelName
@property models
@type Array
*/
get models() {
return this._models;
}
/**
* meta information about internalModels
* @property metadata
* @type Object
*/
get metadata() {
return this._metadata || (this._metadata = Object.create(null));
}
/**
deprecated (and unsupported) way of accessing modelClass
@property type
@deprecated
*/
get type() {
throw new Error('InternalModelMap.type is no longer available');
}
/**
Destroy all models in the internalModelTest and wipe metadata.
@method clear
*/
clear() {
var models = this._models;
this._models = [];
for (var i = 0; i < models.length; i++) {
var model = models[i];
model.unloadRecord();
}
this._metadata = null;
}
} |
JavaScript | class IdentityMap {
constructor() {
this._map = Object.create(null);
}
/**
Retrieves the `InternalModelMap` for a given modelName,
creating one if one did not already exist. This is
similar to `getWithDefault` or `get` on a `MapWithDefault`
@method retrieve
@param modelName a previously normalized modelName
@return {InternalModelMap} the InternalModelMap for the given modelName
*/
retrieve(modelName) {
var map = this._map[modelName];
if (map === undefined) {
map = this._map[modelName] = new InternalModelMap(modelName);
}
return map;
}
/**
Clears the contents of all known `RecordMaps`, but does
not remove the InternalModelMap instances.
@method clear
*/
clear() {
var map = this._map;
var keys = Object.keys(map);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
map[key].clear();
}
}
} |
JavaScript | class TypeCache {
constructor() {
this.types = Object.create(null);
}
get(modelName, id) {
var { types } = this;
if (types[modelName] !== undefined) {
return types[modelName][id];
}
}
set(modelName, id, payload) {
var { types } = this;
var typeMap = types[modelName];
if (typeMap === undefined) {
typeMap = types[modelName] = Object.create(null);
}
typeMap[id] = payload;
}
delete(modelName, id) {
var { types } = this;
if (types[modelName] !== undefined) {
delete types[modelName][id];
}
}
} |
JavaScript | class RelationshipPayloads {
constructor(relInfo) {
this._relInfo = relInfo;
// a map of id -> payloads for the left hand side of the relationship.
this.lhs_payloads = new TypeCache();
this.rhs_payloads = relInfo.isReflexive ? this.lhs_payloads : new TypeCache();
// When we push relationship payloads, just stash them in a queue until
// somebody actually asks for one of them.
//
// This is a queue of the relationship payloads that have been pushed for
// either side of this relationship
this._pendingPayloads = [];
}
/**
Get the payload for the relationship of an individual record.
This might return the raw payload as pushed into the store, or one computed
from the payload of the inverse relationship.
@method
*/
get(modelName, id, relationshipName) {
this._flushPending();
if (this._isLHS(modelName, relationshipName)) {
return this.lhs_payloads.get(modelName, id);
} else {
(true && !(this._isRHS(modelName, relationshipName)) && Ember.assert(`${modelName}:${relationshipName} is not either side of this relationship, ${this._relInfo.lhs_key}<->${this._relInfo.rhs_key}`, this._isRHS(modelName, relationshipName)));
return this.rhs_payloads.get(modelName, id);
}
}
/**
Push a relationship payload for an individual record.
This will make the payload available later for both this relationship and its inverse.
@method
*/
push(modelName, id, relationshipName, relationshipData) {
this._pendingPayloads.push([modelName, id, relationshipName, relationshipData]);
}
/**
Unload the relationship payload for an individual record.
This does not unload the inverse relationship payload.
@method
*/
unload(modelName, id, relationshipName) {
this._flushPending();
if (this._isLHS(modelName, relationshipName)) {
this.lhs_payloads.delete(modelName, id);
} else {
(true && !(this._isRHS(modelName, relationshipName)) && Ember.assert(`${modelName}:${relationshipName} is not either side of this relationship, ${this._relInfo.lhs_baseModelName}:${this._relInfo.lhs_relationshipName}<->${this._relInfo.rhs_baseModelName}:${this._relInfo.rhs_relationshipName}`, this._isRHS(modelName, relationshipName)));
this.rhs_payloads.delete(modelName, id);
}
}
/**
@return {boolean} true iff `modelName` and `relationshipName` refer to the
left hand side of this relationship, as opposed to the right hand side.
@method
*/
_isLHS(modelName, relationshipName) {
var relInfo = this._relInfo;
var isSelfReferential = relInfo.isSelfReferential;
var isRelationship = relationshipName === relInfo.lhs_relationshipName;
if (isRelationship === true) {
return isSelfReferential === true || // itself
modelName === relInfo.lhs_baseModelName || // base or non-polymorphic
relInfo.lhs_modelNames.indexOf(modelName) !== -1; // polymorphic
}
return false;
}
/**
@return {boolean} true iff `modelName` and `relationshipName` refer to the
right hand side of this relationship, as opposed to the left hand side.
@method
*/
_isRHS(modelName, relationshipName) {
var relInfo = this._relInfo;
var isSelfReferential = relInfo.isSelfReferential;
var isRelationship = relationshipName === relInfo.rhs_relationshipName;
if (isRelationship === true) {
return isSelfReferential === true || // itself
modelName === relInfo.rhs_baseModelName || // base or non-polymorphic
relInfo.rhs_modelNames.indexOf(modelName) !== -1; // polymorphic
}
return false;
}
_flushPending() {
if (this._pendingPayloads.length === 0) {
return;
}
var payloadsToBeProcessed = this._pendingPayloads.splice(0, this._pendingPayloads.length);
for (var i = 0; i < payloadsToBeProcessed.length; ++i) {
var modelName = payloadsToBeProcessed[i][0];
var id = payloadsToBeProcessed[i][1];
var relationshipName = payloadsToBeProcessed[i][2];
var relationshipData = payloadsToBeProcessed[i][3];
// TODO: maybe delay this allocation slightly?
var inverseRelationshipData = {
data: {
id: id,
type: modelName
}
};
// start flushing this individual payload. The logic is the same whether
// it's for the left hand side of the relationship or the right hand side,
// except the role of primary and inverse idToPayloads is reversed
//
var previousPayload = void 0;
var payloadMap = void 0;
var inversePayloadMap = void 0;
var inverseIsMany = void 0;
if (this._isLHS(modelName, relationshipName)) {
previousPayload = this.lhs_payloads.get(modelName, id);
payloadMap = this.lhs_payloads;
inversePayloadMap = this.rhs_payloads;
inverseIsMany = this._rhsRelationshipIsMany;
} else {
(true && !(this._isRHS(modelName, relationshipName)) && Ember.assert(`${modelName}:${relationshipName} is not either side of this relationship, ${this._relInfo.lhs_key}<->${this._relInfo.rhs_key}`, this._isRHS(modelName, relationshipName)));
previousPayload = this.rhs_payloads.get(modelName, id);
payloadMap = this.rhs_payloads;
inversePayloadMap = this.lhs_payloads;
inverseIsMany = this._lhsRelationshipIsMany;
}
// actually flush this individual payload
//
// We remove the previous inverse before populating our current one
// because we may have multiple payloads for the same relationship, in
// which case the last one wins.
//
// eg if user hasMany helicopters, and helicopter belongsTo user and we see
//
// [{
// data: {
// id: 1,
// type: 'helicopter',
// relationships: {
// user: {
// id: 2,
// type: 'user'
// }
// }
// }
// }, {
// data: {
// id: 1,
// type: 'helicopter',
// relationships: {
// user: {
// id: 4,
// type: 'user'
// }
// }
// }
// }]
//
// Then we will initially have set user:2 as having helicopter:1, which we
// need to remove before adding helicopter:1 to user:4
//
// only remove relationship information before adding if there is relationshipData.data
// * null is considered new information "empty", and it should win
// * undefined is NOT considered new information, we should keep original state
// * anything else is considered new information, and it should win
var isMatchingIdentifier = this._isMatchingIdentifier(relationshipData && relationshipData.data, previousPayload && previousPayload.data);
if (relationshipData.data !== undefined) {
if (!isMatchingIdentifier) {
this._removeInverse(id, previousPayload, inversePayloadMap);
}
}
mergeForwardPayload(previousPayload, relationshipData);
payloadMap.set(modelName, id, relationshipData);
if (!isMatchingIdentifier) {
this._populateInverse(relationshipData, inverseRelationshipData, inversePayloadMap, inverseIsMany);
}
}
}
_isMatchingIdentifier(a, b) {
return a && b && a.type === b.type && a.id === b.id && !Array.isArray(a) && !Array.isArray(b);
}
/**
Populate the inverse relationship for `relationshipData`.
If `relationshipData` is an array (eg because the relationship is hasMany)
this means populate each inverse, otherwise populate only the single
inverse.
@private
@method
*/
_populateInverse(relationshipData, inversePayload, inversePayloadMap, inverseIsMany) {
if (!relationshipData.data) {
// This id doesn't have an inverse, eg a belongsTo with a payload
// { data: null }, so there's nothing to populate
return;
}
if (Array.isArray(relationshipData.data)) {
for (var i = 0; i < relationshipData.data.length; ++i) {
var resourceIdentifier = relationshipData.data[i];
this._addToInverse(inversePayload, resourceIdentifier, inversePayloadMap, inverseIsMany);
}
} else {
var _resourceIdentifier = relationshipData.data;
this._addToInverse(inversePayload, _resourceIdentifier, inversePayloadMap, inverseIsMany);
}
}
/**
Actually add `inversePayload` to `inverseIdToPayloads`. This is part of
`_populateInverse` after we've normalized the case of `relationshipData`
being either an array or a pojo.
We still have to handle the case that the *inverse* relationship payload may
be an array or pojo.
@private
@method
*/
_addToInverse(inversePayload, resourceIdentifier, inversePayloadMap, inverseIsMany) {
var relInfo = this._relInfo;
var inverseData = inversePayload.data;
if (relInfo.isReflexive && inverseData && inverseData.id === resourceIdentifier.id) {
// eg <user:1>.friends = [{ id: 1, type: 'user' }]
return;
}
var existingPayload = inversePayloadMap.get(resourceIdentifier.type, resourceIdentifier.id);
if (existingPayload) {
// There already is an inverse, either add or overwrite depending on
// whether the inverse is a many relationship or not
//
if (inverseIsMany) {
var existingData = existingPayload.data;
// in the case of a hasMany
// we do not want create a `data` array where there was none before
// if we also have links, which this would indicate
if (existingData) {
existingData.push(inversePayload.data);
} else {
existingPayload._partialData = existingPayload._partialData || [];
existingPayload._partialData.push(inversePayload.data);
}
} else {
mergeForwardPayload(existingPayload, inversePayload);
inversePayloadMap.set(resourceIdentifier.type, resourceIdentifier.id, inversePayload);
}
} else {
// first time we're populating the inverse side
//
if (inverseIsMany) {
inversePayloadMap.set(resourceIdentifier.type, resourceIdentifier.id, {
_partialData: [inversePayload.data]
});
} else {
inversePayloadMap.set(resourceIdentifier.type, resourceIdentifier.id, inversePayload);
}
}
}
get _lhsRelationshipIsMany() {
var meta = this._relInfo.lhs_relationshipMeta;
return meta !== null && meta.kind === 'hasMany';
}
get _rhsRelationshipIsMany() {
var meta = this._relInfo.rhs_relationshipMeta;
return meta !== null && meta.kind === 'hasMany';
}
/**
Remove the relationship in `previousPayload` from its inverse(s), because
this relationship payload has just been updated (eg because the same
relationship had multiple payloads pushed before the relationship was
initialized).
@method
*/
_removeInverse(id, previousPayload, inversePayloadMap) {
var data = previousPayload && previousPayload.data;
var partialData = previousPayload && previousPayload._partialData;
var maybeData = data || partialData;
if (!maybeData) {
// either this is the first time we've seen a payload for this id, or its
// previous payload indicated that it had no inverse, eg a belongsTo
// relationship with payload { data: null }
//
// In either case there's nothing that needs to be removed from the
// inverse map of payloads
return;
}
if (Array.isArray(maybeData)) {
// TODO: diff rather than removeall addall?
for (var i = 0; i < maybeData.length; ++i) {
var resourceIdentifier = maybeData[i];
this._removeFromInverse(id, resourceIdentifier, inversePayloadMap);
}
} else {
this._removeFromInverse(id, data, inversePayloadMap);
}
}
/**
Remove `id` from its inverse record with id `inverseId`. If the inverse
relationship is a belongsTo, this means just setting it to null, if the
inverse relationship is a hasMany, then remove that id from its array of ids.
@method
*/
_removeFromInverse(id, resourceIdentifier, inversePayloads) {
var inversePayload = inversePayloads.get(resourceIdentifier.type, resourceIdentifier.id);
var data = inversePayload && inversePayload.data;
var partialData = inversePayload && inversePayload._partialData;
if (!data && !partialData) {
return;
}
if (Array.isArray(data)) {
inversePayload.data = data.filter(x => x.id !== id);
} else if (Array.isArray(partialData)) {
inversePayload._partialData = partialData.filter(x => x.id !== id);
} else {
// this merges forward links and meta
inversePayload.data = null;
}
}
} |
JavaScript | class RelationshipPayloadsManager {
constructor(store) {
this._store = store;
// cache of `RelationshipPayload`s
this._cache = Object.create(null);
this._inverseLookupCache = new TypeCache();
}
/**
Find the payload for the given relationship of the given model.
Returns the payload for the given relationship, whether raw or computed from
the payload of the inverse relationship.
@example
relationshipPayloadsManager.get('hobby', 2, 'user') === {
{
data: {
id: 1,
type: 'user'
}
}
}
@method
*/
get(modelName, id, relationshipName) {
var relationshipPayloads = this._getRelationshipPayloads(modelName, relationshipName, false);
return relationshipPayloads && relationshipPayloads.get(modelName, id, relationshipName);
}
/**
Push a model's relationships payload into this cache.
@example
let userPayload = {
data: {
id: 1,
type: 'user',
relationships: {
hobbies: {
data: [{
id: 2,
type: 'hobby'
}]
}
}
},
};
relationshipPayloadsManager.push('user', 1, userPayload.data.relationships);
@method
*/
push(modelName, id, relationshipsData) {
if (!relationshipsData) {
return;
}
Object.keys(relationshipsData).forEach(key => {
var relationshipPayloads = this._getRelationshipPayloads(modelName, key, true);
if (relationshipPayloads) {
relationshipPayloads.push(modelName, id, key, relationshipsData[key]);
}
});
}
/**
Unload a model's relationships payload.
@method
*/
unload(modelName, id) {
var modelClass = this._store.modelFor(modelName);
var relationshipsByName = Ember.get(modelClass, 'relationshipsByName');
relationshipsByName.forEach((_, relationshipName) => {
var relationshipPayloads = this._getRelationshipPayloads(modelName, relationshipName, false);
if (relationshipPayloads) {
relationshipPayloads.unload(modelName, id, relationshipName);
}
});
}
/**
Find the RelationshipPayloads object for the given relationship. The same
RelationshipPayloads object is returned for either side of a relationship.
@example
const User = DS.Model.extend({
hobbies: DS.hasMany('hobby')
});
const Hobby = DS.Model.extend({
user: DS.belongsTo('user')
});
relationshipPayloads.get('user', 'hobbies') === relationshipPayloads.get('hobby', 'user');
The signature has a somewhat large arity to avoid extra work, such as
a) string manipulation & allocation with `modelName` and
`relationshipName`
b) repeatedly getting `relationshipsByName` via `Ember.get`
@private
@method
*/
_getRelationshipPayloads(modelName, relationshipName, init) {
var relInfo = this.getRelationshipInfo(modelName, relationshipName);
if (relInfo === null) {
return;
}
var cache = this._cache[relInfo.lhs_key];
if (!cache && init) {
return this._initializeRelationshipPayloads(relInfo);
}
return cache;
}
getRelationshipInfo(modelName, relationshipName) {
var inverseCache = this._inverseLookupCache;
var store = this._store;
var cached = inverseCache.get(modelName, relationshipName);
// CASE: We have a cached resolution (null if no relationship exists)
if (cached !== undefined) {
return cached;
}
var modelClass = store.modelFor(modelName);
var relationshipsByName = Ember.get(modelClass, 'relationshipsByName');
// CASE: We don't have a relationship at all
if (!relationshipsByName.has(relationshipName)) {
inverseCache.set(modelName, relationshipName, null);
return null;
}
var relationshipMeta = relationshipsByName.get(relationshipName);
var inverseMeta = void 0;
// CASE: Inverse is explicitly null
if (relationshipMeta.options && relationshipMeta.options.inverse === null) {
inverseMeta = null;
} else {
inverseMeta = modelClass.inverseFor(relationshipName, store);
}
var selfIsPolymorphic = relationshipMeta.options !== undefined && relationshipMeta.options.polymorphic === true;
var inverseBaseModelName = relationshipMeta.type;
// CASE: We have no inverse
if (!inverseMeta) {
var _info = {
lhs_key: `${modelName}:${relationshipName}`,
lhs_modelNames: [modelName],
lhs_baseModelName: modelName,
lhs_relationshipName: relationshipName,
lhs_relationshipMeta: relationshipMeta,
lhs_isPolymorphic: selfIsPolymorphic,
rhs_key: '',
rhs_modelNames: [],
rhs_baseModelName: inverseBaseModelName,
rhs_relationshipName: '',
rhs_relationshipMeta: null,
rhs_isPolymorphic: false,
hasInverse: false,
isSelfReferential: false, // modelName === inverseBaseModelName,
isReflexive: false
};
inverseCache.set(modelName, relationshipName, _info);
return _info;
}
// CASE: We do have an inverse
var inverseRelationshipName = inverseMeta.name;
var inverseRelationshipMeta = Ember.get(inverseMeta.type, 'relationshipsByName').get(inverseRelationshipName);
var baseModelName = inverseRelationshipMeta.type;
var isSelfReferential = baseModelName === inverseBaseModelName;
// TODO we want to assert this but this breaks all of our shoddily written tests
/*
if (DEBUG) {
let inverseDoubleCheck = inverseMeta.type.inverseFor(inverseRelationshipName, store);
assert(`The ${inverseBaseModelName}:${inverseRelationshipName} relationship declares 'inverse: null', but it was resolved as the inverse for ${baseModelName}:${relationshipName}.`, inverseDoubleCheck);
}
*/
// CASE: We may have already discovered the inverse for the baseModelName
// CASE: We have already discovered the inverse
cached = inverseCache.get(baseModelName, relationshipName) || inverseCache.get(inverseBaseModelName, inverseRelationshipName);
if (cached) {
// TODO this assert can be removed if the above assert is enabled
(true && !(cached.hasInverse !== false) && Ember.assert(`The ${inverseBaseModelName}:${inverseRelationshipName} relationship declares 'inverse: null', but it was resolved as the inverse for ${baseModelName}:${relationshipName}.`, cached.hasInverse !== false));
var isLHS = cached.lhs_baseModelName === baseModelName;
var modelNames = isLHS ? cached.lhs_modelNames : cached.rhs_modelNames;
// make this lookup easier in the future by caching the key
modelNames.push(modelName);
inverseCache.set(modelName, relationshipName, cached);
return cached;
}
var info = {
lhs_key: `${baseModelName}:${relationshipName}`,
lhs_modelNames: [modelName],
lhs_baseModelName: baseModelName,
lhs_relationshipName: relationshipName,
lhs_relationshipMeta: relationshipMeta,
lhs_isPolymorphic: selfIsPolymorphic,
rhs_key: `${inverseBaseModelName}:${inverseRelationshipName}`,
rhs_modelNames: [],
rhs_baseModelName: inverseBaseModelName,
rhs_relationshipName: inverseRelationshipName,
rhs_relationshipMeta: inverseRelationshipMeta,
rhs_isPolymorphic: inverseRelationshipMeta.options !== undefined && inverseRelationshipMeta.options.polymorphic === true,
hasInverse: true,
isSelfReferential,
isReflexive: isSelfReferential && relationshipName === inverseRelationshipName
};
// Create entries for the baseModelName as well as modelName to speed up
// inverse lookups
inverseCache.set(baseModelName, relationshipName, info);
inverseCache.set(modelName, relationshipName, info);
// Greedily populate the inverse
inverseCache.set(inverseBaseModelName, inverseRelationshipName, info);
return info;
}
/**
Create the `RelationshipsPayload` for the relationship `modelName`, `relationshipName`, and its inverse.
@private
@method
*/
_initializeRelationshipPayloads(relInfo) {
var lhsKey = relInfo.lhs_key;
var rhsKey = relInfo.rhs_key;
var existingPayloads = this._cache[lhsKey];
if (relInfo.hasInverse === true && relInfo.rhs_isPolymorphic === true) {
existingPayloads = this._cache[rhsKey];
if (existingPayloads !== undefined) {
this._cache[lhsKey] = existingPayloads;
return existingPayloads;
}
}
// populate the cache for both sides of the relationship, as they both use
// the same `RelationshipPayloads`.
//
// This works out better than creating a single common key, because to
// compute that key we would need to do work to look up the inverse
//
var cache = this._cache[lhsKey] = new RelationshipPayloads(relInfo);
if (relInfo.hasInverse === true) {
this._cache[rhsKey] = cache;
}
return cache;
}
} |
JavaScript | class AnalyzeRequest {
/**
* Create a AnalyzeRequest.
* @member {string} text The text to break into tokens.
* @member {object} [analyzer] The name of the analyzer to use to break the
* given text. If this parameter is not specified, you must specify a
* tokenizer instead. The tokenizer and analyzer parameters are mutually
* exclusive.
* @member {string} [analyzer.name]
* @member {object} [tokenizer] The name of the tokenizer to use to break the
* given text. If this parameter is not specified, you must specify an
* analyzer instead. The tokenizer and analyzer parameters are mutually
* exclusive.
* @member {string} [tokenizer.name]
* @member {array} [tokenFilters] An optional list of token filters to use
* when breaking the given text. This parameter can only be set when using
* the tokenizer parameter.
* @member {array} [charFilters] An optional list of character filters to use
* when breaking the given text. This parameter can only be set when using
* the tokenizer parameter.
*/
constructor() {
}
/**
* Defines the metadata of AnalyzeRequest
*
* @returns {object} metadata of AnalyzeRequest
*
*/
mapper() {
return {
required: false,
serializedName: 'AnalyzeRequest',
type: {
name: 'Composite',
className: 'AnalyzeRequest',
modelProperties: {
text: {
required: true,
serializedName: 'text',
type: {
name: 'String'
}
},
analyzer: {
required: false,
serializedName: 'analyzer',
type: {
name: 'Composite',
className: 'AnalyzerName'
}
},
tokenizer: {
required: false,
serializedName: 'tokenizer',
type: {
name: 'Composite',
className: 'TokenizerName'
}
},
tokenFilters: {
required: false,
serializedName: 'tokenFilters',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'TokenFilterNameElementType',
type: {
name: 'Composite',
className: 'TokenFilterName'
}
}
}
},
charFilters: {
required: false,
serializedName: 'charFilters',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'CharFilterNameElementType',
type: {
name: 'Composite',
className: 'CharFilterName'
}
}
}
}
}
}
};
}
} |
JavaScript | class AutoUpdater {
/** @constructor */
constructor() {
this._latestRelease = null;
}
/** @method */
/**
* @return Promise
*/
checkForNewRelease() {
return new Promise((resolve, reject) => {
if (this._latestRelease) return resolve(true);
_getLatestRelease()
.then(latestRelease => {
if (!latestRelease) return resolve(false);
let updateAvailable = semver.lt(appConfig.version, latestRelease.version);
if (updateAvailable) this._latestRelease = latestRelease;
return resolve(updateAvailable);
})
.catch(reject);
});
}
get latestRelease() {
return this._latestRelease;
}
} |
JavaScript | class UnPacker extends events_1.EventEmitter {
constructor() {
super();
}
/**
* extracts needed config files from archive
* - .conf files are emited as events during extraction so they can be parsed asyncronously
* - all other files returned at end in promise completion to be added to the conf tree
* @param input path/file to .conf|.ucs|.qkview|.gz
*/
stream(input) {
return __awaiter(this, void 0, void 0, function* () {
/**
* look at streaming specific files from the archive without having to load the entire thing into memory
*
* https://github.com/mafintosh/tar-fs
* https://github.com/mafintosh/gunzip-maybe
* https://github.com/mafintosh/tar-stream
* https://github.com/npm/node-tar#readme
*
* https://stackoverflow.com/questions/19978452/how-to-extract-single-file-from-tar-gz-archive-using-node-js
*
*/
// parse input to usable pieces
const filePath = path_1.default.parse(input);
/**
* what kind of file we workin with?
*/
if (filePath.ext === '.conf') {
try {
// get file size
const size = fs.statSync(path_1.default.join(filePath.dir, filePath.base)).size;
// try to read file contents
const content = fs.readFileSync(path_1.default.join(filePath.dir, filePath.base), 'utf-8');
logger_1.default.debug(`got .conf file [${input}], size [${size}]`);
this.emit('conf', { fileName: filePath.base, size, content });
// return [{ fileName: filePath.base, size, content }];
return;
}
catch (e) {
logger_1.default.error('not able to read file', e.message);
throw new Error(`not able to read file => ${e.message}`);
}
}
else if (filePath.ext === '.gz' || filePath.ext === '.ucs' || filePath.ext === '.qkview') {
const size = fs.statSync(path_1.default.join(filePath.dir, filePath.base)).size;
logger_1.default.debug(`detected file: [${input}], size: [${size}]`);
const extract = tar_stream_1.default.extract();
const files = [];
return new Promise((resolve, reject) => {
extract.on('entry', (header, stream, next) => {
let captureFile = false;
const contentBuffer = [];
// detect the files we want and set capture flag
if (fileFilter(header.name) && header.type === 'file') {
captureFile = true;
}
else {
// not the file we want, so call the next entry
next();
}
stream.on('data', (chunk) => {
// if this is a file we want, buffer it's content
if (captureFile) {
contentBuffer.push(chunk);
}
});
stream.on('end', () => {
if (captureFile) {
if (header.name.endsWith('.conf')) {
// emit conf files
this.emit('conf', {
fileName: header.name,
size: header.size,
content: contentBuffer.join('')
});
}
else if (header.name.endsWith('.xml')) {
// emit .xml stats files
this.emit('stat', {
fileName: header.name,
size: header.size,
content: contentBuffer.join('')
});
}
else {
// buffer all other files to be returned when complete
files.push({
fileName: header.name,
size: header.size,
content: contentBuffer.join('')
});
}
}
next();
});
stream.resume();
});
extract.on('finish', () => {
// we finished processing, .conf file should have been emited as events, so now resolve the promise with all the other config files
return resolve({
files,
size
});
});
extract.on('error', err => {
return reject(err);
});
fs.createReadStream(input)
.pipe(zlib_1.default.createGunzip())
.pipe(extract);
});
}
else {
const msg = `file type of "${filePath.ext}", not supported, try (.conf|.ucs|.kqview|.gz)`;
logger_1.default.error(msg);
throw new Error(`not able to read file => ${msg}`);
}
});
}
} |
JavaScript | class App extends React.Component {
constructor(props) {
super(props)
this.state = {
isDownloadModalOpen: false,
loginClicked: false,
signUpClicked: false,
isSideMenuOpen: false,
gridItemsChanged: true,
isImageClicked: false,
clickedImageId: 0,
aboutUsClicked: false,
itemsKey: [],
distances: [],
areItemsReady: false,
items: [],
distUnits: [],
isLocationAvailable: true,
currentRadius: 0.2,
carCategoryArray: [],
phoneCategoryArray: [],
apartmentCategoryArray: [],
homeCategoryArrry: [],
dogCategoryArray: [],
sportCategroyArray: [],
clothesCategoryArray: [],
kidsCategoryArray: [],
booksCategoryArray: [],
otherCategoryArray: [],
itemsCurrentSize: 0,
maxRadius: 20,
lat: 0,
long: 0,
enableBottomScrolling: false,
currentItems: [],
finalArray: [],
bottomLoader: false,
clickedCategory: 0,
locationReady: false,
userSignedIn: false,
photoURL: null,
searchClicked: false,
searchKeys: []
};
this.onDismiss = this.onDismiss.bind(this);
this.onTouchHeader = this.onTouchHeader.bind(this);
this.onDismissImage = this.onDismissImage.bind(this);
this.getItems = this.getItems.bind(this);
this.itemsReady = this.itemsReady.bind(this);
this.renderLargeGrid = this.renderLargeGrid.bind(this);
this.onClickDownloadFromItem = this.onClickDownloadFromItem.bind(this)
this.setLocationEnabled = this.setLocationEnabled.bind(this)
this.setLocationDisabled = this.setLocationDisabled.bind(this)
this.handleScroll = this.handleScroll.bind(this);
this.onClickCategory = this.onClickCategory.bind(this);
this.renderLocation = this.renderLocation.bind(this);
this.onClickSearch = this.onClickSearch.bind(this)
this.searchQuery = this.searchQuery.bind(this)
this.searchCanceled = this.searchCanceled.bind(this)
var self = this
// firebase.auth().signOut()
// console.log(firebase.auth().cu.photoURL)
}
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
this.renderLocation()
this.props.onRef(this)
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleScroll);
this.props.onRef(undefined)
}
itemsReady(keys, dist, distUnits, lat, long) {
var databaseRef = firebase.database()
var counter = 0
var self = this
var itms = []
//console.log("finalse array" + this.state.finalArray)
if (keys.length == 0) {
self.setState({
items: self.state.items.concat(itms),
finalArray: self.state.finalArray.concat(keys),
areItemsReady: true,
bottomLoader: false,
distances: dist,
distUnits: distUnits,
itemsCurrentSize: keys.length + self.state.finalArray.length,
lat: lat,
long: long,
enableBottomScrolling: true
});
}
for (var i = 0; i < keys.length; i++) {
firebase.database().ref('/items/' + keys[i]).once('value').then(function (snapshot) {
var price = snapshot.val().price
if (price != "غير محدد") {
price = snapshot.val().price + snapshot.val().currency
}
var description = snapshot.val().description
var displayName = snapshot.val().displayName
var itemUserId = snapshot.val().userId
var title = snapshot.val().title
var imagesCount = snapshot.val().imagesCount
var favourites = snapshot.val().favourites
itms.push({
price: price,
description: description,
displayName: displayName,
itemUserId: itemUserId,
title: title,
imagesCount: imagesCount,
favourites: favourites
})
if (counter == keys.length - 1) {
self.setState({
items: self.state.items.concat(itms),
finalArray: self.state.finalArray.concat(keys),
areItemsReady: true,
bottomLoader: false,
distances: dist,
distUnits: distUnits,
itemsCurrentSize: keys.length + self.state.finalArray.length,
lat: lat,
long: long,
enableBottomScrolling: true
});
}
counter = counter + 1
});
}
}
intersect(a, b) {
var t;
if (b.length > a.length) t = b, b = a, a = t; // indexOf to loop over shorter
return a.filter(function (e) {
return b.indexOf(e) > -1;
});
}
searchQuery(uncommonArray, distances, distUnits)
{
console.log("distances " + distances)
console.log("distances units" + distUnits)
var keysRef = firebase.database().ref().child("tags")
var fetchedKeys = []
var self = this
var counter = 0
for (var i = 0; i < this.state.searchKeys.length; i++)
{
var keys = []
var key = self.state.searchKeys[i]
keysRef.child(key).once('value').then(function (snapshot, error) {
if (error == null)
{
snapshot.forEach(b=>{
var childKey = b.key
console.log("child key " + childKey)
keys.push(childKey)
})
if (counter == 0)
{
fetchedKeys = keys
}
else{
fetchedKeys = self.intersect(uncommonArray, keys);
}
if (counter == self.state.searchKeys.length - 1){
var finaleArray = self.intersect(uncommonArray, fetchedKeys);
console.log("finale array is " + uncommonArray)
if(finaleArray.length < 12)
{
if (self.state.currentRadius < self.state.maxRadius)
{
self.setState({
currentRadius: self.state.currentRadius + 4,
itemsKey: [],
itemsCurrentSize: finaleArray.length
}, () => {
self.getItems(self.state.lat, self.state.long)
}
)
}
else{
if (finaleArray.length == 0)
{
console.log("length is zero " + finaleArray)
self.itemsReady([],[], [], self.state.lat, self.state.long)
}
else{
console.log("length is one" + finaleArray)
self.itemsReady(finaleArray, distances, distUnits, self.state.lat, self.state.long)
}
}
}
else{
console.log("length is two" + finaleArray)
self.itemsReady(finaleArray, distances, distUnits, self.state.lat, self.state.long)
}
}
}
counter = counter + 1
})
}
}
searchCanceled()
{
this.setState({
searchClicked: false,
finalArray: [],
currentRadius: 0.2,
items: [],
itemsKey: [],
distances: [],
distUnits:[],
itemsCurrentSize: 0,
currentItems: [],
areItemsReady: false
}, () => {
this.getItems(this.state.lat, this.state.long)
})
}
onClickProfile() {
console.log("profile clicked")
}
onClickSearch(string)
{
var searchKeys = string.toLowerCase().split(" ")
this.setState({
searchClicked: true,
finalArray: [],
currentRadius: 0.2,
items: [],
itemsKey: [],
searchKeys: searchKeys,
distances: [],
distUnits: [],
itemsCurrentSize: 0,
currentItems: [],
areItemsReady: false
}, () => {
this.getItems(this.state.lat, this.state.long)
})
}
getItems(lat, long) {
var firebaseRef = firebase.database().ref()
var categoryHash = { 10: "category-others", 9: "category-sports", 8: "category-books", 7: "category-kids", 6: "category-clothes", 5: "category-dog", 4: "cateogry-home", 3: "category-aparment", 2: "phone-category", 1: "category-car" }
//console.log(this.state.clickedCategory)
//console.log(this.state.items)
// console.log("lat is: " + lat, "long is: "+ long)
// console.log(this.state.currentRadius)
this.setState({
lat: lat,
long: long
})
// this.setState({locationReady: true})
if (this.state.clickedCategory == 0) {
firebaseRef = firebaseRef.child("items-location")
}
else {
firebaseRef = firebaseRef.child("categories-location").child(categoryHash[this.state.clickedCategory])
}
var geoFire = new Geofire(firebaseRef)
var itmKey = []
var dist = []
var distUnits = []
var self = this
var geoQuery = geoFire.query({
center: [lat, long],
radius: this.state.currentRadius
})
var onKeyEnteredRegistration = geoQuery.on("key_entered", function (key, location, distance) {
if (distance < 1) {
distance = (distance.toFixed(1) * 100).toString()
distUnits.push("متر")
}
else {
distance = distance.toFixed(2).toString()
distUnits.push("كلم")
}
self.state.itemsKey.push(key)
console.log(key)
dist.push(distance)
});
var onReadyRegistration = geoQuery.on("ready", function () {
if (self.state.currentRadius > self.state.maxRadius) {
console.log(self.state.searchClicked )
var uncommonArray = self.state.itemsKey.filter(function (obj) { return self.state.finalArray.indexOf(obj) == -1; });
if (self.state.searchClicked == true)
{
self.searchQuery(uncommonArray, dist, distUnits)
}
else{
self.itemsReady(uncommonArray, dist, distUnits, lat, long)
}
}
else if (self.state.itemsKey.length - self.state.itemsCurrentSize < 10) {
self.setState({
distUnits: [],
distances: [],
itemsKey: [],
currentRadius: self.state.currentRadius + 4
}, () => {
self.getItems(lat, long)
});
}
else {
var uncommonArray = self.state.itemsKey.filter(function (obj) { return self.state.finalArray.indexOf(obj) == -1; });
console.log(self.state.searchClicked )
if (self.state.searchClicked == true)
{
self.searchQuery(uncommonArray, dist, distUnits)
}
else
{
self.itemsReady(uncommonArray, dist, distUnits, lat, long)
}
//self.setState({value: event.target.value});
}
});
}
onDismiss = () => {
this.setState({
isDownloadModalOpen: !this.state.isDownloadModalOpen
});
}
onClickDownloadFromItem() {
this.onDismissImage()
this.onDismiss()
}
onDismissImage(imageId) {
if (image == null)
{
this.setState({
isImageClicked: !this.state.isImageClicked,
});
}
else
{
this.setState({
isImageClicked: !this.state.isImageClicked,
clickedImageId: imageId
});
}
}
onTouchHeader(event) {
event.stopPropagation()
}
renderHeader() {
return (<Column span={12} mdSpan={2}>
<Navigation onClickCategory={this.onClickCategory} />
</Column>
)
}
handleStateChange(state) {
this.setState({ isSideMenuOpen: state.isOpen })
}
renderLargeGrid() {
const gridStyle = {
marginTop: "50px"
}
if (isBrowser || isSmartTV) {
var gridItems = []
for (var i = 0; i < this.state.finalArray.length; i++) {
const itemId = i
gridItems.push(<GridItem price={this.state.items[i].price} itemId={i} imageId={this.state.finalArray[i]} onDismissImage={() => this.onDismissImage(itemId)} />)
}
return (
<div>
<StackGrid
gutterHeight={20}
gutterWidth={20}
appear={scaleUp.appear}
appeared={scaleUp.appeared}
enter={scaleUp.enter}
entered={scaleUp.entered}
style={
gridStyle
}
columnWidth={230}
>
{
gridItems
}
</StackGrid>
<Box marginTop={2} marginBottom={2}>
<Spinner show={this.state.bottomLoader} accessibilityLabel="Loading Spinner" />
</Box>
</div>
)
}
else {
var gridItems = []
for (var i = 0; i < this.state.finalArray.length; i++) {
const itemId = i
gridItems.push(<SmallGridItem price={this.state.items[i].price} itemId={i} imageId={this.state.finalArray[i]} onDismissImage={() => this.onDismissImage(itemId)} />)
}
return (<div>
<StackGrid
appear={scaleDown.appear}
appeared={scaleDown.appeared}
enter={scaleDown.enter}
entered={scaleDown.entered}
leaved={scaleDown.leaved}
gutterWidth={15}
gutterHeight={15}
style={
gridStyle
}
columnWidth={175}
>
{
gridItems
}
</StackGrid>
<Box marginTop={2}>
<Spinner show={this.state.bottomLoader} accessibilityLabel="Loading Spinner" />
</Box>
</div>
)
}
}
onClickCategory(key) {
window.scrollTo(0, 0)
console.log(key)
this.setState({
clickedCategory: key,
currentRadius: 0.2,
distUnits: [],
distances: [],
itemsKey: [],
areItemsReady: false,
finalArray: [],
items: [],
currentItems: [],
itemsCurrentSize: 0,
bottomLoader: false,
enableBottomScrolling: false
}, () => {
this.getItems(this.state.lat, this.state.long)
});
}
setLocationEnabled() {
this.setState(
{
isLocationAvailable: true
}
)
}
setLocationDisabled() {
this.setState(
{
isLocationAvailable: false
}
)
}
handleScroll() {
const windowHeight = "innerHeight" in window ? window.innerHeight : document.documentElement.offsetHeight;
const body = document.body;
const html = document.documentElement;
const docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
const windowBottom = windowHeight + window.pageYOffset;
if (windowBottom >= docHeight && this.state.enableBottomScrolling) {
if (this.state.currentRadius < this.state.maxRadius) {
this.setState({
enableBottomScrolling: false,
currentRadius: this.state.currentRadius + 0.5,
distUnits: [],
distances: [],
itemsKey: [],
bottomLoader: true
}, () => {
this.getItems(this.state.lat, this.state.long)
});
} else {
}
}
else {
// not the bottom
}
}
renderLocation() {
return (
<div>
{
!this.props.isGeolocationAvailable
? <div>Your browser does not support Geolocation</div>
: !this.props.isGeolocationEnabled
? <div>Geolocation is not enabled</div>
: this.props.coords && !this.state.locationReady
?
this.setState({locationReady: true, lat: this.props.coords.latitude, long: this.props.coords.longitude})
: <div></div>
}
</div>
)
}
render() {
const { children } = this.props;
const { isDownloadModalOpen } = this.state;
const { isMenuOpen } = this.state;
const downloadLabelStyle = {
color: 'black',
fontSize: "14px",
fontWeight: "bold",
textAlign: "right"
};
const sideMenuDonwloadLabelStyle = {
fontWeight: "bold",
color: "black",
fontSize: "16pt",
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
textAlign: "right"
};
return (
<Box minHeight="100vh" onScroll={this.handleScroll}>
<Box marginTop={0} mdDisplay="flex" direction="row"
>
<ToastContainer hideProgressBar={true} />
<GeoLocation setLocationDisabled={this.setLocationDisabled} setLocationEnabled={this.setLocationEnabled} getItems={this.getItems} />
{this.state.isImageClicked && (
<ItemContent showDownloadModal = {this.props.showDownloadModal} onClickDownload={this.onClickDownloadFromItem} distanceUnit={this.state.distUnits[this.state.clickedImageId]} distance={this.state.distances[this.state.clickedImageId]} itemId={this.state.finalArray[this.state.clickedImageId]} item={this.state.items[this.state.clickedImageId]} onDismissImage={this.onDismissImage} />
)}
{this.renderHeader()}
{isDownloadModalOpen && (
this.renderDownloadModal()
)
}
{/* {this.state.locationReady &&(
this.getItems(this.props.coords.latitude, this.props.coords.longitude)
)} */}
<div className="content" >
{
this.state.areItemsReady && (
this.renderLargeGrid()
)}
<Box marginTop={12}>
<Spinner show={!this.state.areItemsReady} accessibilityLabel="Loading Spinner" />
{/* {this.renderLocation()} */}
{/* {!this.state.isLocationAvailable && (
<h3 style={{ marginLeft: "30%", marginRight: "30%", textAlign: "center" }}> !الرجاء تفعيل خدمة المواقع في المتصفح</h3>
)} */}
</Box>
</div>
</Box>
</Box>
);
}
} |
JavaScript | class CellSetsZarrLoader extends BaseAnnDataLoader {
load() {
const { options } = this;
// eslint-disable-next-line camelcase
const cellSetZarrLocation = options.map(({ set_name }) => set_name);
return Promise
.all([this.loadCellNames(), this.loadCellSetIds(cellSetZarrLocation)])
.then((data) => {
const [cellNames, cellSets] = data;
const cellSetsTree = treeInitialize(SETS_DATATYPE_CELL);
cellSets.forEach((cellSetIds, j) => {
const name = options[j].group_name;
let levelZeroNode = {
name,
children: [],
};
const uniqueCellSetIds = Array(...(new Set(cellSetIds))).sort();
const clusters = {};
// eslint-disable-next-line no-return-assign
uniqueCellSetIds.forEach(id => clusters[id] = {
name: id,
set: [],
});
cellSetIds.forEach((id, i) => clusters[id].set.push([cellNames[i], null]));
Object.values(clusters).forEach(
// eslint-disable-next-line no-return-assign
cluster => levelZeroNode = nodeAppendChild(levelZeroNode, cluster),
);
cellSetsTree.tree.push(levelZeroNode);
});
return Promise.resolve({ data: cellSetsTree, url: null });
});
}
} |
JavaScript | class NbCustomMessageService {
constructor() {
this.customMessages = new Map();
}
register(type, instance) {
this.customMessages.set(type, instance);
}
unregister(type) {
return this.customMessages.delete(type);
}
getInstance(type) {
return this.customMessages.get(type);
}
} |
JavaScript | class RecordAction {
text;
secondaryText;
icon;
intent;
className;
tooltip;
actionFn;
items;
disabled;
hidden;
displayFn;
recordsRequired;
/**
* @param {Object} c - RecordAction configuration.
* @param {string} [c.text] - label to be displayed.
* @param {string} [c.secondaryText] - additional label to be displayed, usually in a minimal fashion.
* @param {Element} [c.icon] - icon to be displayed.
* @param {string} [c.intent] - intent to be used for rendering the action.
* @param {string} [c.className] - css class name to be added when rendering the action.
* @param {string} [c.tooltip] - tooltip to display when hovering over the action.
* @param {Object[]} [c.items] - child actions.
* @param {ActionCb} [c.actionFn] - called on store action activation.
* @param {boolean} [c.disabled] - true to disable this item.
* @param {boolean} [c.hidden] - true to hide this item.
* @param {DisplayFn} [c.displayFn] - called prior to showing the action in the UI.
* @param {(number|boolean)} [c.recordsRequired] - how many records must be 'active'
* (selected and / or clicked upon) for the action to be enabled.
* int: specifies exactly n number of records. Defaults to 1 for single record actions.
* Can specify 0 to only enable action if no records are active.
* true: specifies that number of records > 0. Allows for arbitrary number of records.
* false: specifies any number of records (0 - infinity, inclusive). Always active.
*/
constructor({
text,
secondaryText,
icon = null,
intent,
className,
tooltip,
actionFn = null,
items = null,
disabled = false,
hidden = false,
displayFn = null,
recordsRequired = false
}) {
this.text = text;
this.secondaryText = secondaryText;
this.icon = icon;
this.intent = intent;
this.className = className;
this.tooltip = tooltip;
this.actionFn = actionFn;
this.items = items;
this.disabled = disabled;
this.hidden = hidden;
this.displayFn = displayFn;
this.recordsRequired = recordsRequired;
}
/**
* Called by UI elements to get the display configuration for rendering the action. Not
* typically used by applications.
*
* @param p - action parameters
* @param {Object} [p.record] - row data object (entire row, if any).
* @param {Object[]} [p.selectedRecords] - all currently selected records (if any).
* @param {GridModel} [p.gridModel] - grid model where action occurred (if any).
* @param {Column} [p.column] - column where action occurred (if any).
* @param {*} [p...rest] - additional data provided by the context where this action presides
*/
getDisplaySpec({record, selectedRecords, gridModel, column, ...rest}) {
const recordCount = record && isEmpty(selectedRecords) ?
1 :
selectedRecords ? selectedRecords.length : 0;
const defaultDisplay = {
icon: this.icon,
text: this.text,
secondaryText: this.secondaryText,
intent: this.intent,
className: this.className,
tooltip: this.tooltip,
items: this.items,
hidden: this.hidden,
disabled: this.disabled || !this.meetsRecordRequirement(recordCount)
};
if (this.displayFn) {
return {
...defaultDisplay,
...this.displayFn({
action: this,
record,
selectedRecords,
gridModel,
column,
...rest
})
};
}
return defaultDisplay;
}
/**
* Called by UI elements to trigger the action. Not typically used by applications.
*
* @param p
* @param {Object} [p.record] - row data object (entire row, if any).
* @param {Object[]} [p.selectedRecords] - all currently selected records (if any).
* @param {GridModel} [p.gridModel] - grid model where action occurred (if any).
* @param {Column} [p.column] - column where action occurred (if any).
* @param {*} [p...rest] - additional data provided by the context where this action presides
*/
call({record, selectedRecords, gridModel, column, ...rest}) {
if (!this.actionFn) return;
let store = record?.store;
if (!store) store = gridModel?.store;
this.actionFn({action: this, record, selectedRecords, store, gridModel, column, ...rest});
}
meetsRecordRequirement(count) {
const required = this.recordsRequired;
return isNil(required) ||
(isBoolean(required) && (!required || required && count > 0)) ||
(isNumber(required) && count === required);
}
} |
JavaScript | class PriorityQueue {
constructor(compareMax=false) {
this._heap = [];
this._size = 0;
this.compare = compareMax ? this.compareMax : this.compareMin;
}
/**
* Adds a new element to the queue.
*
* @param {mixed} element Element to be stored in the queue
* @param {number} priority Priority assigned to the element
*/
push(element, priority) {
this._heap[++this._size] = [element, priority];
this.bubbleUp(this._size);
}
get length() {
return this._size;
}
isEmpty() {
return this._size == 0;
}
peek() {
return this._heap[1][0];
}
poll() {
const [element] = this.pollIndex();
return element;
}
pollIndex() {
const index = this._heap[1];
this.swap(1, this._size--);
this._heap[this._size+1] = null;
this.bubbleDown(1);
return index;
}
adjustBy(priority) {
for (let i=1; i<=this._size; i++) {
this._heap[i][1] += priority;
}
}
[Symbol.iterator]() {
const traversal = this._heap.slice(1);
traversal.sort((a, b) => a[1] - b[1]);
let index = 0;
return {
next: () => {
const result = traversal[index++];
if (result) {
return {
value: result[0],
done: false
}
} else {
return {
value: undefined,
done: true
}
}
}
}
}
bubbleUp(pos) {
while (pos > 1 && this.compare(Math.floor(pos / 2), pos)) {
this.swap(Math.floor(pos / 2), pos);
pos = Math.floor(pos / 2);
}
}
bubbleDown(pos) {
let next;
while (2 * pos <= this._size) {
next = 2 * pos;
if (next < this._size && this.compare(next, next +1)) next++;
if (!this.compare(pos, next)) break;
this.swap(pos, next);
pos = next;
}
}
compareMin(a, b) {
return this._heap[a][1] > this._heap[b][1];
}
compareMax(a, b) {
return this._heap[b][1] > this._heap[a][1];
}
swap(a, b) {
const item = this._heap[a];
this._heap[a] = this._heap[b];
this._heap[b] = item;
}
clear() {
this._heap = [];
this._size = 0;
}
} |
JavaScript | class Trex {
/**
* T-rex player config.
* @enum {number}
*/
static config = {
DROP_VELOCITY: -5,
GRAVITY: 0.6,
HEIGHT: 47,
HEIGHT_DUCK: 25,
INIITAL_JUMP_VELOCITY: -10,
INTRO_DURATION: 1500,
MAX_JUMP_HEIGHT: 30,
MIN_JUMP_HEIGHT: 30,
SPEED_DROP_COEFFICIENT: 3,
SPRITE_WIDTH: 262,
START_X_POS: 50,
WIDTH: 44,
WIDTH_DUCK: 59,
};
/**
* Used in collision detection.
* @type {Array<CollisionBox>}
*/
static collisionBoxes = {
DUCKING: [new CollisionBox(1, 18, 55, 25)],
RUNNING: [
new CollisionBox(22, 0, 17, 16),
new CollisionBox(1, 18, 30, 9),
new CollisionBox(10, 35, 14, 8),
new CollisionBox(1, 24, 29, 5),
new CollisionBox(5, 30, 21, 4),
new CollisionBox(9, 34, 15, 4),
],
};
/**
* Animation states.
* @enum {string}
*/
static status = {
CRASHED: 'CRASHED',
DUCKING: 'DUCKING',
JUMPING: 'JUMPING',
RUNNING: 'RUNNING',
WAITING: 'WAITING',
};
/**
* Blinking coefficient.
* @const
*/
static BLINK_TIMING = 7000;
/**
* Animation config for different states.
* @enum {Object}
*/
static animFrames = {
WAITING: {
frames: [44, 0],
msPerFrame: 1000 / 3,
},
RUNNING: {
frames: [88, 132],
msPerFrame: 1000 / 12,
},
CRASHED: {
frames: [220],
msPerFrame: 1000 / 60,
},
JUMPING: {
frames: [0],
msPerFrame: 1000 / 60,
},
DUCKING: {
frames: [262, 321],
msPerFrame: 1000 / 8,
},
};
constructor(canvas, spritePos) {
this.canvas = canvas;
this.canvasCtx = canvas.getContext('2d');
this.spritePos = spritePos;
this.xPos = 0;
this.yPos = 0;
// Position when on the ground.
this.groundYPos = 0;
this.currentFrame = 0;
this.currentAnimFrames = [];
this.blinkDelay = 0;
this.blinkCount = 0;
this.animStartTime = 0;
this.timer = 0;
this.msPerFrame = 1000 / FPS;
this.config = Trex.config;
// Current status.
this.status = Trex.status.WAITING;
this.jumping = false;
this.ducking = false;
this.jumpVelocity = 0;
this.reachedMinHeight = false;
this.speedDrop = false;
this.jumpCount = 0;
this.jumpspotX = 0;
this.init();
}
/**
* T-rex player initaliser.
* Sets the t-rex to blink at random intervals.
*/
init() {
this.groundYPos =
Runner.defaultDimensions.HEIGHT -
this.config.HEIGHT -
Runner.config.BOTTOM_PAD;
this.yPos = this.groundYPos;
this.minJumpHeight = this.groundYPos - this.config.MIN_JUMP_HEIGHT;
this.draw(0, 0);
this.update(0, Trex.status.WAITING);
}
/**
* Setter for the jump velocity.
* The approriate drop velocity is also set.
*/
setJumpVelocity(setting) {
this.config.INIITAL_JUMP_VELOCITY = -setting;
this.config.DROP_VELOCITY = -setting / 2;
}
/**
* Set the animation status.
* @param {!number} deltaTime
* @param {Trex.status} status Optional status to switch to.
*/
update(deltaTime, opt_status) {
this.timer += deltaTime;
// Update the status.
if (opt_status) {
this.status = opt_status;
this.currentFrame = 0;
this.msPerFrame = Trex.animFrames[opt_status].msPerFrame;
this.currentAnimFrames = Trex.animFrames[opt_status].frames;
if (opt_status == Trex.status.WAITING) {
this.animStartTime = getTimeStamp();
this.setBlinkDelay();
}
}
// Game intro animation, T-rex moves in from the left.
if (this.playingIntro && this.xPos < this.config.START_X_POS) {
this.xPos += Math.round(
(this.config.START_X_POS / this.config.INTRO_DURATION) * deltaTime
);
}
if (this.status == Trex.status.WAITING) {
this.blink(getTimeStamp());
} else {
this.draw(this.currentAnimFrames[this.currentFrame], 0);
}
// Update the frame position.
if (this.timer >= this.msPerFrame) {
this.currentFrame =
this.currentFrame == this.currentAnimFrames.length - 1
? 0
: this.currentFrame + 1;
this.timer = 0;
}
// Speed drop becomes duck if the down key is still being pressed.
if (this.speedDrop && this.yPos == this.groundYPos) {
this.speedDrop = false;
this.setDuck(true);
}
}
/**
* Draw the t-rex to a particular position.
* @param {number} x
* @param {number} y
*/
draw(x, y) {
let sourceX = x;
let sourceY = y;
let sourceWidth =
this.ducking && this.status != Trex.status.CRASHED
? this.config.WIDTH_DUCK
: this.config.WIDTH;
let sourceHeight = this.config.HEIGHT;
if (IS_HIDPI) {
sourceX *= 2;
sourceY *= 2;
sourceWidth *= 2;
sourceHeight *= 2;
}
// Adjustments for sprite sheet position.
sourceX += this.spritePos.x;
sourceY += this.spritePos.y;
// Ducking.
if (this.ducking && this.status != Trex.status.CRASHED) {
this.canvasCtx.drawImage(
Runner.imageSprite,
sourceX,
sourceY,
sourceWidth,
sourceHeight,
this.xPos,
this.yPos,
this.config.WIDTH_DUCK,
this.config.HEIGHT
);
} else {
// Crashed whilst ducking. Trex is standing up so needs adjustment.
if (this.ducking && this.status == Trex.status.CRASHED) {
this.xPos++;
}
// Standing / running
this.canvasCtx.drawImage(
Runner.imageSprite,
sourceX,
sourceY,
sourceWidth,
sourceHeight,
this.xPos,
this.yPos,
this.config.WIDTH,
this.config.HEIGHT
);
}
}
/**
* Sets a random time for the blink to happen.
*/
setBlinkDelay() {
this.blinkDelay = Math.ceil(Math.random() * Trex.BLINK_TIMING);
}
/**
* Make t-rex blink at random intervals.
* @param {number} time Current time in milliseconds.
*/
blink(time) {
let deltaTime = time - this.animStartTime;
if (deltaTime >= this.blinkDelay) {
this.draw(this.currentAnimFrames[this.currentFrame], 0);
if (this.currentFrame == 1) {
// Set new random delay to blink.
this.setBlinkDelay();
this.animStartTime = time;
this.blinkCount++;
}
}
}
/**
* Initialise a jump.
* @param {number} speed
*/
startJump(speed) {
if (!this.jumping) {
this.update(0, Trex.status.JUMPING);
// Tweak the jump velocity based on the speed.
this.jumpVelocity = this.config.INIITAL_JUMP_VELOCITY - speed / 10;
this.jumping = true;
this.reachedMinHeight = false;
this.speedDrop = false;
}
}
/**
* Jump is complete, falling down.
*/
endJump() {
if (
this.reachedMinHeight &&
this.jumpVelocity < this.config.DROP_VELOCITY
) {
this.jumpVelocity = this.config.DROP_VELOCITY;
}
}
/**
* Update frame for a jump.
* @param {number} deltaTime
* @param {number} speed
*/
updateJump(deltaTime, speed) {
let msPerFrame = Trex.animFrames[this.status].msPerFrame;
let framesElapsed = deltaTime / msPerFrame;
// Speed drop makes Trex fall faster.
if (this.speedDrop) {
this.yPos += Math.round(
this.jumpVelocity * this.config.SPEED_DROP_COEFFICIENT * framesElapsed
);
} else {
this.yPos += Math.round(this.jumpVelocity * framesElapsed);
}
this.jumpVelocity += this.config.GRAVITY * framesElapsed;
// Minimum height has been reached.
if (this.yPos < this.minJumpHeight || this.speedDrop) {
this.reachedMinHeight = true;
}
// Reached max height
if (this.yPos < this.config.MAX_JUMP_HEIGHT || this.speedDrop) {
this.endJump();
}
// Back down at ground level. Jump completed.
if (this.yPos > this.groundYPos) {
this.reset();
this.jumpCount++;
}
this.update(deltaTime);
}
/**
* Set the speed drop. Immediately cancels the current jump.
*/
setSpeedDrop() {
this.speedDrop = true;
this.jumpVelocity = 1;
}
/**
* @param {boolean} isDucking.
*/
setDuck(isDucking) {
if (isDucking && this.status != Trex.status.DUCKING) {
this.update(0, Trex.status.DUCKING);
this.ducking = true;
} else if (this.status == Trex.status.DUCKING) {
this.update(0, Trex.status.RUNNING);
this.ducking = false;
}
}
/**
* Reset the t-rex to running at start of game.
*/
reset() {
this.yPos = this.groundYPos;
this.jumpVelocity = 0;
this.jumping = false;
this.ducking = false;
this.update(0, Trex.status.RUNNING);
this.midair = false;
this.speedDrop = false;
this.jumpCount = 0;
}
} |
JavaScript | class TdStepBodyComponent {
constructor() {
/**
* state?: StepState or ['none' | 'required' | 'complete']
* Sets styles for state of body.
* Defaults to [StepState.None | 'none'].
*/
this.state = StepState.None;
}
/**
* @return {?}
*/
get hasContent() {
return this.contentRef &&
(this.contentRef.nativeElement.children.length > 0 || !!this.contentRef.nativeElement.textContent.trim());
}
/**
* @return {?}
*/
get hasActions() {
return this.actionsRef &&
(this.actionsRef.nativeElement.children.length > 0 || !!this.actionsRef.nativeElement.textContent.trim());
}
/**
* @return {?}
*/
get hasSummary() {
return this.summaryRef &&
(this.summaryRef.nativeElement.children.length > 0 || !!this.summaryRef.nativeElement.textContent.trim());
}
/**
* Returns 'true' if [state] equals to [StepState.Complete | 'complete'], else 'false'.
* @return {?}
*/
isComplete() {
return this.state === StepState.Complete;
}
} |
JavaScript | class SegmentTree {
constructor(length) {
this._size = length;
this._elementsSum = new Array(length * 2);
this._elementsMin = new Array(length * 2);
this._elementsMax = new Array(length * 2);
for (let i = 0; i < this._size; i++) {
this._elementsSum[i] = 0;
this._elementsMin[i] = 0;
this._elementsMax[i] = 0;
}
}
/**
Updates the value at index with the given value
*/
modify(position, value) {
let index = position + this._size;
this._elementsSum[index] = value;
this._elementsMin[index] = value;
this._elementsMax[index] = value;
for (let i = index; i > 1; i >>= 1) {
this._elementsSum[i >> 1] = (
this._elementsSum[i] + this._elementsSum[i ^ 1]
);
this._elementsMin[i >> 1] = Math.min(
this._elementsMin[i], this._elementsMin[i ^ 1]
);
this._elementsMax[i >> 1] = Math.max(
this._elementsMax[i], this._elementsMax[i ^ 1]
);
}
}
/*
code is taken from suggestion by @juanplopes.
calculate performs the binary operation (addition, maximum, minimum) over
the index containing the query range [from,to] and stores the value in ans
*/
calculate(from, to, where, initialValue, binaryFunction) {
let ans = initialValue;
let startIdx = from + this._size;
let endIdx = to + this._size + 1;
for (; startIdx < endIdx; startIdx >>= 1, endIdx >>= 1) {
if (startIdx & 1) ans = binaryFunction(ans, where[startIdx++]);
if (endIdx & 1) ans = binaryFunction(ans, where[--endIdx]);
}
return ans;
}
/**
Return the sum of all elements in the range [from, to]
*/
getSum(from, to) {
return this.calculate(from, to, this._elementsSum, 0, (a, b) => a + b);
}
/**
Return the minimum of all elements in the range [from, to]
*/
getMin(from, to) {
return this.calculate(from, to, this._elementsMin,
Number.MAX_SAFE_INTEGER, Math.min);
}
/**
Return the maximum of all elements in the range [from, to]
*/
getMax(from, to) {
return this.calculate(from, to, this._elementsMax,
Number.MIN_SAFE_INTEGER, Math.max);
}
} |
JavaScript | class ButtonSet extends RingComponent {
render() {
const classes = classNames(styles.buttonSet, this.props.className);
return (
<div
{...this.props}
className={classes}
>
{this.props.children}
</div>
);
}
} |
JavaScript | class SortableTableBody extends PureComponent {
static propTypes = {
/** Disable the drag sort ability */
disabled: PropTypes.bool,
/** The table rows */
children: PropTypes.node.isRequired,
/** On drag/sort end. returns old and new index for changing the order with. */
onSortEnd: PropTypes.func,
/** On drag/sort start */
onSortStart: PropTypes.func,
/** The class added to the body while sorting, useful to disable user-select */
sortingBodyClassName: PropTypes.string,
/** The classname of the React Portal created for the floating sort item */
sortingPortalClassName: PropTypes.string,
/** Locks which axis the row can move */
lockAxis: PropTypes.oneOf(['x', 'y', 'xy']),
/** Locks the floating sort item to the table container */
lockToContainerEdges: PropTypes.bool,
/** Use a handle like SortableTableItemHandle instead of dragging the entire row */
useDragHandle: PropTypes.bool,
/** Optional additional class names to apply at the table body level */
className: PropTypes.string,
/** Optional styles */
style: PropTypes.shape({}),
}
static defaultProps = {
disabled: false,
onSortEnd: () => {},
onSortStart: () => {},
sortingBodyClassName: 'table-v2-sorting',
sortingPortalClassName: '',
lockAxis: 'y',
lockToContainerEdges: true,
useDragHandle: false,
className: null,
style: null,
}
/**
* Move an item from oldIndex to newIndex
* arrayMove(array, oldIndex, newIndex)
*/
static arrayMove = arrayMove;
static createSortHandle = SortableHandle;
constructor(props) {
super(props);
this.state = {
items: Children.toArray(this.props.children),
};
this.onSortEnd = this.onSortEnd.bind(this);
this.onSortStart = this.onSortStart.bind(this);
}
componentWillReceiveProps(nextProps) {
this.setState({
items: Children.toArray(nextProps.children),
});
}
onSortEnd(attrs) {
document.body.classList.remove(this.props.sortingBodyClassName);
this.props.onSortEnd(attrs);
}
onSortStart(attrs) {
document.body.classList.add(this.props.sortingBodyClassName);
this.props.onSortStart(attrs);
}
render() {
return (
<SortableTableBodyInternal
tableBodyClassName={this.props.className}
tableBodyStyle={this.props.style}
helperClass={this.props.sortingPortalClassName}
useDragHandle={this.props.useDragHandle}
lockToContainerEdges={this.props.lockToContainerEdges}
lockAxis={this.props.lockAxis}
items={this.state.items}
onSortEnd={this.onSortEnd}
onSortStart={this.onSortStart}
disabled={this.props.disabled}
/>
);
}
} |
JavaScript | class Kernel extends ConsoleKernel {
/**
* @inheritdoc
*/
async beforeHandling() {
// Here, you can perform actions before handling request.
await this.loadTranslations();
this.registerCommands();
}
/**
* @inheritdoc
*/
afterHandling() {
// Here, you can perform actions after request was handled, if no error was thrown.
}
/**
* @inheritdoc
*/
terminating() {
// Here, you can perform actions before the application terminates.
}
/**
* Load translations to prevent async translations.
*
* @returns {Promise} The async process promise.
*/
async loadTranslations() {
await this.app.make('translator').driver().loadTranslations();
}
/**
* Register commands in the command registrar based on application command path.
*/
registerCommands() {
this.commandRegistrar.addFromFolder(this.app.commandPath());
}
} |
JavaScript | class App extends Component {
constructor(props) {
super(props);
this.state = {
loading: true,
imgSelection: false,
photosBuffer:[],
photosHistory:[],
votedOn: true,
color: "",
textColor: "",
currentUrl: "",
counter: {
Wrong: 0,
Correct: 0,
},
apiKeys:{
pexelsKey: "",
clarifaiKey:"",
},
clarifai: [],
clarifaiConcepts:null,
currentClarifaiId: "",
}
}
getRandomPic = () => {
this.setState({loading: true});
return axios.get('https://picsum.photos/' + window.innerHeight + '/' + window.innerWidth, {
maxRedirects: 1
});
};
isValidPicURL = str =>{
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name and extension
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?'+ // port
'(\\/[-a-z\\d%@_.~+&:]*)*'+ // path
'(\\?[;&a-z\\d%@_.,~+&:=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
//todo - add swal to tell about format
return (pattern.test(str) && /\.(jpe?g|png|gif|bmp)$/g.test(str));
};
//fixme - the drop animation flashes around the header
handleDrop = (files, event) =>{
event.stopPropagation();
event.preventDefault();
let domNode = document.getElementById("arrow");
domNode.classList.add("arrow-down");
const reader = new FileReader();
//only runs if is single file in valid format
if (files.length < 2 && /\.(jpe?g|png|gif|bmp)$/g.test(files[0].name)){
//convert to bas64
reader.onloadend = (fileLoadedEvent) => {
const B64 = fileLoadedEvent.target.result;
this.setState({
currentUrl: B64,
photosHistory:[...this.state.photosHistory, {
//todo - check if the id already exists
id: Math.random(),
large_url: B64,
url: B64,
site:"user_provided"
}]
});
this.performAnalysis(B64);
domNode.classList.remove("arrow-down");
};
} else {
const alert = withReactContent(Swal);
alert.fire({
type: "error",
title: "Oops... too many files!",
text: "You can only set one picture at a time.",
showConfirmButton: false,
customClass: "alertBox",
width: "45%",
background: "rgba(255,255,255, 0.85)"
});
}
if (files) {
reader.readAsDataURL(files[0]);
}
};
findElement = (array, id, option) =>{
//todo - use switch statement
//option 1 = concept
//option 2 = photo history
//option 3 = clarifai object
let object = null;
if (option === 1) {
//only run if exists
if (!!array) {
array.find((element)=>{
if (element.outputs.id === id){
}
});
//find the clarifai object save the concepts
} else {
return false
}
}
if (option === 2) {
array.find((element)=>{if (element.id === id){
object = element;
}})
}
if (option === 3) {
array.find((element)=>{if (element.outputs[0].id === id){
object = element;
}})
}
return object;
};
performSearch = query => {
query.preventDefault();
query.persist();
//start the loading animation
this.setState({loading: true});
//runs if the input is url
if (this.isValidPicURL(query.target.input.value) === 2 ) {
this.setState({
currentUrl: query.target.input.value,
loading: true,
photosHistory: [...this.state.photosHistory, {large_url: query.target.input.value}]
}, this.performAnalysis(this.state.currentUrl));
}
//runs if no input
else if (query.target.input.value === ""){
this.getRandomPic().then(resp=>{
this.setState({
currentUrl: resp.request.responseURL,
photosHistory: [...this.state.photosHistory, {
//this to be reworked, I just quickly added the object as that's what the spashbase used to sent back
id: Math.random(),
large_url: resp.request.responseURL
}],
loading: false,
});
}).then(()=>{
this.performAnalysis(this.state.currentUrl)
});
}
//runs when the url is invalid or there's a search term
else {
//fetch the photo and pushes it into the array then calls the perform analysis
axios.get(`${'https://cors-anywhere.herokuapp.com/'}http://www.splashbase.co/api/v1/images/search?query="${query.target.input.value}"`)
.then(resp => {
if (resp.data.images.length>0) {
this.setState({
photosBuffer: resp.data.images,
//to follow the program check out the renderApp method
imgSelection: true,
});
//to save api request limit:
} else if (resp.data.images.length < 4 && this.state.apiKeys.pexelsKey){
this.pexelsSearch(query.target.input.value);
} else {
const alert = withReactContent(Swal);
//todo - if no pexels key give them option to input
alert.fire({
type: "error",
title: "Oops... no result!",
text: "Try something else.",
showConfirmButton: false,
customClass: "alertBox",
width: "45%",
background: "rgba(255,255,255, 0.85)"
});
this.setState({loading: false});
}
})
.catch(error => {
this.setState({loading: false});
console.log('Error during fetching, parsing data or setting state of the photo: ' + error);
});
}
};
pexelsSearch = searchTerm =>{
//comfort to and push the buffer
searchTerm = searchTerm.replace(/ +/g, '+');
axios({
method: "get",
url:"https://api.pexels.com/v1/search?query=" + searchTerm + "&per_page=15&page=1",
headers: {
Authorization: this.state.apiKeys.pexelsKey,}
}).then(resp =>{
function mapper(resp){
return resp.data.photos.map(photo =>{
return {
id: photo.id,
large_url: photo.src.large2x,
site: "pexels",
};
});
}
this.setState({
photosBuffer: this.state.photosBuffer.concat(mapper(resp)),
imgSelection: true,
});
}).catch(e=>{console.log("Nothing from pexels: " + e)});
};
//available clarafai models
//general: Clarifai.GENERAL_MODEL
//apparel: e0be3b9d6a454f0493ac3a30784001ff
//celebrity: e466caa0619f444ab97497640cefc4dc
//color: eeed0b6733a644cea07cf4c60f87ebb7
//demographics: c0c0ac362b03416da06ab3fa36fb58e3
//food: bd367be194cf45149e75f01d59f77ba7
//textures & patterns: fbefb47f9fdb410e8ce14f24f54b47ff
//travel: eee28c313d69466f836ab83287a54ed9
//wedding: c386b7a870114f4a87477c0824499348
performAnalysis = (url, model = Clarifai.GENERAL_MODEL) =>{
// if (url.slice(0, 11) === "data:image/"){
// //regex matches everything before ";base64,"
// url = {base64: url.replace(/^(.*?);base64,/, "")};
// }
const clarifai = new Clarifai.App({
//todo - create UI clarifai model selection
apiKey: this.state.apiKeys.clarifaiKey,});
// this.performColorAnalysis(url);
clarifai.models.predict(model, url, {maxConcepts: 10})
.then((res) =>{
this.setState({
//todo - eliminate unused data
clarifai: [...this.state.clarifai, res],
//this can be eliminated on serving from clarafai
clarifaiConcepts: res.outputs[0].data.concepts,
currentClarifaiId: res.outputs[0].id,
photosHistory: this.state.photosHistory.map((element, i)=>{
//last item is always the latest
if (i === this.state.photosHistory.length-1){
element.clarifaiId = res.outputs[0].id
}
return element
}),
loading: false,
});
},
(err)=>{
const alert = withReactContent(Swal);
alert.fire({
type: "error",
title: "An error occurred at the analysis stage: ",
text: err.statusText,
showConfirmButton: false,
customClass: "alertBox",
width: "45%",
background: "rgba(255,255,255, 0.85)"
});
console.log("An error occurred at the analysis stage: ");
console.dir(err);
})
.then(this.setState({
imgSelection: false,
photosBuffer:[],
votedOn: false,
}));
document.getElementById("search-bar").value = "";
};
//fixme - colors doesn't work
// performColorAnalysis = url =>{
// clarifai.models.predict(Clarifai.COLOR_MODEL, url, {maxConcepts: 1}).then((res)=>{
// this.state.color = this.calculateColors(res.data.colors[0].raw_hex, true);
// this.setState(this.state);
// }).catch(err=>{
// console.log("error back from color analysis: " + err)
// })
// };
calculateColors = (hex, bw) =>{
if (hex.indexOf('#') === 0) {
hex = hex.slice(1);
}
// convert 3-digit hex to 6-digits.
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
if (hex.length !== 6) {
throw new Error('Invalid HEX color.');
}
let r = parseInt(hex.slice(0, 2), 16),
g = parseInt(hex.slice(2, 4), 16),
b = parseInt(hex.slice(4, 6), 16);
if (bw) {
// taken from http://stackoverflow.com/a/3943023/112731
const textcolor = (r * 0.299 + g * 0.587 + b * 0.114) > 186
? '#000000'
: '#FFFFFF';
this.setState({textColor: textcolor});
}
// invert color components
r = (255 - r).toString(16);
g = (255 - g).toString(16);
b = (255 - b).toString(16);
// pad each with zeros and return
return `#${r}${g}${b}`;
};
increaseScore = subject =>{
//this condition allows only one vote/picture
if (!this.state.votedOn) {
this.setState({
votedOn: true,
//with bracket notation you can accept the string as the property
counter: {
...this.state.counter,
[subject]: this.state.counter[subject] + 1,
},
photosHistory: this.state.photosHistory.map((element)=>{
if (element.large_url === this.state.currentUrl){
element.fair = subject;
}
return element
}),
});
} else{
const alert = withReactContent(Swal);
if (this.state.counter.Wrong === 0 && this.state.counter.Correct === 0) {
alert.fire({
type: "error",
title: "No concepts to vote on...",
text: "Try a new search!",
showConfirmButton: false,
customClass: "alertBox",
width: "45%",
background: "rgba(255,255,255, 0.85)"
});
}
else if (this.state.votedOn) {
alert.fire({
type: "error",
title: "You already voted...",
text: "Try a new search!",
showConfirmButton: false,
customClass: "alertBox",
width: "45%",
background: "rgba(255,255,255, 0.85)"
});
}
}
};
keywordVote = (status, votedOn, id) => {
this.setState({
clarifai: this.state.clarifai.map(
(element) => {
if (element.outputs[0].id === this.state.currentClarifaiId) {
return {
outputs: [
{
created_at: element.outputs[0].created_at,
data: (element.outputs[0].data.concepts.map(
//fixme - can only vote once
(concept) => {
if (concept.id === id) {
return {
app_id: concept.app_id,
id: concept.id,
name: concept.name,
value:concept.value,
status: status,
votedOn: votedOn,
}
} else return concept;
})
),
input: element.outputs[0].input,
model: element.outputs[0].model,
status: element.outputs[0],
}
],
rawData: element.rawData,
status: element.status,
};
} else return element;
}
),
});
};
closeSelectPicture = () =>{
this.setState({
imgSelection: false,
photosBuffer: [],
loading: false
});
};
//fixme - there's got to be a more efficient way than using a buffer
selectPicture = id =>{
//handles both selection before analysis and selection from history
const element = this.findElement(this.state.photosHistory, id, 2);
//element exists in the history stack?
if (element) {
this.setState({
currentUrl: element.large_url,
// fixme - can only set the concepts array once (the array setting error in console might have something to do with it)
currentClarifaiId: element.clarifaiId,
clarifaiConcepts: this.state.clarifai[
this.state.clarifai.findIndex((item)=>{
//fetches the correct photo's clarifai id from history and compares it to the element id if matched it returns the index
return (()=>{if (item.outputs[0].id === element.claifaiId){
return item} else {
//todo - fallback
}})
})
].outputs[0].data.concepts,
imgSelection: false,
});
}
else{
const bufferElement = this.state.photosBuffer.find((element)=> {
if (element.id === id) {
return element;
}
});
this.setState({
photosHistory: [...this.state.photosHistory, bufferElement],
imgSelection: false,
currentUrl: bufferElement.large_url,
});
this.performAnalysis(bufferElement.large_url);
}
};
swalKeys = () => {
const customHistory = createBrowserHistory();
if (!this.state.apiKeys.clarifaiKey && customHistory.location.pathname === "/") {
Swal({
type: "info",
title: 'API key(s) needed!',
html:'<form><fieldset class="form-flex"> <legend>API Keys</legend><div class="clarafaiKey"><label for="clarafaiKey">Clarafai Key:<sup style="color: red;">*</sup></label><input id="clarafaiKey" type="text" placeholder="Your Clarafai API key here" required autofocus></div><div class="pexelsKey"><label for="PexelsKey">Pexels:</label><input id="pexelsKey" type="text" placeholder="Your Pexels API key here"></div></fieldset></form>',
customClass: "alertBox",
background: "rgba(255,255,255, 0.85)",
focusConfirm: false,
allowOutsideClick: false,
preConfirm: () => {
const formValues = [
document.getElementById('clarafaiKey').value,
document.getElementById('pexelsKey').value
];
if(formValues[0].length === 32){
//won't check for pexels as it's not critical for the functioning
if(formValues[1] && formValues[1].length !== 56){
Swal.showValidationError("The Pexels key should be 56 characters");
} else {
return formValues
}
return formValues
} else {
Swal.showValidationError("The Clarafai key should be 32 characters");
}
}
}).then((formValues)=>{
this.setState({
apiKeys: {
clarifaiKey: formValues.value[0],
pexelsKey: formValues.value[1]
}
});
});
}
};
componentWillMount() {
this.getRandomPic().then(resp=>{
this.setState({currentUrl: resp.request.responseURL, loading: false});
}).catch((e)=>{
const alert = withReactContent(Swal);
alert.fire({
type: "error",
title: "Could not fetch the initial background: ",
text: e,
showConfirmButton: false,
customClass: "alertBox",
width: "45%",
background: "rgba(255,255,255, 0.85)"
});
console.log("Could not fetch the initial background: " + e);
this.setState({loading: false});
});
this.swalKeys();
}
renderApp = () =>{
return (
<FileDrop
onDrop={this.handleDrop}
onDragOver={()=>{document.getElementById("arrow").classList.add("arrow-down");}}
onDragLeave={()=>{document.getElementById("arrow").classList.remove("arrow-down");}}>
{/*the span element is part of the dropzone animation*/}
<span id={"arrow"}></span>
{this.state.imgSelection
?
<PictureSelection close={this.closeSelectPicture} pictures={this.state.photosBuffer} selectPicture={this.selectPicture}/>
:
<Header counter={this.state.counter}/>
}
<div className="searchKeywordContainer">
<SearchForm loading={this.state.loading} performSearch={this.performSearch} increaseScore={this.increaseScore}/>
{this.state.clarifai.length>0
?
//errorpage hardcoded as only 2 instance exists of the KeywordContainer
<KeywordsContainer
keywordVote={this.keywordVote}
errorPage={false}
concepts={this.state.clarifaiConcepts}
/>
:
<span></span>}
</div>
</FileDrop>
);
};
noHistoryAlert = () => {
const alert = withReactContent(Swal);
alert.fire({
type: "error",
title: "Oops... Nothing to see here!",
text: "Try searching first.",
showConfirmButton: false,
customClass: "alertBox",
width: "45%",
background: "rgba(255,255,255, 0.85)"
});
};
isPictureSelection = () =>{
return (<PictureSelection pictures={this.state.photosHistory} selectPicture={this.selectPicture}/>)
};
renderHistory = () =>(
<div className="PictureSelectionWrapper">
<Link to="/" className="close"></Link>
<div className="flexBox">
{this.state.photosHistory.length>0
?
this.isPictureSelection()
:
(this.noHistoryAlert(),
(<Redirect to="/"/>))
}
</div>
</div>);
render(){
return (
<div id="background" style={{backgroundImage: `url(${this.state.currentUrl})`}}>
<BrowserRouter>
<Switch>
{/*routes calling functions because "this" is out of the namespace and cannot be binded?*/}
<Route exact path="/" render={()=>this.renderApp()}/>
<Route path="/history" history={this.props.history} render={()=>this.renderHistory()}/>
<Route path="/" component={props => <NotFound keywordVote={this.keywordVote}
swalKeys={this.swalKeys}/>}/>
</Switch>
</BrowserRouter>
</div>
);
}
} |
JavaScript | class Rectangle{
// takes x and y coordinates, width, height (integers), colour (as rgba string from colArray)
constructor(x,y,w,h,fillcolour){
// defining variables
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.c = fillcolour;
}
draw(){
ctx.beginPath();
ctx.rect(this.x,this.y,this.w,this.h);
ctx.fillStyle = this.c;
ctx.fill();
}
update(){
// draw the rectangle
this.draw();
}
} |
JavaScript | class Ellipse{
// constructor takes centre x and y coordinates, width, height (integers), colour (as rgba string from colArray)
constructor(x,y,w,h, fillcolour){
// x centre
this.x = x + w/2;
// y centre
this.y = y + h/2;
// radius of x that is positive
this.xR = Math.abs(w/2);
// radius of y that is positive
this.yR = Math.abs(h/2);
this.c = fillcolour;
}
draw(){
ctx.beginPath();
ctx.ellipse(this.x, this.y, this.xR, this.yR, 0, 0, 2 * Math.PI);
ctx.fillStyle = this.c;
ctx.fill();
}
update(){
// draw ellipse
this.draw();
}
} |
JavaScript | class Triangle{
// constructor takes start mouse coordinates, width, height (integers), colour (as rgba string from colArray)
constructor(xS,yS,w,h,fillcolour){
this.x = xS;
this.y = yS;
this.w = w;
this.h = h;
this.c = fillcolour;
}
draw(){
ctx.beginPath();
ctx.moveTo(this.x + this.w/2, this.y);
ctx.lineTo(this.x+this.w, this.y+this.h);
ctx.lineTo(this.x, this.y+this.h);
ctx.closePath();
ctx.fillStyle = this.c;
ctx.fill();
}
update(){
// draw triangle
this.draw();
}
} |
JavaScript | class Polygon{
// constructor takes centre of polygon coordinates, width, height, number of sides, colour)
constructor(xC,yC, w, h, n, c){
this.xC = xC;
this.yC = yC;
this.w = w;
this.h = h;
this.n = n;
this.c = c;
}
// function starts here
draw(){
var x = 0;
var y = 0;
var R = Math.min(Math.abs(this.w),Math.abs(this.h))/2;
// draw polygon
ctx.beginPath();
for(var i=0; i<=this.n; i++){
x = Math.round(this.xC + (R*Math.cos(i*2*Math.PI/this.n)));
y = Math.round(this.yC + (R*Math.sin(i*2*Math.PI/this.n)));
if (i == 0){
//only begin a path once
ctx.moveTo(x,y);
}
else{
ctx.lineTo(x,y);
}
}
ctx.closePath();
ctx.fillStyle = this.c;
ctx.fill();
}
update(){
this.draw();
}
} |
JavaScript | class Line{
// constructor takes start x and y coordinates, end x and y coordinates, width, colour
constructor(xS, yS, xE, yE, w, c){
// variables needed to draw line
this.xS = xS;
this.yS = yS;
this.xE = xE;
this.yE = yE;
this.w = w;
this.fill = c;
}
update(){
this.draw();
}
draw(){
// draw line function
ctx.strokeStyle = this.fill;
ctx.lineWidth = this.w;
// round edge
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(this.xS, this.yS);
ctx.lineTo(this.xE, this.yE);
ctx.stroke();
}
} |
JavaScript | class Brush{
// constructor takes x coordinate, y coordinate, radius and colour
constructor(x, y, r, c){
// centre x;
this.xC = x;
// centre y;
this.yC =y;
this.r = r;
this.fill = c;
}
update(){
this.draw();
}
draw(){
// brush is drawn
ctx.beginPath();
// drawing circles to replicate what a draw drawes
ctx.arc(this.xC, this.yC, this.r, 0, 2*Math.PI);
ctx.fillStyle = this.fill;
ctx.fill();
}
} |
JavaScript | class Diamond{
// constructor takes x and y start coordinates, width, height, colour
constructor(xS, yS, w, h, c){
this.x = xS;
this.y = yS;
this.w = w;
this.h = h;
this.fill = c;
}
update(){
this.draw();
}
draw(){
// draw diamond
ctx.beginPath();
ctx.moveTo(this.x + this.w/2, this.y);
ctx.lineTo(this.x+this.w, this.y+this.h/2);
ctx.lineTo(this.x +this.w/2, this.y+this.h);
ctx.lineTo(this.x, this.y+this.h/2);
ctx.closePath();
ctx.fillStyle = this.fill;
ctx.fill();
}
} |
JavaScript | class Star{
// variables that the constructor takes are centre x and y coordinates, radius, number of points, colour
constructor(xC, yC, r, points, c){
this.r = r;
this.xC = xC;
this.yC = yC;
this.n = points;
this.fillStyle = c;
this.counter = 0;
this.dy = 4;
this.dx = 4;
}
draw(){
var x = 0;
var y = 0;
var n = this.n * 2;
var rad = this.r/3;
var R;
ctx.lineWidth = 10;
ctx.beginPath();
for(var i=0; i<n; i++){
// every second point drawn will be on the outer circle
if (i%2==0){
R = this.r;
}else{
R = rad;
}
x = this.xC + R*Math.cos(i*2*Math.PI/n +this.counter/20);
y = this.yC + R*Math.sin(i*2*Math.PI/n +this.counter/20);
if(i==0){
//for the first point
ctx.moveTo(x, y);
}else{
// for all other star points
ctx.lineTo(x, y);
}
}
ctx.closePath();
ctx.rotate(Math.PI * 2);
ctx.fillStyle = this.fillStyle;
ctx.fill();
}
update(){
// counter increases by 1 for every 1/40th of a second
this.counter += 1;
this.xC += this.dx
this.yC += this.dy
if(this.yC>25+650 || this.yC<25){
this.dy = -this.dy
}
if(this.xC< 500|| this.xC>500+475){
this.dx = -this.dx
}
// draw a star
this.draw();
}
} |
JavaScript | class App extends Component {
render() {
return (
<Switch>
{routes.map(({path, exact, component: C, ...rest}, key) => (
<Route
key = {key}
path = {path}
exact = {exact}
render = {(props) => (
<C {...props} {...rest} />
)}
/>
))}
</Switch>
)
}
} |
JavaScript | class User {
constructor(id,username,password,role,created_at,updated_at){
this.id =id
this.username=username,
this.password=password,
this.role=role,
this.created_at=created_at,
this.updated_at=updated_at
}
} |
JavaScript | class ValidationError extends AbstractError {
/**
* Create an ValidationError.
*
* @constructor
*
* @param {String} invalidField Field name which caused ValidationError
* @param {String} invalidValue Value which caused ValidationError
* @param {String} invalidReason Why the value is invalidated
*/
constructor(invalidField, invalidValue, invalidReason) {
const message = invalidField + ' with value ' + invalidValue +
' is failed to validate. Because ' + invalidReason
super('Validation Error', message)
this.errorDesc = {
invalidField: invalidField,
invalidValue: invalidValue,
invalidReason: invalidReason
}
}
} |
JavaScript | class ScreenUIElementsAuto extends ScreenUIElements {
/**
@param {string} [className=] CSS class
@param {...UIElement} arguments an array containing the UIElements of the screen
*/
constructor(...args) {
super(...args);
}
createUI() {
this.node = document.createElement("div");
this.applyCSS();
for (let i = 0; i < this.uiElements.length; i++) {
if (!(this.uiElements[i] instanceof UIElement)) {
TheFragebogen.logger.warn(this.constructor.name + ".createUI()", "Element[" + i + "] has no 'createUI' method");
continue;
}
const uiElementNode = this.uiElements[i].createUI();
if (uiElementNode instanceof HTMLElement) {
this.node.appendChild(uiElementNode);
} else {
TheFragebogen.logger.warn(this.constructor.name + ".createUI()", "Element[" + i + "].createUI() did not a HTMLElement.");
}
if (this.uiElements[i].setOnReadyStateChangedCallback instanceof Function) {
this.uiElements[i].setOnReadyStateChangedCallback(() => this._onUIElementReady());
}
}
return this.node;
}
_onUIElementReady() {
if (this.isReady()) {
this._sendPaginateCallback();
}
}
setPaginateUI(paginateUI) {
TheFragebogen.logger.warn(this.constructor.name + ".setPaginateUI()", "Does not support pagination.");
return false;
}
} |
JavaScript | class Buf extends Input{
/**
* Returns if the input is empty
* @return {boolean}
*/
isEmpty(){
return (super.isEmpty() || this.value().length === 0);
}
/**
* Implements input's validations
*
* @param {null|number} at - index used when input has been created as a vector that
* tells which value should be used
* @return {Promise<*>} value held by the input based on the current context (at)
* @protected
*/
_validation(at){
// calling super class validations
return super._validation(at).then((value) => {
const maxBufferSize = this.property('maxBufferSize');
// type checking
if (!(value instanceof Buffer)){
throw new ValidationFail(
'Value needs to be a Buffer!',
'4c5c74ab-21f1-4df2-8985-8b4c030df3ed',
);
}
// specific type check
else if (maxBufferSize !== null && value.length > maxBufferSize){
throw new ValidationFail(
'Value exceeds the maximum length',
'4387c432-ffd6-48d6-a144-91566d262fa0',
);
}
return value;
});
}
/**
* Decodes the input value from the string representation ({@link _encodeScalar}) to the
* data type of the input. This method is called internally during {@link parseValue}
*
* @param {string} value - string containing the encoded value
* @return {bool}
* @protected
*/
static _decodeScalar(value){
return Buffer.from(value, 'base64');
}
/**
* Encodes the input value to a string representation that can be later decoded
* through {@link _decodeScalar}. This method is called internally during the
* {@link serializeValue}
*
* @param {*} value - value that should be encoded to a string
* @return {string}
* @protected
*/
static _encodeScalar(value){
return value.toString('base64');
}
} |
JavaScript | class Provider extends Component {
// the global state ..
state = {
counter : 0 ,
dispatch : action => this.setState(state => Counter_Reducer(state,action))
};
render() {
return (
<Context.Provider value={this.state}>
{
// all html tags replace here .. => injectable
this.props.children
}
</Context.Provider>
)
}
} |
JavaScript | class JobSchedule {
/**
* Create a JobSchedule.
* @param {BatchServiceClient} client Reference to the service client.
*/
constructor(client) {
this.client = client;
}
/**
* @summary Checks the specified job schedule exists.
*
* @param {string} jobScheduleId The ID of the job schedule which you want to
* check.
*
* @param {JobScheduleExistsOptionalParams} [options] Optional Parameters.
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
existsWithHttpOperationResponse(jobScheduleId, options) {
return __awaiter(this, void 0, void 0, function* () {
let client = this.client;
let jobScheduleExistsOptions = (options && options.jobScheduleExistsOptions !== undefined) ? options.jobScheduleExistsOptions : undefined;
// Validate
try {
if (jobScheduleId === null || jobScheduleId === undefined || typeof jobScheduleId.valueOf() !== 'string') {
throw new Error('jobScheduleId cannot be null or undefined and it must be of type string.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
}
catch (error) {
return Promise.reject(error);
}
let timeout;
let clientRequestId;
let returnClientRequestId;
let ocpDate;
let ifMatch;
let ifNoneMatch;
let ifModifiedSince;
let ifUnmodifiedSince;
try {
if (jobScheduleExistsOptions !== null && jobScheduleExistsOptions !== undefined) {
timeout = jobScheduleExistsOptions.timeout;
if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
throw new Error('timeout must be of type number.');
}
}
if (jobScheduleExistsOptions !== null && jobScheduleExistsOptions !== undefined) {
clientRequestId = jobScheduleExistsOptions.clientRequestId;
if (clientRequestId !== null && clientRequestId !== undefined && !(typeof clientRequestId.valueOf() === 'string' && msRest.isValidUuid(clientRequestId))) {
throw new Error('clientRequestId must be of type string and must be a valid string.');
}
}
if (jobScheduleExistsOptions !== null && jobScheduleExistsOptions !== undefined) {
returnClientRequestId = jobScheduleExistsOptions.returnClientRequestId;
if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
throw new Error('returnClientRequestId must be of type boolean.');
}
}
if (jobScheduleExistsOptions !== null && jobScheduleExistsOptions !== undefined) {
ocpDate = jobScheduleExistsOptions.ocpDate;
if (ocpDate && !(ocpDate instanceof Date ||
(typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
throw new Error('ocpDate must be of type date.');
}
}
if (jobScheduleExistsOptions !== null && jobScheduleExistsOptions !== undefined) {
ifMatch = jobScheduleExistsOptions.ifMatch;
if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
throw new Error('ifMatch must be of type string.');
}
}
if (jobScheduleExistsOptions !== null && jobScheduleExistsOptions !== undefined) {
ifNoneMatch = jobScheduleExistsOptions.ifNoneMatch;
if (ifNoneMatch !== null && ifNoneMatch !== undefined && typeof ifNoneMatch.valueOf() !== 'string') {
throw new Error('ifNoneMatch must be of type string.');
}
}
if (jobScheduleExistsOptions !== null && jobScheduleExistsOptions !== undefined) {
ifModifiedSince = jobScheduleExistsOptions.ifModifiedSince;
if (ifModifiedSince && !(ifModifiedSince instanceof Date ||
(typeof ifModifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifModifiedSince))))) {
throw new Error('ifModifiedSince must be of type date.');
}
}
if (jobScheduleExistsOptions !== null && jobScheduleExistsOptions !== undefined) {
ifUnmodifiedSince = jobScheduleExistsOptions.ifUnmodifiedSince;
if (ifUnmodifiedSince && !(ifUnmodifiedSince instanceof Date ||
(typeof ifUnmodifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifUnmodifiedSince))))) {
throw new Error('ifUnmodifiedSince must be of type date.');
}
}
}
catch (error) {
return Promise.reject(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'jobschedules/{jobScheduleId}';
requestUrl = requestUrl.replace('{jobScheduleId}', encodeURIComponent(jobScheduleId));
let queryParamsArray = [];
queryParamsArray.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (timeout !== null && timeout !== undefined) {
queryParamsArray.push('timeout=' + encodeURIComponent(timeout.toString()));
}
if (queryParamsArray.length > 0) {
requestUrl += '?' + queryParamsArray.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'HEAD';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['client-request-id'] = msRest.generateUuid();
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if (clientRequestId !== undefined && clientRequestId !== null) {
httpRequest.headers['client-request-id'] = clientRequestId.toString();
}
if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
}
if (ocpDate !== undefined && ocpDate !== null) {
httpRequest.headers['ocp-date'] = ocpDate instanceof Date ? ocpDate.toUTCString() : ocpDate;
}
if (ifMatch !== undefined && ifMatch !== null) {
httpRequest.headers['If-Match'] = ifMatch;
}
if (ifNoneMatch !== undefined && ifNoneMatch !== null) {
httpRequest.headers['If-None-Match'] = ifNoneMatch;
}
if (ifModifiedSince !== undefined && ifModifiedSince !== null) {
httpRequest.headers['If-Modified-Since'] = ifModifiedSince instanceof Date ? ifModifiedSince.toUTCString() : ifModifiedSince;
}
if (ifUnmodifiedSince !== undefined && ifUnmodifiedSince !== null) {
httpRequest.headers['If-Unmodified-Since'] = ifUnmodifiedSince instanceof Date ? ifUnmodifiedSince.toUTCString() : ifUnmodifiedSince;
}
if (options && options.customHeaders) {
for (let headerName in options.customHeaders) {
if (options.customHeaders.hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options.customHeaders[headerName];
}
}
}
// Send Request
let operationRes;
try {
operationRes = yield client.pipeline(httpRequest);
let response = operationRes.response;
let statusCode = response.status;
if (statusCode !== 200 && statusCode !== 404) {
let error = new msRest.RestError(operationRes.bodyAsText);
error.statusCode = response.status;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
let parsedErrorResponse = operationRes.bodyAsJson;
try {
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error)
internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = Mappers.BatchError;
error.body = client.serializer.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
}
catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${operationRes.bodyAsText}" for the default response.`;
return Promise.reject(error);
}
return Promise.reject(error);
}
operationRes.bodyAsJson = (statusCode === 200);
}
catch (err) {
return Promise.reject(err);
}
return Promise.resolve(operationRes);
});
}
/**
* @summary Deletes a job schedule from the specified account.
*
* When you delete a job schedule, this also deletes all jobs and tasks under
* that schedule. When tasks are deleted, all the files in their working
* directories on the compute nodes are also deleted (the retention period is
* ignored). The job schedule statistics are no longer accessible once the job
* schedule is deleted, though they are still counted towards account lifetime
* statistics.
*
* @param {string} jobScheduleId The ID of the job schedule to delete.
*
* @param {JobScheduleDeleteMethodOptionalParams} [options] Optional
* Parameters.
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(jobScheduleId, options) {
return __awaiter(this, void 0, void 0, function* () {
let client = this.client;
let jobScheduleDeleteMethodOptions = (options && options.jobScheduleDeleteMethodOptions !== undefined) ? options.jobScheduleDeleteMethodOptions : undefined;
// Validate
try {
if (jobScheduleId === null || jobScheduleId === undefined || typeof jobScheduleId.valueOf() !== 'string') {
throw new Error('jobScheduleId cannot be null or undefined and it must be of type string.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
}
catch (error) {
return Promise.reject(error);
}
let timeout;
let clientRequestId;
let returnClientRequestId;
let ocpDate;
let ifMatch;
let ifNoneMatch;
let ifModifiedSince;
let ifUnmodifiedSince;
try {
if (jobScheduleDeleteMethodOptions !== null && jobScheduleDeleteMethodOptions !== undefined) {
timeout = jobScheduleDeleteMethodOptions.timeout;
if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
throw new Error('timeout must be of type number.');
}
}
if (jobScheduleDeleteMethodOptions !== null && jobScheduleDeleteMethodOptions !== undefined) {
clientRequestId = jobScheduleDeleteMethodOptions.clientRequestId;
if (clientRequestId !== null && clientRequestId !== undefined && !(typeof clientRequestId.valueOf() === 'string' && msRest.isValidUuid(clientRequestId))) {
throw new Error('clientRequestId must be of type string and must be a valid string.');
}
}
if (jobScheduleDeleteMethodOptions !== null && jobScheduleDeleteMethodOptions !== undefined) {
returnClientRequestId = jobScheduleDeleteMethodOptions.returnClientRequestId;
if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
throw new Error('returnClientRequestId must be of type boolean.');
}
}
if (jobScheduleDeleteMethodOptions !== null && jobScheduleDeleteMethodOptions !== undefined) {
ocpDate = jobScheduleDeleteMethodOptions.ocpDate;
if (ocpDate && !(ocpDate instanceof Date ||
(typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
throw new Error('ocpDate must be of type date.');
}
}
if (jobScheduleDeleteMethodOptions !== null && jobScheduleDeleteMethodOptions !== undefined) {
ifMatch = jobScheduleDeleteMethodOptions.ifMatch;
if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
throw new Error('ifMatch must be of type string.');
}
}
if (jobScheduleDeleteMethodOptions !== null && jobScheduleDeleteMethodOptions !== undefined) {
ifNoneMatch = jobScheduleDeleteMethodOptions.ifNoneMatch;
if (ifNoneMatch !== null && ifNoneMatch !== undefined && typeof ifNoneMatch.valueOf() !== 'string') {
throw new Error('ifNoneMatch must be of type string.');
}
}
if (jobScheduleDeleteMethodOptions !== null && jobScheduleDeleteMethodOptions !== undefined) {
ifModifiedSince = jobScheduleDeleteMethodOptions.ifModifiedSince;
if (ifModifiedSince && !(ifModifiedSince instanceof Date ||
(typeof ifModifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifModifiedSince))))) {
throw new Error('ifModifiedSince must be of type date.');
}
}
if (jobScheduleDeleteMethodOptions !== null && jobScheduleDeleteMethodOptions !== undefined) {
ifUnmodifiedSince = jobScheduleDeleteMethodOptions.ifUnmodifiedSince;
if (ifUnmodifiedSince && !(ifUnmodifiedSince instanceof Date ||
(typeof ifUnmodifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifUnmodifiedSince))))) {
throw new Error('ifUnmodifiedSince must be of type date.');
}
}
}
catch (error) {
return Promise.reject(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'jobschedules/{jobScheduleId}';
requestUrl = requestUrl.replace('{jobScheduleId}', encodeURIComponent(jobScheduleId));
let queryParamsArray = [];
queryParamsArray.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (timeout !== null && timeout !== undefined) {
queryParamsArray.push('timeout=' + encodeURIComponent(timeout.toString()));
}
if (queryParamsArray.length > 0) {
requestUrl += '?' + queryParamsArray.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'DELETE';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['client-request-id'] = msRest.generateUuid();
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if (clientRequestId !== undefined && clientRequestId !== null) {
httpRequest.headers['client-request-id'] = clientRequestId.toString();
}
if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
}
if (ocpDate !== undefined && ocpDate !== null) {
httpRequest.headers['ocp-date'] = ocpDate instanceof Date ? ocpDate.toUTCString() : ocpDate;
}
if (ifMatch !== undefined && ifMatch !== null) {
httpRequest.headers['If-Match'] = ifMatch;
}
if (ifNoneMatch !== undefined && ifNoneMatch !== null) {
httpRequest.headers['If-None-Match'] = ifNoneMatch;
}
if (ifModifiedSince !== undefined && ifModifiedSince !== null) {
httpRequest.headers['If-Modified-Since'] = ifModifiedSince instanceof Date ? ifModifiedSince.toUTCString() : ifModifiedSince;
}
if (ifUnmodifiedSince !== undefined && ifUnmodifiedSince !== null) {
httpRequest.headers['If-Unmodified-Since'] = ifUnmodifiedSince instanceof Date ? ifUnmodifiedSince.toUTCString() : ifUnmodifiedSince;
}
if (options && options.customHeaders) {
for (let headerName in options.customHeaders) {
if (options.customHeaders.hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options.customHeaders[headerName];
}
}
}
// Send Request
let operationRes;
try {
operationRes = yield client.pipeline(httpRequest);
let response = operationRes.response;
let statusCode = response.status;
if (statusCode !== 202) {
let error = new msRest.RestError(operationRes.bodyAsText);
error.statusCode = response.status;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
let parsedErrorResponse = operationRes.bodyAsJson;
try {
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error)
internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = Mappers.BatchError;
error.body = client.serializer.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
}
catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${operationRes.bodyAsText}" for the default response.`;
return Promise.reject(error);
}
return Promise.reject(error);
}
}
catch (err) {
return Promise.reject(err);
}
return Promise.resolve(operationRes);
});
}
/**
* Gets information about the specified job schedule.
*
* @param {string} jobScheduleId The ID of the job schedule to get.
*
* @param {JobScheduleGetOptionalParams} [options] Optional Parameters.
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(jobScheduleId, options) {
return __awaiter(this, void 0, void 0, function* () {
let client = this.client;
let jobScheduleGetOptions = (options && options.jobScheduleGetOptions !== undefined) ? options.jobScheduleGetOptions : undefined;
// Validate
try {
if (jobScheduleId === null || jobScheduleId === undefined || typeof jobScheduleId.valueOf() !== 'string') {
throw new Error('jobScheduleId cannot be null or undefined and it must be of type string.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
}
catch (error) {
return Promise.reject(error);
}
let select;
let expand;
let timeout;
let clientRequestId;
let returnClientRequestId;
let ocpDate;
let ifMatch;
let ifNoneMatch;
let ifModifiedSince;
let ifUnmodifiedSince;
try {
if (jobScheduleGetOptions !== null && jobScheduleGetOptions !== undefined) {
select = jobScheduleGetOptions.select;
if (select !== null && select !== undefined && typeof select.valueOf() !== 'string') {
throw new Error('select must be of type string.');
}
}
if (jobScheduleGetOptions !== null && jobScheduleGetOptions !== undefined) {
expand = jobScheduleGetOptions.expand;
if (expand !== null && expand !== undefined && typeof expand.valueOf() !== 'string') {
throw new Error('expand must be of type string.');
}
}
if (jobScheduleGetOptions !== null && jobScheduleGetOptions !== undefined) {
timeout = jobScheduleGetOptions.timeout;
if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
throw new Error('timeout must be of type number.');
}
}
if (jobScheduleGetOptions !== null && jobScheduleGetOptions !== undefined) {
clientRequestId = jobScheduleGetOptions.clientRequestId;
if (clientRequestId !== null && clientRequestId !== undefined && !(typeof clientRequestId.valueOf() === 'string' && msRest.isValidUuid(clientRequestId))) {
throw new Error('clientRequestId must be of type string and must be a valid string.');
}
}
if (jobScheduleGetOptions !== null && jobScheduleGetOptions !== undefined) {
returnClientRequestId = jobScheduleGetOptions.returnClientRequestId;
if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
throw new Error('returnClientRequestId must be of type boolean.');
}
}
if (jobScheduleGetOptions !== null && jobScheduleGetOptions !== undefined) {
ocpDate = jobScheduleGetOptions.ocpDate;
if (ocpDate && !(ocpDate instanceof Date ||
(typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
throw new Error('ocpDate must be of type date.');
}
}
if (jobScheduleGetOptions !== null && jobScheduleGetOptions !== undefined) {
ifMatch = jobScheduleGetOptions.ifMatch;
if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
throw new Error('ifMatch must be of type string.');
}
}
if (jobScheduleGetOptions !== null && jobScheduleGetOptions !== undefined) {
ifNoneMatch = jobScheduleGetOptions.ifNoneMatch;
if (ifNoneMatch !== null && ifNoneMatch !== undefined && typeof ifNoneMatch.valueOf() !== 'string') {
throw new Error('ifNoneMatch must be of type string.');
}
}
if (jobScheduleGetOptions !== null && jobScheduleGetOptions !== undefined) {
ifModifiedSince = jobScheduleGetOptions.ifModifiedSince;
if (ifModifiedSince && !(ifModifiedSince instanceof Date ||
(typeof ifModifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifModifiedSince))))) {
throw new Error('ifModifiedSince must be of type date.');
}
}
if (jobScheduleGetOptions !== null && jobScheduleGetOptions !== undefined) {
ifUnmodifiedSince = jobScheduleGetOptions.ifUnmodifiedSince;
if (ifUnmodifiedSince && !(ifUnmodifiedSince instanceof Date ||
(typeof ifUnmodifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifUnmodifiedSince))))) {
throw new Error('ifUnmodifiedSince must be of type date.');
}
}
}
catch (error) {
return Promise.reject(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'jobschedules/{jobScheduleId}';
requestUrl = requestUrl.replace('{jobScheduleId}', encodeURIComponent(jobScheduleId));
let queryParamsArray = [];
queryParamsArray.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (select !== null && select !== undefined) {
queryParamsArray.push('$select=' + encodeURIComponent(select));
}
if (expand !== null && expand !== undefined) {
queryParamsArray.push('$expand=' + encodeURIComponent(expand));
}
if (timeout !== null && timeout !== undefined) {
queryParamsArray.push('timeout=' + encodeURIComponent(timeout.toString()));
}
if (queryParamsArray.length > 0) {
requestUrl += '?' + queryParamsArray.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['client-request-id'] = msRest.generateUuid();
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if (clientRequestId !== undefined && clientRequestId !== null) {
httpRequest.headers['client-request-id'] = clientRequestId.toString();
}
if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
}
if (ocpDate !== undefined && ocpDate !== null) {
httpRequest.headers['ocp-date'] = ocpDate instanceof Date ? ocpDate.toUTCString() : ocpDate;
}
if (ifMatch !== undefined && ifMatch !== null) {
httpRequest.headers['If-Match'] = ifMatch;
}
if (ifNoneMatch !== undefined && ifNoneMatch !== null) {
httpRequest.headers['If-None-Match'] = ifNoneMatch;
}
if (ifModifiedSince !== undefined && ifModifiedSince !== null) {
httpRequest.headers['If-Modified-Since'] = ifModifiedSince instanceof Date ? ifModifiedSince.toUTCString() : ifModifiedSince;
}
if (ifUnmodifiedSince !== undefined && ifUnmodifiedSince !== null) {
httpRequest.headers['If-Unmodified-Since'] = ifUnmodifiedSince instanceof Date ? ifUnmodifiedSince.toUTCString() : ifUnmodifiedSince;
}
if (options && options.customHeaders) {
for (let headerName in options.customHeaders) {
if (options.customHeaders.hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options.customHeaders[headerName];
}
}
}
// Send Request
let operationRes;
try {
operationRes = yield client.pipeline(httpRequest);
let response = operationRes.response;
let statusCode = response.status;
if (statusCode !== 200) {
let error = new msRest.RestError(operationRes.bodyAsText);
error.statusCode = response.status;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
let parsedErrorResponse = operationRes.bodyAsJson;
try {
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error)
internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = Mappers.BatchError;
error.body = client.serializer.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
}
catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${operationRes.bodyAsText}" for the default response.`;
return Promise.reject(error);
}
return Promise.reject(error);
}
// Deserialize Response
if (statusCode === 200) {
let parsedResponse = operationRes.bodyAsJson;
try {
if (parsedResponse !== null && parsedResponse !== undefined) {
let resultMapper = Mappers.CloudJobSchedule;
operationRes.bodyAsJson = client.serializer.deserialize(resultMapper, parsedResponse, 'operationRes.bodyAsJson');
}
}
catch (error) {
let deserializationError = new msRest.RestError(`Error ${error} occurred in deserializing the responseBody - ${operationRes.bodyAsText}`);
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return Promise.reject(deserializationError);
}
}
}
catch (err) {
return Promise.reject(err);
}
return Promise.resolve(operationRes);
});
}
/**
* @summary Updates the properties of the specified job schedule.
*
* This replaces only the job schedule properties specified in the request. For
* example, if the schedule property is not specified with this request, then
* the Batch service will keep the existing schedule. Changes to a job schedule
* only impact jobs created by the schedule after the update has taken place;
* currently running jobs are unaffected.
*
* @param {string} jobScheduleId The ID of the job schedule to update.
*
* @param {JobSchedulePatchParameter} jobSchedulePatchParameter The parameters
* for the request.
*
* @param {JobSchedulePatchOptionalParams} [options] Optional Parameters.
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
patchWithHttpOperationResponse(jobScheduleId, jobSchedulePatchParameter, options) {
return __awaiter(this, void 0, void 0, function* () {
let client = this.client;
let jobSchedulePatchOptions = (options && options.jobSchedulePatchOptions !== undefined) ? options.jobSchedulePatchOptions : undefined;
if (jobSchedulePatchParameter === null || jobSchedulePatchParameter === undefined) {
jobSchedulePatchParameter = {};
}
// Validate
try {
if (jobScheduleId === null || jobScheduleId === undefined || typeof jobScheduleId.valueOf() !== 'string') {
throw new Error('jobScheduleId cannot be null or undefined and it must be of type string.');
}
if (jobSchedulePatchParameter === null || jobSchedulePatchParameter === undefined) {
throw new Error('jobSchedulePatchParameter cannot be null or undefined.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
}
catch (error) {
return Promise.reject(error);
}
let timeout;
let clientRequestId;
let returnClientRequestId;
let ocpDate;
let ifMatch;
let ifNoneMatch;
let ifModifiedSince;
let ifUnmodifiedSince;
try {
if (jobSchedulePatchOptions !== null && jobSchedulePatchOptions !== undefined) {
timeout = jobSchedulePatchOptions.timeout;
if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
throw new Error('timeout must be of type number.');
}
}
if (jobSchedulePatchOptions !== null && jobSchedulePatchOptions !== undefined) {
clientRequestId = jobSchedulePatchOptions.clientRequestId;
if (clientRequestId !== null && clientRequestId !== undefined && !(typeof clientRequestId.valueOf() === 'string' && msRest.isValidUuid(clientRequestId))) {
throw new Error('clientRequestId must be of type string and must be a valid string.');
}
}
if (jobSchedulePatchOptions !== null && jobSchedulePatchOptions !== undefined) {
returnClientRequestId = jobSchedulePatchOptions.returnClientRequestId;
if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
throw new Error('returnClientRequestId must be of type boolean.');
}
}
if (jobSchedulePatchOptions !== null && jobSchedulePatchOptions !== undefined) {
ocpDate = jobSchedulePatchOptions.ocpDate;
if (ocpDate && !(ocpDate instanceof Date ||
(typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
throw new Error('ocpDate must be of type date.');
}
}
if (jobSchedulePatchOptions !== null && jobSchedulePatchOptions !== undefined) {
ifMatch = jobSchedulePatchOptions.ifMatch;
if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
throw new Error('ifMatch must be of type string.');
}
}
if (jobSchedulePatchOptions !== null && jobSchedulePatchOptions !== undefined) {
ifNoneMatch = jobSchedulePatchOptions.ifNoneMatch;
if (ifNoneMatch !== null && ifNoneMatch !== undefined && typeof ifNoneMatch.valueOf() !== 'string') {
throw new Error('ifNoneMatch must be of type string.');
}
}
if (jobSchedulePatchOptions !== null && jobSchedulePatchOptions !== undefined) {
ifModifiedSince = jobSchedulePatchOptions.ifModifiedSince;
if (ifModifiedSince && !(ifModifiedSince instanceof Date ||
(typeof ifModifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifModifiedSince))))) {
throw new Error('ifModifiedSince must be of type date.');
}
}
if (jobSchedulePatchOptions !== null && jobSchedulePatchOptions !== undefined) {
ifUnmodifiedSince = jobSchedulePatchOptions.ifUnmodifiedSince;
if (ifUnmodifiedSince && !(ifUnmodifiedSince instanceof Date ||
(typeof ifUnmodifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifUnmodifiedSince))))) {
throw new Error('ifUnmodifiedSince must be of type date.');
}
}
}
catch (error) {
return Promise.reject(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'jobschedules/{jobScheduleId}';
requestUrl = requestUrl.replace('{jobScheduleId}', encodeURIComponent(jobScheduleId));
let queryParamsArray = [];
queryParamsArray.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (timeout !== null && timeout !== undefined) {
queryParamsArray.push('timeout=' + encodeURIComponent(timeout.toString()));
}
if (queryParamsArray.length > 0) {
requestUrl += '?' + queryParamsArray.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'PATCH';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['client-request-id'] = msRest.generateUuid();
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if (clientRequestId !== undefined && clientRequestId !== null) {
httpRequest.headers['client-request-id'] = clientRequestId.toString();
}
if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
}
if (ocpDate !== undefined && ocpDate !== null) {
httpRequest.headers['ocp-date'] = ocpDate instanceof Date ? ocpDate.toUTCString() : ocpDate;
}
if (ifMatch !== undefined && ifMatch !== null) {
httpRequest.headers['If-Match'] = ifMatch;
}
if (ifNoneMatch !== undefined && ifNoneMatch !== null) {
httpRequest.headers['If-None-Match'] = ifNoneMatch;
}
if (ifModifiedSince !== undefined && ifModifiedSince !== null) {
httpRequest.headers['If-Modified-Since'] = ifModifiedSince instanceof Date ? ifModifiedSince.toUTCString() : ifModifiedSince;
}
if (ifUnmodifiedSince !== undefined && ifUnmodifiedSince !== null) {
httpRequest.headers['If-Unmodified-Since'] = ifUnmodifiedSince instanceof Date ? ifUnmodifiedSince.toUTCString() : ifUnmodifiedSince;
}
if (options && options.customHeaders) {
for (let headerName in options.customHeaders) {
if (options.customHeaders.hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options.customHeaders[headerName];
}
}
}
// Serialize Request
let requestContent = null;
let requestModel = null;
try {
if (jobSchedulePatchParameter !== null && jobSchedulePatchParameter !== undefined) {
let requestModelMapper = Mappers.JobSchedulePatchParameter;
requestModel = client.serializer.serialize(requestModelMapper, jobSchedulePatchParameter, 'jobSchedulePatchParameter');
requestContent = JSON.stringify(requestModel);
}
}
catch (error) {
let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
`payload - ${JSON.stringify(jobSchedulePatchParameter, null, 2)}.`);
return Promise.reject(serializationError);
}
httpRequest.body = requestContent;
// Send Request
let operationRes;
try {
operationRes = yield client.pipeline(httpRequest);
let response = operationRes.response;
let statusCode = response.status;
if (statusCode !== 200) {
let error = new msRest.RestError(operationRes.bodyAsText);
error.statusCode = response.status;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
let parsedErrorResponse = operationRes.bodyAsJson;
try {
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error)
internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = Mappers.BatchError;
error.body = client.serializer.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
}
catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${operationRes.bodyAsText}" for the default response.`;
return Promise.reject(error);
}
return Promise.reject(error);
}
}
catch (err) {
return Promise.reject(err);
}
return Promise.resolve(operationRes);
});
}
/**
* @summary Updates the properties of the specified job schedule.
*
* This fully replaces all the updateable properties of the job schedule. For
* example, if the schedule property is not specified with this request, then
* the Batch service will remove the existing schedule. Changes to a job
* schedule only impact jobs created by the schedule after the update has taken
* place; currently running jobs are unaffected.
*
* @param {string} jobScheduleId The ID of the job schedule to update.
*
* @param {JobScheduleUpdateParameter} jobScheduleUpdateParameter The
* parameters for the request.
*
* @param {JobScheduleUpdateOptionalParams} [options] Optional Parameters.
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(jobScheduleId, jobScheduleUpdateParameter, options) {
return __awaiter(this, void 0, void 0, function* () {
let client = this.client;
let jobScheduleUpdateOptions = (options && options.jobScheduleUpdateOptions !== undefined) ? options.jobScheduleUpdateOptions : undefined;
if (jobScheduleUpdateParameter === null || jobScheduleUpdateParameter === undefined) {
jobScheduleUpdateParameter = {};
}
// Validate
try {
if (jobScheduleId === null || jobScheduleId === undefined || typeof jobScheduleId.valueOf() !== 'string') {
throw new Error('jobScheduleId cannot be null or undefined and it must be of type string.');
}
if (jobScheduleUpdateParameter === null || jobScheduleUpdateParameter === undefined) {
throw new Error('jobScheduleUpdateParameter cannot be null or undefined.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
}
catch (error) {
return Promise.reject(error);
}
let timeout;
let clientRequestId;
let returnClientRequestId;
let ocpDate;
let ifMatch;
let ifNoneMatch;
let ifModifiedSince;
let ifUnmodifiedSince;
try {
if (jobScheduleUpdateOptions !== null && jobScheduleUpdateOptions !== undefined) {
timeout = jobScheduleUpdateOptions.timeout;
if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
throw new Error('timeout must be of type number.');
}
}
if (jobScheduleUpdateOptions !== null && jobScheduleUpdateOptions !== undefined) {
clientRequestId = jobScheduleUpdateOptions.clientRequestId;
if (clientRequestId !== null && clientRequestId !== undefined && !(typeof clientRequestId.valueOf() === 'string' && msRest.isValidUuid(clientRequestId))) {
throw new Error('clientRequestId must be of type string and must be a valid string.');
}
}
if (jobScheduleUpdateOptions !== null && jobScheduleUpdateOptions !== undefined) {
returnClientRequestId = jobScheduleUpdateOptions.returnClientRequestId;
if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
throw new Error('returnClientRequestId must be of type boolean.');
}
}
if (jobScheduleUpdateOptions !== null && jobScheduleUpdateOptions !== undefined) {
ocpDate = jobScheduleUpdateOptions.ocpDate;
if (ocpDate && !(ocpDate instanceof Date ||
(typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
throw new Error('ocpDate must be of type date.');
}
}
if (jobScheduleUpdateOptions !== null && jobScheduleUpdateOptions !== undefined) {
ifMatch = jobScheduleUpdateOptions.ifMatch;
if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
throw new Error('ifMatch must be of type string.');
}
}
if (jobScheduleUpdateOptions !== null && jobScheduleUpdateOptions !== undefined) {
ifNoneMatch = jobScheduleUpdateOptions.ifNoneMatch;
if (ifNoneMatch !== null && ifNoneMatch !== undefined && typeof ifNoneMatch.valueOf() !== 'string') {
throw new Error('ifNoneMatch must be of type string.');
}
}
if (jobScheduleUpdateOptions !== null && jobScheduleUpdateOptions !== undefined) {
ifModifiedSince = jobScheduleUpdateOptions.ifModifiedSince;
if (ifModifiedSince && !(ifModifiedSince instanceof Date ||
(typeof ifModifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifModifiedSince))))) {
throw new Error('ifModifiedSince must be of type date.');
}
}
if (jobScheduleUpdateOptions !== null && jobScheduleUpdateOptions !== undefined) {
ifUnmodifiedSince = jobScheduleUpdateOptions.ifUnmodifiedSince;
if (ifUnmodifiedSince && !(ifUnmodifiedSince instanceof Date ||
(typeof ifUnmodifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifUnmodifiedSince))))) {
throw new Error('ifUnmodifiedSince must be of type date.');
}
}
}
catch (error) {
return Promise.reject(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'jobschedules/{jobScheduleId}';
requestUrl = requestUrl.replace('{jobScheduleId}', encodeURIComponent(jobScheduleId));
let queryParamsArray = [];
queryParamsArray.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (timeout !== null && timeout !== undefined) {
queryParamsArray.push('timeout=' + encodeURIComponent(timeout.toString()));
}
if (queryParamsArray.length > 0) {
requestUrl += '?' + queryParamsArray.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'PUT';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['client-request-id'] = msRest.generateUuid();
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if (clientRequestId !== undefined && clientRequestId !== null) {
httpRequest.headers['client-request-id'] = clientRequestId.toString();
}
if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
}
if (ocpDate !== undefined && ocpDate !== null) {
httpRequest.headers['ocp-date'] = ocpDate instanceof Date ? ocpDate.toUTCString() : ocpDate;
}
if (ifMatch !== undefined && ifMatch !== null) {
httpRequest.headers['If-Match'] = ifMatch;
}
if (ifNoneMatch !== undefined && ifNoneMatch !== null) {
httpRequest.headers['If-None-Match'] = ifNoneMatch;
}
if (ifModifiedSince !== undefined && ifModifiedSince !== null) {
httpRequest.headers['If-Modified-Since'] = ifModifiedSince instanceof Date ? ifModifiedSince.toUTCString() : ifModifiedSince;
}
if (ifUnmodifiedSince !== undefined && ifUnmodifiedSince !== null) {
httpRequest.headers['If-Unmodified-Since'] = ifUnmodifiedSince instanceof Date ? ifUnmodifiedSince.toUTCString() : ifUnmodifiedSince;
}
if (options && options.customHeaders) {
for (let headerName in options.customHeaders) {
if (options.customHeaders.hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options.customHeaders[headerName];
}
}
}
// Serialize Request
let requestContent = null;
let requestModel = null;
try {
if (jobScheduleUpdateParameter !== null && jobScheduleUpdateParameter !== undefined) {
let requestModelMapper = Mappers.JobScheduleUpdateParameter;
requestModel = client.serializer.serialize(requestModelMapper, jobScheduleUpdateParameter, 'jobScheduleUpdateParameter');
requestContent = JSON.stringify(requestModel);
}
}
catch (error) {
let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
`payload - ${JSON.stringify(jobScheduleUpdateParameter, null, 2)}.`);
return Promise.reject(serializationError);
}
httpRequest.body = requestContent;
// Send Request
let operationRes;
try {
operationRes = yield client.pipeline(httpRequest);
let response = operationRes.response;
let statusCode = response.status;
if (statusCode !== 200) {
let error = new msRest.RestError(operationRes.bodyAsText);
error.statusCode = response.status;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
let parsedErrorResponse = operationRes.bodyAsJson;
try {
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error)
internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = Mappers.BatchError;
error.body = client.serializer.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
}
catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${operationRes.bodyAsText}" for the default response.`;
return Promise.reject(error);
}
return Promise.reject(error);
}
}
catch (err) {
return Promise.reject(err);
}
return Promise.resolve(operationRes);
});
}
/**
* @summary Disables a job schedule.
*
* No new jobs will be created until the job schedule is enabled again.
*
* @param {string} jobScheduleId The ID of the job schedule to disable.
*
* @param {JobScheduleDisableOptionalParams} [options] Optional Parameters.
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
disableWithHttpOperationResponse(jobScheduleId, options) {
return __awaiter(this, void 0, void 0, function* () {
let client = this.client;
let jobScheduleDisableOptions = (options && options.jobScheduleDisableOptions !== undefined) ? options.jobScheduleDisableOptions : undefined;
// Validate
try {
if (jobScheduleId === null || jobScheduleId === undefined || typeof jobScheduleId.valueOf() !== 'string') {
throw new Error('jobScheduleId cannot be null or undefined and it must be of type string.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
}
catch (error) {
return Promise.reject(error);
}
let timeout;
let clientRequestId;
let returnClientRequestId;
let ocpDate;
let ifMatch;
let ifNoneMatch;
let ifModifiedSince;
let ifUnmodifiedSince;
try {
if (jobScheduleDisableOptions !== null && jobScheduleDisableOptions !== undefined) {
timeout = jobScheduleDisableOptions.timeout;
if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
throw new Error('timeout must be of type number.');
}
}
if (jobScheduleDisableOptions !== null && jobScheduleDisableOptions !== undefined) {
clientRequestId = jobScheduleDisableOptions.clientRequestId;
if (clientRequestId !== null && clientRequestId !== undefined && !(typeof clientRequestId.valueOf() === 'string' && msRest.isValidUuid(clientRequestId))) {
throw new Error('clientRequestId must be of type string and must be a valid string.');
}
}
if (jobScheduleDisableOptions !== null && jobScheduleDisableOptions !== undefined) {
returnClientRequestId = jobScheduleDisableOptions.returnClientRequestId;
if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
throw new Error('returnClientRequestId must be of type boolean.');
}
}
if (jobScheduleDisableOptions !== null && jobScheduleDisableOptions !== undefined) {
ocpDate = jobScheduleDisableOptions.ocpDate;
if (ocpDate && !(ocpDate instanceof Date ||
(typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
throw new Error('ocpDate must be of type date.');
}
}
if (jobScheduleDisableOptions !== null && jobScheduleDisableOptions !== undefined) {
ifMatch = jobScheduleDisableOptions.ifMatch;
if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
throw new Error('ifMatch must be of type string.');
}
}
if (jobScheduleDisableOptions !== null && jobScheduleDisableOptions !== undefined) {
ifNoneMatch = jobScheduleDisableOptions.ifNoneMatch;
if (ifNoneMatch !== null && ifNoneMatch !== undefined && typeof ifNoneMatch.valueOf() !== 'string') {
throw new Error('ifNoneMatch must be of type string.');
}
}
if (jobScheduleDisableOptions !== null && jobScheduleDisableOptions !== undefined) {
ifModifiedSince = jobScheduleDisableOptions.ifModifiedSince;
if (ifModifiedSince && !(ifModifiedSince instanceof Date ||
(typeof ifModifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifModifiedSince))))) {
throw new Error('ifModifiedSince must be of type date.');
}
}
if (jobScheduleDisableOptions !== null && jobScheduleDisableOptions !== undefined) {
ifUnmodifiedSince = jobScheduleDisableOptions.ifUnmodifiedSince;
if (ifUnmodifiedSince && !(ifUnmodifiedSince instanceof Date ||
(typeof ifUnmodifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifUnmodifiedSince))))) {
throw new Error('ifUnmodifiedSince must be of type date.');
}
}
}
catch (error) {
return Promise.reject(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'jobschedules/{jobScheduleId}/disable';
requestUrl = requestUrl.replace('{jobScheduleId}', encodeURIComponent(jobScheduleId));
let queryParamsArray = [];
queryParamsArray.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (timeout !== null && timeout !== undefined) {
queryParamsArray.push('timeout=' + encodeURIComponent(timeout.toString()));
}
if (queryParamsArray.length > 0) {
requestUrl += '?' + queryParamsArray.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['client-request-id'] = msRest.generateUuid();
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if (clientRequestId !== undefined && clientRequestId !== null) {
httpRequest.headers['client-request-id'] = clientRequestId.toString();
}
if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
}
if (ocpDate !== undefined && ocpDate !== null) {
httpRequest.headers['ocp-date'] = ocpDate instanceof Date ? ocpDate.toUTCString() : ocpDate;
}
if (ifMatch !== undefined && ifMatch !== null) {
httpRequest.headers['If-Match'] = ifMatch;
}
if (ifNoneMatch !== undefined && ifNoneMatch !== null) {
httpRequest.headers['If-None-Match'] = ifNoneMatch;
}
if (ifModifiedSince !== undefined && ifModifiedSince !== null) {
httpRequest.headers['If-Modified-Since'] = ifModifiedSince instanceof Date ? ifModifiedSince.toUTCString() : ifModifiedSince;
}
if (ifUnmodifiedSince !== undefined && ifUnmodifiedSince !== null) {
httpRequest.headers['If-Unmodified-Since'] = ifUnmodifiedSince instanceof Date ? ifUnmodifiedSince.toUTCString() : ifUnmodifiedSince;
}
if (options && options.customHeaders) {
for (let headerName in options.customHeaders) {
if (options.customHeaders.hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options.customHeaders[headerName];
}
}
}
// Send Request
let operationRes;
try {
operationRes = yield client.pipeline(httpRequest);
let response = operationRes.response;
let statusCode = response.status;
if (statusCode !== 204) {
let error = new msRest.RestError(operationRes.bodyAsText);
error.statusCode = response.status;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
let parsedErrorResponse = operationRes.bodyAsJson;
try {
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error)
internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = Mappers.BatchError;
error.body = client.serializer.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
}
catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${operationRes.bodyAsText}" for the default response.`;
return Promise.reject(error);
}
return Promise.reject(error);
}
}
catch (err) {
return Promise.reject(err);
}
return Promise.resolve(operationRes);
});
}
/**
* @summary Enables a job schedule.
*
* @param {string} jobScheduleId The ID of the job schedule to enable.
*
* @param {JobScheduleEnableOptionalParams} [options] Optional Parameters.
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
enableWithHttpOperationResponse(jobScheduleId, options) {
return __awaiter(this, void 0, void 0, function* () {
let client = this.client;
let jobScheduleEnableOptions = (options && options.jobScheduleEnableOptions !== undefined) ? options.jobScheduleEnableOptions : undefined;
// Validate
try {
if (jobScheduleId === null || jobScheduleId === undefined || typeof jobScheduleId.valueOf() !== 'string') {
throw new Error('jobScheduleId cannot be null or undefined and it must be of type string.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
}
catch (error) {
return Promise.reject(error);
}
let timeout;
let clientRequestId;
let returnClientRequestId;
let ocpDate;
let ifMatch;
let ifNoneMatch;
let ifModifiedSince;
let ifUnmodifiedSince;
try {
if (jobScheduleEnableOptions !== null && jobScheduleEnableOptions !== undefined) {
timeout = jobScheduleEnableOptions.timeout;
if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
throw new Error('timeout must be of type number.');
}
}
if (jobScheduleEnableOptions !== null && jobScheduleEnableOptions !== undefined) {
clientRequestId = jobScheduleEnableOptions.clientRequestId;
if (clientRequestId !== null && clientRequestId !== undefined && !(typeof clientRequestId.valueOf() === 'string' && msRest.isValidUuid(clientRequestId))) {
throw new Error('clientRequestId must be of type string and must be a valid string.');
}
}
if (jobScheduleEnableOptions !== null && jobScheduleEnableOptions !== undefined) {
returnClientRequestId = jobScheduleEnableOptions.returnClientRequestId;
if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
throw new Error('returnClientRequestId must be of type boolean.');
}
}
if (jobScheduleEnableOptions !== null && jobScheduleEnableOptions !== undefined) {
ocpDate = jobScheduleEnableOptions.ocpDate;
if (ocpDate && !(ocpDate instanceof Date ||
(typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
throw new Error('ocpDate must be of type date.');
}
}
if (jobScheduleEnableOptions !== null && jobScheduleEnableOptions !== undefined) {
ifMatch = jobScheduleEnableOptions.ifMatch;
if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
throw new Error('ifMatch must be of type string.');
}
}
if (jobScheduleEnableOptions !== null && jobScheduleEnableOptions !== undefined) {
ifNoneMatch = jobScheduleEnableOptions.ifNoneMatch;
if (ifNoneMatch !== null && ifNoneMatch !== undefined && typeof ifNoneMatch.valueOf() !== 'string') {
throw new Error('ifNoneMatch must be of type string.');
}
}
if (jobScheduleEnableOptions !== null && jobScheduleEnableOptions !== undefined) {
ifModifiedSince = jobScheduleEnableOptions.ifModifiedSince;
if (ifModifiedSince && !(ifModifiedSince instanceof Date ||
(typeof ifModifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifModifiedSince))))) {
throw new Error('ifModifiedSince must be of type date.');
}
}
if (jobScheduleEnableOptions !== null && jobScheduleEnableOptions !== undefined) {
ifUnmodifiedSince = jobScheduleEnableOptions.ifUnmodifiedSince;
if (ifUnmodifiedSince && !(ifUnmodifiedSince instanceof Date ||
(typeof ifUnmodifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifUnmodifiedSince))))) {
throw new Error('ifUnmodifiedSince must be of type date.');
}
}
}
catch (error) {
return Promise.reject(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'jobschedules/{jobScheduleId}/enable';
requestUrl = requestUrl.replace('{jobScheduleId}', encodeURIComponent(jobScheduleId));
let queryParamsArray = [];
queryParamsArray.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (timeout !== null && timeout !== undefined) {
queryParamsArray.push('timeout=' + encodeURIComponent(timeout.toString()));
}
if (queryParamsArray.length > 0) {
requestUrl += '?' + queryParamsArray.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['client-request-id'] = msRest.generateUuid();
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if (clientRequestId !== undefined && clientRequestId !== null) {
httpRequest.headers['client-request-id'] = clientRequestId.toString();
}
if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
}
if (ocpDate !== undefined && ocpDate !== null) {
httpRequest.headers['ocp-date'] = ocpDate instanceof Date ? ocpDate.toUTCString() : ocpDate;
}
if (ifMatch !== undefined && ifMatch !== null) {
httpRequest.headers['If-Match'] = ifMatch;
}
if (ifNoneMatch !== undefined && ifNoneMatch !== null) {
httpRequest.headers['If-None-Match'] = ifNoneMatch;
}
if (ifModifiedSince !== undefined && ifModifiedSince !== null) {
httpRequest.headers['If-Modified-Since'] = ifModifiedSince instanceof Date ? ifModifiedSince.toUTCString() : ifModifiedSince;
}
if (ifUnmodifiedSince !== undefined && ifUnmodifiedSince !== null) {
httpRequest.headers['If-Unmodified-Since'] = ifUnmodifiedSince instanceof Date ? ifUnmodifiedSince.toUTCString() : ifUnmodifiedSince;
}
if (options && options.customHeaders) {
for (let headerName in options.customHeaders) {
if (options.customHeaders.hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options.customHeaders[headerName];
}
}
}
// Send Request
let operationRes;
try {
operationRes = yield client.pipeline(httpRequest);
let response = operationRes.response;
let statusCode = response.status;
if (statusCode !== 204) {
let error = new msRest.RestError(operationRes.bodyAsText);
error.statusCode = response.status;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
let parsedErrorResponse = operationRes.bodyAsJson;
try {
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error)
internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = Mappers.BatchError;
error.body = client.serializer.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
}
catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${operationRes.bodyAsText}" for the default response.`;
return Promise.reject(error);
}
return Promise.reject(error);
}
}
catch (err) {
return Promise.reject(err);
}
return Promise.resolve(operationRes);
});
}
/**
* @summary Terminates a job schedule.
*
* @param {string} jobScheduleId The ID of the job schedule to terminates.
*
* @param {JobScheduleTerminateOptionalParams} [options] Optional Parameters.
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
terminateWithHttpOperationResponse(jobScheduleId, options) {
return __awaiter(this, void 0, void 0, function* () {
let client = this.client;
let jobScheduleTerminateOptions = (options && options.jobScheduleTerminateOptions !== undefined) ? options.jobScheduleTerminateOptions : undefined;
// Validate
try {
if (jobScheduleId === null || jobScheduleId === undefined || typeof jobScheduleId.valueOf() !== 'string') {
throw new Error('jobScheduleId cannot be null or undefined and it must be of type string.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
}
catch (error) {
return Promise.reject(error);
}
let timeout;
let clientRequestId;
let returnClientRequestId;
let ocpDate;
let ifMatch;
let ifNoneMatch;
let ifModifiedSince;
let ifUnmodifiedSince;
try {
if (jobScheduleTerminateOptions !== null && jobScheduleTerminateOptions !== undefined) {
timeout = jobScheduleTerminateOptions.timeout;
if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
throw new Error('timeout must be of type number.');
}
}
if (jobScheduleTerminateOptions !== null && jobScheduleTerminateOptions !== undefined) {
clientRequestId = jobScheduleTerminateOptions.clientRequestId;
if (clientRequestId !== null && clientRequestId !== undefined && !(typeof clientRequestId.valueOf() === 'string' && msRest.isValidUuid(clientRequestId))) {
throw new Error('clientRequestId must be of type string and must be a valid string.');
}
}
if (jobScheduleTerminateOptions !== null && jobScheduleTerminateOptions !== undefined) {
returnClientRequestId = jobScheduleTerminateOptions.returnClientRequestId;
if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
throw new Error('returnClientRequestId must be of type boolean.');
}
}
if (jobScheduleTerminateOptions !== null && jobScheduleTerminateOptions !== undefined) {
ocpDate = jobScheduleTerminateOptions.ocpDate;
if (ocpDate && !(ocpDate instanceof Date ||
(typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
throw new Error('ocpDate must be of type date.');
}
}
if (jobScheduleTerminateOptions !== null && jobScheduleTerminateOptions !== undefined) {
ifMatch = jobScheduleTerminateOptions.ifMatch;
if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
throw new Error('ifMatch must be of type string.');
}
}
if (jobScheduleTerminateOptions !== null && jobScheduleTerminateOptions !== undefined) {
ifNoneMatch = jobScheduleTerminateOptions.ifNoneMatch;
if (ifNoneMatch !== null && ifNoneMatch !== undefined && typeof ifNoneMatch.valueOf() !== 'string') {
throw new Error('ifNoneMatch must be of type string.');
}
}
if (jobScheduleTerminateOptions !== null && jobScheduleTerminateOptions !== undefined) {
ifModifiedSince = jobScheduleTerminateOptions.ifModifiedSince;
if (ifModifiedSince && !(ifModifiedSince instanceof Date ||
(typeof ifModifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifModifiedSince))))) {
throw new Error('ifModifiedSince must be of type date.');
}
}
if (jobScheduleTerminateOptions !== null && jobScheduleTerminateOptions !== undefined) {
ifUnmodifiedSince = jobScheduleTerminateOptions.ifUnmodifiedSince;
if (ifUnmodifiedSince && !(ifUnmodifiedSince instanceof Date ||
(typeof ifUnmodifiedSince.valueOf() === 'string' && !isNaN(Date.parse(ifUnmodifiedSince))))) {
throw new Error('ifUnmodifiedSince must be of type date.');
}
}
}
catch (error) {
return Promise.reject(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'jobschedules/{jobScheduleId}/terminate';
requestUrl = requestUrl.replace('{jobScheduleId}', encodeURIComponent(jobScheduleId));
let queryParamsArray = [];
queryParamsArray.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (timeout !== null && timeout !== undefined) {
queryParamsArray.push('timeout=' + encodeURIComponent(timeout.toString()));
}
if (queryParamsArray.length > 0) {
requestUrl += '?' + queryParamsArray.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['client-request-id'] = msRest.generateUuid();
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if (clientRequestId !== undefined && clientRequestId !== null) {
httpRequest.headers['client-request-id'] = clientRequestId.toString();
}
if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
}
if (ocpDate !== undefined && ocpDate !== null) {
httpRequest.headers['ocp-date'] = ocpDate instanceof Date ? ocpDate.toUTCString() : ocpDate;
}
if (ifMatch !== undefined && ifMatch !== null) {
httpRequest.headers['If-Match'] = ifMatch;
}
if (ifNoneMatch !== undefined && ifNoneMatch !== null) {
httpRequest.headers['If-None-Match'] = ifNoneMatch;
}
if (ifModifiedSince !== undefined && ifModifiedSince !== null) {
httpRequest.headers['If-Modified-Since'] = ifModifiedSince instanceof Date ? ifModifiedSince.toUTCString() : ifModifiedSince;
}
if (ifUnmodifiedSince !== undefined && ifUnmodifiedSince !== null) {
httpRequest.headers['If-Unmodified-Since'] = ifUnmodifiedSince instanceof Date ? ifUnmodifiedSince.toUTCString() : ifUnmodifiedSince;
}
if (options && options.customHeaders) {
for (let headerName in options.customHeaders) {
if (options.customHeaders.hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options.customHeaders[headerName];
}
}
}
// Send Request
let operationRes;
try {
operationRes = yield client.pipeline(httpRequest);
let response = operationRes.response;
let statusCode = response.status;
if (statusCode !== 202) {
let error = new msRest.RestError(operationRes.bodyAsText);
error.statusCode = response.status;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
let parsedErrorResponse = operationRes.bodyAsJson;
try {
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error)
internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = Mappers.BatchError;
error.body = client.serializer.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
}
catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${operationRes.bodyAsText}" for the default response.`;
return Promise.reject(error);
}
return Promise.reject(error);
}
}
catch (err) {
return Promise.reject(err);
}
return Promise.resolve(operationRes);
});
}
/**
* @summary Adds a job schedule to the specified account.
*
* @param {JobScheduleAddParameter} cloudJobSchedule The job schedule to be
* added.
*
* @param {JobScheduleAddOptionalParams} [options] Optional Parameters.
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
addWithHttpOperationResponse(cloudJobSchedule, options) {
return __awaiter(this, void 0, void 0, function* () {
let client = this.client;
let jobScheduleAddOptions = (options && options.jobScheduleAddOptions !== undefined) ? options.jobScheduleAddOptions : undefined;
if (cloudJobSchedule === null || cloudJobSchedule === undefined) {
cloudJobSchedule = {};
}
// Validate
try {
if (cloudJobSchedule === null || cloudJobSchedule === undefined) {
throw new Error('cloudJobSchedule cannot be null or undefined.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
}
catch (error) {
return Promise.reject(error);
}
let timeout;
let clientRequestId;
let returnClientRequestId;
let ocpDate;
try {
if (jobScheduleAddOptions !== null && jobScheduleAddOptions !== undefined) {
timeout = jobScheduleAddOptions.timeout;
if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
throw new Error('timeout must be of type number.');
}
}
if (jobScheduleAddOptions !== null && jobScheduleAddOptions !== undefined) {
clientRequestId = jobScheduleAddOptions.clientRequestId;
if (clientRequestId !== null && clientRequestId !== undefined && !(typeof clientRequestId.valueOf() === 'string' && msRest.isValidUuid(clientRequestId))) {
throw new Error('clientRequestId must be of type string and must be a valid string.');
}
}
if (jobScheduleAddOptions !== null && jobScheduleAddOptions !== undefined) {
returnClientRequestId = jobScheduleAddOptions.returnClientRequestId;
if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
throw new Error('returnClientRequestId must be of type boolean.');
}
}
if (jobScheduleAddOptions !== null && jobScheduleAddOptions !== undefined) {
ocpDate = jobScheduleAddOptions.ocpDate;
if (ocpDate && !(ocpDate instanceof Date ||
(typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
throw new Error('ocpDate must be of type date.');
}
}
}
catch (error) {
return Promise.reject(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'jobschedules';
let queryParamsArray = [];
queryParamsArray.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (timeout !== null && timeout !== undefined) {
queryParamsArray.push('timeout=' + encodeURIComponent(timeout.toString()));
}
if (queryParamsArray.length > 0) {
requestUrl += '?' + queryParamsArray.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['client-request-id'] = msRest.generateUuid();
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if (clientRequestId !== undefined && clientRequestId !== null) {
httpRequest.headers['client-request-id'] = clientRequestId.toString();
}
if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
}
if (ocpDate !== undefined && ocpDate !== null) {
httpRequest.headers['ocp-date'] = ocpDate instanceof Date ? ocpDate.toUTCString() : ocpDate;
}
if (options && options.customHeaders) {
for (let headerName in options.customHeaders) {
if (options.customHeaders.hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options.customHeaders[headerName];
}
}
}
// Serialize Request
let requestContent = null;
let requestModel = null;
try {
if (cloudJobSchedule !== null && cloudJobSchedule !== undefined) {
let requestModelMapper = Mappers.JobScheduleAddParameter;
requestModel = client.serializer.serialize(requestModelMapper, cloudJobSchedule, 'cloudJobSchedule');
requestContent = JSON.stringify(requestModel);
}
}
catch (error) {
let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
`payload - ${JSON.stringify(cloudJobSchedule, null, 2)}.`);
return Promise.reject(serializationError);
}
httpRequest.body = requestContent;
// Send Request
let operationRes;
try {
operationRes = yield client.pipeline(httpRequest);
let response = operationRes.response;
let statusCode = response.status;
if (statusCode !== 201) {
let error = new msRest.RestError(operationRes.bodyAsText);
error.statusCode = response.status;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
let parsedErrorResponse = operationRes.bodyAsJson;
try {
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error)
internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = Mappers.BatchError;
error.body = client.serializer.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
}
catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${operationRes.bodyAsText}" for the default response.`;
return Promise.reject(error);
}
return Promise.reject(error);
}
}
catch (err) {
return Promise.reject(err);
}
return Promise.resolve(operationRes);
});
}
/**
* @summary Lists all of the job schedules in the specified account.
*
* @param {JobScheduleListOptionalParams} [options] Optional Parameters.
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options) {
return __awaiter(this, void 0, void 0, function* () {
let client = this.client;
let jobScheduleListOptions = (options && options.jobScheduleListOptions !== undefined) ? options.jobScheduleListOptions : undefined;
// Validate
try {
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
}
catch (error) {
return Promise.reject(error);
}
let filter;
let select;
let expand;
let maxResults;
let timeout;
let clientRequestId;
let returnClientRequestId;
let ocpDate;
try {
if (jobScheduleListOptions !== null && jobScheduleListOptions !== undefined) {
filter = jobScheduleListOptions.filter;
if (filter !== null && filter !== undefined && typeof filter.valueOf() !== 'string') {
throw new Error('filter must be of type string.');
}
}
if (jobScheduleListOptions !== null && jobScheduleListOptions !== undefined) {
select = jobScheduleListOptions.select;
if (select !== null && select !== undefined && typeof select.valueOf() !== 'string') {
throw new Error('select must be of type string.');
}
}
if (jobScheduleListOptions !== null && jobScheduleListOptions !== undefined) {
expand = jobScheduleListOptions.expand;
if (expand !== null && expand !== undefined && typeof expand.valueOf() !== 'string') {
throw new Error('expand must be of type string.');
}
}
if (jobScheduleListOptions !== null && jobScheduleListOptions !== undefined) {
maxResults = jobScheduleListOptions.maxResults;
if (maxResults !== null && maxResults !== undefined && typeof maxResults !== 'number') {
throw new Error('maxResults must be of type number.');
}
}
if (jobScheduleListOptions !== null && jobScheduleListOptions !== undefined) {
timeout = jobScheduleListOptions.timeout;
if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') {
throw new Error('timeout must be of type number.');
}
}
if (jobScheduleListOptions !== null && jobScheduleListOptions !== undefined) {
clientRequestId = jobScheduleListOptions.clientRequestId;
if (clientRequestId !== null && clientRequestId !== undefined && !(typeof clientRequestId.valueOf() === 'string' && msRest.isValidUuid(clientRequestId))) {
throw new Error('clientRequestId must be of type string and must be a valid string.');
}
}
if (jobScheduleListOptions !== null && jobScheduleListOptions !== undefined) {
returnClientRequestId = jobScheduleListOptions.returnClientRequestId;
if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
throw new Error('returnClientRequestId must be of type boolean.');
}
}
if (jobScheduleListOptions !== null && jobScheduleListOptions !== undefined) {
ocpDate = jobScheduleListOptions.ocpDate;
if (ocpDate && !(ocpDate instanceof Date ||
(typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
throw new Error('ocpDate must be of type date.');
}
}
}
catch (error) {
return Promise.reject(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'jobschedules';
let queryParamsArray = [];
queryParamsArray.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (filter !== null && filter !== undefined) {
queryParamsArray.push('$filter=' + encodeURIComponent(filter));
}
if (select !== null && select !== undefined) {
queryParamsArray.push('$select=' + encodeURIComponent(select));
}
if (expand !== null && expand !== undefined) {
queryParamsArray.push('$expand=' + encodeURIComponent(expand));
}
if (maxResults !== null && maxResults !== undefined) {
queryParamsArray.push('maxresults=' + encodeURIComponent(maxResults.toString()));
}
if (timeout !== null && timeout !== undefined) {
queryParamsArray.push('timeout=' + encodeURIComponent(timeout.toString()));
}
if (queryParamsArray.length > 0) {
requestUrl += '?' + queryParamsArray.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['client-request-id'] = msRest.generateUuid();
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if (clientRequestId !== undefined && clientRequestId !== null) {
httpRequest.headers['client-request-id'] = clientRequestId.toString();
}
if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
}
if (ocpDate !== undefined && ocpDate !== null) {
httpRequest.headers['ocp-date'] = ocpDate instanceof Date ? ocpDate.toUTCString() : ocpDate;
}
if (options && options.customHeaders) {
for (let headerName in options.customHeaders) {
if (options.customHeaders.hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options.customHeaders[headerName];
}
}
}
// Send Request
let operationRes;
try {
operationRes = yield client.pipeline(httpRequest);
let response = operationRes.response;
let statusCode = response.status;
if (statusCode !== 200) {
let error = new msRest.RestError(operationRes.bodyAsText);
error.statusCode = response.status;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
let parsedErrorResponse = operationRes.bodyAsJson;
try {
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error)
internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = Mappers.BatchError;
error.body = client.serializer.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
}
catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${operationRes.bodyAsText}" for the default response.`;
return Promise.reject(error);
}
return Promise.reject(error);
}
// Deserialize Response
if (statusCode === 200) {
let parsedResponse = operationRes.bodyAsJson;
try {
if (parsedResponse !== null && parsedResponse !== undefined) {
let resultMapper = Mappers.CloudJobScheduleListResult;
operationRes.bodyAsJson = client.serializer.deserialize(resultMapper, parsedResponse, 'operationRes.bodyAsJson');
}
}
catch (error) {
let deserializationError = new msRest.RestError(`Error ${error} occurred in deserializing the responseBody - ${operationRes.bodyAsText}`);
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return Promise.reject(deserializationError);
}
}
}
catch (err) {
return Promise.reject(err);
}
return Promise.resolve(operationRes);
});
}
/**
* @summary Lists all of the job schedules in the specified account.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {JobScheduleListNextOptionalParams} [options] Optional Parameters.
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink, options) {
return __awaiter(this, void 0, void 0, function* () {
let client = this.client;
let jobScheduleListNextOptions = (options && options.jobScheduleListNextOptions !== undefined) ? options.jobScheduleListNextOptions : undefined;
// Validate
try {
if (nextPageLink === null || nextPageLink === undefined || typeof nextPageLink.valueOf() !== 'string') {
throw new Error('nextPageLink cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
}
catch (error) {
return Promise.reject(error);
}
let clientRequestId;
let returnClientRequestId;
let ocpDate;
try {
if (jobScheduleListNextOptions !== null && jobScheduleListNextOptions !== undefined) {
clientRequestId = jobScheduleListNextOptions.clientRequestId;
if (clientRequestId !== null && clientRequestId !== undefined && !(typeof clientRequestId.valueOf() === 'string' && msRest.isValidUuid(clientRequestId))) {
throw new Error('clientRequestId must be of type string and must be a valid string.');
}
}
if (jobScheduleListNextOptions !== null && jobScheduleListNextOptions !== undefined) {
returnClientRequestId = jobScheduleListNextOptions.returnClientRequestId;
if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') {
throw new Error('returnClientRequestId must be of type boolean.');
}
}
if (jobScheduleListNextOptions !== null && jobScheduleListNextOptions !== undefined) {
ocpDate = jobScheduleListNextOptions.ocpDate;
if (ocpDate && !(ocpDate instanceof Date ||
(typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) {
throw new Error('ocpDate must be of type date.');
}
}
}
catch (error) {
return Promise.reject(error);
}
// Construct URL
let requestUrl = '{nextLink}';
requestUrl = requestUrl.replace('{nextLink}', nextPageLink);
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['client-request-id'] = msRest.generateUuid();
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if (clientRequestId !== undefined && clientRequestId !== null) {
httpRequest.headers['client-request-id'] = clientRequestId.toString();
}
if (returnClientRequestId !== undefined && returnClientRequestId !== null) {
httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString();
}
if (ocpDate !== undefined && ocpDate !== null) {
httpRequest.headers['ocp-date'] = ocpDate instanceof Date ? ocpDate.toUTCString() : ocpDate;
}
if (options && options.customHeaders) {
for (let headerName in options.customHeaders) {
if (options.customHeaders.hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options.customHeaders[headerName];
}
}
}
// Send Request
let operationRes;
try {
operationRes = yield client.pipeline(httpRequest);
let response = operationRes.response;
let statusCode = response.status;
if (statusCode !== 200) {
let error = new msRest.RestError(operationRes.bodyAsText);
error.statusCode = response.status;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
let parsedErrorResponse = operationRes.bodyAsJson;
try {
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error)
internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = Mappers.BatchError;
error.body = client.serializer.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
}
catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${operationRes.bodyAsText}" for the default response.`;
return Promise.reject(error);
}
return Promise.reject(error);
}
// Deserialize Response
if (statusCode === 200) {
let parsedResponse = operationRes.bodyAsJson;
try {
if (parsedResponse !== null && parsedResponse !== undefined) {
let resultMapper = Mappers.CloudJobScheduleListResult;
operationRes.bodyAsJson = client.serializer.deserialize(resultMapper, parsedResponse, 'operationRes.bodyAsJson');
}
}
catch (error) {
let deserializationError = new msRest.RestError(`Error ${error} occurred in deserializing the responseBody - ${operationRes.bodyAsText}`);
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return Promise.reject(deserializationError);
}
}
}
catch (err) {
return Promise.reject(err);
}
return Promise.resolve(operationRes);
});
}
exists(jobScheduleId, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
let cb = callback;
if (!callback) {
return this.existsWithHttpOperationResponse(jobScheduleId, options).then((operationRes) => {
return Promise.resolve(operationRes.bodyAsJson);
}).catch((err) => {
return Promise.reject(err);
});
}
else {
msRest.promiseToCallback(this.existsWithHttpOperationResponse(jobScheduleId, options))((err, data) => {
if (err) {
return cb(err);
}
let result = data.bodyAsJson;
return cb(err, result, data.request, data.response);
});
}
}
deleteMethod(jobScheduleId, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
let cb = callback;
if (!callback) {
return this.deleteMethodWithHttpOperationResponse(jobScheduleId, options).then((operationRes) => {
return Promise.resolve(operationRes.bodyAsJson);
}).catch((err) => {
return Promise.reject(err);
});
}
else {
msRest.promiseToCallback(this.deleteMethodWithHttpOperationResponse(jobScheduleId, options))((err, data) => {
if (err) {
return cb(err);
}
let result = data.bodyAsJson;
return cb(err, result, data.request, data.response);
});
}
}
get(jobScheduleId, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
let cb = callback;
if (!callback) {
return this.getWithHttpOperationResponse(jobScheduleId, options).then((operationRes) => {
return Promise.resolve(operationRes.bodyAsJson);
}).catch((err) => {
return Promise.reject(err);
});
}
else {
msRest.promiseToCallback(this.getWithHttpOperationResponse(jobScheduleId, options))((err, data) => {
if (err) {
return cb(err);
}
let result = data.bodyAsJson;
return cb(err, result, data.request, data.response);
});
}
}
patch(jobScheduleId, jobSchedulePatchParameter, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
let cb = callback;
if (!callback) {
return this.patchWithHttpOperationResponse(jobScheduleId, jobSchedulePatchParameter, options).then((operationRes) => {
return Promise.resolve(operationRes.bodyAsJson);
}).catch((err) => {
return Promise.reject(err);
});
}
else {
msRest.promiseToCallback(this.patchWithHttpOperationResponse(jobScheduleId, jobSchedulePatchParameter, options))((err, data) => {
if (err) {
return cb(err);
}
let result = data.bodyAsJson;
return cb(err, result, data.request, data.response);
});
}
}
update(jobScheduleId, jobScheduleUpdateParameter, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
let cb = callback;
if (!callback) {
return this.updateWithHttpOperationResponse(jobScheduleId, jobScheduleUpdateParameter, options).then((operationRes) => {
return Promise.resolve(operationRes.bodyAsJson);
}).catch((err) => {
return Promise.reject(err);
});
}
else {
msRest.promiseToCallback(this.updateWithHttpOperationResponse(jobScheduleId, jobScheduleUpdateParameter, options))((err, data) => {
if (err) {
return cb(err);
}
let result = data.bodyAsJson;
return cb(err, result, data.request, data.response);
});
}
}
disable(jobScheduleId, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
let cb = callback;
if (!callback) {
return this.disableWithHttpOperationResponse(jobScheduleId, options).then((operationRes) => {
return Promise.resolve(operationRes.bodyAsJson);
}).catch((err) => {
return Promise.reject(err);
});
}
else {
msRest.promiseToCallback(this.disableWithHttpOperationResponse(jobScheduleId, options))((err, data) => {
if (err) {
return cb(err);
}
let result = data.bodyAsJson;
return cb(err, result, data.request, data.response);
});
}
}
enable(jobScheduleId, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
let cb = callback;
if (!callback) {
return this.enableWithHttpOperationResponse(jobScheduleId, options).then((operationRes) => {
return Promise.resolve(operationRes.bodyAsJson);
}).catch((err) => {
return Promise.reject(err);
});
}
else {
msRest.promiseToCallback(this.enableWithHttpOperationResponse(jobScheduleId, options))((err, data) => {
if (err) {
return cb(err);
}
let result = data.bodyAsJson;
return cb(err, result, data.request, data.response);
});
}
}
terminate(jobScheduleId, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
let cb = callback;
if (!callback) {
return this.terminateWithHttpOperationResponse(jobScheduleId, options).then((operationRes) => {
return Promise.resolve(operationRes.bodyAsJson);
}).catch((err) => {
return Promise.reject(err);
});
}
else {
msRest.promiseToCallback(this.terminateWithHttpOperationResponse(jobScheduleId, options))((err, data) => {
if (err) {
return cb(err);
}
let result = data.bodyAsJson;
return cb(err, result, data.request, data.response);
});
}
}
add(cloudJobSchedule, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
let cb = callback;
if (!callback) {
return this.addWithHttpOperationResponse(cloudJobSchedule, options).then((operationRes) => {
return Promise.resolve(operationRes.bodyAsJson);
}).catch((err) => {
return Promise.reject(err);
});
}
else {
msRest.promiseToCallback(this.addWithHttpOperationResponse(cloudJobSchedule, options))((err, data) => {
if (err) {
return cb(err);
}
let result = data.bodyAsJson;
return cb(err, result, data.request, data.response);
});
}
}
list(options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
let cb = callback;
if (!callback) {
return this.listWithHttpOperationResponse(options).then((operationRes) => {
return Promise.resolve(operationRes.bodyAsJson);
}).catch((err) => {
return Promise.reject(err);
});
}
else {
msRest.promiseToCallback(this.listWithHttpOperationResponse(options))((err, data) => {
if (err) {
return cb(err);
}
let result = data.bodyAsJson;
return cb(err, result, data.request, data.response);
});
}
}
listNext(nextPageLink, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
let cb = callback;
if (!callback) {
return this.listNextWithHttpOperationResponse(nextPageLink, options).then((operationRes) => {
return Promise.resolve(operationRes.bodyAsJson);
}).catch((err) => {
return Promise.reject(err);
});
}
else {
msRest.promiseToCallback(this.listNextWithHttpOperationResponse(nextPageLink, options))((err, data) => {
if (err) {
return cb(err);
}
let result = data.bodyAsJson;
return cb(err, result, data.request, data.response);
});
}
}
} |
JavaScript | class TopCategory extends Component {
render() {
return (
<div>
This is a top category box
</div>
);
}
} |
JavaScript | class Login extends Component {
constructor(props) {
super(props);
this.state = {
userText: '',
loggingIn: false,
};
}
/**
* Log in as a user.
*/
handleLogin() {
const { userText } = this.state;
const { cookies } = this.props;
cookies.set('userID', userText);
this.setState({ userText: '' }, () => {
axios
.post(`/api/login`, {
userID: userText,
})
.then((res) => {
console.log('Login registered on server');
this.setState({ loggingIn: true });
});
});
}
/**
* Log out current user.
*/
handleLogout() {
const { cookies } = this.props;
cookies.set('userID', '');
this.setState({ userText: '' });
}
render() {
const { userID, classes, clientPermissions } = this.props;
const { userText, loggingIn } = this.state;
return (
<>
{loggingIn && <Redirect to="/profile" />}
<Header selectedPage={userID ? 'Logout' : 'Login'} userID={userID} clientPermissions={clientPermissions}/>
<PageBody>
<Typography variant="h5" align="center">
WARNING: THIS IS A TEMPORARY LOGIN PAGE. PLEASE IMPLEMENT SECURE
USER MANAGEMENT SYSTEM.
</Typography>
{userID ? (
<>
<Card>
<Toolbar className={classes.loginToolbar}>
<Grid container justify="space-between" alignItems="center">
<Typography>Currently logged in as {userID}.</Typography>
<Button
variant="contained"
color="primary"
onClick={() => {
this.handleLogout();
}}
>
Logout
</Button>
</Grid>
</Toolbar>
</Card>
</>
) : (
<>
<Card>
<Toolbar className={classes.loginToolbar}>
<Grid container justify="space-between" alignItems="center">
<TextField
label="Username"
variant="outlined"
value={userText}
className={classes.loginField}
onChange={(event) => {
this.setState({ userText: event.target.value });
}}
/>
<Button
variant="contained"
color="primary"
onClick={() => {
this.handleLogin();
}}
>
Login
</Button>
</Grid>
</Toolbar>
</Card>
</>
)}
</PageBody>
</>
);
}
} |
JavaScript | class Api1RqlJobsRequest {
/**
* Constructs a new <code>Api1RqlJobsRequest</code>.
* @alias module:model/Api1RqlJobsRequest
* @param queryString {String} The RQL query to run
*/
constructor(queryString) {
Api1RqlJobsRequest.initialize(this, queryString);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj, queryString) {
obj['query_string'] = queryString;
}
/**
* Constructs a <code>Api1RqlJobsRequest</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/Api1RqlJobsRequest} obj Optional instance to populate.
* @return {module:model/Api1RqlJobsRequest} The populated <code>Api1RqlJobsRequest</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new Api1RqlJobsRequest();
if (data.hasOwnProperty('query_string')) {
obj['query_string'] = ApiClient.convertToType(data['query_string'], 'String');
}
if (data.hasOwnProperty('force_refresh')) {
obj['force_refresh'] = ApiClient.convertToType(data['force_refresh'], 'Boolean');
}
}
return obj;
}
} |
JavaScript | class BorderLinePolyLayer {
/**
* Create a new layer showing polygon outlines
*
* @param map a MapBox GL instance
* @param uniqueId a unique identifier for the MapBox layer
* @param color the color as a rgba/rgb/#xxx etc value.
* defaults to black
* @param lineWidth the line width as a float. sometimes useful to have
* this as 0.5 for very packed schemas such as postcodes.
* defaults to 1.0
* @param mapBoxSourceId a MapBoxSource ID, either for cases or underlays
* @param addBeforeLayer
*/
constructor(map, uniqueId, color, lineWidth, mapBoxSourceId, addBeforeLayer) {
this.map = map.map || map;
this.uniqueId = uniqueId;
this.color = color;
this.lineWidth = lineWidth;
this.mapBoxSourceId = mapBoxSourceId;
this.addBeforeLayer = addBeforeLayer;
this.__addLayer();
}
__addLayer() {
// Add the line outline
const map = this.map;
map.addLayer({
id: this.uniqueId,
type: 'line',
source: this.mapBoxSourceId,
paint: {
'line-color': this.color || '#000',
'line-opacity': 1,
'line-width': this.lineWidth || 0.5
}
}, this.addBeforeLayer);
this.__shown = true;
}
/*******************************************************************
* Line poly
*******************************************************************/
/**
* Hide the polygon outlines
*/
removeLayer() {
if (this.__shown) {
const map = this.map;
map.removeLayer(this.uniqueId);
this.__shown = false;
}
}
} |
JavaScript | class RDF {
constructor(mData) {
this.mData = mData;
this.graphStore = rdflib.graph();
this.id = undefined;
this.vocabs = {
LDP: this.namespace('http://www.w3.org/ns/ldp#'),
RDF: this.namespace('http://www.w3.org/2000/01/this-schema#'),
RDFS: this.namespace('http://www.w3.org/1999/02/22-this-syntax-ns#'),
FOAF: this.namespace('http://xmlns.com/foaf/0.1/'),
OWL: this.namespace('http://www.w3.org/2002/07/owl#'),
DCTERMS: this.namespace('http://purl.org/dc/terms/'),
SAFETERMS: this.namespace('http://safenetwork.org/safevocab/')
};
}
setId(id) {
this.id = id;
}
/**
* Fetch the RDF data stored in the underlying MutableData on the network
* and load it in memory to allow manipulating triples before commit them again.
*
* @param {Array} ids list of RDF graph IDs to use as a filter for fetching
* graphs, e.g. ['safe://mywebid.mypubname', 'safe://mypubname']
* @param {Boolean} [toDecrypt=false] flag to decrypt the data being fetched
*
* @returns {Promise}
*/
async nowOrWhenFetched(ids, toDecrypt = false) {
let entriesList = [];
let entries;
if (ids && ids.length > 0) {
const graphsToFetch = (!Array.isArray(ids)) ? [ids] : ids;
// TODO: support a list of more than one id
// Promise.all(ids.map(async (e) => {
const serialisedGraph = await this.mData.get(graphsToFetch[0]);
entriesList.push({ key: graphsToFetch[0], value: serialisedGraph });
// }));
} else {
entries = await this.mData.getEntries();
entriesList = await entries.listEntries();
}
if (entriesList.length === 0) return;
let id;
const validGraphs = await entriesList.reduce(async (graphs, entry) => {
const reducedGraphs = await graphs;
let keyStr = entry.key.toString();
let valueStr = entry.value.buf.toString();
if (toDecrypt && valueStr.length > 0) {
try {
const decryptedKey = await this.mData.decrypt(entry.key);
keyStr = decryptedKey.toString();
const decryptedValue = await this.mData.decrypt(entry.value.buf);
valueStr = decryptedValue.toString();
} catch (error) {
if (error.code !== errConst.ERR_SERIALISING_DESERIALISING.code) {
console.warn('Error decrypting MutableData entry in rdf.nowOrWhenFetched()');
}
// ok, let's then assume the entry is not encrypted
// this maybe temporary, just for backward compatibility,
// but in the future we should always expect them to be encrpyted
}
}
// If the entry was soft-deleted skip it, or if it's not
// an RDF graph entry also ignore it
if (valueStr.length === 0 || !keyStr.startsWith('safe://')) {
return reducedGraphs;
}
if (!id) {
// FIXME: we need to know which is the main graph in a deterministic way
// perhaps when we have XOR-URLs we will be able to check a match between
// this MD's location and the @id value which will be set to the XOR-URL.
id = JSON.parse(valueStr)[RDF_GRAPH_ID];
}
reducedGraphs.push(valueStr);
return reducedGraphs;
}, Promise.resolve([]));
const entriesGraphs = await Promise.all(validGraphs);
if (!id) {
// This simply means that none of the existing entries are RDF graphs.
// We throw the error and it's up to the caller to decide
// what to do in such an scenario
throw makeError(errConst.MISSING_RDF_ID.code, errConst.MISSING_RDF_ID.msg);
}
return Promise.all(entriesGraphs.map((graph) => this.parse(graph, JSON_LD_MIME_TYPE, id)));
}
/* eslint-disable class-methods-use-this */
namespace(uri) {
return rdflib.Namespace(uri);
}
literal(value, language, datatype) {
return rdflib.literal(value, language, datatype);
}
list(nodes) {
return rdflib.list(nodes);
}
bnode() {
return rdflib.bnode();
}
sym(uri) {
return rdflib.sym(uri);
}
/* eslint-enable class-methods-use-this */
any(subject, predicate, object) {
return this.graphStore.any(subject, predicate, object);
}
each(subject, predicate, object) {
return this.graphStore.each(subject, predicate, object);
}
statementsMatching(subject, predicate, object) {
return this.graphStore.statementsMatching(subject, predicate, object);
}
removeMany(subject, predicate, object) {
return this.graphStore.removeMany(subject, predicate, object);
}
parse(data, mimeType, id) {
return new Promise((resolve, reject) => {
const cb = (err, parsed) => {
if (err) {
return reject(err);
}
this.setId(id);
resolve(parsed);
};
// since we provide a callback then parse becomes async
rdflib.parse(data, this.graphStore, id, mimeType, cb);
});
}
add(subject, predicate, object) {
this.graphStore.add(subject, predicate, object);
}
async serialise(mimeType) {
return new Promise((resolve, reject) => {
const cb = (err, parsed) => {
if (err) {
return reject(err);
}
resolve(parsed);
};
// TODO: serialise it with compact when it's jsonld. This is
// currently not possible as it's not supporrted by rdflib.js
rdflib.serialize(null, this.graphStore, this.id, mimeType, cb);
});
}
/**
* Commit the RDF document to the underlying MutableData on the network
*
* @param {Boolean} [toEncrypt=false] flag to encrypt the data to be committed
*
* @returns {Promise}
*/
async commit(toEncrypt = false) {
const serialJsonLd = await this.serialise(JSON_LD_MIME_TYPE);
const graphs = JSON.parse(serialJsonLd);
const entries = await this.mData.getEntries();
const entriesList = await entries.listEntries();
const mutation = await this.mData.app.mutableData.newMutation();
const mData = this.mData;
const graphPromises = graphs.map(async (graph) => {
const unencryptedKey = graph[RDF_GRAPH_ID];
let key = unencryptedKey;
let match = false;
// find the current graph in the entries list and remove it
// (before replacing via the rdf graph) this is to be able to remove any
// remaining entries (not readded via rdf) as they have been
// removed from this graph.
await Promise.all(entriesList.map(async (entry, i) => {
if (!entry || !entry.key || match) return;
let keyToCheck = entry.key.toString();
if (toEncrypt) {
try {
const decryptedKey = await mData.decrypt(entry.key);
keyToCheck = decryptedKey.toString();
} catch (error) {
if (error.code !== errConst.ERR_SERIALISING_DESERIALISING.code) {
console.warn('Error decrypting MutableData entry in rdf.commit():', error);
}
// ok, let's then assume the entry is not encrypted
// this maybe temporary, just for backward compatibility,
// but in the future we should always expect them to be encrpyted
}
}
if (unencryptedKey === keyToCheck) {
delete entriesList[i];
match = entry;
}
}));
let stringifiedGraph = JSON.stringify(graph);
if (toEncrypt) {
key = await mData.encryptKey(key);
stringifiedGraph = await mData.encryptValue(stringifiedGraph);
}
if (match) {
return mutation.update(key, stringifiedGraph, match.value.version + 1);
}
return mutation.insert(key, stringifiedGraph);
});
await Promise.all(graphPromises);
// remove RDF entries which are not present in new RDF
await entriesList.forEach(async (entry) => {
if (entry) {
let keyToCheck = entry.key.toString();
if (toEncrypt) {
try {
const decryptedKey = await mData.decrypt(entry.key);
keyToCheck = decryptedKey.toString();
} catch (error) {
if (error.code !== errConst.ERR_SERIALISING_DESERIALISING.code) {
console.warn('Error decrypting MutableData entry in rdf.commit():', error);
}
// ok, let's then assume the entry is not encrypted
// this maybe temporary, just for backward compatibility,
// but in the future we should always expect them to be encrpyted
}
}
if (keyToCheck.startsWith('safe://')) {
await mutation.delete(entry.key, entry.value.version + 1);
}
}
});
await this.mData.applyEntriesMutation(mutation);
const nameAndTag = await this.mData.getNameAndTag();
return nameAndTag;
}
/**
* Append the triples to the RDF document into the underlying MutableData on the network
* @returns {Promise}
*/
async append() {
// TODO: this currently only supports adding graphs with different ID
const serialJsonLd = await this.serialise(JSON_LD_MIME_TYPE);
const graphs = JSON.parse(serialJsonLd);
const mutation = await this.mData.app.mutableData.newMutation();
graphs.forEach((e) => {
const key = e[RDF_GRAPH_ID];
const stringifiedGraph = JSON.stringify(e);
mutation.insert(key, stringifiedGraph);
});
await this.mData.applyEntriesMutation(mutation);
const nameAndTag = await this.mData.getNameAndTag();
return nameAndTag;
}
} |
JavaScript | class Animal {
constructor(name, type) {
this.name = name;
this.type = type;
this.color = color;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.