repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
ILLGrenoble/guacamole-common-js
src/StringWriter.js
__expand
function __expand(bytes) { // Resize buffer if more space needed if (length+bytes >= buffer.length) { var new_buffer = new Uint8Array((length+bytes)*2); new_buffer.set(buffer); buffer = new_buffer; } length += bytes; }
javascript
function __expand(bytes) { // Resize buffer if more space needed if (length+bytes >= buffer.length) { var new_buffer = new Uint8Array((length+bytes)*2); new_buffer.set(buffer); buffer = new_buffer; } length += bytes; }
[ "function", "__expand", "(", "bytes", ")", "{", "if", "(", "length", "+", "bytes", ">=", "buffer", ".", "length", ")", "{", "var", "new_buffer", "=", "new", "Uint8Array", "(", "(", "length", "+", "bytes", ")", "*", "2", ")", ";", "new_buffer", ".", "set", "(", "buffer", ")", ";", "buffer", "=", "new_buffer", ";", "}", "length", "+=", "bytes", ";", "}" ]
Expands the size of the underlying buffer by the given number of bytes, updating the length appropriately. @private @param {Number} bytes The number of bytes to add to the underlying buffer.
[ "Expands", "the", "size", "of", "the", "underlying", "buffer", "by", "the", "given", "number", "of", "bytes", "updating", "the", "length", "appropriately", "." ]
71925794155ea3fc37d2a125adbca6f8be532887
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/StringWriter.js#L71-L82
train
ILLGrenoble/guacamole-common-js
src/StringWriter.js
__append_utf8
function __append_utf8(codepoint) { var mask; var bytes; // 1 byte if (codepoint <= 0x7F) { mask = 0x00; bytes = 1; } // 2 byte else if (codepoint <= 0x7FF) { mask = 0xC0; bytes = 2; } // 3 byte else if (codepoint <= 0xFFFF) { mask = 0xE0; bytes = 3; } // 4 byte else if (codepoint <= 0x1FFFFF) { mask = 0xF0; bytes = 4; } // If invalid codepoint, append replacement character else { __append_utf8(0xFFFD); return; } // Offset buffer by size __expand(bytes); var offset = length - 1; // Add trailing bytes, if any for (var i=1; i<bytes; i++) { buffer[offset--] = 0x80 | (codepoint & 0x3F); codepoint >>= 6; } // Set initial byte buffer[offset] = mask | codepoint; }
javascript
function __append_utf8(codepoint) { var mask; var bytes; // 1 byte if (codepoint <= 0x7F) { mask = 0x00; bytes = 1; } // 2 byte else if (codepoint <= 0x7FF) { mask = 0xC0; bytes = 2; } // 3 byte else if (codepoint <= 0xFFFF) { mask = 0xE0; bytes = 3; } // 4 byte else if (codepoint <= 0x1FFFFF) { mask = 0xF0; bytes = 4; } // If invalid codepoint, append replacement character else { __append_utf8(0xFFFD); return; } // Offset buffer by size __expand(bytes); var offset = length - 1; // Add trailing bytes, if any for (var i=1; i<bytes; i++) { buffer[offset--] = 0x80 | (codepoint & 0x3F); codepoint >>= 6; } // Set initial byte buffer[offset] = mask | codepoint; }
[ "function", "__append_utf8", "(", "codepoint", ")", "{", "var", "mask", ";", "var", "bytes", ";", "if", "(", "codepoint", "<=", "0x7F", ")", "{", "mask", "=", "0x00", ";", "bytes", "=", "1", ";", "}", "else", "if", "(", "codepoint", "<=", "0x7FF", ")", "{", "mask", "=", "0xC0", ";", "bytes", "=", "2", ";", "}", "else", "if", "(", "codepoint", "<=", "0xFFFF", ")", "{", "mask", "=", "0xE0", ";", "bytes", "=", "3", ";", "}", "else", "if", "(", "codepoint", "<=", "0x1FFFFF", ")", "{", "mask", "=", "0xF0", ";", "bytes", "=", "4", ";", "}", "else", "{", "__append_utf8", "(", "0xFFFD", ")", ";", "return", ";", "}", "__expand", "(", "bytes", ")", ";", "var", "offset", "=", "length", "-", "1", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "bytes", ";", "i", "++", ")", "{", "buffer", "[", "offset", "--", "]", "=", "0x80", "|", "(", "codepoint", "&", "0x3F", ")", ";", "codepoint", ">>=", "6", ";", "}", "buffer", "[", "offset", "]", "=", "mask", "|", "codepoint", ";", "}" ]
Appends a single Unicode character to the current buffer, resizing the buffer if necessary. The character will be encoded as UTF-8. @private @param {Number} codepoint The codepoint of the Unicode character to append.
[ "Appends", "a", "single", "Unicode", "character", "to", "the", "current", "buffer", "resizing", "the", "buffer", "if", "necessary", ".", "The", "character", "will", "be", "encoded", "as", "UTF", "-", "8", "." ]
71925794155ea3fc37d2a125adbca6f8be532887
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/StringWriter.js#L92-L140
train
ILLGrenoble/guacamole-common-js
src/StringWriter.js
__encode_utf8
function __encode_utf8(text) { // Fill buffer with UTF-8 for (var i=0; i<text.length; i++) { var codepoint = text.charCodeAt(i); __append_utf8(codepoint); } // Flush buffer if (length > 0) { var out_buffer = buffer.subarray(0, length); length = 0; return out_buffer; } }
javascript
function __encode_utf8(text) { // Fill buffer with UTF-8 for (var i=0; i<text.length; i++) { var codepoint = text.charCodeAt(i); __append_utf8(codepoint); } // Flush buffer if (length > 0) { var out_buffer = buffer.subarray(0, length); length = 0; return out_buffer; } }
[ "function", "__encode_utf8", "(", "text", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "text", ".", "length", ";", "i", "++", ")", "{", "var", "codepoint", "=", "text", ".", "charCodeAt", "(", "i", ")", ";", "__append_utf8", "(", "codepoint", ")", ";", "}", "if", "(", "length", ">", "0", ")", "{", "var", "out_buffer", "=", "buffer", ".", "subarray", "(", "0", ",", "length", ")", ";", "length", "=", "0", ";", "return", "out_buffer", ";", "}", "}" ]
Encodes the given string as UTF-8, returning an ArrayBuffer containing the resulting bytes. @private @param {String} text The string to encode as UTF-8. @return {Uint8Array} The encoded UTF-8 data.
[ "Encodes", "the", "given", "string", "as", "UTF", "-", "8", "returning", "an", "ArrayBuffer", "containing", "the", "resulting", "bytes", "." ]
71925794155ea3fc37d2a125adbca6f8be532887
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/StringWriter.js#L150-L165
train
octet-stream/object-to-form-data
serialize.js
set
function set(prefix, value) { for (const key of keys(value)) { const name = prefix ? `${prefix}[${key}]` : key const field = value[key] if (isArray(field) || isPlainObject(field)) { set(name, field) } else { if (options.strict && (isBoolean(field) && field === false)) { continue } fd[method](name, field) } } }
javascript
function set(prefix, value) { for (const key of keys(value)) { const name = prefix ? `${prefix}[${key}]` : key const field = value[key] if (isArray(field) || isPlainObject(field)) { set(name, field) } else { if (options.strict && (isBoolean(field) && field === false)) { continue } fd[method](name, field) } } }
[ "function", "set", "(", "prefix", ",", "value", ")", "{", "for", "(", "const", "key", "of", "keys", "(", "value", ")", ")", "{", "const", "name", "=", "prefix", "?", "`", "${", "prefix", "}", "${", "key", "}", "`", ":", "key", "const", "field", "=", "value", "[", "key", "]", "if", "(", "isArray", "(", "field", ")", "||", "isPlainObject", "(", "field", ")", ")", "{", "set", "(", "name", ",", "field", ")", "}", "else", "{", "if", "(", "options", ".", "strict", "&&", "(", "isBoolean", "(", "field", ")", "&&", "field", "===", "false", ")", ")", "{", "continue", "}", "fd", "[", "method", "]", "(", "name", ",", "field", ")", "}", "}", "}" ]
Set object fields to FormData instance @param {string} [prefix = undefined] – parent field key @param {any} value – A value of the current field @api private
[ "Set", "object", "fields", "to", "FormData", "instance" ]
a6cbb2accc5df56be1266f8e21c7510c12fc3304
https://github.com/octet-stream/object-to-form-data/blob/a6cbb2accc5df56be1266f8e21c7510c12fc3304/serialize.js#L61-L76
train
ILLGrenoble/guacamole-common-js
src/AudioRecorder.js
getValueAt
function getValueAt(audioData, t) { // Convert [0, 1] range to [0, audioData.length - 1] var index = (audioData.length - 1) * t; // Determine the start and end points for the summation used by the // Lanczos interpolation algorithm (see: https://en.wikipedia.org/wiki/Lanczos_resampling) var start = Math.floor(index) - LANCZOS_WINDOW_SIZE + 1; var end = Math.floor(index) + LANCZOS_WINDOW_SIZE; // Calculate the value of the Lanczos interpolation function for the // required range var sum = 0; for (var i = start; i <= end; i++) { sum += (audioData[i] || 0) * lanczos(index - i, LANCZOS_WINDOW_SIZE); } return sum; }
javascript
function getValueAt(audioData, t) { // Convert [0, 1] range to [0, audioData.length - 1] var index = (audioData.length - 1) * t; // Determine the start and end points for the summation used by the // Lanczos interpolation algorithm (see: https://en.wikipedia.org/wiki/Lanczos_resampling) var start = Math.floor(index) - LANCZOS_WINDOW_SIZE + 1; var end = Math.floor(index) + LANCZOS_WINDOW_SIZE; // Calculate the value of the Lanczos interpolation function for the // required range var sum = 0; for (var i = start; i <= end; i++) { sum += (audioData[i] || 0) * lanczos(index - i, LANCZOS_WINDOW_SIZE); } return sum; }
[ "function", "getValueAt", "(", "audioData", ",", "t", ")", "{", "var", "index", "=", "(", "audioData", ".", "length", "-", "1", ")", "*", "t", ";", "var", "start", "=", "Math", ".", "floor", "(", "index", ")", "-", "LANCZOS_WINDOW_SIZE", "+", "1", ";", "var", "end", "=", "Math", ".", "floor", "(", "index", ")", "+", "LANCZOS_WINDOW_SIZE", ";", "var", "sum", "=", "0", ";", "for", "(", "var", "i", "=", "start", ";", "i", "<=", "end", ";", "i", "++", ")", "{", "sum", "+=", "(", "audioData", "[", "i", "]", "||", "0", ")", "*", "lanczos", "(", "index", "-", "i", ",", "LANCZOS_WINDOW_SIZE", ")", ";", "}", "return", "sum", ";", "}" ]
Determines the value of the waveform represented by the audio data at the given location. If the value cannot be determined exactly as it does not correspond to an exact sample within the audio data, the value will be derived through interpolating nearby samples. @private @param {Float32Array} audioData An array of audio data, as returned by AudioBuffer.getChannelData(). @param {Number} t The relative location within the waveform from which the value should be retrieved, represented as a floating point number between 0 and 1 inclusive, where 0 represents the earliest point in time and 1 represents the latest. @returns {Number} The value of the waveform at the given location.
[ "Determines", "the", "value", "of", "the", "waveform", "represented", "by", "the", "audio", "data", "at", "the", "given", "location", ".", "If", "the", "value", "cannot", "be", "determined", "exactly", "as", "it", "does", "not", "correspond", "to", "an", "exact", "sample", "within", "the", "audio", "data", "the", "value", "will", "be", "derived", "through", "interpolating", "nearby", "samples", "." ]
71925794155ea3fc37d2a125adbca6f8be532887
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/AudioRecorder.js#L342-L361
train
ILLGrenoble/guacamole-common-js
src/AudioRecorder.js
toSampleArray
function toSampleArray(audioBuffer) { // Track overall amount of data read var inSamples = audioBuffer.length; readSamples += inSamples; // Calculate the total number of samples that should be written as of // the audio data just received and adjust the size of the output // packet accordingly var expectedWrittenSamples = Math.round(readSamples * format.rate / audioBuffer.sampleRate); var outSamples = expectedWrittenSamples - writtenSamples; // Update number of samples written writtenSamples += outSamples; // Get array for raw PCM storage var data = new SampleArray(outSamples * format.channels); // Convert each channel for (var channel = 0; channel < format.channels; channel++) { var audioData = audioBuffer.getChannelData(channel); // Fill array with data from audio buffer channel var offset = channel; for (var i = 0; i < outSamples; i++) { data[offset] = interpolateSample(audioData, i / (outSamples - 1)) * maxSampleValue; offset += format.channels; } } return data; }
javascript
function toSampleArray(audioBuffer) { // Track overall amount of data read var inSamples = audioBuffer.length; readSamples += inSamples; // Calculate the total number of samples that should be written as of // the audio data just received and adjust the size of the output // packet accordingly var expectedWrittenSamples = Math.round(readSamples * format.rate / audioBuffer.sampleRate); var outSamples = expectedWrittenSamples - writtenSamples; // Update number of samples written writtenSamples += outSamples; // Get array for raw PCM storage var data = new SampleArray(outSamples * format.channels); // Convert each channel for (var channel = 0; channel < format.channels; channel++) { var audioData = audioBuffer.getChannelData(channel); // Fill array with data from audio buffer channel var offset = channel; for (var i = 0; i < outSamples; i++) { data[offset] = interpolateSample(audioData, i / (outSamples - 1)) * maxSampleValue; offset += format.channels; } } return data; }
[ "function", "toSampleArray", "(", "audioBuffer", ")", "{", "var", "inSamples", "=", "audioBuffer", ".", "length", ";", "readSamples", "+=", "inSamples", ";", "var", "expectedWrittenSamples", "=", "Math", ".", "round", "(", "readSamples", "*", "format", ".", "rate", "/", "audioBuffer", ".", "sampleRate", ")", ";", "var", "outSamples", "=", "expectedWrittenSamples", "-", "writtenSamples", ";", "writtenSamples", "+=", "outSamples", ";", "var", "data", "=", "new", "SampleArray", "(", "outSamples", "*", "format", ".", "channels", ")", ";", "for", "(", "var", "channel", "=", "0", ";", "channel", "<", "format", ".", "channels", ";", "channel", "++", ")", "{", "var", "audioData", "=", "audioBuffer", ".", "getChannelData", "(", "channel", ")", ";", "var", "offset", "=", "channel", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "outSamples", ";", "i", "++", ")", "{", "data", "[", "offset", "]", "=", "interpolateSample", "(", "audioData", ",", "i", "/", "(", "outSamples", "-", "1", ")", ")", "*", "maxSampleValue", ";", "offset", "+=", "format", ".", "channels", ";", "}", "}", "return", "data", ";", "}" ]
Converts the given AudioBuffer into an audio packet, ready for streaming along the underlying output stream. Unlike the raw audio packets used by this audio recorder, AudioBuffers require floating point samples and are split into isolated planes of channel-specific data. @private @param {AudioBuffer} audioBuffer The Web Audio API AudioBuffer that should be converted to a raw audio packet. @returns {SampleArray} A new raw audio packet containing the audio data from the provided AudioBuffer.
[ "Converts", "the", "given", "AudioBuffer", "into", "an", "audio", "packet", "ready", "for", "streaming", "along", "the", "underlying", "output", "stream", ".", "Unlike", "the", "raw", "audio", "packets", "used", "by", "this", "audio", "recorder", "AudioBuffers", "require", "floating", "point", "samples", "and", "are", "split", "into", "isolated", "planes", "of", "channel", "-", "specific", "data", "." ]
71925794155ea3fc37d2a125adbca6f8be532887
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/AudioRecorder.js#L378-L412
train
ILLGrenoble/guacamole-common-js
src/AudioRecorder.js
beginAudioCapture
function beginAudioCapture() { // Attempt to retrieve an audio input stream from the browser navigator.mediaDevices.getUserMedia({ 'audio' : true }, function streamReceived(stream) { // Create processing node which receives appropriately-sized audio buffers processor = context.createScriptProcessor(BUFFER_SIZE, format.channels, format.channels); processor.connect(context.destination); // Send blobs when audio buffers are received processor.onaudioprocess = function processAudio(e) { writer.sendData(toSampleArray(e.inputBuffer).buffer); }; // Connect processing node to user's audio input source source = context.createMediaStreamSource(stream); source.connect(processor); // Save stream for later cleanup mediaStream = stream; }, function streamDenied() { // Simply end stream if audio access is not allowed writer.sendEnd(); // Notify of closure if (recorder.onerror) recorder.onerror(); }); }
javascript
function beginAudioCapture() { // Attempt to retrieve an audio input stream from the browser navigator.mediaDevices.getUserMedia({ 'audio' : true }, function streamReceived(stream) { // Create processing node which receives appropriately-sized audio buffers processor = context.createScriptProcessor(BUFFER_SIZE, format.channels, format.channels); processor.connect(context.destination); // Send blobs when audio buffers are received processor.onaudioprocess = function processAudio(e) { writer.sendData(toSampleArray(e.inputBuffer).buffer); }; // Connect processing node to user's audio input source source = context.createMediaStreamSource(stream); source.connect(processor); // Save stream for later cleanup mediaStream = stream; }, function streamDenied() { // Simply end stream if audio access is not allowed writer.sendEnd(); // Notify of closure if (recorder.onerror) recorder.onerror(); }); }
[ "function", "beginAudioCapture", "(", ")", "{", "navigator", ".", "mediaDevices", ".", "getUserMedia", "(", "{", "'audio'", ":", "true", "}", ",", "function", "streamReceived", "(", "stream", ")", "{", "processor", "=", "context", ".", "createScriptProcessor", "(", "BUFFER_SIZE", ",", "format", ".", "channels", ",", "format", ".", "channels", ")", ";", "processor", ".", "connect", "(", "context", ".", "destination", ")", ";", "processor", ".", "onaudioprocess", "=", "function", "processAudio", "(", "e", ")", "{", "writer", ".", "sendData", "(", "toSampleArray", "(", "e", ".", "inputBuffer", ")", ".", "buffer", ")", ";", "}", ";", "source", "=", "context", ".", "createMediaStreamSource", "(", "stream", ")", ";", "source", ".", "connect", "(", "processor", ")", ";", "mediaStream", "=", "stream", ";", "}", ",", "function", "streamDenied", "(", ")", "{", "writer", ".", "sendEnd", "(", ")", ";", "if", "(", "recorder", ".", "onerror", ")", "recorder", ".", "onerror", "(", ")", ";", "}", ")", ";", "}" ]
Requests access to the user's microphone and begins capturing audio. All received audio data is resampled as necessary and forwarded to the Guacamole stream underlying this Guacamole.RawAudioRecorder. This function must be invoked ONLY ONCE per instance of Guacamole.RawAudioRecorder. @private
[ "Requests", "access", "to", "the", "user", "s", "microphone", "and", "begins", "capturing", "audio", ".", "All", "received", "audio", "data", "is", "resampled", "as", "necessary", "and", "forwarded", "to", "the", "Guacamole", "stream", "underlying", "this", "Guacamole", ".", "RawAudioRecorder", ".", "This", "function", "must", "be", "invoked", "ONLY", "ONCE", "per", "instance", "of", "Guacamole", ".", "RawAudioRecorder", "." ]
71925794155ea3fc37d2a125adbca6f8be532887
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/AudioRecorder.js#L423-L455
train
ILLGrenoble/guacamole-common-js
src/AudioRecorder.js
stopAudioCapture
function stopAudioCapture() { // Disconnect media source node from script processor if (source) source.disconnect(); // Disconnect associated script processor node if (processor) processor.disconnect(); // Stop capture if (mediaStream) { var tracks = mediaStream.getTracks(); for (var i = 0; i < tracks.length; i++) tracks[i].stop(); } // Remove references to now-unneeded components processor = null; source = null; mediaStream = null; // End stream writer.sendEnd(); }
javascript
function stopAudioCapture() { // Disconnect media source node from script processor if (source) source.disconnect(); // Disconnect associated script processor node if (processor) processor.disconnect(); // Stop capture if (mediaStream) { var tracks = mediaStream.getTracks(); for (var i = 0; i < tracks.length; i++) tracks[i].stop(); } // Remove references to now-unneeded components processor = null; source = null; mediaStream = null; // End stream writer.sendEnd(); }
[ "function", "stopAudioCapture", "(", ")", "{", "if", "(", "source", ")", "source", ".", "disconnect", "(", ")", ";", "if", "(", "processor", ")", "processor", ".", "disconnect", "(", ")", ";", "if", "(", "mediaStream", ")", "{", "var", "tracks", "=", "mediaStream", ".", "getTracks", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "tracks", ".", "length", ";", "i", "++", ")", "tracks", "[", "i", "]", ".", "stop", "(", ")", ";", "}", "processor", "=", "null", ";", "source", "=", "null", ";", "mediaStream", "=", "null", ";", "writer", ".", "sendEnd", "(", ")", ";", "}" ]
Stops capturing audio, if the capture has started, freeing all associated resources. If the capture has not started, this function simply ends the underlying Guacamole stream. @private
[ "Stops", "capturing", "audio", "if", "the", "capture", "has", "started", "freeing", "all", "associated", "resources", ".", "If", "the", "capture", "has", "not", "started", "this", "function", "simply", "ends", "the", "underlying", "Guacamole", "stream", "." ]
71925794155ea3fc37d2a125adbca6f8be532887
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/src/AudioRecorder.js#L464-L489
train
ILLGrenoble/guacamole-common-js
guacamole.js
__decode_utf8
function __decode_utf8(buffer) { var text = ""; var bytes = new Uint8Array(buffer); for (var i=0; i<bytes.length; i++) { // Get current byte var value = bytes[i]; // Start new codepoint if nothing yet read if (bytes_remaining === 0) { // 1 byte (0xxxxxxx) if ((value | 0x7F) === 0x7F) text += String.fromCharCode(value); // 2 byte (110xxxxx) else if ((value | 0x1F) === 0xDF) { codepoint = value & 0x1F; bytes_remaining = 1; } // 3 byte (1110xxxx) else if ((value | 0x0F )=== 0xEF) { codepoint = value & 0x0F; bytes_remaining = 2; } // 4 byte (11110xxx) else if ((value | 0x07) === 0xF7) { codepoint = value & 0x07; bytes_remaining = 3; } // Invalid byte else text += "\uFFFD"; } // Continue existing codepoint (10xxxxxx) else if ((value | 0x3F) === 0xBF) { codepoint = (codepoint << 6) | (value & 0x3F); bytes_remaining--; // Write codepoint if finished if (bytes_remaining === 0) text += String.fromCharCode(codepoint); } // Invalid byte else { bytes_remaining = 0; text += "\uFFFD"; } } return text; }
javascript
function __decode_utf8(buffer) { var text = ""; var bytes = new Uint8Array(buffer); for (var i=0; i<bytes.length; i++) { // Get current byte var value = bytes[i]; // Start new codepoint if nothing yet read if (bytes_remaining === 0) { // 1 byte (0xxxxxxx) if ((value | 0x7F) === 0x7F) text += String.fromCharCode(value); // 2 byte (110xxxxx) else if ((value | 0x1F) === 0xDF) { codepoint = value & 0x1F; bytes_remaining = 1; } // 3 byte (1110xxxx) else if ((value | 0x0F )=== 0xEF) { codepoint = value & 0x0F; bytes_remaining = 2; } // 4 byte (11110xxx) else if ((value | 0x07) === 0xF7) { codepoint = value & 0x07; bytes_remaining = 3; } // Invalid byte else text += "\uFFFD"; } // Continue existing codepoint (10xxxxxx) else if ((value | 0x3F) === 0xBF) { codepoint = (codepoint << 6) | (value & 0x3F); bytes_remaining--; // Write codepoint if finished if (bytes_remaining === 0) text += String.fromCharCode(codepoint); } // Invalid byte else { bytes_remaining = 0; text += "\uFFFD"; } } return text; }
[ "function", "__decode_utf8", "(", "buffer", ")", "{", "var", "text", "=", "\"\"", ";", "var", "bytes", "=", "new", "Uint8Array", "(", "buffer", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "bytes", ".", "length", ";", "i", "++", ")", "{", "var", "value", "=", "bytes", "[", "i", "]", ";", "if", "(", "bytes_remaining", "===", "0", ")", "{", "if", "(", "(", "value", "|", "0x7F", ")", "===", "0x7F", ")", "text", "+=", "String", ".", "fromCharCode", "(", "value", ")", ";", "else", "if", "(", "(", "value", "|", "0x1F", ")", "===", "0xDF", ")", "{", "codepoint", "=", "value", "&", "0x1F", ";", "bytes_remaining", "=", "1", ";", "}", "else", "if", "(", "(", "value", "|", "0x0F", ")", "===", "0xEF", ")", "{", "codepoint", "=", "value", "&", "0x0F", ";", "bytes_remaining", "=", "2", ";", "}", "else", "if", "(", "(", "value", "|", "0x07", ")", "===", "0xF7", ")", "{", "codepoint", "=", "value", "&", "0x07", ";", "bytes_remaining", "=", "3", ";", "}", "else", "text", "+=", "\"\\uFFFD\"", ";", "}", "else", "\\uFFFD", "}", "if", "(", "(", "value", "|", "0x3F", ")", "===", "0xBF", ")", "{", "codepoint", "=", "(", "codepoint", "<<", "6", ")", "|", "(", "value", "&", "0x3F", ")", ";", "bytes_remaining", "--", ";", "if", "(", "bytes_remaining", "===", "0", ")", "text", "+=", "String", ".", "fromCharCode", "(", "codepoint", ")", ";", "}", "else", "{", "bytes_remaining", "=", "0", ";", "text", "+=", "\"\\uFFFD\"", ";", "}", "}" ]
Decodes the given UTF-8 data into a Unicode string. The data may end in the middle of a multibyte character. @private @param {ArrayBuffer} buffer Arbitrary UTF-8 data. @return {String} A decoded Unicode string.
[ "Decodes", "the", "given", "UTF", "-", "8", "data", "into", "a", "Unicode", "string", ".", "The", "data", "may", "end", "in", "the", "middle", "of", "a", "multibyte", "character", "." ]
71925794155ea3fc37d2a125adbca6f8be532887
https://github.com/ILLGrenoble/guacamole-common-js/blob/71925794155ea3fc37d2a125adbca6f8be532887/guacamole.js#L10731-L10794
train
egislook/fucss
fucss.js
extractMediaQuery
function extractMediaQuery(props){ var mediaValue = props.length && props[0]; if(Object.keys(fucss.media).indexOf(mediaValue) !== -1){ return props.shift(); } }
javascript
function extractMediaQuery(props){ var mediaValue = props.length && props[0]; if(Object.keys(fucss.media).indexOf(mediaValue) !== -1){ return props.shift(); } }
[ "function", "extractMediaQuery", "(", "props", ")", "{", "var", "mediaValue", "=", "props", ".", "length", "&&", "props", "[", "0", "]", ";", "if", "(", "Object", ".", "keys", "(", "fucss", ".", "media", ")", ".", "indexOf", "(", "mediaValue", ")", "!==", "-", "1", ")", "{", "return", "props", ".", "shift", "(", ")", ";", "}", "}" ]
from class to css rule
[ "from", "class", "to", "css", "rule" ]
e0dd7941092ee3f2da44704027c233149ed4e9f1
https://github.com/egislook/fucss/blob/e0dd7941092ee3f2da44704027c233149ed4e9f1/fucss.js#L722-L727
train
aMarCruz/jspreproc
lib/ccparser.js
include
function include(ckey, file) { var match = file.match(INCNAME) file = match && match[1] if (file) { var ch = file[0] if ((ch === '"' || ch === "'") && ch === file.slice(-1)) file = file.slice(1, -1).trim() } if (file) { result.insert = file result.once = !!ckey[8] } else emitError('Expected filename for #' + ckey + ' in @') }
javascript
function include(ckey, file) { var match = file.match(INCNAME) file = match && match[1] if (file) { var ch = file[0] if ((ch === '"' || ch === "'") && ch === file.slice(-1)) file = file.slice(1, -1).trim() } if (file) { result.insert = file result.once = !!ckey[8] } else emitError('Expected filename for #' + ckey + ' in @') }
[ "function", "include", "(", "ckey", ",", "file", ")", "{", "var", "match", "=", "file", ".", "match", "(", "INCNAME", ")", "file", "=", "match", "&&", "match", "[", "1", "]", "if", "(", "file", ")", "{", "var", "ch", "=", "file", "[", "0", "]", "if", "(", "(", "ch", "===", "'\"'", "||", "ch", "===", "\"'\"", ")", "&&", "ch", "===", "file", ".", "slice", "(", "-", "1", ")", ")", "file", "=", "file", ".", "slice", "(", "1", ",", "-", "1", ")", ".", "trim", "(", ")", "}", "if", "(", "file", ")", "{", "result", ".", "insert", "=", "file", "result", ".", "once", "=", "!", "!", "ckey", "[", "8", "]", "}", "else", "emitError", "(", "'Expected filename for #'", "+", "ckey", "+", "' in @'", ")", "}" ]
Prepares `cc` for file insertion setting the `insert` and `once` properties of `cc`. Accepts quoted or unquoted filenames
[ "Prepares", "cc", "for", "file", "insertion", "setting", "the", "insert", "and", "once", "properties", "of", "cc", ".", "Accepts", "quoted", "or", "unquoted", "filenames" ]
5f31820d702a329e8aa25f0f3983f13097610250
https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/lib/ccparser.js#L53-L69
train
aMarCruz/jspreproc
lib/ccparser.js
normalize
function normalize(key, expr) { if (key.slice(0, 4) !== 'incl') { expr = expr.replace(/[/\*]\/.*/, '').trim() // all keywords must have an expression, except `#else/#endif` if (!expr && key !== 'else' && key !== 'endif') { emitError('Expected expression for #' + key + ' in @') return false } } return expr }
javascript
function normalize(key, expr) { if (key.slice(0, 4) !== 'incl') { expr = expr.replace(/[/\*]\/.*/, '').trim() // all keywords must have an expression, except `#else/#endif` if (!expr && key !== 'else' && key !== 'endif') { emitError('Expected expression for #' + key + ' in @') return false } } return expr }
[ "function", "normalize", "(", "key", ",", "expr", ")", "{", "if", "(", "key", ".", "slice", "(", "0", ",", "4", ")", "!==", "'incl'", ")", "{", "expr", "=", "expr", ".", "replace", "(", "/", "[/\\*]\\/.*", "/", ",", "''", ")", ".", "trim", "(", ")", "if", "(", "!", "expr", "&&", "key", "!==", "'else'", "&&", "key", "!==", "'endif'", ")", "{", "emitError", "(", "'Expected expression for #'", "+", "key", "+", "' in @'", ")", "return", "false", "}", "}", "return", "expr", "}" ]
Removes any one-line comment and checks if expression is present
[ "Removes", "any", "one", "-", "line", "comment", "and", "checks", "if", "expression", "is", "present" ]
5f31820d702a329e8aa25f0f3983f13097610250
https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/lib/ccparser.js#L72-L84
train
aMarCruz/jspreproc
lib/ccparser.js
checkInBlock
function checkInBlock(mask) { var block = cc.block[last] if (block && block === (block & mask)) return true emitError('Unexpected #' + key + ' in @') return false }
javascript
function checkInBlock(mask) { var block = cc.block[last] if (block && block === (block & mask)) return true emitError('Unexpected #' + key + ' in @') return false }
[ "function", "checkInBlock", "(", "mask", ")", "{", "var", "block", "=", "cc", ".", "block", "[", "last", "]", "if", "(", "block", "&&", "block", "===", "(", "block", "&", "mask", ")", ")", "return", "true", "emitError", "(", "'Unexpected #'", "+", "key", "+", "' in @'", ")", "return", "false", "}" ]
Inner helper - throws if the current block is not of the expected type
[ "Inner", "helper", "-", "throws", "if", "the", "current", "block", "is", "not", "of", "the", "expected", "type" ]
5f31820d702a329e8aa25f0f3983f13097610250
https://github.com/aMarCruz/jspreproc/blob/5f31820d702a329e8aa25f0f3983f13097610250/lib/ccparser.js#L170-L176
train
ascartabelli/lamb
src/privates/_repeat.js
_repeat
function _repeat (source, times) { var result = ""; for (var i = 0; i < times; i++) { result += source; } return result; }
javascript
function _repeat (source, times) { var result = ""; for (var i = 0; i < times; i++) { result += source; } return result; }
[ "function", "_repeat", "(", "source", ",", "times", ")", "{", "var", "result", "=", "\"\"", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "times", ";", "i", "++", ")", "{", "result", "+=", "source", ";", "}", "return", "result", ";", "}" ]
A null-safe function to repeat the source string the desired amount of times. @private @param {String} source @param {Number} times @returns {String}
[ "A", "null", "-", "safe", "function", "to", "repeat", "the", "source", "string", "the", "desired", "amount", "of", "times", "." ]
d36e45945c4789e4f1a2d8805936514b53f32362
https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_repeat.js#L8-L16
train
buttercup/credentials
source/Credentials.js
unsignEncryptedContent
function unsignEncryptedContent(content) { const newIndex = content.indexOf(SIGNING_KEY); const oldIndex = content.indexOf(SIGNING_KEY_OLD); if (newIndex === -1 && oldIndex === -1) { throw new Error("Invalid credentials content (unknown signature)"); } return newIndex >= 0 ? content.substr(SIGNING_KEY.length) : content.substr(SIGNING_KEY_OLD.length); }
javascript
function unsignEncryptedContent(content) { const newIndex = content.indexOf(SIGNING_KEY); const oldIndex = content.indexOf(SIGNING_KEY_OLD); if (newIndex === -1 && oldIndex === -1) { throw new Error("Invalid credentials content (unknown signature)"); } return newIndex >= 0 ? content.substr(SIGNING_KEY.length) : content.substr(SIGNING_KEY_OLD.length); }
[ "function", "unsignEncryptedContent", "(", "content", ")", "{", "const", "newIndex", "=", "content", ".", "indexOf", "(", "SIGNING_KEY", ")", ";", "const", "oldIndex", "=", "content", ".", "indexOf", "(", "SIGNING_KEY_OLD", ")", ";", "if", "(", "newIndex", "===", "-", "1", "&&", "oldIndex", "===", "-", "1", ")", "{", "throw", "new", "Error", "(", "\"Invalid credentials content (unknown signature)\"", ")", ";", "}", "return", "newIndex", ">=", "0", "?", "content", ".", "substr", "(", "SIGNING_KEY", ".", "length", ")", ":", "content", ".", "substr", "(", "SIGNING_KEY_OLD", ".", "length", ")", ";", "}" ]
Remove the signature from encrypted content @private @param {String} content The encrypted text @returns {String} The unsigned encrypted key @throws {Error} Throws if no SIGNING_KEY is detected @see SIGNING_KEY
[ "Remove", "the", "signature", "from", "encrypted", "content" ]
4296c9b36a313fa42e72d80cf8565148a5e26b47
https://github.com/buttercup/credentials/blob/4296c9b36a313fa42e72d80cf8565148a5e26b47/source/Credentials.js#L45-L54
train
Inspired-by-Boredom/generator-vintage-frontend
generators/app/templates/gulp/tasks/styles.js
compileCss
function compileCss(src, dest) { gulp .src(src) .pipe(plumber(config.plumberOptions)) .pipe(gulpif(!config.production, sourcemaps.init())) .pipe(sass({ outputStyle: config.production ? 'compressed' : 'expanded', precision: 5 })) .pipe(postcss(processors)) .pipe(gulpif(config.production, rename({ suffix: '.min', extname: '.css' }))) .pipe(gulpif(!config.production, sourcemaps.write())) .pipe(gulp.dest(dest)); }
javascript
function compileCss(src, dest) { gulp .src(src) .pipe(plumber(config.plumberOptions)) .pipe(gulpif(!config.production, sourcemaps.init())) .pipe(sass({ outputStyle: config.production ? 'compressed' : 'expanded', precision: 5 })) .pipe(postcss(processors)) .pipe(gulpif(config.production, rename({ suffix: '.min', extname: '.css' }))) .pipe(gulpif(!config.production, sourcemaps.write())) .pipe(gulp.dest(dest)); }
[ "function", "compileCss", "(", "src", ",", "dest", ")", "{", "gulp", ".", "src", "(", "src", ")", ".", "pipe", "(", "plumber", "(", "config", ".", "plumberOptions", ")", ")", ".", "pipe", "(", "gulpif", "(", "!", "config", ".", "production", ",", "sourcemaps", ".", "init", "(", ")", ")", ")", ".", "pipe", "(", "sass", "(", "{", "outputStyle", ":", "config", ".", "production", "?", "'compressed'", ":", "'expanded'", ",", "precision", ":", "5", "}", ")", ")", ".", "pipe", "(", "postcss", "(", "processors", ")", ")", ".", "pipe", "(", "gulpif", "(", "config", ".", "production", ",", "rename", "(", "{", "suffix", ":", "'.min'", ",", "extname", ":", "'.css'", "}", ")", ")", ")", ".", "pipe", "(", "gulpif", "(", "!", "config", ".", "production", ",", "sourcemaps", ".", "write", "(", ")", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "dest", ")", ")", ";", "}" ]
Default CSS compilation function. @param {String} src @param {String} dest
[ "Default", "CSS", "compilation", "function", "." ]
316ebc981961a39d3c47ba830f377350d529452b
https://github.com/Inspired-by-Boredom/generator-vintage-frontend/blob/316ebc981961a39d3c47ba830f377350d529452b/generators/app/templates/gulp/tasks/styles.js#L51-L67
train
jorisvervuurt/JVSDisplayOTron
examples/dothat/bar_graph.js
setEnabledStateOfLed
function setEnabledStateOfLed(callback) { var index = 0; var setEnabledStateOfLedInterval = setInterval(function() { if (index <= 5) { dothat.barGraph.setEnabledStateOfLed(index, false); index++; } else { clearInterval(setEnabledStateOfLedInterval); if (callback) { callback(); } } }, 500); }
javascript
function setEnabledStateOfLed(callback) { var index = 0; var setEnabledStateOfLedInterval = setInterval(function() { if (index <= 5) { dothat.barGraph.setEnabledStateOfLed(index, false); index++; } else { clearInterval(setEnabledStateOfLedInterval); if (callback) { callback(); } } }, 500); }
[ "function", "setEnabledStateOfLed", "(", "callback", ")", "{", "var", "index", "=", "0", ";", "var", "setEnabledStateOfLedInterval", "=", "setInterval", "(", "function", "(", ")", "{", "if", "(", "index", "<=", "5", ")", "{", "dothat", ".", "barGraph", ".", "setEnabledStateOfLed", "(", "index", ",", "false", ")", ";", "index", "++", ";", "}", "else", "{", "clearInterval", "(", "setEnabledStateOfLedInterval", ")", ";", "if", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", "}", "}", ",", "500", ")", ";", "}" ]
Sets the enabled state of each individual LED in the bar graph. @param {Function} callback A function to call when the operation has finished.
[ "Sets", "the", "enabled", "state", "of", "each", "individual", "LED", "in", "the", "bar", "graph", "." ]
c8f9bfdbf4e2658bb12fc83bbf49853c938e7dcc
https://github.com/jorisvervuurt/JVSDisplayOTron/blob/c8f9bfdbf4e2658bb12fc83bbf49853c938e7dcc/examples/dothat/bar_graph.js#L33-L49
train
ascartabelli/lamb
src/privates/_setIn.js
_setIn
function _setIn (source, key, value) { var result = {}; for (var prop in source) { result[prop] = source[prop]; } result[key] = value; return result; }
javascript
function _setIn (source, key, value) { var result = {}; for (var prop in source) { result[prop] = source[prop]; } result[key] = value; return result; }
[ "function", "_setIn", "(", "source", ",", "key", ",", "value", ")", "{", "var", "result", "=", "{", "}", ";", "for", "(", "var", "prop", "in", "source", ")", "{", "result", "[", "prop", "]", "=", "source", "[", "prop", "]", ";", "}", "result", "[", "key", "]", "=", "value", ";", "return", "result", ";", "}" ]
Sets, or creates, a property in a copy of the provided object to the desired value. @private @param {Object} source @param {String} key @param {*} value @returns {Object}
[ "Sets", "or", "creates", "a", "property", "in", "a", "copy", "of", "the", "provided", "object", "to", "the", "desired", "value", "." ]
d36e45945c4789e4f1a2d8805936514b53f32362
https://github.com/ascartabelli/lamb/blob/d36e45945c4789e4f1a2d8805936514b53f32362/src/privates/_setIn.js#L9-L19
train
FINRAOS/MSL
msl-server-node/mslMiddleware.js
getInterceptedXHR
function getInterceptedXHR(req) { var requestPath = req.requestPath; var interceptedXHRs = interceptXHRMap[requestPath]; var interceptedXHRsObj = {}; var counter = 1; if (interceptedXHRs != undefined) { for (var i = 0; i < interceptedXHRs.length; i++) { interceptedXHRsObj["xhr_" + counter] = interceptedXHRs[i]; counter++; } } return interceptedXHRsObj; }
javascript
function getInterceptedXHR(req) { var requestPath = req.requestPath; var interceptedXHRs = interceptXHRMap[requestPath]; var interceptedXHRsObj = {}; var counter = 1; if (interceptedXHRs != undefined) { for (var i = 0; i < interceptedXHRs.length; i++) { interceptedXHRsObj["xhr_" + counter] = interceptedXHRs[i]; counter++; } } return interceptedXHRsObj; }
[ "function", "getInterceptedXHR", "(", "req", ")", "{", "var", "requestPath", "=", "req", ".", "requestPath", ";", "var", "interceptedXHRs", "=", "interceptXHRMap", "[", "requestPath", "]", ";", "var", "interceptedXHRsObj", "=", "{", "}", ";", "var", "counter", "=", "1", ";", "if", "(", "interceptedXHRs", "!=", "undefined", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "interceptedXHRs", ".", "length", ";", "i", "++", ")", "{", "interceptedXHRsObj", "[", "\"xhr_\"", "+", "counter", "]", "=", "interceptedXHRs", "[", "i", "]", ";", "counter", "++", ";", "}", "}", "return", "interceptedXHRsObj", ";", "}" ]
Returns the intercepted XHRs @param req => XHR containing request path to look up (request query string contains request path) @return returns object containing list of XHRs with key xhr_#
[ "Returns", "the", "intercepted", "XHRs" ]
c8e2d79749551c551fc42b8ed80d3321141df845
https://github.com/FINRAOS/MSL/blob/c8e2d79749551c551fc42b8ed80d3321141df845/msl-server-node/mslMiddleware.js#L375-L389
train
FINRAOS/MSL
msl-server-node/mslMiddleware.js
isFakeRespond
function isFakeRespond(req) { var temp = req.url.toString(); var uniqueID = md5(JSON.stringify(req.body)); if (temp.indexOf("?") >= 0) req.url = reparsePath(temp); if (req.method === 'POST' && ((req.url in mockReqRespMap) && (mockReqRespMap[req.url] !== undefined)) && ((!((req.url + uniqueID) in mockReqRespMap)) && (mockReqRespMap[req.url + uniqueID] === undefined))) { mockReqRespMap[req.url + uniqueID] = mockReqRespMap[req.url]; delete mockReqRespMap[req.url]; console.log('This is POST call, but we are mocking it as a GET method, please use setMockPOSTRespond function to mock the data!!'); } if (((req.url in mockReqRespMap) && (mockReqRespMap[req.url] !== undefined)) || ((req._parsedUrl.pathname in mockReqRespMap) && (mockReqRespMap[req._parsedUrl.pathname] !== undefined)) || (((req.url + uniqueID) in mockReqRespMap) && (mockReqRespMap[req.url + uniqueID] !== undefined))) { return true; } else { return false; } }
javascript
function isFakeRespond(req) { var temp = req.url.toString(); var uniqueID = md5(JSON.stringify(req.body)); if (temp.indexOf("?") >= 0) req.url = reparsePath(temp); if (req.method === 'POST' && ((req.url in mockReqRespMap) && (mockReqRespMap[req.url] !== undefined)) && ((!((req.url + uniqueID) in mockReqRespMap)) && (mockReqRespMap[req.url + uniqueID] === undefined))) { mockReqRespMap[req.url + uniqueID] = mockReqRespMap[req.url]; delete mockReqRespMap[req.url]; console.log('This is POST call, but we are mocking it as a GET method, please use setMockPOSTRespond function to mock the data!!'); } if (((req.url in mockReqRespMap) && (mockReqRespMap[req.url] !== undefined)) || ((req._parsedUrl.pathname in mockReqRespMap) && (mockReqRespMap[req._parsedUrl.pathname] !== undefined)) || (((req.url + uniqueID) in mockReqRespMap) && (mockReqRespMap[req.url + uniqueID] !== undefined))) { return true; } else { return false; } }
[ "function", "isFakeRespond", "(", "req", ")", "{", "var", "temp", "=", "req", ".", "url", ".", "toString", "(", ")", ";", "var", "uniqueID", "=", "md5", "(", "JSON", ".", "stringify", "(", "req", ".", "body", ")", ")", ";", "if", "(", "temp", ".", "indexOf", "(", "\"?\"", ")", ">=", "0", ")", "req", ".", "url", "=", "reparsePath", "(", "temp", ")", ";", "if", "(", "req", ".", "method", "===", "'POST'", "&&", "(", "(", "req", ".", "url", "in", "mockReqRespMap", ")", "&&", "(", "mockReqRespMap", "[", "req", ".", "url", "]", "!==", "undefined", ")", ")", "&&", "(", "(", "!", "(", "(", "req", ".", "url", "+", "uniqueID", ")", "in", "mockReqRespMap", ")", ")", "&&", "(", "mockReqRespMap", "[", "req", ".", "url", "+", "uniqueID", "]", "===", "undefined", ")", ")", ")", "{", "mockReqRespMap", "[", "req", ".", "url", "+", "uniqueID", "]", "=", "mockReqRespMap", "[", "req", ".", "url", "]", ";", "delete", "mockReqRespMap", "[", "req", ".", "url", "]", ";", "console", ".", "log", "(", "'This is POST call, but we are mocking it as a GET method, please use setMockPOSTRespond function to mock the data!!'", ")", ";", "}", "if", "(", "(", "(", "req", ".", "url", "in", "mockReqRespMap", ")", "&&", "(", "mockReqRespMap", "[", "req", ".", "url", "]", "!==", "undefined", ")", ")", "||", "(", "(", "req", ".", "_parsedUrl", ".", "pathname", "in", "mockReqRespMap", ")", "&&", "(", "mockReqRespMap", "[", "req", ".", "_parsedUrl", ".", "pathname", "]", "!==", "undefined", ")", ")", "||", "(", "(", "(", "req", ".", "url", "+", "uniqueID", ")", "in", "mockReqRespMap", ")", "&&", "(", "mockReqRespMap", "[", "req", ".", "url", "+", "uniqueID", "]", "!==", "undefined", ")", ")", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Determines whether the request made by the path requires mock response by checking mockReqRespMap. @param req => XHR @return true/false
[ "Determines", "whether", "the", "request", "made", "by", "the", "path", "requires", "mock", "response", "by", "checking", "mockReqRespMap", "." ]
c8e2d79749551c551fc42b8ed80d3321141df845
https://github.com/FINRAOS/MSL/blob/c8e2d79749551c551fc42b8ed80d3321141df845/msl-server-node/mslMiddleware.js#L398-L416
train
FINRAOS/MSL
msl-server-node/mslMiddleware.js
isInterceptXHR
function isInterceptXHR(req) { if (((req.url in interceptXHRMap) && (interceptXHRMap[req.url] !== undefined)) || ((req._parsedUrl.pathname in interceptXHRMap) && (interceptXHRMap[req._parsedUrl.pathname] !== undefined))) { return true; } else { return false; } }
javascript
function isInterceptXHR(req) { if (((req.url in interceptXHRMap) && (interceptXHRMap[req.url] !== undefined)) || ((req._parsedUrl.pathname in interceptXHRMap) && (interceptXHRMap[req._parsedUrl.pathname] !== undefined))) { return true; } else { return false; } }
[ "function", "isInterceptXHR", "(", "req", ")", "{", "if", "(", "(", "(", "req", ".", "url", "in", "interceptXHRMap", ")", "&&", "(", "interceptXHRMap", "[", "req", ".", "url", "]", "!==", "undefined", ")", ")", "||", "(", "(", "req", ".", "_parsedUrl", ".", "pathname", "in", "interceptXHRMap", ")", "&&", "(", "interceptXHRMap", "[", "req", ".", "_parsedUrl", ".", "pathname", "]", "!==", "undefined", ")", ")", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Determines whether the request made by the path requires interception. @param req => XHR @return true/false
[ "Determines", "whether", "the", "request", "made", "by", "the", "path", "requires", "interception", "." ]
c8e2d79749551c551fc42b8ed80d3321141df845
https://github.com/FINRAOS/MSL/blob/c8e2d79749551c551fc42b8ed80d3321141df845/msl-server-node/mslMiddleware.js#L424-L431
train
FINRAOS/MSL
msl-server-node/mslMiddleware.js
reparsePath
function reparsePath(oldpath) { if (oldpath.indexOf("?") >= 0) { var vars = oldpath.split("?")[1].split("&"); var result = oldpath.split("?")[0] + '?'; var firstFlag = 0; for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if (ignoredParams.search(pair[0]) < 0) { if (firstFlag === 0) { result = result + pair[0] + '=' + pair[1]; firstFlag = 1; } else { result = result + '&' + pair[0] + '=' + pair[1]; } } } return result; } else { return oldpath; } }
javascript
function reparsePath(oldpath) { if (oldpath.indexOf("?") >= 0) { var vars = oldpath.split("?")[1].split("&"); var result = oldpath.split("?")[0] + '?'; var firstFlag = 0; for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if (ignoredParams.search(pair[0]) < 0) { if (firstFlag === 0) { result = result + pair[0] + '=' + pair[1]; firstFlag = 1; } else { result = result + '&' + pair[0] + '=' + pair[1]; } } } return result; } else { return oldpath; } }
[ "function", "reparsePath", "(", "oldpath", ")", "{", "if", "(", "oldpath", ".", "indexOf", "(", "\"?\"", ")", ">=", "0", ")", "{", "var", "vars", "=", "oldpath", ".", "split", "(", "\"?\"", ")", "[", "1", "]", ".", "split", "(", "\"&\"", ")", ";", "var", "result", "=", "oldpath", ".", "split", "(", "\"?\"", ")", "[", "0", "]", "+", "'?'", ";", "var", "firstFlag", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "vars", ".", "length", ";", "i", "++", ")", "{", "var", "pair", "=", "vars", "[", "i", "]", ".", "split", "(", "\"=\"", ")", ";", "if", "(", "ignoredParams", ".", "search", "(", "pair", "[", "0", "]", ")", "<", "0", ")", "{", "if", "(", "firstFlag", "===", "0", ")", "{", "result", "=", "result", "+", "pair", "[", "0", "]", "+", "'='", "+", "pair", "[", "1", "]", ";", "firstFlag", "=", "1", ";", "}", "else", "{", "result", "=", "result", "+", "'&'", "+", "pair", "[", "0", "]", "+", "'='", "+", "pair", "[", "1", "]", ";", "}", "}", "}", "return", "result", ";", "}", "else", "{", "return", "oldpath", ";", "}", "}" ]
Supporting function to parse the the URL to ignore the parameters that user don't need. Not exposed to the client.
[ "Supporting", "function", "to", "parse", "the", "the", "URL", "to", "ignore", "the", "parameters", "that", "user", "don", "t", "need", ".", "Not", "exposed", "to", "the", "client", "." ]
c8e2d79749551c551fc42b8ed80d3321141df845
https://github.com/FINRAOS/MSL/blob/c8e2d79749551c551fc42b8ed80d3321141df845/msl-server-node/mslMiddleware.js#L468-L490
train
datanews/tables
lib/db.js
modelMethod
function modelMethod(model, method, data, done) { model[method](data).then(function(results) { done(null, results); }) .catch(function(error) { // Try again on timeout if (error.message == "connect ETIMEDOUT") { modelMethod(model, method, data, done); return; } done(error); }); }
javascript
function modelMethod(model, method, data, done) { model[method](data).then(function(results) { done(null, results); }) .catch(function(error) { // Try again on timeout if (error.message == "connect ETIMEDOUT") { modelMethod(model, method, data, done); return; } done(error); }); }
[ "function", "modelMethod", "(", "model", ",", "method", ",", "data", ",", "done", ")", "{", "model", "[", "method", "]", "(", "data", ")", ".", "then", "(", "function", "(", "results", ")", "{", "done", "(", "null", ",", "results", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "if", "(", "error", ".", "message", "==", "\"connect ETIMEDOUT\"", ")", "{", "modelMethod", "(", "model", ",", "method", ",", "data", ",", "done", ")", ";", "return", ";", "}", "done", "(", "error", ")", ";", "}", ")", ";", "}" ]
Queue-ify db request
[ "Queue", "-", "ify", "db", "request" ]
4b33aa7a944a93260c49baecbb90345211cac789
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/db.js#L15-L27
train
datanews/tables
lib/db.js
runQuery
function runQuery(connection, query, options, done) { options = _.isObject(options) ? options : connection.QueryTypes[options] ? { type: connection.QueryTypes[options] } : {}; connection.query(query, options) .then(function(results) { done(null, results); }) .catch(function(error) { if (error) { output.error("Query error. SQL has been written to .tables.debug. Use a smaller batchSize to more easily find the issue."); output.error(error); fs.writeFileSync(".tables.debug", query); } done(error); }); }
javascript
function runQuery(connection, query, options, done) { options = _.isObject(options) ? options : connection.QueryTypes[options] ? { type: connection.QueryTypes[options] } : {}; connection.query(query, options) .then(function(results) { done(null, results); }) .catch(function(error) { if (error) { output.error("Query error. SQL has been written to .tables.debug. Use a smaller batchSize to more easily find the issue."); output.error(error); fs.writeFileSync(".tables.debug", query); } done(error); }); }
[ "function", "runQuery", "(", "connection", ",", "query", ",", "options", ",", "done", ")", "{", "options", "=", "_", ".", "isObject", "(", "options", ")", "?", "options", ":", "connection", ".", "QueryTypes", "[", "options", "]", "?", "{", "type", ":", "connection", ".", "QueryTypes", "[", "options", "]", "}", ":", "{", "}", ";", "connection", ".", "query", "(", "query", ",", "options", ")", ".", "then", "(", "function", "(", "results", ")", "{", "done", "(", "null", ",", "results", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "output", ".", "error", "(", "\"Query error. SQL has been written to .tables.debug. Use a smaller batchSize to more easily find the issue.\"", ")", ";", "output", ".", "error", "(", "error", ")", ";", "fs", ".", "writeFileSync", "(", "\".tables.debug\"", ",", "query", ")", ";", "}", "done", "(", "error", ")", ";", "}", ")", ";", "}" ]
Queue-ify db query
[ "Queue", "-", "ify", "db", "query" ]
4b33aa7a944a93260c49baecbb90345211cac789
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/db.js#L30-L47
train
datanews/tables
lib/db.js
mysqlBulkUpsert
function mysqlBulkUpsert(model, data) { var mysql = require("mysql"); var queries = ["SET AUTOCOMMIT = 0"]; // Transform data _.each(data, function(d) { var query = "REPLACE INTO " + model.tableName + " ([[COLUMNS]]) VALUES (?)"; query = query.replace("[[COLUMNS]]", _.keys(d).join(", ")); query = mysql.format(query, [ _.values(d) ]); queries.push(query); }); // Create final output and format queries.push("COMMIT"); queries.push("SET AUTOCOMMIT = 1"); return queries.join("; "); }
javascript
function mysqlBulkUpsert(model, data) { var mysql = require("mysql"); var queries = ["SET AUTOCOMMIT = 0"]; // Transform data _.each(data, function(d) { var query = "REPLACE INTO " + model.tableName + " ([[COLUMNS]]) VALUES (?)"; query = query.replace("[[COLUMNS]]", _.keys(d).join(", ")); query = mysql.format(query, [ _.values(d) ]); queries.push(query); }); // Create final output and format queries.push("COMMIT"); queries.push("SET AUTOCOMMIT = 1"); return queries.join("; "); }
[ "function", "mysqlBulkUpsert", "(", "model", ",", "data", ")", "{", "var", "mysql", "=", "require", "(", "\"mysql\"", ")", ";", "var", "queries", "=", "[", "\"SET AUTOCOMMIT = 0\"", "]", ";", "_", ".", "each", "(", "data", ",", "function", "(", "d", ")", "{", "var", "query", "=", "\"REPLACE INTO \"", "+", "model", ".", "tableName", "+", "\" ([[COLUMNS]]) VALUES (?)\"", ";", "query", "=", "query", ".", "replace", "(", "\"[[COLUMNS]]\"", ",", "_", ".", "keys", "(", "d", ")", ".", "join", "(", "\", \"", ")", ")", ";", "query", "=", "mysql", ".", "format", "(", "query", ",", "[", "_", ".", "values", "(", "d", ")", "]", ")", ";", "queries", ".", "push", "(", "query", ")", ";", "}", ")", ";", "queries", ".", "push", "(", "\"COMMIT\"", ")", ";", "queries", ".", "push", "(", "\"SET AUTOCOMMIT = 1\"", ")", ";", "return", "queries", ".", "join", "(", "\"; \"", ")", ";", "}" ]
Mysql query format bulk upsert
[ "Mysql", "query", "format", "bulk", "upsert" ]
4b33aa7a944a93260c49baecbb90345211cac789
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/db.js#L86-L102
train
datanews/tables
lib/db.js
sqliteBulkUpsert
function sqliteBulkUpsert(model, data) { var queries = ["BEGIN"]; var values = []; // Transform data _.each(data, function(d) { var query = "INSERT OR REPLACE INTO " + model.tableName + " ([[COLUMNS]]) VALUES ([[VALUES]])"; query = query.replace("[[COLUMNS]]", _.keys(d).join(", ")); // Put in ?'s query = query.replace("[[VALUES]]", _.map(d, function(v) { return "?"; }).join(", ")); // Get values values = values.concat(_.values(d)); queries.push(query); }); // Create final output and format queries.push("COMMIT"); return { query: queries.join("; "), replacements: values }; }
javascript
function sqliteBulkUpsert(model, data) { var queries = ["BEGIN"]; var values = []; // Transform data _.each(data, function(d) { var query = "INSERT OR REPLACE INTO " + model.tableName + " ([[COLUMNS]]) VALUES ([[VALUES]])"; query = query.replace("[[COLUMNS]]", _.keys(d).join(", ")); // Put in ?'s query = query.replace("[[VALUES]]", _.map(d, function(v) { return "?"; }).join(", ")); // Get values values = values.concat(_.values(d)); queries.push(query); }); // Create final output and format queries.push("COMMIT"); return { query: queries.join("; "), replacements: values }; }
[ "function", "sqliteBulkUpsert", "(", "model", ",", "data", ")", "{", "var", "queries", "=", "[", "\"BEGIN\"", "]", ";", "var", "values", "=", "[", "]", ";", "_", ".", "each", "(", "data", ",", "function", "(", "d", ")", "{", "var", "query", "=", "\"INSERT OR REPLACE INTO \"", "+", "model", ".", "tableName", "+", "\" ([[COLUMNS]]) VALUES ([[VALUES]])\"", ";", "query", "=", "query", ".", "replace", "(", "\"[[COLUMNS]]\"", ",", "_", ".", "keys", "(", "d", ")", ".", "join", "(", "\", \"", ")", ")", ";", "query", "=", "query", ".", "replace", "(", "\"[[VALUES]]\"", ",", "_", ".", "map", "(", "d", ",", "function", "(", "v", ")", "{", "return", "\"?\"", ";", "}", ")", ".", "join", "(", "\", \"", ")", ")", ";", "values", "=", "values", ".", "concat", "(", "_", ".", "values", "(", "d", ")", ")", ";", "queries", ".", "push", "(", "query", ")", ";", "}", ")", ";", "queries", ".", "push", "(", "\"COMMIT\"", ")", ";", "return", "{", "query", ":", "queries", ".", "join", "(", "\"; \"", ")", ",", "replacements", ":", "values", "}", ";", "}" ]
SQLite query format bulk upsert. SQLite uses a bind function that automatically replaces ?
[ "SQLite", "query", "format", "bulk", "upsert", ".", "SQLite", "uses", "a", "bind", "function", "that", "automatically", "replaces", "?" ]
4b33aa7a944a93260c49baecbb90345211cac789
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/db.js#L106-L131
train
datanews/tables
lib/db.js
pgsqlBulkUpsert
function pgsqlBulkUpsert(model, data) { var queries = []; // Transform data _.each(data, function(d) { // TODO: Postgres does not have easy UPSERT syntax, the ON CONFLICT UPDATE requires specific columns var query = "INSERT INTO " + model.tableName + " ([[COLUMNS]]) VALUES ([[VALUES]])"; query = query.replace("[[COLUMNS]]", _.keys(d).join(", ")); query = query.replace("[[VALUES]]", _.map(d, function(v) { return sequelizeSS.escape(v, undefined, "postgres"); }).join(", ")); queries.push(query); }); // Create final output and format return queries.join("; "); }
javascript
function pgsqlBulkUpsert(model, data) { var queries = []; // Transform data _.each(data, function(d) { // TODO: Postgres does not have easy UPSERT syntax, the ON CONFLICT UPDATE requires specific columns var query = "INSERT INTO " + model.tableName + " ([[COLUMNS]]) VALUES ([[VALUES]])"; query = query.replace("[[COLUMNS]]", _.keys(d).join(", ")); query = query.replace("[[VALUES]]", _.map(d, function(v) { return sequelizeSS.escape(v, undefined, "postgres"); }).join(", ")); queries.push(query); }); // Create final output and format return queries.join("; "); }
[ "function", "pgsqlBulkUpsert", "(", "model", ",", "data", ")", "{", "var", "queries", "=", "[", "]", ";", "_", ".", "each", "(", "data", ",", "function", "(", "d", ")", "{", "var", "query", "=", "\"INSERT INTO \"", "+", "model", ".", "tableName", "+", "\" ([[COLUMNS]]) VALUES ([[VALUES]])\"", ";", "query", "=", "query", ".", "replace", "(", "\"[[COLUMNS]]\"", ",", "_", ".", "keys", "(", "d", ")", ".", "join", "(", "\", \"", ")", ")", ";", "query", "=", "query", ".", "replace", "(", "\"[[VALUES]]\"", ",", "_", ".", "map", "(", "d", ",", "function", "(", "v", ")", "{", "return", "sequelizeSS", ".", "escape", "(", "v", ",", "undefined", ",", "\"postgres\"", ")", ";", "}", ")", ".", "join", "(", "\", \"", ")", ")", ";", "queries", ".", "push", "(", "query", ")", ";", "}", ")", ";", "return", "queries", ".", "join", "(", "\"; \"", ")", ";", "}" ]
PGSQL query format bulk upsert
[ "PGSQL", "query", "format", "bulk", "upsert" ]
4b33aa7a944a93260c49baecbb90345211cac789
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/db.js#L134-L150
train
datanews/tables
lib/db.js
vacuum
function vacuum(connection, done) { var n = connection.connectionManager.dialectName; var query; // Make query based on dialiect if (n === "mysql" || n === "mariadb" || n === "mysqli") { query = "SELECT 1"; } else if (n === "sqlite") { query = "VACUUM"; } else if (n === "pgsql" || n === "postgres") { query = "VACUUM"; } runQuery(connection, query, { type: connection.QueryTypes.UPSERT, raw: true }, done); }
javascript
function vacuum(connection, done) { var n = connection.connectionManager.dialectName; var query; // Make query based on dialiect if (n === "mysql" || n === "mariadb" || n === "mysqli") { query = "SELECT 1"; } else if (n === "sqlite") { query = "VACUUM"; } else if (n === "pgsql" || n === "postgres") { query = "VACUUM"; } runQuery(connection, query, { type: connection.QueryTypes.UPSERT, raw: true }, done); }
[ "function", "vacuum", "(", "connection", ",", "done", ")", "{", "var", "n", "=", "connection", ".", "connectionManager", ".", "dialectName", ";", "var", "query", ";", "if", "(", "n", "===", "\"mysql\"", "||", "n", "===", "\"mariadb\"", "||", "n", "===", "\"mysqli\"", ")", "{", "query", "=", "\"SELECT 1\"", ";", "}", "else", "if", "(", "n", "===", "\"sqlite\"", ")", "{", "query", "=", "\"VACUUM\"", ";", "}", "else", "if", "(", "n", "===", "\"pgsql\"", "||", "n", "===", "\"postgres\"", ")", "{", "query", "=", "\"VACUUM\"", ";", "}", "runQuery", "(", "connection", ",", "query", ",", "{", "type", ":", "connection", ".", "QueryTypes", ".", "UPSERT", ",", "raw", ":", "true", "}", ",", "done", ")", ";", "}" ]
Run vaccume query
[ "Run", "vaccume", "query" ]
4b33aa7a944a93260c49baecbb90345211cac789
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/db.js#L153-L169
train
catbee/catbee
lib/providers/URLArgsProvider.js
getUriMappers
function getUriMappers (serviceLocator) { var routeDefinitions; try { routeDefinitions = serviceLocator.resolveAll('routeDefinition'); } catch (e) { routeDefinitions = []; } return routeDefinitions .map(route => { var mapper = routeHelper.compileRoute(route.expression); return { expression: mapper.expression, map: route.map || noop, argsMap: uri => { var args = mapper.map(uri); Object.assign(args, route.args); return args; } }; }); }
javascript
function getUriMappers (serviceLocator) { var routeDefinitions; try { routeDefinitions = serviceLocator.resolveAll('routeDefinition'); } catch (e) { routeDefinitions = []; } return routeDefinitions .map(route => { var mapper = routeHelper.compileRoute(route.expression); return { expression: mapper.expression, map: route.map || noop, argsMap: uri => { var args = mapper.map(uri); Object.assign(args, route.args); return args; } }; }); }
[ "function", "getUriMappers", "(", "serviceLocator", ")", "{", "var", "routeDefinitions", ";", "try", "{", "routeDefinitions", "=", "serviceLocator", ".", "resolveAll", "(", "'routeDefinition'", ")", ";", "}", "catch", "(", "e", ")", "{", "routeDefinitions", "=", "[", "]", ";", "}", "return", "routeDefinitions", ".", "map", "(", "route", "=>", "{", "var", "mapper", "=", "routeHelper", ".", "compileRoute", "(", "route", ".", "expression", ")", ";", "return", "{", "expression", ":", "mapper", ".", "expression", ",", "map", ":", "route", ".", "map", "||", "noop", ",", "argsMap", ":", "uri", "=>", "{", "var", "args", "=", "mapper", ".", "map", "(", "uri", ")", ";", "Object", ".", "assign", "(", "args", ",", "route", ".", "args", ")", ";", "return", "args", ";", "}", "}", ";", "}", ")", ";", "}" ]
Gets list of URI mappers. @param {ServiceLocator} serviceLocator Service locator to get route definitions. @returns {Array} List of URI mappers.
[ "Gets", "list", "of", "URI", "mappers", "." ]
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/providers/URLArgsProvider.js#L45-L68
train
catbee/catbee
lib/providers/URLArgsProvider.js
runPostMapping
function runPostMapping (args, uriMappers, location) { uriMappers.some(mapper => { if (mapper.expression.test(location.path)) { args = mapper.map(args); return true; } return false; }); return args; }
javascript
function runPostMapping (args, uriMappers, location) { uriMappers.some(mapper => { if (mapper.expression.test(location.path)) { args = mapper.map(args); return true; } return false; }); return args; }
[ "function", "runPostMapping", "(", "args", ",", "uriMappers", ",", "location", ")", "{", "uriMappers", ".", "some", "(", "mapper", "=>", "{", "if", "(", "mapper", ".", "expression", ".", "test", "(", "location", ".", "path", ")", ")", "{", "args", "=", "mapper", ".", "map", "(", "args", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "return", "args", ";", "}" ]
Run handler after signal and args was get @param {Object} args @param {Array} uriMappers @param {URI} location @return {Object}
[ "Run", "handler", "after", "signal", "and", "args", "was", "get" ]
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/providers/URLArgsProvider.js#L97-L107
train
wiresjs/async-watch
dist/async-watch.js
dotNotation
function dotNotation(path) { if (path instanceof Array) { return { path: path, str: path.join('.') } } if (typeof path !== 'string') { return; } return { path: path.split('\.'), str: path } }
javascript
function dotNotation(path) { if (path instanceof Array) { return { path: path, str: path.join('.') } } if (typeof path !== 'string') { return; } return { path: path.split('\.'), str: path } }
[ "function", "dotNotation", "(", "path", ")", "{", "if", "(", "path", "instanceof", "Array", ")", "{", "return", "{", "path", ":", "path", ",", "str", ":", "path", ".", "join", "(", "'.'", ")", "}", "}", "if", "(", "typeof", "path", "!==", "'string'", ")", "{", "return", ";", "}", "return", "{", "path", ":", "path", ".", "split", "(", "'\\.'", ")", ",", "\\.", "}", "}" ]
dotNotation - A helper to extract dot notation @param {type} path string or array @return {type} Object { path : ['a','b'], str : 'a.b'}
[ "dotNotation", "-", "A", "helper", "to", "extract", "dot", "notation" ]
4f813c2b747a64db6ade9053637d813a75a04c03
https://github.com/wiresjs/async-watch/blob/4f813c2b747a64db6ade9053637d813a75a04c03/dist/async-watch.js#L116-L130
train
wiresjs/async-watch
dist/async-watch.js
getPropertyValue
function getPropertyValue(obj, path) { if (path.length === 0 || obj === undefined) { return undefined; } var notation = dotNotation(path); if (!notation) { return; } path = notation.path; for (var i = 0; i < path.length; i++) { obj = obj[path[i]]; if (obj === undefined) { return undefined; } } return obj; }
javascript
function getPropertyValue(obj, path) { if (path.length === 0 || obj === undefined) { return undefined; } var notation = dotNotation(path); if (!notation) { return; } path = notation.path; for (var i = 0; i < path.length; i++) { obj = obj[path[i]]; if (obj === undefined) { return undefined; } } return obj; }
[ "function", "getPropertyValue", "(", "obj", ",", "path", ")", "{", "if", "(", "path", ".", "length", "===", "0", "||", "obj", "===", "undefined", ")", "{", "return", "undefined", ";", "}", "var", "notation", "=", "dotNotation", "(", "path", ")", ";", "if", "(", "!", "notation", ")", "{", "return", ";", "}", "path", "=", "notation", ".", "path", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "path", ".", "length", ";", "i", "++", ")", "{", "obj", "=", "obj", "[", "path", "[", "i", "]", "]", ";", "if", "(", "obj", "===", "undefined", ")", "{", "return", "undefined", ";", "}", "}", "return", "obj", ";", "}" ]
getPropertyValue - get a value from an object with dot notation @param {type} obj Target object @param {type} path dot notation @return {type} Target object
[ "getPropertyValue", "-", "get", "a", "value", "from", "an", "object", "with", "dot", "notation" ]
4f813c2b747a64db6ade9053637d813a75a04c03
https://github.com/wiresjs/async-watch/blob/4f813c2b747a64db6ade9053637d813a75a04c03/dist/async-watch.js#L139-L156
train
wiresjs/async-watch
dist/async-watch.js
setHiddenProperty
function setHiddenProperty(obj, key, value) { Object.defineProperty(obj, key, { enumerable: false, value: value }); return value; }
javascript
function setHiddenProperty(obj, key, value) { Object.defineProperty(obj, key, { enumerable: false, value: value }); return value; }
[ "function", "setHiddenProperty", "(", "obj", ",", "key", ",", "value", ")", "{", "Object", ".", "defineProperty", "(", "obj", ",", "key", ",", "{", "enumerable", ":", "false", ",", "value", ":", "value", "}", ")", ";", "return", "value", ";", "}" ]
setHiddenProperty - description @param {type} obj target object @param {type} key property name @param {type} value default value @return {type} target object
[ "setHiddenProperty", "-", "description" ]
4f813c2b747a64db6ade9053637d813a75a04c03
https://github.com/wiresjs/async-watch/blob/4f813c2b747a64db6ade9053637d813a75a04c03/dist/async-watch.js#L166-L172
train
vectree/JS-jail
index.js
tryToCoverWindow
function tryToCoverWindow(code) { if (typeof window === "object") { var variables = Object.getOwnPropertyNames(window); if (!window.hasOwnProperty('window')) { variables.push('window'); } var stubDeclarations = ''; variables.forEach(function(name) { // If the name really can be the name of variable. if (lodash.isString(name)) { var stub = 'var ' + name + '; \n'; stubDeclarations = stubDeclarations + stub; } }); code = stubDeclarations + code; } return code; }
javascript
function tryToCoverWindow(code) { if (typeof window === "object") { var variables = Object.getOwnPropertyNames(window); if (!window.hasOwnProperty('window')) { variables.push('window'); } var stubDeclarations = ''; variables.forEach(function(name) { // If the name really can be the name of variable. if (lodash.isString(name)) { var stub = 'var ' + name + '; \n'; stubDeclarations = stubDeclarations + stub; } }); code = stubDeclarations + code; } return code; }
[ "function", "tryToCoverWindow", "(", "code", ")", "{", "if", "(", "typeof", "window", "===", "\"object\"", ")", "{", "var", "variables", "=", "Object", ".", "getOwnPropertyNames", "(", "window", ")", ";", "if", "(", "!", "window", ".", "hasOwnProperty", "(", "'window'", ")", ")", "{", "variables", ".", "push", "(", "'window'", ")", ";", "}", "var", "stubDeclarations", "=", "''", ";", "variables", ".", "forEach", "(", "function", "(", "name", ")", "{", "if", "(", "lodash", ".", "isString", "(", "name", ")", ")", "{", "var", "stub", "=", "'var '", "+", "name", "+", "'; \\n'", ";", "\\n", "}", "}", ")", ";", "stubDeclarations", "=", "stubDeclarations", "+", "stub", ";", "}", "code", "=", "stubDeclarations", "+", "code", ";", "}" ]
Makes stubs of variables for avoid the changing of outside environment which has these variables too. TODO need to take this function into a separate module. @private @param {String} code The source code.
[ "Makes", "stubs", "of", "variables", "for", "avoid", "the", "changing", "of", "outside", "environment", "which", "has", "these", "variables", "too", "." ]
c650fbc8dc14459d44d6a6e2592302945171b2ee
https://github.com/vectree/JS-jail/blob/c650fbc8dc14459d44d6a6e2592302945171b2ee/index.js#L65-L97
train
spreadshirt/rAppid.js-sprd
sprd/lib/raygun.js
createCORSRequest
function createCORSRequest (method, url) { var xhr; xhr = new window.XMLHttpRequest(); if ("withCredentials" in xhr) { // XHR for Chrome/Firefox/Opera/Safari. xhr.open(method, url, true); } else if (window.XDomainRequest) { // XDomainRequest for IE. if (_allowInsecureSubmissions) { // remove 'https:' and use relative protocol // this allows IE8 to post messages when running // on http url = url.slice(6); } xhr = new window.XDomainRequest(); xhr.open(method, url); } xhr.timeout = 10000; return xhr; }
javascript
function createCORSRequest (method, url) { var xhr; xhr = new window.XMLHttpRequest(); if ("withCredentials" in xhr) { // XHR for Chrome/Firefox/Opera/Safari. xhr.open(method, url, true); } else if (window.XDomainRequest) { // XDomainRequest for IE. if (_allowInsecureSubmissions) { // remove 'https:' and use relative protocol // this allows IE8 to post messages when running // on http url = url.slice(6); } xhr = new window.XDomainRequest(); xhr.open(method, url); } xhr.timeout = 10000; return xhr; }
[ "function", "createCORSRequest", "(", "method", ",", "url", ")", "{", "var", "xhr", ";", "xhr", "=", "new", "window", ".", "XMLHttpRequest", "(", ")", ";", "if", "(", "\"withCredentials\"", "in", "xhr", ")", "{", "xhr", ".", "open", "(", "method", ",", "url", ",", "true", ")", ";", "}", "else", "if", "(", "window", ".", "XDomainRequest", ")", "{", "if", "(", "_allowInsecureSubmissions", ")", "{", "url", "=", "url", ".", "slice", "(", "6", ")", ";", "}", "xhr", "=", "new", "window", ".", "XDomainRequest", "(", ")", ";", "xhr", ".", "open", "(", "method", ",", "url", ")", ";", "}", "xhr", ".", "timeout", "=", "10000", ";", "return", "xhr", ";", "}" ]
Create the XHR object.
[ "Create", "the", "XHR", "object", "." ]
b56f9f47fe01332f5bf885eaf4db59014f099019
https://github.com/spreadshirt/rAppid.js-sprd/blob/b56f9f47fe01332f5bf885eaf4db59014f099019/sprd/lib/raygun.js#L1968-L1993
train
spreadshirt/rAppid.js-sprd
sprd/lib/raygun.js
makePostCorsRequest
function makePostCorsRequest (url, data) { var xhr = createCORSRequest('POST', url, data); if (typeof _beforeXHRCallback === 'function') { _beforeXHRCallback(xhr); } if ('withCredentials' in xhr) { xhr.onreadystatechange = function() { if (xhr.readyState !== 4) { return; } if (xhr.status === 202) { sendSavedErrors(); } else if (_enableOfflineSave && xhr.status !== 403 && xhr.status !== 400 && xhr.status !== 429) { offlineSave(url, data); } }; xhr.onload = function() { _private.log('posted to Raygun'); callAfterSend(this); }; } else if (window.XDomainRequest) { xhr.ontimeout = function() { if (_enableOfflineSave) { _private.log('Raygun: saved locally'); offlineSave(url, data); } }; xhr.onload = function() { _private.log('posted to Raygun'); sendSavedErrors(); callAfterSend(this); }; } xhr.onerror = function() { _private.log('failed to post to Raygun'); callAfterSend(this); }; if (!xhr) { _private.log('CORS not supported'); return; } xhr.send(data); }
javascript
function makePostCorsRequest (url, data) { var xhr = createCORSRequest('POST', url, data); if (typeof _beforeXHRCallback === 'function') { _beforeXHRCallback(xhr); } if ('withCredentials' in xhr) { xhr.onreadystatechange = function() { if (xhr.readyState !== 4) { return; } if (xhr.status === 202) { sendSavedErrors(); } else if (_enableOfflineSave && xhr.status !== 403 && xhr.status !== 400 && xhr.status !== 429) { offlineSave(url, data); } }; xhr.onload = function() { _private.log('posted to Raygun'); callAfterSend(this); }; } else if (window.XDomainRequest) { xhr.ontimeout = function() { if (_enableOfflineSave) { _private.log('Raygun: saved locally'); offlineSave(url, data); } }; xhr.onload = function() { _private.log('posted to Raygun'); sendSavedErrors(); callAfterSend(this); }; } xhr.onerror = function() { _private.log('failed to post to Raygun'); callAfterSend(this); }; if (!xhr) { _private.log('CORS not supported'); return; } xhr.send(data); }
[ "function", "makePostCorsRequest", "(", "url", ",", "data", ")", "{", "var", "xhr", "=", "createCORSRequest", "(", "'POST'", ",", "url", ",", "data", ")", ";", "if", "(", "typeof", "_beforeXHRCallback", "===", "'function'", ")", "{", "_beforeXHRCallback", "(", "xhr", ")", ";", "}", "if", "(", "'withCredentials'", "in", "xhr", ")", "{", "xhr", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "xhr", ".", "readyState", "!==", "4", ")", "{", "return", ";", "}", "if", "(", "xhr", ".", "status", "===", "202", ")", "{", "sendSavedErrors", "(", ")", ";", "}", "else", "if", "(", "_enableOfflineSave", "&&", "xhr", ".", "status", "!==", "403", "&&", "xhr", ".", "status", "!==", "400", "&&", "xhr", ".", "status", "!==", "429", ")", "{", "offlineSave", "(", "url", ",", "data", ")", ";", "}", "}", ";", "xhr", ".", "onload", "=", "function", "(", ")", "{", "_private", ".", "log", "(", "'posted to Raygun'", ")", ";", "callAfterSend", "(", "this", ")", ";", "}", ";", "}", "else", "if", "(", "window", ".", "XDomainRequest", ")", "{", "xhr", ".", "ontimeout", "=", "function", "(", ")", "{", "if", "(", "_enableOfflineSave", ")", "{", "_private", ".", "log", "(", "'Raygun: saved locally'", ")", ";", "offlineSave", "(", "url", ",", "data", ")", ";", "}", "}", ";", "xhr", ".", "onload", "=", "function", "(", ")", "{", "_private", ".", "log", "(", "'posted to Raygun'", ")", ";", "sendSavedErrors", "(", ")", ";", "callAfterSend", "(", "this", ")", ";", "}", ";", "}", "xhr", ".", "onerror", "=", "function", "(", ")", "{", "_private", ".", "log", "(", "'failed to post to Raygun'", ")", ";", "callAfterSend", "(", "this", ")", ";", "}", ";", "if", "(", "!", "xhr", ")", "{", "_private", ".", "log", "(", "'CORS not supported'", ")", ";", "return", ";", "}", "xhr", ".", "send", "(", "data", ")", ";", "}" ]
Make the actual CORS request.
[ "Make", "the", "actual", "CORS", "request", "." ]
b56f9f47fe01332f5bf885eaf4db59014f099019
https://github.com/spreadshirt/rAppid.js-sprd/blob/b56f9f47fe01332f5bf885eaf4db59014f099019/sprd/lib/raygun.js#L1996-L2051
train
catbee/catbee
lib/helpers/routeHelper.js
createUriPathMapper
function createUriPathMapper (expression, parameters) { return (uriPath, args) => { var matches = uriPath.match(expression); if (!matches || matches.length < 2) { return args; } // start with second match because first match is always // the whole URI path matches = matches.splice(1); parameters.forEach((parameter, index) => { var value = matches[index]; try { value = decodeURIComponent(value); } catch (e) { // nothing to do } args[parameter.name] = value; }); }; }
javascript
function createUriPathMapper (expression, parameters) { return (uriPath, args) => { var matches = uriPath.match(expression); if (!matches || matches.length < 2) { return args; } // start with second match because first match is always // the whole URI path matches = matches.splice(1); parameters.forEach((parameter, index) => { var value = matches[index]; try { value = decodeURIComponent(value); } catch (e) { // nothing to do } args[parameter.name] = value; }); }; }
[ "function", "createUriPathMapper", "(", "expression", ",", "parameters", ")", "{", "return", "(", "uriPath", ",", "args", ")", "=>", "{", "var", "matches", "=", "uriPath", ".", "match", "(", "expression", ")", ";", "if", "(", "!", "matches", "||", "matches", ".", "length", "<", "2", ")", "{", "return", "args", ";", "}", "matches", "=", "matches", ".", "splice", "(", "1", ")", ";", "parameters", ".", "forEach", "(", "(", "parameter", ",", "index", ")", "=>", "{", "var", "value", "=", "matches", "[", "index", "]", ";", "try", "{", "value", "=", "decodeURIComponent", "(", "value", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "args", "[", "parameter", ".", "name", "]", "=", "value", ";", "}", ")", ";", "}", ";", "}" ]
Creates new URI path-to-state object mapper. @param {RegExp} expression Regular expression to match URI path. @param {Array} parameters List of parameter descriptors. @returns {Function} URI mapper function.
[ "Creates", "new", "URI", "path", "-", "to", "-", "state", "object", "mapper", "." ]
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/helpers/routeHelper.js#L59-L82
train
catbee/catbee
lib/helpers/routeHelper.js
createUriQueryMapper
function createUriQueryMapper (query) { var parameters = extractQueryParameters(query); return (queryValues, args) => { queryValues = queryValues || Object.create(null); Object.keys(queryValues) .forEach(queryKey => { var parameter = parameters[queryKey]; if (!parameter) { return; } var value = util.isArray(queryValues[queryKey]) ? queryValues[queryKey] .map(parameter.map) .filter(value => value !== null) : parameter.map(queryValues[queryKey]); if (value === null) { return; } args[parameter.name] = value; }); }; }
javascript
function createUriQueryMapper (query) { var parameters = extractQueryParameters(query); return (queryValues, args) => { queryValues = queryValues || Object.create(null); Object.keys(queryValues) .forEach(queryKey => { var parameter = parameters[queryKey]; if (!parameter) { return; } var value = util.isArray(queryValues[queryKey]) ? queryValues[queryKey] .map(parameter.map) .filter(value => value !== null) : parameter.map(queryValues[queryKey]); if (value === null) { return; } args[parameter.name] = value; }); }; }
[ "function", "createUriQueryMapper", "(", "query", ")", "{", "var", "parameters", "=", "extractQueryParameters", "(", "query", ")", ";", "return", "(", "queryValues", ",", "args", ")", "=>", "{", "queryValues", "=", "queryValues", "||", "Object", ".", "create", "(", "null", ")", ";", "Object", ".", "keys", "(", "queryValues", ")", ".", "forEach", "(", "queryKey", "=>", "{", "var", "parameter", "=", "parameters", "[", "queryKey", "]", ";", "if", "(", "!", "parameter", ")", "{", "return", ";", "}", "var", "value", "=", "util", ".", "isArray", "(", "queryValues", "[", "queryKey", "]", ")", "?", "queryValues", "[", "queryKey", "]", ".", "map", "(", "parameter", ".", "map", ")", ".", "filter", "(", "value", "=>", "value", "!==", "null", ")", ":", "parameter", ".", "map", "(", "queryValues", "[", "queryKey", "]", ")", ";", "if", "(", "value", "===", "null", ")", "{", "return", ";", "}", "args", "[", "parameter", ".", "name", "]", "=", "value", ";", "}", ")", ";", "}", ";", "}" ]
Creates new URI query-to-args object mapper. @param {String} query Query string from uri mapping query parameter names. @returns {Function} URI mapper function.
[ "Creates", "new", "URI", "query", "-", "to", "-", "args", "object", "mapper", "." ]
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/helpers/routeHelper.js#L91-L117
train
catbee/catbee
lib/helpers/routeHelper.js
createUriQueryValueMapper
function createUriQueryValueMapper (expression) { return value => { value = value.toString(); var matches = value.match(expression); if (!matches || matches.length === 0) { return null; } // the value is the second item, the first is a whole string var mappedValue = matches[matches.length - 1]; try { mappedValue = decodeURIComponent(mappedValue); } catch (e) { // nothing to do } return mappedValue; }; }
javascript
function createUriQueryValueMapper (expression) { return value => { value = value.toString(); var matches = value.match(expression); if (!matches || matches.length === 0) { return null; } // the value is the second item, the first is a whole string var mappedValue = matches[matches.length - 1]; try { mappedValue = decodeURIComponent(mappedValue); } catch (e) { // nothing to do } return mappedValue; }; }
[ "function", "createUriQueryValueMapper", "(", "expression", ")", "{", "return", "value", "=>", "{", "value", "=", "value", ".", "toString", "(", ")", ";", "var", "matches", "=", "value", ".", "match", "(", "expression", ")", ";", "if", "(", "!", "matches", "||", "matches", ".", "length", "===", "0", ")", "{", "return", "null", ";", "}", "var", "mappedValue", "=", "matches", "[", "matches", ".", "length", "-", "1", "]", ";", "try", "{", "mappedValue", "=", "decodeURIComponent", "(", "mappedValue", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "return", "mappedValue", ";", "}", ";", "}" ]
Maps query parameter value using the parameters expression. @param {RegExp} expression Regular expression to get parameter value. @returns {Function} URI query string parameter value mapper function.
[ "Maps", "query", "parameter", "value", "using", "the", "parameters", "expression", "." ]
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/helpers/routeHelper.js#L124-L142
train
catbee/catbee
lib/helpers/routeHelper.js
getParameterDescriptor
function getParameterDescriptor (parameter) { var parts = parameter.split(SLASHED_BRACKETS_REG_EXP); return { name: parts[0].trim().substring(1) }; }
javascript
function getParameterDescriptor (parameter) { var parts = parameter.split(SLASHED_BRACKETS_REG_EXP); return { name: parts[0].trim().substring(1) }; }
[ "function", "getParameterDescriptor", "(", "parameter", ")", "{", "var", "parts", "=", "parameter", ".", "split", "(", "SLASHED_BRACKETS_REG_EXP", ")", ";", "return", "{", "name", ":", "parts", "[", "0", "]", ".", "trim", "(", ")", ".", "substring", "(", "1", ")", "}", ";", "}" ]
Gets description of parameters from its expression. @param {string} parameter Parameter expression. @returns {{name: string}} Parameter descriptor.
[ "Gets", "description", "of", "parameters", "from", "its", "expression", "." ]
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/helpers/routeHelper.js#L149-L155
train
catbee/catbee
lib/helpers/routeHelper.js
extractQueryParameters
function extractQueryParameters (query) { return Object.keys(query.values) .reduce((queryParameters, name) => { // arrays in routing definitions are not supported if (util.isArray(query.values[name])) { return queryParameters; } // escape regular expression characters var escaped = query.values[name].replace(EXPRESSION_ESCAPE_REG_EXP, '\\$&'); // get all occurrences of routing parameters in URI path var regExpSource = '^' + escaped.replace(PARAMETER_REG_EXP, URI_QUERY_REPLACEMENT_REG_EXP_SOURCE) + '$'; var queryParameterMatches = escaped.match(PARAMETER_REG_EXP); if (!queryParameterMatches || queryParameterMatches.length === 0) { return; } var parameter = getParameterDescriptor(queryParameterMatches[queryParameterMatches.length - 1]); var expression = new RegExp(regExpSource, 'i'); parameter.map = createUriQueryValueMapper(expression); queryParameters[name] = parameter; return queryParameters; }, Object.create(null)); }
javascript
function extractQueryParameters (query) { return Object.keys(query.values) .reduce((queryParameters, name) => { // arrays in routing definitions are not supported if (util.isArray(query.values[name])) { return queryParameters; } // escape regular expression characters var escaped = query.values[name].replace(EXPRESSION_ESCAPE_REG_EXP, '\\$&'); // get all occurrences of routing parameters in URI path var regExpSource = '^' + escaped.replace(PARAMETER_REG_EXP, URI_QUERY_REPLACEMENT_REG_EXP_SOURCE) + '$'; var queryParameterMatches = escaped.match(PARAMETER_REG_EXP); if (!queryParameterMatches || queryParameterMatches.length === 0) { return; } var parameter = getParameterDescriptor(queryParameterMatches[queryParameterMatches.length - 1]); var expression = new RegExp(regExpSource, 'i'); parameter.map = createUriQueryValueMapper(expression); queryParameters[name] = parameter; return queryParameters; }, Object.create(null)); }
[ "function", "extractQueryParameters", "(", "query", ")", "{", "return", "Object", ".", "keys", "(", "query", ".", "values", ")", ".", "reduce", "(", "(", "queryParameters", ",", "name", ")", "=>", "{", "if", "(", "util", ".", "isArray", "(", "query", ".", "values", "[", "name", "]", ")", ")", "{", "return", "queryParameters", ";", "}", "var", "escaped", "=", "query", ".", "values", "[", "name", "]", ".", "replace", "(", "EXPRESSION_ESCAPE_REG_EXP", ",", "'\\\\$&'", ")", ";", "\\\\", "var", "regExpSource", "=", "'^'", "+", "escaped", ".", "replace", "(", "PARAMETER_REG_EXP", ",", "URI_QUERY_REPLACEMENT_REG_EXP_SOURCE", ")", "+", "'$'", ";", "var", "queryParameterMatches", "=", "escaped", ".", "match", "(", "PARAMETER_REG_EXP", ")", ";", "if", "(", "!", "queryParameterMatches", "||", "queryParameterMatches", ".", "length", "===", "0", ")", "{", "return", ";", "}", "var", "parameter", "=", "getParameterDescriptor", "(", "queryParameterMatches", "[", "queryParameterMatches", ".", "length", "-", "1", "]", ")", ";", "var", "expression", "=", "new", "RegExp", "(", "regExpSource", ",", "'i'", ")", ";", "parameter", ".", "map", "=", "createUriQueryValueMapper", "(", "expression", ")", ";", "queryParameters", "[", "name", "]", "=", "parameter", ";", "}", ",", "return", "queryParameters", ";", ")", ";", "}" ]
Extracts query parameters to a key-value object @param {String} query @returns {Object} key-value query parameter map
[ "Extracts", "query", "parameters", "to", "a", "key", "-", "value", "object" ]
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/helpers/routeHelper.js#L162-L188
train
catbee/catbee
lib/helpers/routeHelper.js
compileStringRouteExpression
function compileStringRouteExpression (routeExpression) { var routeUri = new URI(routeExpression); routeUri.path = module.exports.removeEndSlash(routeUri.path); if (!routeUri) { return null; } // escape regular expression characters var escaped = routeUri.path.replace( EXPRESSION_ESCAPE_REG_EXP, '\\$&' ); // get all occurrences of routing parameters in URI path var regExpSource = '^' + escaped.replace(PARAMETER_REG_EXP, URI_PATH_REPLACEMENT_REG_EXP_SOURCE) + '$'; var expression = new RegExp(regExpSource, 'i'); var pathParameterMatches = escaped.match(PARAMETER_REG_EXP); var pathParameters = pathParameterMatches ? pathParameterMatches.map(getParameterDescriptor) : null; var pathMapper = pathParameters ? createUriPathMapper(expression, pathParameters) : null; var queryMapper = routeUri.query ? createUriQueryMapper(routeUri.query) : null; return { expression: expression, map: uri => { var args = Object.create(null); if (pathMapper) { pathMapper(uri.path, args); } if (queryMapper && uri.query) { queryMapper(uri.query.values, args); } return args; } }; }
javascript
function compileStringRouteExpression (routeExpression) { var routeUri = new URI(routeExpression); routeUri.path = module.exports.removeEndSlash(routeUri.path); if (!routeUri) { return null; } // escape regular expression characters var escaped = routeUri.path.replace( EXPRESSION_ESCAPE_REG_EXP, '\\$&' ); // get all occurrences of routing parameters in URI path var regExpSource = '^' + escaped.replace(PARAMETER_REG_EXP, URI_PATH_REPLACEMENT_REG_EXP_SOURCE) + '$'; var expression = new RegExp(regExpSource, 'i'); var pathParameterMatches = escaped.match(PARAMETER_REG_EXP); var pathParameters = pathParameterMatches ? pathParameterMatches.map(getParameterDescriptor) : null; var pathMapper = pathParameters ? createUriPathMapper(expression, pathParameters) : null; var queryMapper = routeUri.query ? createUriQueryMapper(routeUri.query) : null; return { expression: expression, map: uri => { var args = Object.create(null); if (pathMapper) { pathMapper(uri.path, args); } if (queryMapper && uri.query) { queryMapper(uri.query.values, args); } return args; } }; }
[ "function", "compileStringRouteExpression", "(", "routeExpression", ")", "{", "var", "routeUri", "=", "new", "URI", "(", "routeExpression", ")", ";", "routeUri", ".", "path", "=", "module", ".", "exports", ".", "removeEndSlash", "(", "routeUri", ".", "path", ")", ";", "if", "(", "!", "routeUri", ")", "{", "return", "null", ";", "}", "var", "escaped", "=", "routeUri", ".", "path", ".", "replace", "(", "EXPRESSION_ESCAPE_REG_EXP", ",", "'\\\\$&'", ")", ";", "\\\\", "var", "regExpSource", "=", "'^'", "+", "escaped", ".", "replace", "(", "PARAMETER_REG_EXP", ",", "URI_PATH_REPLACEMENT_REG_EXP_SOURCE", ")", "+", "'$'", ";", "var", "expression", "=", "new", "RegExp", "(", "regExpSource", ",", "'i'", ")", ";", "var", "pathParameterMatches", "=", "escaped", ".", "match", "(", "PARAMETER_REG_EXP", ")", ";", "var", "pathParameters", "=", "pathParameterMatches", "?", "pathParameterMatches", ".", "map", "(", "getParameterDescriptor", ")", ":", "null", ";", "var", "pathMapper", "=", "pathParameters", "?", "createUriPathMapper", "(", "expression", ",", "pathParameters", ")", ":", "null", ";", "var", "queryMapper", "=", "routeUri", ".", "query", "?", "createUriQueryMapper", "(", "routeUri", ".", "query", ")", ":", "null", ";", "}" ]
Creates a mapper for string route definition @param {String} routeExpression string route uri definition @returns {{expression: RegExp, map: Function}|null} URI mapper object.
[ "Creates", "a", "mapper", "for", "string", "route", "definition" ]
bddc7012d973ec3e147b07cee02bf3ad52fc99cd
https://github.com/catbee/catbee/blob/bddc7012d973ec3e147b07cee02bf3ad52fc99cd/lib/helpers/routeHelper.js#L195-L232
train
datanews/tables
lib/utils.js
toSQLName
function toSQLName(input) { return !input || _.isObject(input) || _.isArray(input) || _.isNaN(input) ? undefined : input.toString().toLowerCase() .replace(/\W+/g, " ") .trim() .replace(/\s+/g, "_") .replace(/_+/g, "_") .substring(0, 64); }
javascript
function toSQLName(input) { return !input || _.isObject(input) || _.isArray(input) || _.isNaN(input) ? undefined : input.toString().toLowerCase() .replace(/\W+/g, " ") .trim() .replace(/\s+/g, "_") .replace(/_+/g, "_") .substring(0, 64); }
[ "function", "toSQLName", "(", "input", ")", "{", "return", "!", "input", "||", "_", ".", "isObject", "(", "input", ")", "||", "_", ".", "isArray", "(", "input", ")", "||", "_", ".", "isNaN", "(", "input", ")", "?", "undefined", ":", "input", ".", "toString", "(", ")", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "\\W+", "/", "g", ",", "\" \"", ")", ".", "trim", "(", ")", ".", "replace", "(", "/", "\\s+", "/", "g", ",", "\"_\"", ")", ".", "replace", "(", "/", "_+", "/", "g", ",", "\"_\"", ")", ".", "substring", "(", "0", ",", "64", ")", ";", "}" ]
Make into a standardize name for SQL tables or columns
[ "Make", "into", "a", "standardize", "name", "for", "SQL", "tables", "or", "columns" ]
4b33aa7a944a93260c49baecbb90345211cac789
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/utils.js#L11-L19
train
datanews/tables
lib/utils.js
standardizeInput
function standardizeInput(input) { if ([undefined, null].indexOf(input) !== -1) { input = null; } else if (_.isNaN(input)) { input = null; } else if (_.isString(input)) { input = input.trim(); // Written empty values if (["unspecified", "unknown", "none", "null", "empty", ""].indexOf(input.toLowerCase()) !== -1) { input = null; } } return input; }
javascript
function standardizeInput(input) { if ([undefined, null].indexOf(input) !== -1) { input = null; } else if (_.isNaN(input)) { input = null; } else if (_.isString(input)) { input = input.trim(); // Written empty values if (["unspecified", "unknown", "none", "null", "empty", ""].indexOf(input.toLowerCase()) !== -1) { input = null; } } return input; }
[ "function", "standardizeInput", "(", "input", ")", "{", "if", "(", "[", "undefined", ",", "null", "]", ".", "indexOf", "(", "input", ")", "!==", "-", "1", ")", "{", "input", "=", "null", ";", "}", "else", "if", "(", "_", ".", "isNaN", "(", "input", ")", ")", "{", "input", "=", "null", ";", "}", "else", "if", "(", "_", ".", "isString", "(", "input", ")", ")", "{", "input", "=", "input", ".", "trim", "(", ")", ";", "if", "(", "[", "\"unspecified\"", ",", "\"unknown\"", ",", "\"none\"", ",", "\"null\"", ",", "\"empty\"", ",", "\"\"", "]", ".", "indexOf", "(", "input", ".", "toLowerCase", "(", ")", ")", "!==", "-", "1", ")", "{", "input", "=", "null", ";", "}", "}", "return", "input", ";", "}" ]
Standardize input, like handling empty
[ "Standardize", "input", "like", "handling", "empty" ]
4b33aa7a944a93260c49baecbb90345211cac789
https://github.com/datanews/tables/blob/4b33aa7a944a93260c49baecbb90345211cac789/lib/utils.js#L31-L48
train
suitcss/rework-suit
index.js
suit
function suit(options) { options = options || {}; // for backwards compatibility with rework-npm < 1.0.0 options.root = options.root || options.dir; return function (ast, reworkObj) { reworkObj // inline imports .use(inliner({ alias: options.alias, prefilter: function (css) { // per-file conformance checks return rework(css).use(conformance).toString(); }, root: options.root, shim: options.shim, })) // check if the number of selectors exceeds the IE limit .use(limits) // custom media queries .use(customMedia) // variables .use(vars()) // calc .use(calc); }; }
javascript
function suit(options) { options = options || {}; // for backwards compatibility with rework-npm < 1.0.0 options.root = options.root || options.dir; return function (ast, reworkObj) { reworkObj // inline imports .use(inliner({ alias: options.alias, prefilter: function (css) { // per-file conformance checks return rework(css).use(conformance).toString(); }, root: options.root, shim: options.shim, })) // check if the number of selectors exceeds the IE limit .use(limits) // custom media queries .use(customMedia) // variables .use(vars()) // calc .use(calc); }; }
[ "function", "suit", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "options", ".", "root", "=", "options", ".", "root", "||", "options", ".", "dir", ";", "return", "function", "(", "ast", ",", "reworkObj", ")", "{", "reworkObj", ".", "use", "(", "inliner", "(", "{", "alias", ":", "options", ".", "alias", ",", "prefilter", ":", "function", "(", "css", ")", "{", "return", "rework", "(", "css", ")", ".", "use", "(", "conformance", ")", ".", "toString", "(", ")", ";", "}", ",", "root", ":", "options", ".", "root", ",", "shim", ":", "options", ".", "shim", ",", "}", ")", ")", ".", "use", "(", "limits", ")", ".", "use", "(", "customMedia", ")", ".", "use", "(", "vars", "(", ")", ")", ".", "use", "(", "calc", ")", ";", "}", ";", "}" ]
Apply rework plugins to a rework instance; export as a rework plugin @param {String} ast Rework AST @param {Object} reworkObj Rework instance
[ "Apply", "rework", "plugins", "to", "a", "rework", "instance", ";", "export", "as", "a", "rework", "plugin" ]
49eb81ab749d839c0410066eef7c71d2b7d8bd0c
https://github.com/suitcss/rework-suit/blob/49eb81ab749d839c0410066eef7c71d2b7d8bd0c/index.js#L28-L54
train
sebpiq/backbone.statemachine
backbone.statemachine.js
function(leaveState, event, data) { // If `data` is a string, it is the destination state of the transition if (_.isString(data)) data = {enterState: data} else data = _.clone(data) if (leaveState !== ANY_STATE && !this._states.hasOwnProperty(leaveState)) this.state(leaveState, {}) if (!this._states.hasOwnProperty(data.enterState)) this.state(data.enterState, {}) if (!this._transitions.hasOwnProperty(leaveState)) this._transitions[leaveState] = {} data.callbacks = this._collectMethods((data.callbacks || [])) this._transitions[leaveState][event] = data }
javascript
function(leaveState, event, data) { // If `data` is a string, it is the destination state of the transition if (_.isString(data)) data = {enterState: data} else data = _.clone(data) if (leaveState !== ANY_STATE && !this._states.hasOwnProperty(leaveState)) this.state(leaveState, {}) if (!this._states.hasOwnProperty(data.enterState)) this.state(data.enterState, {}) if (!this._transitions.hasOwnProperty(leaveState)) this._transitions[leaveState] = {} data.callbacks = this._collectMethods((data.callbacks || [])) this._transitions[leaveState][event] = data }
[ "function", "(", "leaveState", ",", "event", ",", "data", ")", "{", "if", "(", "_", ".", "isString", "(", "data", ")", ")", "data", "=", "{", "enterState", ":", "data", "}", "else", "data", "=", "_", ".", "clone", "(", "data", ")", "if", "(", "leaveState", "!==", "ANY_STATE", "&&", "!", "this", ".", "_states", ".", "hasOwnProperty", "(", "leaveState", ")", ")", "this", ".", "state", "(", "leaveState", ",", "{", "}", ")", "if", "(", "!", "this", ".", "_states", ".", "hasOwnProperty", "(", "data", ".", "enterState", ")", ")", "this", ".", "state", "(", "data", ".", "enterState", ",", "{", "}", ")", "if", "(", "!", "this", ".", "_transitions", ".", "hasOwnProperty", "(", "leaveState", ")", ")", "this", ".", "_transitions", "[", "leaveState", "]", "=", "{", "}", "data", ".", "callbacks", "=", "this", ".", "_collectMethods", "(", "(", "data", ".", "callbacks", "||", "[", "]", ")", ")", "this", ".", "_transitions", "[", "leaveState", "]", "[", "event", "]", "=", "data", "}" ]
Declares a new transition on the state machine.
[ "Declares", "a", "new", "transition", "on", "the", "state", "machine", "." ]
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L69-L85
train
sebpiq/backbone.statemachine
backbone.statemachine.js
function(name, data) { if (name === ANY_STATE) throw new Error('state name "' + ANY_STATE + '" is forbidden') data = _.clone(data) data.enter = this._collectMethods((data.enter || [])) data.leave = this._collectMethods((data.leave || [])) this._states[name] = data }
javascript
function(name, data) { if (name === ANY_STATE) throw new Error('state name "' + ANY_STATE + '" is forbidden') data = _.clone(data) data.enter = this._collectMethods((data.enter || [])) data.leave = this._collectMethods((data.leave || [])) this._states[name] = data }
[ "function", "(", "name", ",", "data", ")", "{", "if", "(", "name", "===", "ANY_STATE", ")", "throw", "new", "Error", "(", "'state name \"'", "+", "ANY_STATE", "+", "'\" is forbidden'", ")", "data", "=", "_", ".", "clone", "(", "data", ")", "data", ".", "enter", "=", "this", ".", "_collectMethods", "(", "(", "data", ".", "enter", "||", "[", "]", ")", ")", "data", ".", "leave", "=", "this", ".", "_collectMethods", "(", "(", "data", ".", "leave", "||", "[", "]", ")", ")", "this", ".", "_states", "[", "name", "]", "=", "data", "}" ]
Declares a new state on the state machine
[ "Declares", "a", "new", "state", "on", "the", "state", "machine" ]
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L88-L96
train
sebpiq/backbone.statemachine
backbone.statemachine.js
function() { var events = _.reduce(_.values(this._transitions), function(memo, transitions) { return memo.concat(_.keys(transitions)) }, []) return _.uniq(events) }
javascript
function() { var events = _.reduce(_.values(this._transitions), function(memo, transitions) { return memo.concat(_.keys(transitions)) }, []) return _.uniq(events) }
[ "function", "(", ")", "{", "var", "events", "=", "_", ".", "reduce", "(", "_", ".", "values", "(", "this", ".", "_transitions", ")", ",", "function", "(", "memo", ",", "transitions", ")", "{", "return", "memo", ".", "concat", "(", "_", ".", "keys", "(", "transitions", ")", ")", "}", ",", "[", "]", ")", "return", "_", ".", "uniq", "(", "events", ")", "}" ]
Returns the list of all events that can trigger a transition
[ "Returns", "the", "list", "of", "all", "events", "that", "can", "trigger", "a", "transition" ]
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L110-L115
train
sebpiq/backbone.statemachine
backbone.statemachine.js
function(event) { var data, extraArgs, key, transitions = this._transitions if (transitions.hasOwnProperty((key = this.currentState)) && transitions[key].hasOwnProperty(event)) { data = transitions[key][event] } else if (transitions.hasOwnProperty(ANY_STATE) && transitions[ANY_STATE].hasOwnProperty(event)) { data = transitions[ANY_STATE][event] } else return extraArgs = _.toArray(arguments).slice(1) this._doTransition.apply(this, [data, event].concat(extraArgs)) }
javascript
function(event) { var data, extraArgs, key, transitions = this._transitions if (transitions.hasOwnProperty((key = this.currentState)) && transitions[key].hasOwnProperty(event)) { data = transitions[key][event] } else if (transitions.hasOwnProperty(ANY_STATE) && transitions[ANY_STATE].hasOwnProperty(event)) { data = transitions[ANY_STATE][event] } else return extraArgs = _.toArray(arguments).slice(1) this._doTransition.apply(this, [data, event].concat(extraArgs)) }
[ "function", "(", "event", ")", "{", "var", "data", ",", "extraArgs", ",", "key", ",", "transitions", "=", "this", ".", "_transitions", "if", "(", "transitions", ".", "hasOwnProperty", "(", "(", "key", "=", "this", ".", "currentState", ")", ")", "&&", "transitions", "[", "key", "]", ".", "hasOwnProperty", "(", "event", ")", ")", "{", "data", "=", "transitions", "[", "key", "]", "[", "event", "]", "}", "else", "if", "(", "transitions", ".", "hasOwnProperty", "(", "ANY_STATE", ")", "&&", "transitions", "[", "ANY_STATE", "]", ".", "hasOwnProperty", "(", "event", ")", ")", "{", "data", "=", "transitions", "[", "ANY_STATE", "]", "[", "event", "]", "}", "else", "return", "extraArgs", "=", "_", ".", "toArray", "(", "arguments", ")", ".", "slice", "(", "1", ")", "this", ".", "_doTransition", ".", "apply", "(", "this", ",", "[", "data", ",", "event", "]", ".", "concat", "(", "extraArgs", ")", ")", "}" ]
Callback bound to all events. If no transition available, do nothing. Otherwise, starts the transition.
[ "Callback", "bound", "to", "all", "events", ".", "If", "no", "transition", "available", "do", "nothing", ".", "Otherwise", "starts", "the", "transition", "." ]
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L119-L131
train
sebpiq/backbone.statemachine
backbone.statemachine.js
function(data, event) { var extraArgs = _.toArray(arguments).slice(2), leaveState = this.currentState, enterState = data.enterState, triggers = data.triggers if (!this.silent) this.trigger.apply(this, ['leaveState:' + leaveState].concat(extraArgs)) this._callCallbacks(this._states[leaveState].leave, extraArgs) if (!this.silent) { this.trigger.apply(this, ['transition', leaveState, enterState].concat(extraArgs)) if (triggers) this.trigger.apply(this, [triggers].concat(extraArgs)) } this._callCallbacks(data.callbacks, extraArgs) if (!this.silent) this.trigger.apply(this, ['enterState:' + enterState].concat(extraArgs)) this.toState.apply(this, [enterState].concat(extraArgs)) }
javascript
function(data, event) { var extraArgs = _.toArray(arguments).slice(2), leaveState = this.currentState, enterState = data.enterState, triggers = data.triggers if (!this.silent) this.trigger.apply(this, ['leaveState:' + leaveState].concat(extraArgs)) this._callCallbacks(this._states[leaveState].leave, extraArgs) if (!this.silent) { this.trigger.apply(this, ['transition', leaveState, enterState].concat(extraArgs)) if (triggers) this.trigger.apply(this, [triggers].concat(extraArgs)) } this._callCallbacks(data.callbacks, extraArgs) if (!this.silent) this.trigger.apply(this, ['enterState:' + enterState].concat(extraArgs)) this.toState.apply(this, [enterState].concat(extraArgs)) }
[ "function", "(", "data", ",", "event", ")", "{", "var", "extraArgs", "=", "_", ".", "toArray", "(", "arguments", ")", ".", "slice", "(", "2", ")", ",", "leaveState", "=", "this", ".", "currentState", ",", "enterState", "=", "data", ".", "enterState", ",", "triggers", "=", "data", ".", "triggers", "if", "(", "!", "this", ".", "silent", ")", "this", ".", "trigger", ".", "apply", "(", "this", ",", "[", "'leaveState:'", "+", "leaveState", "]", ".", "concat", "(", "extraArgs", ")", ")", "this", ".", "_callCallbacks", "(", "this", ".", "_states", "[", "leaveState", "]", ".", "leave", ",", "extraArgs", ")", "if", "(", "!", "this", ".", "silent", ")", "{", "this", ".", "trigger", ".", "apply", "(", "this", ",", "[", "'transition'", ",", "leaveState", ",", "enterState", "]", ".", "concat", "(", "extraArgs", ")", ")", "if", "(", "triggers", ")", "this", ".", "trigger", ".", "apply", "(", "this", ",", "[", "triggers", "]", ".", "concat", "(", "extraArgs", ")", ")", "}", "this", ".", "_callCallbacks", "(", "data", ".", "callbacks", ",", "extraArgs", ")", "if", "(", "!", "this", ".", "silent", ")", "this", ".", "trigger", ".", "apply", "(", "this", ",", "[", "'enterState:'", "+", "enterState", "]", ".", "concat", "(", "extraArgs", ")", ")", "this", ".", "toState", ".", "apply", "(", "this", ",", "[", "enterState", "]", ".", "concat", "(", "extraArgs", ")", ")", "}" ]
Executes a transition.
[ "Executes", "a", "transition", "." ]
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L134-L155
train
sebpiq/backbone.statemachine
backbone.statemachine.js
function(methodNames) { var methods = [], i, length, method for (i = 0, length = methodNames.length; i < length; i++) { // first, check if this is an anonymous function if (_.isFunction(methodNames[i])) method = methodNames[i] else { // else, get the function from the View method = this[methodNames[i]] if (!method) throw new Error('Method "' + methodNames[i] + '" does not exist') } methods.push(method) } return methods }
javascript
function(methodNames) { var methods = [], i, length, method for (i = 0, length = methodNames.length; i < length; i++) { // first, check if this is an anonymous function if (_.isFunction(methodNames[i])) method = methodNames[i] else { // else, get the function from the View method = this[methodNames[i]] if (!method) throw new Error('Method "' + methodNames[i] + '" does not exist') } methods.push(method) } return methods }
[ "function", "(", "methodNames", ")", "{", "var", "methods", "=", "[", "]", ",", "i", ",", "length", ",", "method", "for", "(", "i", "=", "0", ",", "length", "=", "methodNames", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "_", ".", "isFunction", "(", "methodNames", "[", "i", "]", ")", ")", "method", "=", "methodNames", "[", "i", "]", "else", "{", "method", "=", "this", "[", "methodNames", "[", "i", "]", "]", "if", "(", "!", "method", ")", "throw", "new", "Error", "(", "'Method \"'", "+", "methodNames", "[", "i", "]", "+", "'\" does not exist'", ")", "}", "methods", ".", "push", "(", "method", ")", "}", "return", "methods", "}" ]
Helper for collecting callbacks provided as strings.
[ "Helper", "for", "collecting", "callbacks", "provided", "as", "strings", "." ]
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L187-L203
train
sebpiq/backbone.statemachine
backbone.statemachine.js
function(cbArray, extraArgs) { var i, length for (i = 0, length = cbArray.length; i < length; i++) cbArray[i].apply(this, extraArgs) }
javascript
function(cbArray, extraArgs) { var i, length for (i = 0, length = cbArray.length; i < length; i++) cbArray[i].apply(this, extraArgs) }
[ "function", "(", "cbArray", ",", "extraArgs", ")", "{", "var", "i", ",", "length", "for", "(", "i", "=", "0", ",", "length", "=", "cbArray", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "cbArray", "[", "i", "]", ".", "apply", "(", "this", ",", "extraArgs", ")", "}" ]
Helper for calling a list of callbacks.
[ "Helper", "for", "calling", "a", "list", "of", "callbacks", "." ]
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L206-L211
train
sebpiq/backbone.statemachine
backbone.statemachine.js
function(instance) { // If this is the first state machine registered in the debugger, // we create the debugger's html. if (this.viewsArray.length === 0) { var container = this.el = $('<div id="backbone-statemachine-debug-container">'+ '<h3>backbone.statemachine: DEBUGGER</h3>'+ '<a id="backbone-statemachine-debug-hideshow">hide</a>'+ '<style>'+ '#backbone-statemachine-debug-container{background-color:rgba(0,0,0,0.5);position:absolute;height:300px;width:300px;right:0;top:0;padding:10px;z-index:10;-moz-border-radius-bottomleft:30px;-webkit-border-radius-bottomleft:30px;border-bottom-left-radius:30px;}'+ '#backbone-statemachine-debug-container.collapsed{height:20px;width:60px;}'+ '#backbone-statemachine-debug-container a{color:blue;cursor:pointer;}'+ '#backbone-statemachine-debug-container h3{margin:0;text-align:center;color:white;margin-bottom:0.5em;}'+ '.backbone-statemachine-debug{width:60px;height:60px;-moz-border-radius:30px;-webkit-border-radius:30px;border-radius:30px;text-align:center;}'+ '.backbone-statemachine-debug .state{font-weight:bold;}'+ 'a#backbone-statemachine-debug-hideshow{position:absolute;bottom:12px;left:12px;font-weight:bold;color:white;}'+ '</style></div>' ).appendTo($('body')) $('#backbone-statemachine-debug-hideshow', this.el).click(function(event){ event.preventDefault() if (this.collapsed) { $(container).removeClass('collapsed').children().show() $(this).html('hide') this.collapsed = false } else { $(container).addClass('collapsed').children().hide() $(this).html('show').show() this.collapsed = true } }) } // create the debug view, pick a random color for it, and add it to the debugger. var debugView = new this({model: instance}) var bgColor = this.pickColor() $(debugView.el).appendTo(this.el).css({'background-color': bgColor}) debugView.render() if (this.collapsed) $(debugView.el).hide() this.viewsArray.push(debugView) }
javascript
function(instance) { // If this is the first state machine registered in the debugger, // we create the debugger's html. if (this.viewsArray.length === 0) { var container = this.el = $('<div id="backbone-statemachine-debug-container">'+ '<h3>backbone.statemachine: DEBUGGER</h3>'+ '<a id="backbone-statemachine-debug-hideshow">hide</a>'+ '<style>'+ '#backbone-statemachine-debug-container{background-color:rgba(0,0,0,0.5);position:absolute;height:300px;width:300px;right:0;top:0;padding:10px;z-index:10;-moz-border-radius-bottomleft:30px;-webkit-border-radius-bottomleft:30px;border-bottom-left-radius:30px;}'+ '#backbone-statemachine-debug-container.collapsed{height:20px;width:60px;}'+ '#backbone-statemachine-debug-container a{color:blue;cursor:pointer;}'+ '#backbone-statemachine-debug-container h3{margin:0;text-align:center;color:white;margin-bottom:0.5em;}'+ '.backbone-statemachine-debug{width:60px;height:60px;-moz-border-radius:30px;-webkit-border-radius:30px;border-radius:30px;text-align:center;}'+ '.backbone-statemachine-debug .state{font-weight:bold;}'+ 'a#backbone-statemachine-debug-hideshow{position:absolute;bottom:12px;left:12px;font-weight:bold;color:white;}'+ '</style></div>' ).appendTo($('body')) $('#backbone-statemachine-debug-hideshow', this.el).click(function(event){ event.preventDefault() if (this.collapsed) { $(container).removeClass('collapsed').children().show() $(this).html('hide') this.collapsed = false } else { $(container).addClass('collapsed').children().hide() $(this).html('show').show() this.collapsed = true } }) } // create the debug view, pick a random color for it, and add it to the debugger. var debugView = new this({model: instance}) var bgColor = this.pickColor() $(debugView.el).appendTo(this.el).css({'background-color': bgColor}) debugView.render() if (this.collapsed) $(debugView.el).hide() this.viewsArray.push(debugView) }
[ "function", "(", "instance", ")", "{", "if", "(", "this", ".", "viewsArray", ".", "length", "===", "0", ")", "{", "var", "container", "=", "this", ".", "el", "=", "$", "(", "'<div id=\"backbone-statemachine-debug-container\">'", "+", "'<h3>backbone.statemachine: DEBUGGER</h3>'", "+", "'<a id=\"backbone-statemachine-debug-hideshow\">hide</a>'", "+", "'<style>'", "+", "'#backbone-statemachine-debug-container{background-color:rgba(0,0,0,0.5);position:absolute;height:300px;width:300px;right:0;top:0;padding:10px;z-index:10;-moz-border-radius-bottomleft:30px;-webkit-border-radius-bottomleft:30px;border-bottom-left-radius:30px;}'", "+", "'#backbone-statemachine-debug-container.collapsed{height:20px;width:60px;}'", "+", "'#backbone-statemachine-debug-container a{color:blue;cursor:pointer;}'", "+", "'#backbone-statemachine-debug-container h3{margin:0;text-align:center;color:white;margin-bottom:0.5em;}'", "+", "'.backbone-statemachine-debug{width:60px;height:60px;-moz-border-radius:30px;-webkit-border-radius:30px;border-radius:30px;text-align:center;}'", "+", "'.backbone-statemachine-debug .state{font-weight:bold;}'", "+", "'a#backbone-statemachine-debug-hideshow{position:absolute;bottom:12px;left:12px;font-weight:bold;color:white;}'", "+", "'</style></div>'", ")", ".", "appendTo", "(", "$", "(", "'body'", ")", ")", "$", "(", "'#backbone-statemachine-debug-hideshow'", ",", "this", ".", "el", ")", ".", "click", "(", "function", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", "if", "(", "this", ".", "collapsed", ")", "{", "$", "(", "container", ")", ".", "removeClass", "(", "'collapsed'", ")", ".", "children", "(", ")", ".", "show", "(", ")", "$", "(", "this", ")", ".", "html", "(", "'hide'", ")", "this", ".", "collapsed", "=", "false", "}", "else", "{", "$", "(", "container", ")", ".", "addClass", "(", "'collapsed'", ")", ".", "children", "(", ")", ".", "hide", "(", ")", "$", "(", "this", ")", ".", "html", "(", "'show'", ")", ".", "show", "(", ")", "this", ".", "collapsed", "=", "true", "}", "}", ")", "}", "var", "debugView", "=", "new", "this", "(", "{", "model", ":", "instance", "}", ")", "var", "bgColor", "=", "this", ".", "pickColor", "(", ")", "$", "(", "debugView", ".", "el", ")", ".", "appendTo", "(", "this", ".", "el", ")", ".", "css", "(", "{", "'background-color'", ":", "bgColor", "}", ")", "debugView", ".", "render", "(", ")", "if", "(", "this", ".", "collapsed", ")", "$", "(", "debugView", ".", "el", ")", ".", "hide", "(", ")", "this", ".", "viewsArray", ".", "push", "(", "debugView", ")", "}" ]
Registers a state machine in the debugger, so that a debug view will be created for it.
[ "Registers", "a", "state", "machine", "in", "the", "debugger", "so", "that", "a", "debug", "view", "will", "be", "created", "for", "it", "." ]
6ba1852f077bad4f09994ad2c8e93d2f3a0a17af
https://github.com/sebpiq/backbone.statemachine/blob/6ba1852f077bad4f09994ad2c8e93d2f3a0a17af/backbone.statemachine.js#L340-L378
train
hex7c0/basic-authentication
index.js
basic_medium
function basic_medium(req, res, next) { var auth = basic_small(req); if (auth !== '') { if (check(auth, my.hash, my.file) === true) { // check if different return setHeader(res, 'WWW-Authenticate', my.realms) === true ? end_work(err, next, 401) : null; } if (my.agent === '' || my.agent === req.headers['user-agent']) { // check UA return end_work(err, next); } return end_work(err, next, 403); } // first attempt res.writeHead(401, my.realm); res.end(); }
javascript
function basic_medium(req, res, next) { var auth = basic_small(req); if (auth !== '') { if (check(auth, my.hash, my.file) === true) { // check if different return setHeader(res, 'WWW-Authenticate', my.realms) === true ? end_work(err, next, 401) : null; } if (my.agent === '' || my.agent === req.headers['user-agent']) { // check UA return end_work(err, next); } return end_work(err, next, 403); } // first attempt res.writeHead(401, my.realm); res.end(); }
[ "function", "basic_medium", "(", "req", ",", "res", ",", "next", ")", "{", "var", "auth", "=", "basic_small", "(", "req", ")", ";", "if", "(", "auth", "!==", "''", ")", "{", "if", "(", "check", "(", "auth", ",", "my", ".", "hash", ",", "my", ".", "file", ")", "===", "true", ")", "{", "return", "setHeader", "(", "res", ",", "'WWW-Authenticate'", ",", "my", ".", "realms", ")", "===", "true", "?", "end_work", "(", "err", ",", "next", ",", "401", ")", ":", "null", ";", "}", "if", "(", "my", ".", "agent", "===", "''", "||", "my", ".", "agent", "===", "req", ".", "headers", "[", "'user-agent'", "]", ")", "{", "return", "end_work", "(", "err", ",", "next", ")", ";", "}", "return", "end_work", "(", "err", ",", "next", ",", "403", ")", ";", "}", "res", ".", "writeHead", "(", "401", ",", "my", ".", "realm", ")", ";", "res", ".", "end", "(", ")", ";", "}" ]
protection middleware with basic authentication without res.end @function basic_medium @param {Object} req - client request @param {Object} res - response to client @param {next} [next] - continue routes
[ "protection", "middleware", "with", "basic", "authentication", "without", "res", ".", "end" ]
2eacf41a3e54c9fce884b3acfe057f77942a30e5
https://github.com/hex7c0/basic-authentication/blob/2eacf41a3e54c9fce884b3acfe057f77942a30e5/index.js#L234-L253
train
Zeindelf/utilify-js
dist/utilify.esm.js
pad
function pad(number, size) { var stringNum = String(number); while (stringNum.length < (size || 2)) { stringNum = '0' + stringNum; } return stringNum; }
javascript
function pad(number, size) { var stringNum = String(number); while (stringNum.length < (size || 2)) { stringNum = '0' + stringNum; } return stringNum; }
[ "function", "pad", "(", "number", ",", "size", ")", "{", "var", "stringNum", "=", "String", "(", "number", ")", ";", "while", "(", "stringNum", ".", "length", "<", "(", "size", "||", "2", ")", ")", "{", "stringNum", "=", "'0'", "+", "stringNum", ";", "}", "return", "stringNum", ";", "}" ]
Zero padding number @param {integer} number Number to format @param {integer} [size=2] Digits limit @return {string} Formatted num with zero padding
[ "Zero", "padding", "number" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L702-L710
train
Zeindelf/utilify-js
dist/utilify.esm.js
strCompact
function strCompact(str) { return this.trim(str).replace(/([\r\n\s])+/g, function (match, whitespace) { return whitespace === ' ' ? whitespace : ' '; }); }
javascript
function strCompact(str) { return this.trim(str).replace(/([\r\n\s])+/g, function (match, whitespace) { return whitespace === ' ' ? whitespace : ' '; }); }
[ "function", "strCompact", "(", "str", ")", "{", "return", "this", ".", "trim", "(", "str", ")", ".", "replace", "(", "/", "([\\r\\n\\s])+", "/", "g", ",", "function", "(", "match", ",", "whitespace", ")", "{", "return", "whitespace", "===", "' ' ?", "?", "w", "itespace :", "'", "';", "}", ")", ";", "}" ]
Compacts whitespace in the string to a single space and trims the ends. @param {String} [str] String to remove spaces @return {String} @example strCompact(' Foo Bar Baz ') // 'Foo Bar Baz'
[ "Compacts", "whitespace", "in", "the", "string", "to", "a", "single", "space", "and", "trims", "the", "ends", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L772-L776
train
Zeindelf/utilify-js
dist/utilify.esm.js
strReplace
function strReplace(search, replace, subject) { var regex = void 0; if (validateHelpers.isArray(search)) { for (var i = 0; i < search.length; i++) { search[i] = search[i].replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); regex = new RegExp(search[i], 'g'); subject = subject.replace(regex, validateHelpers.isArray(replace) ? replace[i] : replace); } } else { search = search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); regex = new RegExp(search, 'g'); subject = subject.replace(regex, validateHelpers.isArray(replace) ? replace[0] : replace); } return subject; }
javascript
function strReplace(search, replace, subject) { var regex = void 0; if (validateHelpers.isArray(search)) { for (var i = 0; i < search.length; i++) { search[i] = search[i].replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); regex = new RegExp(search[i], 'g'); subject = subject.replace(regex, validateHelpers.isArray(replace) ? replace[i] : replace); } } else { search = search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); regex = new RegExp(search, 'g'); subject = subject.replace(regex, validateHelpers.isArray(replace) ? replace[0] : replace); } return subject; }
[ "function", "strReplace", "(", "search", ",", "replace", ",", "subject", ")", "{", "var", "regex", "=", "void", "0", ";", "if", "(", "validateHelpers", ".", "isArray", "(", "search", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "search", ".", "length", ";", "i", "++", ")", "{", "search", "[", "i", "]", "=", "search", "[", "i", "]", ".", "replace", "(", "/", "[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]", "/", "g", ",", "'\\\\$&'", ")", ";", "\\\\", "regex", "=", "new", "RegExp", "(", "search", "[", "i", "]", ",", "'g'", ")", ";", "}", "}", "else", "subject", "=", "subject", ".", "replace", "(", "regex", ",", "validateHelpers", ".", "isArray", "(", "replace", ")", "?", "replace", "[", "i", "]", ":", "replace", ")", ";", "{", "search", "=", "search", ".", "replace", "(", "/", "[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]", "/", "g", ",", "'\\\\$&'", ")", ";", "\\\\", "regex", "=", "new", "RegExp", "(", "search", ",", "'g'", ")", ";", "}", "}" ]
Multiple string replace, PHP str_replace clone @param {string|Array} search - The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles. @param {string|Array} replace - The replacement value that replaces found search values. An array may be used to designate multiple replacements. @param {string} subject - The subject of the replacement @return {string} The modified string @example strReplace(['olá', 'mundo'], ['hello', 'world'], 'olá mundo'); // 'hello world' strReplace(['um', 'dois'], 'olá', 'um dois três'); // Output 'olá olá três'
[ "Multiple", "string", "replace", "PHP", "str_replace", "clone" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L791-L807
train
Zeindelf/utilify-js
dist/utilify.esm.js
underscore
function underscore(str) { return str.replace(/[-\s]+/g, '_').replace(/([A-Z\d]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z\d])([A-Z])/g, '$1_$2').toLowerCase(); }
javascript
function underscore(str) { return str.replace(/[-\s]+/g, '_').replace(/([A-Z\d]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z\d])([A-Z])/g, '$1_$2').toLowerCase(); }
[ "function", "underscore", "(", "str", ")", "{", "return", "str", ".", "replace", "(", "/", "[-\\s]+", "/", "g", ",", "'_'", ")", ".", "replace", "(", "/", "([A-Z\\d]+)([A-Z][a-z])", "/", "g", ",", "'$1_$2'", ")", ".", "replace", "(", "/", "([a-z\\d])([A-Z])", "/", "g", ",", "'$1_$2'", ")", ".", "toLowerCase", "(", ")", ";", "}" ]
Converts hyphens and camel casing to underscores. @param {String} str String to convert @return {String}
[ "Converts", "hyphens", "and", "camel", "casing", "to", "underscores", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L850-L852
train
Zeindelf/utilify-js
dist/utilify.esm.js
camelize
function camelize(obj) { var _this = this; var _camelize = function _camelize(str) { str = stringHelpers.underscore(str); str = stringHelpers.slugifyText(str); return str.replace(/[_.-\s](\w|$)/g, function (_, x) { return x.toUpperCase(); }); }; if (validateHelpers.isDate(obj) || validateHelpers.isRegExp(obj)) { return obj; } if (validateHelpers.isArray(obj)) { return obj.map(function (item, index) { if (validateHelpers.isObject(item)) { return _this.camelize(item); } return item; }); } if (validateHelpers.isString(obj)) { return _camelize(obj); } return Object.keys(obj).reduce(function (acc, key) { var camel = _camelize(key); acc[camel] = obj[key]; if (validateHelpers.isObject(obj[key])) { acc[camel] = _this.camelize(obj[key]); } return acc; }, {}); }
javascript
function camelize(obj) { var _this = this; var _camelize = function _camelize(str) { str = stringHelpers.underscore(str); str = stringHelpers.slugifyText(str); return str.replace(/[_.-\s](\w|$)/g, function (_, x) { return x.toUpperCase(); }); }; if (validateHelpers.isDate(obj) || validateHelpers.isRegExp(obj)) { return obj; } if (validateHelpers.isArray(obj)) { return obj.map(function (item, index) { if (validateHelpers.isObject(item)) { return _this.camelize(item); } return item; }); } if (validateHelpers.isString(obj)) { return _camelize(obj); } return Object.keys(obj).reduce(function (acc, key) { var camel = _camelize(key); acc[camel] = obj[key]; if (validateHelpers.isObject(obj[key])) { acc[camel] = _this.camelize(obj[key]); } return acc; }, {}); }
[ "function", "camelize", "(", "obj", ")", "{", "var", "_this", "=", "this", ";", "var", "_camelize", "=", "function", "_camelize", "(", "str", ")", "{", "str", "=", "stringHelpers", ".", "underscore", "(", "str", ")", ";", "str", "=", "stringHelpers", ".", "slugifyText", "(", "str", ")", ";", "return", "str", ".", "replace", "(", "/", "[_.-\\s](\\w|$)", "/", "g", ",", "function", "(", "_", ",", "x", ")", "{", "return", "x", ".", "toUpperCase", "(", ")", ";", "}", ")", ";", "}", ";", "if", "(", "validateHelpers", ".", "isDate", "(", "obj", ")", "||", "validateHelpers", ".", "isRegExp", "(", "obj", ")", ")", "{", "return", "obj", ";", "}", "if", "(", "validateHelpers", ".", "isArray", "(", "obj", ")", ")", "{", "return", "obj", ".", "map", "(", "function", "(", "item", ",", "index", ")", "{", "if", "(", "validateHelpers", ".", "isObject", "(", "item", ")", ")", "{", "return", "_this", ".", "camelize", "(", "item", ")", ";", "}", "return", "item", ";", "}", ")", ";", "}", "if", "(", "validateHelpers", ".", "isString", "(", "obj", ")", ")", "{", "return", "_camelize", "(", "obj", ")", ";", "}", "return", "Object", ".", "keys", "(", "obj", ")", ".", "reduce", "(", "function", "(", "acc", ",", "key", ")", "{", "var", "camel", "=", "_camelize", "(", "key", ")", ";", "acc", "[", "camel", "]", "=", "obj", "[", "key", "]", ";", "if", "(", "validateHelpers", ".", "isObject", "(", "obj", "[", "key", "]", ")", ")", "{", "acc", "[", "camel", "]", "=", "_this", ".", "camelize", "(", "obj", "[", "key", "]", ")", ";", "}", "return", "acc", ";", "}", ",", "{", "}", ")", ";", "}" ]
Recursively transform key strings to camelCase if param is an Object. If param is string, return an camel cased string. @param {Object|String} obj Object or string to transform @returns {Object|String}
[ "Recursively", "transform", "key", "strings", "to", "camelCase", "if", "param", "is", "an", "Object", ".", "If", "param", "is", "string", "return", "an", "camel", "cased", "string", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L873-L913
train
Zeindelf/utilify-js
dist/utilify.esm.js
contains
function contains(value, elem) { if (validateHelpers.isArray(elem)) { for (var i = 0, len = elem.length; i < len; i += 1) { if (elem[i] === value) { return true; } } } if (validateHelpers.isString(elem)) { return elem.indexOf(value) >= 0; } return false; }
javascript
function contains(value, elem) { if (validateHelpers.isArray(elem)) { for (var i = 0, len = elem.length; i < len; i += 1) { if (elem[i] === value) { return true; } } } if (validateHelpers.isString(elem)) { return elem.indexOf(value) >= 0; } return false; }
[ "function", "contains", "(", "value", ",", "elem", ")", "{", "if", "(", "validateHelpers", ".", "isArray", "(", "elem", ")", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "elem", ".", "length", ";", "i", "<", "len", ";", "i", "+=", "1", ")", "{", "if", "(", "elem", "[", "i", "]", "===", "value", ")", "{", "return", "true", ";", "}", "}", "}", "if", "(", "validateHelpers", ".", "isString", "(", "elem", ")", ")", "{", "return", "elem", ".", "indexOf", "(", "value", ")", ">=", "0", ";", "}", "return", "false", ";", "}" ]
Check if value contains in an element @category Global @param {String} value - Value to check @param {String|Array} elem - String or array @return {Boolean} - Return true if element contains a value
[ "Check", "if", "value", "contains", "in", "an", "element" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L924-L938
train
Zeindelf/utilify-js
dist/utilify.esm.js
getUrlParameter
function getUrlParameter(name, entryPoint) { entryPoint = !validateHelpers.isString(entryPoint) ? window.location.href : entryPoint.substring(0, 1) === '?' ? entryPoint : '?' + entryPoint; name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'); var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'); var results = regex.exec(entryPoint); return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' ')); }
javascript
function getUrlParameter(name, entryPoint) { entryPoint = !validateHelpers.isString(entryPoint) ? window.location.href : entryPoint.substring(0, 1) === '?' ? entryPoint : '?' + entryPoint; name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'); var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'); var results = regex.exec(entryPoint); return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' ')); }
[ "function", "getUrlParameter", "(", "name", ",", "entryPoint", ")", "{", "entryPoint", "=", "!", "validateHelpers", ".", "isString", "(", "entryPoint", ")", "?", "window", ".", "location", ".", "href", ":", "entryPoint", ".", "substring", "(", "0", ",", "1", ")", "===", "'?'", "?", "entryPoint", ":", "'?'", "+", "entryPoint", ";", "name", "=", "name", ".", "replace", "(", "/", "[\\[]", "/", ",", "'\\\\['", ")", ".", "\\\\", "replace", ";", "(", "/", "[\\]]", "/", ",", "'\\\\]'", ")", "\\\\", "var", "regex", "=", "new", "RegExp", "(", "'[\\\\?&]'", "+", "\\\\", "+", "name", ")", ";", "}" ]
Get url params from a query string @category Global @param {string} name - Param name @param {string} entryPoint - Full url or query string @return {string} Value query string param @example // URL: https://site.com?param1=foo&param2=bar getUrlParameter('param1'); // foo getUrlParameter('param2'); // bar // Given entry point var url = 'http://www.site.com?param1=foo&param2=bar&param3=baz'; getUrlParameter('param3', url); // baz
[ "Get", "url", "params", "from", "a", "query", "string" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1203-L1211
train
Zeindelf/utilify-js
dist/utilify.esm.js
resizeImageByRatio
function resizeImageByRatio(type, newSize, aspectRatio, decimal) { if (!validateHelpers.isNumber(newSize) || !validateHelpers.isNumber(aspectRatio)) { newSize = parseFloat(newSize, 10); aspectRatio = parseFloat(aspectRatio, 10); } var dimensions = {}; decimal = decimal || 4; switch (type) { case 'width': dimensions.width = parseFloat(newSize, 10); dimensions.height = parseFloat((newSize / aspectRatio).toFixed(decimal), 10); break; case 'height': dimensions.width = parseFloat((newSize * aspectRatio).toFixed(decimal), 10); dimensions.height = parseFloat(newSize, 10); break; default: throw new Error('\'type\' needs to be \'width\' or \'height\''); } return dimensions; }
javascript
function resizeImageByRatio(type, newSize, aspectRatio, decimal) { if (!validateHelpers.isNumber(newSize) || !validateHelpers.isNumber(aspectRatio)) { newSize = parseFloat(newSize, 10); aspectRatio = parseFloat(aspectRatio, 10); } var dimensions = {}; decimal = decimal || 4; switch (type) { case 'width': dimensions.width = parseFloat(newSize, 10); dimensions.height = parseFloat((newSize / aspectRatio).toFixed(decimal), 10); break; case 'height': dimensions.width = parseFloat((newSize * aspectRatio).toFixed(decimal), 10); dimensions.height = parseFloat(newSize, 10); break; default: throw new Error('\'type\' needs to be \'width\' or \'height\''); } return dimensions; }
[ "function", "resizeImageByRatio", "(", "type", ",", "newSize", ",", "aspectRatio", ",", "decimal", ")", "{", "if", "(", "!", "validateHelpers", ".", "isNumber", "(", "newSize", ")", "||", "!", "validateHelpers", ".", "isNumber", "(", "aspectRatio", ")", ")", "{", "newSize", "=", "parseFloat", "(", "newSize", ",", "10", ")", ";", "aspectRatio", "=", "parseFloat", "(", "aspectRatio", ",", "10", ")", ";", "}", "var", "dimensions", "=", "{", "}", ";", "decimal", "=", "decimal", "||", "4", ";", "switch", "(", "type", ")", "{", "case", "'width'", ":", "dimensions", ".", "width", "=", "parseFloat", "(", "newSize", ",", "10", ")", ";", "dimensions", ".", "height", "=", "parseFloat", "(", "(", "newSize", "/", "aspectRatio", ")", ".", "toFixed", "(", "decimal", ")", ",", "10", ")", ";", "break", ";", "case", "'height'", ":", "dimensions", ".", "width", "=", "parseFloat", "(", "(", "newSize", "*", "aspectRatio", ")", ".", "toFixed", "(", "decimal", ")", ",", "10", ")", ";", "dimensions", ".", "height", "=", "parseFloat", "(", "newSize", ",", "10", ")", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "'\\'type\\' needs to be \\'width\\' or \\'height\\''", ")", ";", "}", "\\'", "}" ]
Resize image by aspect ratio @category Global @param {String} type Resize by 'width' or 'height' @param {Number} newSize New value to resize @param {Number} aspectRatio Image aspect ratio (calculate by (width / height)) @return {Object} Object with new 'width' and 'height'
[ "Resize", "image", "by", "aspect", "ratio" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1231-L1258
train
Zeindelf/utilify-js
dist/utilify.esm.js
semverCompare
function semverCompare(v1, v2) { var semver = /^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; var validate = function validate(version) { if (!validateHelpers.isString(version)) { throw new TypeError('Invalid argument: expected string'); } if (!semver.test(version)) { throw new Error('Invalid argument: not valid semver'); } }; [v1, v2].forEach(validate); var pa = v1.split('.'); var pb = v2.split('.'); for (var i = 0; i < 3; i++) { var na = Number(pa[i]); var nb = Number(pb[i]); if (na > nb) { return 1; } if (nb > na) { return -1; } if (!isNaN(na) && isNaN(nb)) { return 1; } if (isNaN(na) && !isNaN(nb)) { return -1; } } return 0; }
javascript
function semverCompare(v1, v2) { var semver = /^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; var validate = function validate(version) { if (!validateHelpers.isString(version)) { throw new TypeError('Invalid argument: expected string'); } if (!semver.test(version)) { throw new Error('Invalid argument: not valid semver'); } }; [v1, v2].forEach(validate); var pa = v1.split('.'); var pb = v2.split('.'); for (var i = 0; i < 3; i++) { var na = Number(pa[i]); var nb = Number(pb[i]); if (na > nb) { return 1; } if (nb > na) { return -1; } if (!isNaN(na) && isNaN(nb)) { return 1; } if (isNaN(na) && !isNaN(nb)) { return -1; } } return 0; }
[ "function", "semverCompare", "(", "v1", ",", "v2", ")", "{", "var", "semver", "=", "/", "^v?(?:\\d+)(\\.(?:[x*]|\\d+)(\\.(?:[x*]|\\d+)(\\.(?:[x*]|\\d+))?(?:-[\\da-z\\-]+(?:\\.[\\da-z\\-]+)*)?(?:\\+[\\da-z\\-]+(?:\\.[\\da-z\\-]+)*)?)?)?$", "/", "i", ";", "var", "validate", "=", "function", "validate", "(", "version", ")", "{", "if", "(", "!", "validateHelpers", ".", "isString", "(", "version", ")", ")", "{", "throw", "new", "TypeError", "(", "'Invalid argument: expected string'", ")", ";", "}", "if", "(", "!", "semver", ".", "test", "(", "version", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid argument: not valid semver'", ")", ";", "}", "}", ";", "[", "v1", ",", "v2", "]", ".", "forEach", "(", "validate", ")", ";", "var", "pa", "=", "v1", ".", "split", "(", "'.'", ")", ";", "var", "pb", "=", "v2", ".", "split", "(", "'.'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "3", ";", "i", "++", ")", "{", "var", "na", "=", "Number", "(", "pa", "[", "i", "]", ")", ";", "var", "nb", "=", "Number", "(", "pb", "[", "i", "]", ")", ";", "if", "(", "na", ">", "nb", ")", "{", "return", "1", ";", "}", "if", "(", "nb", ">", "na", ")", "{", "return", "-", "1", ";", "}", "if", "(", "!", "isNaN", "(", "na", ")", "&&", "isNaN", "(", "nb", ")", ")", "{", "return", "1", ";", "}", "if", "(", "isNaN", "(", "na", ")", "&&", "!", "isNaN", "(", "nb", ")", ")", "{", "return", "-", "1", ";", "}", "}", "return", "0", ";", "}" ]
Compare two semver version strings, returning -1, 0, or 1 If the semver string `v1` is greater than `v2`, return 1. If the semver string `v2` is greater than `v1`, return -1. If `v1` equals `v2`, return 0 @from @semver-compare @category Global @param {String} v1 Your semver to compare @param {String} v2 Compared semver @return {Number} -1, 0, 1
[ "Compare", "two", "semver", "version", "strings", "returning", "-", "1", "0", "or", "1", "If", "the", "semver", "string", "v1", "is", "greater", "than", "v2", "return", "1", ".", "If", "the", "semver", "string", "v2", "is", "greater", "than", "v1", "return", "-", "1", ".", "If", "v1", "equals", "v2", "return", "0" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1271-L1309
train
Zeindelf/utilify-js
dist/utilify.esm.js
stripTags
function stripTags(input, allowed) { allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // Making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>) var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi; var commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi; return stringHelpers.strCompact(input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) { return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ' '; })); }
javascript
function stripTags(input, allowed) { allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // Making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>) var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi; var commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi; return stringHelpers.strCompact(input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) { return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ' '; })); }
[ "function", "stripTags", "(", "input", ",", "allowed", ")", "{", "allowed", "=", "(", "(", "(", "allowed", "||", "''", ")", "+", "''", ")", ".", "toLowerCase", "(", ")", ".", "match", "(", "/", "<[a-z][a-z0-9]*>", "/", "g", ")", "||", "[", "]", ")", ".", "join", "(", "''", ")", ";", "var", "tags", "=", "/", "<\\/?([a-z][a-z0-9]*)\\b[^>]*>", "/", "gi", ";", "var", "commentsAndPhpTags", "=", "/", "<!--[\\s\\S]*?", "/", "gi", ";", "return", "stringHelpers", ".", "strCompact", "(", "input", ".", "replace", "(", "commentsAndPhpTags", ",", "''", ")", ".", "replace", "(", "tags", ",", "function", "(", "$0", ",", "$1", ")", "{", "return", "allowed", ".", "indexOf", "(", "'<'", "+", "$1", ".", "toLowerCase", "(", ")", "+", "'>'", ")", ">", "-", "1", "?", "$0", ":", "' '", ";", "}", ")", ")", ";", "}" ]
Native javascript function to emulate the PHP function strip_tags. @param {String} str The original HTML string to filter. @param {String|Array} allowed A tag name or array of tag names to keep @returns {string} The filtered HTML string. @example
[ "Native", "javascript", "function", "to", "emulate", "the", "PHP", "function", "strip_tags", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1350-L1359
train
Zeindelf/utilify-js
dist/utilify.esm.js
times
function times(n, iteratee) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; if (n < 1 || n > MAX_SAFE_INTEGER) { return []; } var index = -1; var length = Math.min(n, MAX_ARRAY_LENGTH); var result = new Array(length); while (++index < length) { result[index] = iteratee(index); } index = MAX_ARRAY_LENGTH; n -= MAX_ARRAY_LENGTH; while (++index < n) { iteratee(index); } return result; }
javascript
function times(n, iteratee) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; if (n < 1 || n > MAX_SAFE_INTEGER) { return []; } var index = -1; var length = Math.min(n, MAX_ARRAY_LENGTH); var result = new Array(length); while (++index < length) { result[index] = iteratee(index); } index = MAX_ARRAY_LENGTH; n -= MAX_ARRAY_LENGTH; while (++index < n) { iteratee(index); } return result; }
[ "function", "times", "(", "n", ",", "iteratee", ")", "{", "var", "MAX_SAFE_INTEGER", "=", "9007199254740991", ";", "var", "MAX_ARRAY_LENGTH", "=", "4294967295", ";", "if", "(", "n", "<", "1", "||", "n", ">", "MAX_SAFE_INTEGER", ")", "{", "return", "[", "]", ";", "}", "var", "index", "=", "-", "1", ";", "var", "length", "=", "Math", ".", "min", "(", "n", ",", "MAX_ARRAY_LENGTH", ")", ";", "var", "result", "=", "new", "Array", "(", "length", ")", ";", "while", "(", "++", "index", "<", "length", ")", "{", "result", "[", "index", "]", "=", "iteratee", "(", "index", ")", ";", "}", "index", "=", "MAX_ARRAY_LENGTH", ";", "n", "-=", "MAX_ARRAY_LENGTH", ";", "while", "(", "++", "index", "<", "n", ")", "{", "iteratee", "(", "index", ")", ";", "}", "return", "result", ";", "}" ]
Invokes the iteratee `n` times, returning an array of the results of each invocation. The iteratee is invoked with one argumentindex). @from Lodash @category Global @param {number} n The number of times to invoke `iteratee`. @param {Function} iteratee The function invoked per iteration. @returns {Array} Returns the array of results. @example times(3, String) // => ['0', '1', '2'] times(4, () => 0) // => [0, 0, 0, 0]
[ "Invokes", "the", "iteratee", "n", "times", "returning", "an", "array", "of", "the", "results", "of", "each", "invocation", ".", "The", "iteratee", "is", "invoked", "with", "one", "argumentindex", ")", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1442-L1468
train
Zeindelf/utilify-js
dist/utilify.esm.js
unserialize
function unserialize(str) { str = !validateHelpers.isString(str) ? window.location.href : str; if (str.indexOf('?') < 0) { return {}; } str = str.indexOf('?') === 0 ? str.substr(1) : str.slice(str.indexOf('?') + 1); var query = {}; var parts = str.split('&'); for (var i = 0, len = parts.length; i < len; i += 1) { var part = parts[i].split('='); query[decodeURIComponent(part[0])] = decodeURIComponent(part[1] || ''); } return query; }
javascript
function unserialize(str) { str = !validateHelpers.isString(str) ? window.location.href : str; if (str.indexOf('?') < 0) { return {}; } str = str.indexOf('?') === 0 ? str.substr(1) : str.slice(str.indexOf('?') + 1); var query = {}; var parts = str.split('&'); for (var i = 0, len = parts.length; i < len; i += 1) { var part = parts[i].split('='); query[decodeURIComponent(part[0])] = decodeURIComponent(part[1] || ''); } return query; }
[ "function", "unserialize", "(", "str", ")", "{", "str", "=", "!", "validateHelpers", ".", "isString", "(", "str", ")", "?", "window", ".", "location", ".", "href", ":", "str", ";", "if", "(", "str", ".", "indexOf", "(", "'?'", ")", "<", "0", ")", "{", "return", "{", "}", ";", "}", "str", "=", "str", ".", "indexOf", "(", "'?'", ")", "===", "0", "?", "str", ".", "substr", "(", "1", ")", ":", "str", ".", "slice", "(", "str", ".", "indexOf", "(", "'?'", ")", "+", "1", ")", ";", "var", "query", "=", "{", "}", ";", "var", "parts", "=", "str", ".", "split", "(", "'&'", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "parts", ".", "length", ";", "i", "<", "len", ";", "i", "+=", "1", ")", "{", "var", "part", "=", "parts", "[", "i", "]", ".", "split", "(", "'='", ")", ";", "query", "[", "decodeURIComponent", "(", "part", "[", "0", "]", ")", "]", "=", "decodeURIComponent", "(", "part", "[", "1", "]", "||", "''", ")", ";", "}", "return", "query", ";", "}" ]
Unserialize a query string into an object. @category Global @param {string} [str = actual url] - The string that will be converted into a object @return {object} @example // str can be '?param1=foo&param2=bar&param3=baz', 'param1=foo&param2=bar&param3=baz' or a full url // If no provided, will get actual url var url = 'http://www.site.com?param1=foo&param2=bar&param3=baz'; unserialize(url); // {param1: 'foo', param2: 'bar', param3: 'baz'}
[ "Unserialize", "a", "query", "string", "into", "an", "object", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1483-L1501
train
Zeindelf/utilify-js
dist/utilify.esm.js
isArguments
function isArguments(value) { // fallback check is for IE return toString.call(value) === '[object Arguments]' || value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && 'callee' in value; }
javascript
function isArguments(value) { // fallback check is for IE return toString.call(value) === '[object Arguments]' || value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && 'callee' in value; }
[ "function", "isArguments", "(", "value", ")", "{", "return", "toString", ".", "call", "(", "value", ")", "===", "'[object Arguments]'", "||", "value", "!=", "null", "&&", "(", "typeof", "value", "===", "'undefined'", "?", "'undefined'", ":", "_typeof", "(", "value", ")", ")", "===", "'object'", "&&", "'callee'", "in", "value", ";", "}" ]
is a given value Arguments? @category Validate
[ "is", "a", "given", "value", "Arguments?" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1512-L1515
train
Zeindelf/utilify-js
dist/utilify.esm.js
isArray
function isArray(value) { // check native isArray first if (Array.isArray) { return Array.isArray(value); } return toString.call(value) === '[object Array]'; }
javascript
function isArray(value) { // check native isArray first if (Array.isArray) { return Array.isArray(value); } return toString.call(value) === '[object Array]'; }
[ "function", "isArray", "(", "value", ")", "{", "if", "(", "Array", ".", "isArray", ")", "{", "return", "Array", ".", "isArray", "(", "value", ")", ";", "}", "return", "toString", ".", "call", "(", "value", ")", "===", "'[object Array]'", ";", "}" ]
Check if the given value is an array. @category Validate @param {*} value - The value to check. @return {boolean} Returns 'true' if the given value is a string, else 'false'.
[ "Check", "if", "the", "given", "value", "is", "an", "array", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1525-L1532
train
Zeindelf/utilify-js
dist/utilify.esm.js
isEmpty
function isEmpty(variable) { var emptyVariables = { 'undefined': true, 'null': true, 'number': false, 'boolean': false, 'function': false, 'regexp': false, 'date': false, 'error': false }; var strType = globalHelpers.getType(variable); var boolReturn = void 0; if (emptyVariables.hasOwnProperty(strType)) { boolReturn = emptyVariables[strType]; } else { switch (strType) { case 'object': boolReturn = this.isObjectEmpty(variable); break; case 'string': boolReturn = variable ? false : true; break; case 'array': boolReturn = variable.length ? false : true; break; } } return boolReturn; }
javascript
function isEmpty(variable) { var emptyVariables = { 'undefined': true, 'null': true, 'number': false, 'boolean': false, 'function': false, 'regexp': false, 'date': false, 'error': false }; var strType = globalHelpers.getType(variable); var boolReturn = void 0; if (emptyVariables.hasOwnProperty(strType)) { boolReturn = emptyVariables[strType]; } else { switch (strType) { case 'object': boolReturn = this.isObjectEmpty(variable); break; case 'string': boolReturn = variable ? false : true; break; case 'array': boolReturn = variable.length ? false : true; break; } } return boolReturn; }
[ "function", "isEmpty", "(", "variable", ")", "{", "var", "emptyVariables", "=", "{", "'undefined'", ":", "true", ",", "'null'", ":", "true", ",", "'number'", ":", "false", ",", "'boolean'", ":", "false", ",", "'function'", ":", "false", ",", "'regexp'", ":", "false", ",", "'date'", ":", "false", ",", "'error'", ":", "false", "}", ";", "var", "strType", "=", "globalHelpers", ".", "getType", "(", "variable", ")", ";", "var", "boolReturn", "=", "void", "0", ";", "if", "(", "emptyVariables", ".", "hasOwnProperty", "(", "strType", ")", ")", "{", "boolReturn", "=", "emptyVariables", "[", "strType", "]", ";", "}", "else", "{", "switch", "(", "strType", ")", "{", "case", "'object'", ":", "boolReturn", "=", "this", ".", "isObjectEmpty", "(", "variable", ")", ";", "break", ";", "case", "'string'", ":", "boolReturn", "=", "variable", "?", "false", ":", "true", ";", "break", ";", "case", "'array'", ":", "boolReturn", "=", "variable", ".", "length", "?", "false", ":", "true", ";", "break", ";", "}", "}", "return", "boolReturn", ";", "}" ]
is a given value empty? Objects, arrays, strings @category Validate
[ "is", "a", "given", "value", "empty?", "Objects", "arrays", "strings" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1633-L1667
train
Zeindelf/utilify-js
dist/utilify.esm.js
isJson
function isJson(str) { try { var obj = JSON.parse(str); return this.isObject(obj); } catch (e) {/* ignore */} return false; }
javascript
function isJson(str) { try { var obj = JSON.parse(str); return this.isObject(obj); } catch (e) {/* ignore */} return false; }
[ "function", "isJson", "(", "str", ")", "{", "try", "{", "var", "obj", "=", "JSON", ".", "parse", "(", "str", ")", ";", "return", "this", ".", "isObject", "(", "obj", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "return", "false", ";", "}" ]
Check if a string is a valid JSON. @category Validate @param {string} str - The string to check @return {boolean}
[ "Check", "if", "a", "string", "is", "a", "valid", "JSON", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1700-L1707
train
Zeindelf/utilify-js
dist/utilify.esm.js
isNumber
function isNumber(value) { var isNaN = Number.isNaN || window.isNaN; return typeof value === 'number' && !isNaN(value); }
javascript
function isNumber(value) { var isNaN = Number.isNaN || window.isNaN; return typeof value === 'number' && !isNaN(value); }
[ "function", "isNumber", "(", "value", ")", "{", "var", "isNaN", "=", "Number", ".", "isNaN", "||", "window", ".", "isNaN", ";", "return", "typeof", "value", "===", "'number'", "&&", "!", "isNaN", "(", "value", ")", ";", "}" ]
Check if the given value is a number. @category Validate @param {*} value - The value to check. @return {boolean} Returns 'true' if the given value is a number, else 'false'.
[ "Check", "if", "the", "given", "value", "is", "a", "number", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1727-L1731
train
Zeindelf/utilify-js
dist/utilify.esm.js
isObjectEmpty
function isObjectEmpty(obj) { if (!this.isObject(obj)) { return false; } for (var x in obj) { if ({}.hasOwnProperty.call(obj, x)) { return false; } } return true; }
javascript
function isObjectEmpty(obj) { if (!this.isObject(obj)) { return false; } for (var x in obj) { if ({}.hasOwnProperty.call(obj, x)) { return false; } } return true; }
[ "function", "isObjectEmpty", "(", "obj", ")", "{", "if", "(", "!", "this", ".", "isObject", "(", "obj", ")", ")", "{", "return", "false", ";", "}", "for", "(", "var", "x", "in", "obj", ")", "{", "if", "(", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "obj", ",", "x", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Verify if as objects is empty @category Validate @param {object} obj - The object to verify @return {boolean} @example isObjectEmpty({}); // true
[ "Verify", "if", "as", "objects", "is", "empty" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1768-L1780
train
Zeindelf/utilify-js
dist/utilify.esm.js
isSameType
function isSameType(value, other) { var tag = toString.call(value); if (tag !== toString.call(other)) { return false; } return true; }
javascript
function isSameType(value, other) { var tag = toString.call(value); if (tag !== toString.call(other)) { return false; } return true; }
[ "function", "isSameType", "(", "value", ",", "other", ")", "{", "var", "tag", "=", "toString", ".", "call", "(", "value", ")", ";", "if", "(", "tag", "!==", "toString", ".", "call", "(", "other", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
are given values same type? @category Validate
[ "are", "given", "values", "same", "type?" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1843-L1851
train
Zeindelf/utilify-js
dist/utilify.esm.js
arrayClone
function arrayClone(arr) { var clone = new Array(arr.length); this._forEach(arr, function (el, i) { clone[i] = el; }); return clone; }
javascript
function arrayClone(arr) { var clone = new Array(arr.length); this._forEach(arr, function (el, i) { clone[i] = el; }); return clone; }
[ "function", "arrayClone", "(", "arr", ")", "{", "var", "clone", "=", "new", "Array", "(", "arr", ".", "length", ")", ";", "this", ".", "_forEach", "(", "arr", ",", "function", "(", "el", ",", "i", ")", "{", "clone", "[", "i", "]", "=", "el", ";", "}", ")", ";", "return", "clone", ";", "}" ]
Creates a shallow clone of the array. @param {Array} arr Array to clone @return {Array} Array cloned
[ "Creates", "a", "shallow", "clone", "of", "the", "array", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1929-L1937
train
Zeindelf/utilify-js
dist/utilify.esm.js
arrayFlatten
function arrayFlatten(arr, level) { var self = this; var result = []; var current = 0; level = level || Infinity; self._forEach(arr, function (el) { if (validateHelpers.isArray(el) && current < level) { result = result.concat(self.arrayFlatten(el, level, current + 1)); } else { result.push(el); } }); return result; }
javascript
function arrayFlatten(arr, level) { var self = this; var result = []; var current = 0; level = level || Infinity; self._forEach(arr, function (el) { if (validateHelpers.isArray(el) && current < level) { result = result.concat(self.arrayFlatten(el, level, current + 1)); } else { result.push(el); } }); return result; }
[ "function", "arrayFlatten", "(", "arr", ",", "level", ")", "{", "var", "self", "=", "this", ";", "var", "result", "=", "[", "]", ";", "var", "current", "=", "0", ";", "level", "=", "level", "||", "Infinity", ";", "self", ".", "_forEach", "(", "arr", ",", "function", "(", "el", ")", "{", "if", "(", "validateHelpers", ".", "isArray", "(", "el", ")", "&&", "current", "<", "level", ")", "{", "result", "=", "result", ".", "concat", "(", "self", ".", "arrayFlatten", "(", "el", ",", "level", ",", "current", "+", "1", ")", ")", ";", "}", "else", "{", "result", ".", "push", "(", "el", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Returns a flattened, one-dimensional copy of the array. You can optionally specify a limit, which will only flatten to that depth. @param {Array} arr Array to flatten @param {Integer} level[Infinity] Depth @return {Array}
[ "Returns", "a", "flattened", "one", "-", "dimensional", "copy", "of", "the", "array", ".", "You", "can", "optionally", "specify", "a", "limit", "which", "will", "only", "flatten", "to", "that", "depth", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L1965-L1979
train
Zeindelf/utilify-js
dist/utilify.esm.js
arraySample
function arraySample(arr, num, remove) { var result = []; var _num = void 0; var _remove = void 0; var single = void 0; if (validateHelpers.isBoolean(num)) { _remove = num; } else { _num = num; _remove = remove; } if (validateHelpers.isUndefined(_num)) { _num = 1; single = true; } if (!_remove) { arr = this.arrayClone(arr); } _num = Math.min(_num, arr.length); for (var i = 0, index; i < _num; i += 1) { index = Math.trunc(Math.random() * arr.length); result.push(arr[index]); arr.splice(index, 1); } return single ? result[0] : result; }
javascript
function arraySample(arr, num, remove) { var result = []; var _num = void 0; var _remove = void 0; var single = void 0; if (validateHelpers.isBoolean(num)) { _remove = num; } else { _num = num; _remove = remove; } if (validateHelpers.isUndefined(_num)) { _num = 1; single = true; } if (!_remove) { arr = this.arrayClone(arr); } _num = Math.min(_num, arr.length); for (var i = 0, index; i < _num; i += 1) { index = Math.trunc(Math.random() * arr.length); result.push(arr[index]); arr.splice(index, 1); } return single ? result[0] : result; }
[ "function", "arraySample", "(", "arr", ",", "num", ",", "remove", ")", "{", "var", "result", "=", "[", "]", ";", "var", "_num", "=", "void", "0", ";", "var", "_remove", "=", "void", "0", ";", "var", "single", "=", "void", "0", ";", "if", "(", "validateHelpers", ".", "isBoolean", "(", "num", ")", ")", "{", "_remove", "=", "num", ";", "}", "else", "{", "_num", "=", "num", ";", "_remove", "=", "remove", ";", "}", "if", "(", "validateHelpers", ".", "isUndefined", "(", "_num", ")", ")", "{", "_num", "=", "1", ";", "single", "=", "true", ";", "}", "if", "(", "!", "_remove", ")", "{", "arr", "=", "this", ".", "arrayClone", "(", "arr", ")", ";", "}", "_num", "=", "Math", ".", "min", "(", "_num", ",", "arr", ".", "length", ")", ";", "for", "(", "var", "i", "=", "0", ",", "index", ";", "i", "<", "_num", ";", "i", "+=", "1", ")", "{", "index", "=", "Math", ".", "trunc", "(", "Math", ".", "random", "(", ")", "*", "arr", ".", "length", ")", ";", "result", ".", "push", "(", "arr", "[", "index", "]", ")", ";", "arr", ".", "splice", "(", "index", ",", "1", ")", ";", "}", "return", "single", "?", "result", "[", "0", "]", ":", "result", ";", "}" ]
Returns a random element from the array. If num is passed, will return an array of num elements. If remove is true, sampled elements will also be removed from the array. remove can also be passed in place of num. @param {Array} [arr] Array to sample @param {Integer|Boolean} [num=1] Num of elements @param {Boolean} [remove=false] Remove sampled elements @return {String|Array}
[ "Returns", "a", "random", "element", "from", "the", "array", ".", "If", "num", "is", "passed", "will", "return", "an", "array", "of", "num", "elements", ".", "If", "remove", "is", "true", "sampled", "elements", "will", "also", "be", "removed", "from", "the", "array", ".", "remove", "can", "also", "be", "passed", "in", "place", "of", "num", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2010-L2041
train
Zeindelf/utilify-js
dist/utilify.esm.js
chunk
function chunk(array, size) { size = Math.max(size, 0); var length = array === null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0; var resIndex = 0; var result = new Array(Math.ceil(length / size)); while (index < length) { result[resIndex++] = this.slice(array, index, index += size); } return result; }
javascript
function chunk(array, size) { size = Math.max(size, 0); var length = array === null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0; var resIndex = 0; var result = new Array(Math.ceil(length / size)); while (index < length) { result[resIndex++] = this.slice(array, index, index += size); } return result; }
[ "function", "chunk", "(", "array", ",", "size", ")", "{", "size", "=", "Math", ".", "max", "(", "size", ",", "0", ")", ";", "var", "length", "=", "array", "===", "null", "?", "0", ":", "array", ".", "length", ";", "if", "(", "!", "length", "||", "size", "<", "1", ")", "{", "return", "[", "]", ";", "}", "var", "index", "=", "0", ";", "var", "resIndex", "=", "0", ";", "var", "result", "=", "new", "Array", "(", "Math", ".", "ceil", "(", "length", "/", "size", ")", ")", ";", "while", "(", "index", "<", "length", ")", "{", "result", "[", "resIndex", "++", "]", "=", "this", ".", "slice", "(", "array", ",", "index", ",", "index", "+=", "size", ")", ";", "}", "return", "result", ";", "}" ]
Creates an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements. @category Array @param {Array} array The array to proccess. @param {Integer} [size=1] The length of each chunk. @return {Array} Returns the new array of chunks. @example chunk(['a', 'b', 'c', 'd'], 2) // => [['a', 'b'], ['c', 'd']] chunk(['a', 'b', 'c', 'd'], 3) // => [['a', 'b', 'c'], ['d']]
[ "Creates", "an", "array", "of", "elements", "split", "into", "groups", "the", "length", "of", "size", ".", "If", "array", "can", "t", "be", "split", "evenly", "the", "final", "chunk", "will", "be", "the", "remaining", "elements", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2073-L2090
train
Zeindelf/utilify-js
dist/utilify.esm.js
cleanArray
function cleanArray(array) { var newArray = []; for (var i = 0, len = array.length; i < len; i += 1) { if (array[i]) { newArray.push(array[i]); } } return newArray; }
javascript
function cleanArray(array) { var newArray = []; for (var i = 0, len = array.length; i < len; i += 1) { if (array[i]) { newArray.push(array[i]); } } return newArray; }
[ "function", "cleanArray", "(", "array", ")", "{", "var", "newArray", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "array", ".", "length", ";", "i", "<", "len", ";", "i", "+=", "1", ")", "{", "if", "(", "array", "[", "i", "]", ")", "{", "newArray", ".", "push", "(", "array", "[", "i", "]", ")", ";", "}", "}", "return", "newArray", ";", "}" ]
Removes empty index from a array. @category Array @param {Array} arr - The array @return {Array}
[ "Removes", "empty", "index", "from", "a", "array", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2100-L2110
train
Zeindelf/utilify-js
dist/utilify.esm.js
explode
function explode(str, separator, limit) { if (!validateHelpers.isString(str)) { throw new Error('\'str\' must be a String'); } var arr = str.split(separator); if (limit !== undefined && arr.length >= limit) { arr.push(arr.splice(limit - 1).join(separator)); } return arr; }
javascript
function explode(str, separator, limit) { if (!validateHelpers.isString(str)) { throw new Error('\'str\' must be a String'); } var arr = str.split(separator); if (limit !== undefined && arr.length >= limit) { arr.push(arr.splice(limit - 1).join(separator)); } return arr; }
[ "function", "explode", "(", "str", ",", "separator", ",", "limit", ")", "{", "if", "(", "!", "validateHelpers", ".", "isString", "(", "str", ")", ")", "{", "throw", "new", "Error", "(", "'\\'str\\' must be a String'", ")", ";", "}", "\\'", "\\'", "var", "arr", "=", "str", ".", "split", "(", "separator", ")", ";", "}" ]
Split array elements by separator - PHP implode alike @category Array @param {String} str - String to split @param {string} separator - The separator @param {Number} limit - Limit splitted elements @return {Array} The array with values @example explode('a', '.', 2); // ['a'] explode('a.b', '.', 2); // ['a', 'b'] explode('a.b.c', '.', 2); // ['a', 'b.c']
[ "Split", "array", "elements", "by", "separator", "-", "PHP", "implode", "alike" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2126-L2138
train
Zeindelf/utilify-js
dist/utilify.esm.js
implode
function implode(pieces, glue) { if (validateHelpers.isArray(pieces)) { return pieces.join(glue || ','); } else if (validateHelpers.isObject(pieces)) { var arr = []; for (var o in pieces) { if (object.hasOwnProperty(o)) { arr.push(pieces[o]); } } return arr.join(glue || ','); } return ''; }
javascript
function implode(pieces, glue) { if (validateHelpers.isArray(pieces)) { return pieces.join(glue || ','); } else if (validateHelpers.isObject(pieces)) { var arr = []; for (var o in pieces) { if (object.hasOwnProperty(o)) { arr.push(pieces[o]); } } return arr.join(glue || ','); } return ''; }
[ "function", "implode", "(", "pieces", ",", "glue", ")", "{", "if", "(", "validateHelpers", ".", "isArray", "(", "pieces", ")", ")", "{", "return", "pieces", ".", "join", "(", "glue", "||", "','", ")", ";", "}", "else", "if", "(", "validateHelpers", ".", "isObject", "(", "pieces", ")", ")", "{", "var", "arr", "=", "[", "]", ";", "for", "(", "var", "o", "in", "pieces", ")", "{", "if", "(", "object", ".", "hasOwnProperty", "(", "o", ")", ")", "{", "arr", ".", "push", "(", "pieces", "[", "o", "]", ")", ";", "}", "}", "return", "arr", ".", "join", "(", "glue", "||", "','", ")", ";", "}", "return", "''", ";", "}" ]
Join array elements with glue string - PHP implode alike @category Array @param {object|array} pieces - The array|object to implode. If object it will implode the values, not the keys. @param {string} [glue=','] - The glue @return {string} The imploded array|object @example implode(['Foo', 'Bar']); // 'Foo,Bar'
[ "Join", "array", "elements", "with", "glue", "string", "-", "PHP", "implode", "alike" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2151-L2166
train
Zeindelf/utilify-js
dist/utilify.esm.js
toNumber
function toNumber(value) { var _this = this; if (validateHelpers.isArray(value)) { return value.map(function (a) { return _this.toNumber(a); }); } var number = parseFloat(value); if (number === undefined) { return value; } if (number.toString().length !== value.toString().length && !validateHelpers.isNumeric(value)) { return value; } return validateHelpers.isNumber(number) ? value : number; }
javascript
function toNumber(value) { var _this = this; if (validateHelpers.isArray(value)) { return value.map(function (a) { return _this.toNumber(a); }); } var number = parseFloat(value); if (number === undefined) { return value; } if (number.toString().length !== value.toString().length && !validateHelpers.isNumeric(value)) { return value; } return validateHelpers.isNumber(number) ? value : number; }
[ "function", "toNumber", "(", "value", ")", "{", "var", "_this", "=", "this", ";", "if", "(", "validateHelpers", ".", "isArray", "(", "value", ")", ")", "{", "return", "value", ".", "map", "(", "function", "(", "a", ")", "{", "return", "_this", ".", "toNumber", "(", "a", ")", ";", "}", ")", ";", "}", "var", "number", "=", "parseFloat", "(", "value", ")", ";", "if", "(", "number", "===", "undefined", ")", "{", "return", "value", ";", "}", "if", "(", "number", ".", "toString", "(", ")", ".", "length", "!==", "value", ".", "toString", "(", ")", ".", "length", "&&", "!", "validateHelpers", ".", "isNumeric", "(", "value", ")", ")", "{", "return", "value", ";", "}", "return", "validateHelpers", ".", "isNumber", "(", "number", ")", "?", "value", ":", "number", ";", "}" ]
Converts a value to a number if possible. @category Global @param {Mix} value The value to convert. @returns {Number} The converted number, otherwise the original value. @example toNumber('123') // 123 toNumber('123.456') // 123.456
[ "Converts", "a", "value", "to", "a", "number", "if", "possible", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2414-L2434
train
Zeindelf/utilify-js
dist/utilify.esm.js
extend
function extend(obj) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (validateHelpers.isObject(obj) && args.length > 0) { if (Object.assign) { return Object.assign.apply(Object, [obj].concat(toConsumableArray(args))); } args.forEach(function (arg) { if (validateHelpers.isObject(arg)) { Object.keys(arg).forEach(function (key) { obj[key] = arg[key]; }); } }); } return obj; }
javascript
function extend(obj) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (validateHelpers.isObject(obj) && args.length > 0) { if (Object.assign) { return Object.assign.apply(Object, [obj].concat(toConsumableArray(args))); } args.forEach(function (arg) { if (validateHelpers.isObject(arg)) { Object.keys(arg).forEach(function (key) { obj[key] = arg[key]; }); } }); } return obj; }
[ "function", "extend", "(", "obj", ")", "{", "for", "(", "var", "_len", "=", "arguments", ".", "length", ",", "args", "=", "Array", "(", "_len", ">", "1", "?", "_len", "-", "1", ":", "0", ")", ",", "_key", "=", "1", ";", "_key", "<", "_len", ";", "_key", "++", ")", "{", "args", "[", "_key", "-", "1", "]", "=", "arguments", "[", "_key", "]", ";", "}", "if", "(", "validateHelpers", ".", "isObject", "(", "obj", ")", "&&", "args", ".", "length", ">", "0", ")", "{", "if", "(", "Object", ".", "assign", ")", "{", "return", "Object", ".", "assign", ".", "apply", "(", "Object", ",", "[", "obj", "]", ".", "concat", "(", "toConsumableArray", "(", "args", ")", ")", ")", ";", "}", "args", ".", "forEach", "(", "function", "(", "arg", ")", "{", "if", "(", "validateHelpers", ".", "isObject", "(", "arg", ")", ")", "{", "Object", ".", "keys", "(", "arg", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "obj", "[", "key", "]", "=", "arg", "[", "key", "]", ";", "}", ")", ";", "}", "}", ")", ";", "}", "return", "obj", ";", "}" ]
Extend the given object @param {object} obj - The object to be extended @param {*} args - The rest objects which will be merged to the first object @return {object} The extended object
[ "Extend", "the", "given", "object" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2466-L2486
train
Zeindelf/utilify-js
dist/utilify.esm.js
getDescendantProp
function getDescendantProp(obj, path) { if (!validateHelpers.isPlainObject(obj)) { throw new TypeError('\'obj\' param must be an plain object'); } return path.split('.').reduce(function (acc, part) { return acc && acc[part]; }, obj); }
javascript
function getDescendantProp(obj, path) { if (!validateHelpers.isPlainObject(obj)) { throw new TypeError('\'obj\' param must be an plain object'); } return path.split('.').reduce(function (acc, part) { return acc && acc[part]; }, obj); }
[ "function", "getDescendantProp", "(", "obj", ",", "path", ")", "{", "if", "(", "!", "validateHelpers", ".", "isPlainObject", "(", "obj", ")", ")", "{", "throw", "new", "TypeError", "(", "'\\'obj\\' param must be an plain object'", ")", ";", "}", "\\'", "}" ]
A function to take a string written in dot notation style, and use it to find a nested object property inside of an object. @param {Object} obj The object to search @param {String} path A dot notation style parameter reference (ie 'a.b.c') @returns the value of the property in question
[ "A", "function", "to", "take", "a", "string", "written", "in", "dot", "notation", "style", "and", "use", "it", "to", "find", "a", "nested", "object", "property", "inside", "of", "an", "object", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2498-L2506
train
Zeindelf/utilify-js
dist/utilify.esm.js
groupObjectByValue
function groupObjectByValue(item, key) { var camelize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (!validateHelpers.isArray(item)) { throw new Error('\'item\' must be an array of objects'); } var grouped = item.reduce(function (r, a) { r[a[key]] = r[a[key]] || []; r[a[key]].push(a); return r; }, Object.create(null)); return camelize ? globalHelpers.camelize(grouped) : grouped; }
javascript
function groupObjectByValue(item, key) { var camelize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (!validateHelpers.isArray(item)) { throw new Error('\'item\' must be an array of objects'); } var grouped = item.reduce(function (r, a) { r[a[key]] = r[a[key]] || []; r[a[key]].push(a); return r; }, Object.create(null)); return camelize ? globalHelpers.camelize(grouped) : grouped; }
[ "function", "groupObjectByValue", "(", "item", ",", "key", ")", "{", "var", "camelize", "=", "arguments", ".", "length", ">", "2", "&&", "arguments", "[", "2", "]", "!==", "undefined", "?", "arguments", "[", "2", "]", ":", "false", ";", "if", "(", "!", "validateHelpers", ".", "isArray", "(", "item", ")", ")", "{", "throw", "new", "Error", "(", "'\\'item\\' must be an array of objects'", ")", ";", "}", "\\'", "\\'", "}" ]
Group an array of objects by same properties value Returns new object with a key grouped values @param {Array} item An array of objects @param {String} key The key where the values are grouped @param {Boolean} camelize Camlize key (e.g. 'John Smith' or 'john-smith' turn into johnSmith) @returns {Object} @example const objToGroup = [ { name: 'John', age: 20 }, { name: 'Mary', age: 20 }, { name: 'Smith', age: 18 }, { name: 'John', age: 22 } ]; groupObjectByValue(objToGroup, 'age') // { 18: [{ name: 'Smith', age: 18 }], 20: [{ name: 'John', age: 20 }, { name: 'Mary', age: 20 }], 22: { name: 'John', age: 22 } } groupObjectByValue(objToGroup, 'name', true) // { john: [{ name: 'John', age: 22 }, { name: 'John', age: 20 }], mary: [{ name: 'Mary', age: 20 }], smith: [{ name: 'Smith', age: 18 }] }
[ "Group", "an", "array", "of", "objects", "by", "same", "properties", "value", "Returns", "new", "object", "with", "a", "key", "grouped", "values" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2528-L2542
train
Zeindelf/utilify-js
dist/utilify.esm.js
objectArraySortByValue
function objectArraySortByValue(arr, map, key) { var _this2 = this; var reverse = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; if (!validateHelpers.isArray(map) || map.length < 1) { var compare = function compare(a, b, n) { return _this2.getDescendantProp(a, n).toString().localeCompare(_this2.getDescendantProp(b, n).toString(), undefined, { numeric: true }); }; return arr.slice().sort(function (a, b) { return reverse ? -compare(a, b, key) : compare(a, b, key); }); } return arr.slice().sort(function (a, b) { var ordered = map.indexOf(_this2.getDescendantProp(a, key).toString()) - map.indexOf(_this2.getDescendantProp(b, key).toString()); return reverse ? ordered * -1 : ordered; }); }
javascript
function objectArraySortByValue(arr, map, key) { var _this2 = this; var reverse = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; if (!validateHelpers.isArray(map) || map.length < 1) { var compare = function compare(a, b, n) { return _this2.getDescendantProp(a, n).toString().localeCompare(_this2.getDescendantProp(b, n).toString(), undefined, { numeric: true }); }; return arr.slice().sort(function (a, b) { return reverse ? -compare(a, b, key) : compare(a, b, key); }); } return arr.slice().sort(function (a, b) { var ordered = map.indexOf(_this2.getDescendantProp(a, key).toString()) - map.indexOf(_this2.getDescendantProp(b, key).toString()); return reverse ? ordered * -1 : ordered; }); }
[ "function", "objectArraySortByValue", "(", "arr", ",", "map", ",", "key", ")", "{", "var", "_this2", "=", "this", ";", "var", "reverse", "=", "arguments", ".", "length", ">", "3", "&&", "arguments", "[", "3", "]", "!==", "undefined", "?", "arguments", "[", "3", "]", ":", "false", ";", "if", "(", "!", "validateHelpers", ".", "isArray", "(", "map", ")", "||", "map", ".", "length", "<", "1", ")", "{", "var", "compare", "=", "function", "compare", "(", "a", ",", "b", ",", "n", ")", "{", "return", "_this2", ".", "getDescendantProp", "(", "a", ",", "n", ")", ".", "toString", "(", ")", ".", "localeCompare", "(", "_this2", ".", "getDescendantProp", "(", "b", ",", "n", ")", ".", "toString", "(", ")", ",", "undefined", ",", "{", "numeric", ":", "true", "}", ")", ";", "}", ";", "return", "arr", ".", "slice", "(", ")", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "reverse", "?", "-", "compare", "(", "a", ",", "b", ",", "key", ")", ":", "compare", "(", "a", ",", "b", ",", "key", ")", ";", "}", ")", ";", "}", "return", "arr", ".", "slice", "(", ")", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "var", "ordered", "=", "map", ".", "indexOf", "(", "_this2", ".", "getDescendantProp", "(", "a", ",", "key", ")", ".", "toString", "(", ")", ")", "-", "map", ".", "indexOf", "(", "_this2", ".", "getDescendantProp", "(", "b", ",", "key", ")", ".", "toString", "(", ")", ")", ";", "return", "reverse", "?", "ordered", "*", "-", "1", ":", "ordered", ";", "}", ")", ";", "}" ]
Sorting an array of objects by values @param {Array} [arr] An Array of objects @param {Mix} [map] Map to custom order. If value isn't an array with values, will do natural sort @param {String} [key] Object key to use for sorting (accepts dot notation) @param {Boolean} [reverse=false] Reverse sorting @returns {Array} New object array with sorting values @example var mapToSort = ['A', 'B', 'C', 'D', 'E']; // Map to sorting var obj = [{param: 'D'}, {param: 'A'}, {param: 'E'}, {param: 'C'}, {param: 'B'}]; globalHelpers.objectArraySortByValue(objToSortByValue, mapToSort, 'param'); //=> [{param: 'A'}, {param: 'B'}, {param: 'C'}, {param: 'D'}, {param: 'E'}] // Deep key var obj = [{deep: {param: 'D'}}, {deep: {param: 'A'}}, {deep: {param: 'E'}}, {deep: {param: 'C'}}, {deep: {param: 'B'}}]; globalHelpers.objectArraySortByValue(objToSortByValue, mapToSort, 'deep.param'); //=> [{deep: {param: 'A'}}, {deep: {param: 'B'}}, {deep: {param: 'C'}}, {deep: {param: 'D'}}, {deep: {param: 'E'}}]
[ "Sorting", "an", "array", "of", "objects", "by", "values" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2583-L2603
train
Zeindelf/utilify-js
dist/utilify.esm.js
objectToArray
function objectToArray(obj) { if (!validateHelpers.isPlainObject(obj)) { throw new Error('\'obj\' must be a plain object'); } return Object.keys(obj).map(function (key) { return obj[key]; }); }
javascript
function objectToArray(obj) { if (!validateHelpers.isPlainObject(obj)) { throw new Error('\'obj\' must be a plain object'); } return Object.keys(obj).map(function (key) { return obj[key]; }); }
[ "function", "objectToArray", "(", "obj", ")", "{", "if", "(", "!", "validateHelpers", ".", "isPlainObject", "(", "obj", ")", ")", "{", "throw", "new", "Error", "(", "'\\'obj\\' must be a plain object'", ")", ";", "}", "\\'", "}" ]
Convert object given into an array values @param {Object} obj Object to convert @return {Array} @example const obj = {a: 'a', b: 'b'}; objectToArray(obj); // ['a', 'b']
[ "Convert", "object", "given", "into", "an", "array", "values" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2682-L2690
train
Zeindelf/utilify-js
dist/utilify.esm.js
renameKeys
function renameKeys(obj, keysMap) { if (!validateHelpers.isPlainObject(obj)) { throw new Error('\'obj\' must be an plain object'); } return Object.keys(obj).reduce(function (acc, key) { return _extends({}, acc, defineProperty({}, keysMap[key] || key, obj[key])); }, {}); }
javascript
function renameKeys(obj, keysMap) { if (!validateHelpers.isPlainObject(obj)) { throw new Error('\'obj\' must be an plain object'); } return Object.keys(obj).reduce(function (acc, key) { return _extends({}, acc, defineProperty({}, keysMap[key] || key, obj[key])); }, {}); }
[ "function", "renameKeys", "(", "obj", ",", "keysMap", ")", "{", "if", "(", "!", "validateHelpers", ".", "isPlainObject", "(", "obj", ")", ")", "{", "throw", "new", "Error", "(", "'\\'obj\\' must be an plain object'", ")", ";", "}", "\\'", "}" ]
Replaces the names of multiple object keys with the values provided. @param {Object} obj The plain object @param {Object} keysMap Object with key and value to replace @returns {Object} @example const obj = { name: 'John', surename: 'Smith', age: 20 }; renameKeys(obj, { name: 'firstName', surename: 'lastName' }); //=> { firstName: 'John', lastName: 'Smith', age: 20 }
[ "Replaces", "the", "names", "of", "multiple", "object", "keys", "with", "the", "values", "provided", "." ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L2704-L2712
train
Zeindelf/utilify-js
dist/utilify.esm.js
getUserLocation
function getUserLocation(cache, storage) { var _this = this; if (cache) { this._initLocationStorage(storage); } var store = storage.session.get(CONSTANTS.STORAGE_NAME); /* eslint-disable */ return $.Deferred(function (def) { /* eslint-enable */ if (!validateHelpers.isObjectEmpty(store)) { def.resolve(store); } else { if (window.navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { var lat = position.coords.latitude; var lng = position.coords.longitude; if (!window.google) { return def.reject('Google Maps Javascript API not found. Follow tutorial: https://developers.google.com/maps/documentation/javascript'); } var latlng = new google.maps.LatLng(lat, lng); var geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'latLng': latlng }, function (results, status) { if (status === google.maps.GeocoderStatus.OK) { if (results[1]) { for (var i = 0, len = results.length; i < len; i += 1) { if (results[i].types[0] === 'locality') { var city = results[i].address_components[0].short_name; var state = results[i].address_components[2].short_name; var storeLocation = { coords: { lat: lat, lng: lng }, city: city, state: state, region: _this.filteredRegion(state) }; if (cache) { storage.session.set(CONSTANTS.STORAGE_NAME, storeLocation, CONSTANTS.EXPIRE_TIME); } def.resolve(storeLocation); } } } else { def.reject('No reverse geocode results.'); } } else { def.reject('Geocoder failed: ' + status); } }); }, function (err) { def.reject('Geolocation not available.'); }); } else { def.reject('Geolocation isn\'t available'); } } }).promise(); }
javascript
function getUserLocation(cache, storage) { var _this = this; if (cache) { this._initLocationStorage(storage); } var store = storage.session.get(CONSTANTS.STORAGE_NAME); /* eslint-disable */ return $.Deferred(function (def) { /* eslint-enable */ if (!validateHelpers.isObjectEmpty(store)) { def.resolve(store); } else { if (window.navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { var lat = position.coords.latitude; var lng = position.coords.longitude; if (!window.google) { return def.reject('Google Maps Javascript API not found. Follow tutorial: https://developers.google.com/maps/documentation/javascript'); } var latlng = new google.maps.LatLng(lat, lng); var geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'latLng': latlng }, function (results, status) { if (status === google.maps.GeocoderStatus.OK) { if (results[1]) { for (var i = 0, len = results.length; i < len; i += 1) { if (results[i].types[0] === 'locality') { var city = results[i].address_components[0].short_name; var state = results[i].address_components[2].short_name; var storeLocation = { coords: { lat: lat, lng: lng }, city: city, state: state, region: _this.filteredRegion(state) }; if (cache) { storage.session.set(CONSTANTS.STORAGE_NAME, storeLocation, CONSTANTS.EXPIRE_TIME); } def.resolve(storeLocation); } } } else { def.reject('No reverse geocode results.'); } } else { def.reject('Geocoder failed: ' + status); } }); }, function (err) { def.reject('Geolocation not available.'); }); } else { def.reject('Geolocation isn\'t available'); } } }).promise(); }
[ "function", "getUserLocation", "(", "cache", ",", "storage", ")", "{", "var", "_this", "=", "this", ";", "if", "(", "cache", ")", "{", "this", ".", "_initLocationStorage", "(", "storage", ")", ";", "}", "var", "store", "=", "storage", ".", "session", ".", "get", "(", "CONSTANTS", ".", "STORAGE_NAME", ")", ";", "return", "$", ".", "Deferred", "(", "function", "(", "def", ")", "{", "if", "(", "!", "validateHelpers", ".", "isObjectEmpty", "(", "store", ")", ")", "{", "def", ".", "resolve", "(", "store", ")", ";", "}", "else", "{", "if", "(", "window", ".", "navigator", ".", "geolocation", ")", "{", "navigator", ".", "geolocation", ".", "getCurrentPosition", "(", "function", "(", "position", ")", "{", "var", "lat", "=", "position", ".", "coords", ".", "latitude", ";", "var", "lng", "=", "position", ".", "coords", ".", "longitude", ";", "if", "(", "!", "window", ".", "google", ")", "{", "return", "def", ".", "reject", "(", "'Google Maps Javascript API not found. Follow tutorial: https://developers.google.com/maps/documentation/javascript'", ")", ";", "}", "var", "latlng", "=", "new", "google", ".", "maps", ".", "LatLng", "(", "lat", ",", "lng", ")", ";", "var", "geocoder", "=", "new", "google", ".", "maps", ".", "Geocoder", "(", ")", ";", "geocoder", ".", "geocode", "(", "{", "'latLng'", ":", "latlng", "}", ",", "function", "(", "results", ",", "status", ")", "{", "if", "(", "status", "===", "google", ".", "maps", ".", "GeocoderStatus", ".", "OK", ")", "{", "if", "(", "results", "[", "1", "]", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "results", ".", "length", ";", "i", "<", "len", ";", "i", "+=", "1", ")", "{", "if", "(", "results", "[", "i", "]", ".", "types", "[", "0", "]", "===", "'locality'", ")", "{", "var", "city", "=", "results", "[", "i", "]", ".", "address_components", "[", "0", "]", ".", "short_name", ";", "var", "state", "=", "results", "[", "i", "]", ".", "address_components", "[", "2", "]", ".", "short_name", ";", "var", "storeLocation", "=", "{", "coords", ":", "{", "lat", ":", "lat", ",", "lng", ":", "lng", "}", ",", "city", ":", "city", ",", "state", ":", "state", ",", "region", ":", "_this", ".", "filteredRegion", "(", "state", ")", "}", ";", "if", "(", "cache", ")", "{", "storage", ".", "session", ".", "set", "(", "CONSTANTS", ".", "STORAGE_NAME", ",", "storeLocation", ",", "CONSTANTS", ".", "EXPIRE_TIME", ")", ";", "}", "def", ".", "resolve", "(", "storeLocation", ")", ";", "}", "}", "}", "else", "{", "def", ".", "reject", "(", "'No reverse geocode results.'", ")", ";", "}", "}", "else", "{", "def", ".", "reject", "(", "'Geocoder failed: '", "+", "status", ")", ";", "}", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "def", ".", "reject", "(", "'Geolocation not available.'", ")", ";", "}", ")", ";", "}", "else", "{", "def", ".", "reject", "(", "'Geolocation isn\\'t available'", ")", ";", "}", "}", "}", ")", ".", "\\'", "promise", ";", "}" ]
Get user location by HTML5 Geolocate API and translate coordinates to Brazilian State, City and Region @param {Boolean} cache Save user coordinates into localstorage @param {Object} storage Store2 lib instance @return {Promise} When success, response are an object with State, City, Region and user Coordinates @example locationHelpers.getCityState() .then(function(res) { window.console.log(res); }) .fail(function(err) { window.console.log(err); });
[ "Get", "user", "location", "by", "HTML5", "Geolocate", "API", "and", "translate", "coordinates", "to", "Brazilian", "State", "City", "and", "Region" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L3166-L3229
train
Zeindelf/utilify-js
dist/utilify.esm.js
filteredRegion
function filteredRegion(state) { var _this2 = this; var filteredRegion = ''; var _loop = function _loop(region) { if ({}.hasOwnProperty.call(_this2._regionMap, region)) { _this2._regionMap[region].some(function (el, i, arr) { if (stringHelpers.removeAccent(el.toLowerCase()) === stringHelpers.removeAccent(state.toLowerCase())) { filteredRegion = region; } }); } }; for (var region in this._regionMap) { _loop(region); } return filteredRegion; }
javascript
function filteredRegion(state) { var _this2 = this; var filteredRegion = ''; var _loop = function _loop(region) { if ({}.hasOwnProperty.call(_this2._regionMap, region)) { _this2._regionMap[region].some(function (el, i, arr) { if (stringHelpers.removeAccent(el.toLowerCase()) === stringHelpers.removeAccent(state.toLowerCase())) { filteredRegion = region; } }); } }; for (var region in this._regionMap) { _loop(region); } return filteredRegion; }
[ "function", "filteredRegion", "(", "state", ")", "{", "var", "_this2", "=", "this", ";", "var", "filteredRegion", "=", "''", ";", "var", "_loop", "=", "function", "_loop", "(", "region", ")", "{", "if", "(", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "_this2", ".", "_regionMap", ",", "region", ")", ")", "{", "_this2", ".", "_regionMap", "[", "region", "]", ".", "some", "(", "function", "(", "el", ",", "i", ",", "arr", ")", "{", "if", "(", "stringHelpers", ".", "removeAccent", "(", "el", ".", "toLowerCase", "(", ")", ")", "===", "stringHelpers", ".", "removeAccent", "(", "state", ".", "toLowerCase", "(", ")", ")", ")", "{", "filteredRegion", "=", "region", ";", "}", "}", ")", ";", "}", "}", ";", "for", "(", "var", "region", "in", "this", ".", "_regionMap", ")", "{", "_loop", "(", "region", ")", ";", "}", "return", "filteredRegion", ";", "}" ]
Get Brazilian region for an state initials given @param {String} state Initials state (e.g. 'SP') @return {String} Region (Norte, Sul, etc.) @example locationHelpers.filteredRegion('SP'); // Sudeste
[ "Get", "Brazilian", "region", "for", "an", "state", "initials", "given" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L3240-L3260
train
Zeindelf/utilify-js
dist/utilify.esm.js
Utilify
function Utilify() { classCallCheck(this, Utilify); /** * Version * @type {String} */ this.version = '0.10.1'; /** * Package name * @type {String} */ this.name = '@UtilifyJS'; /** * Global Helpers instance * @type {GlobalHelpers} */ this.globalHelpers = new GlobalHelpers(); /** * Location Helpers instance * @type {LocationHelpers} */ this.locationHelpers = new LocationHelpers(store); /** * Local/Session Storage * @type {Object} */ this.storage = store; /** * JS Cookies * @type {Object} */ this.cookies = initCookies(function () {}); }
javascript
function Utilify() { classCallCheck(this, Utilify); /** * Version * @type {String} */ this.version = '0.10.1'; /** * Package name * @type {String} */ this.name = '@UtilifyJS'; /** * Global Helpers instance * @type {GlobalHelpers} */ this.globalHelpers = new GlobalHelpers(); /** * Location Helpers instance * @type {LocationHelpers} */ this.locationHelpers = new LocationHelpers(store); /** * Local/Session Storage * @type {Object} */ this.storage = store; /** * JS Cookies * @type {Object} */ this.cookies = initCookies(function () {}); }
[ "function", "Utilify", "(", ")", "{", "classCallCheck", "(", "this", ",", "Utilify", ")", ";", "this", ".", "version", "=", "'0.10.1'", ";", "this", ".", "name", "=", "'@UtilifyJS'", ";", "this", ".", "globalHelpers", "=", "new", "GlobalHelpers", "(", ")", ";", "this", ".", "locationHelpers", "=", "new", "LocationHelpers", "(", "store", ")", ";", "this", ".", "storage", "=", "store", ";", "this", ".", "cookies", "=", "initCookies", "(", "function", "(", ")", "{", "}", ")", ";", "}" ]
Create a Utilify class Main class
[ "Create", "a", "Utilify", "class", "Main", "class" ]
a16f6e578c953b10cec5ca89c06aeba73ff6674f
https://github.com/Zeindelf/utilify-js/blob/a16f6e578c953b10cec5ca89c06aeba73ff6674f/dist/utilify.esm.js#L3338-L3376
train
avoidwork/abaaso
src/datalist.js
function ( target, store, template, options ) { var ref = [store], obj, instance; if ( !( target instanceof Element ) || typeof store !== "object" || !regex.string_object.test( typeof template ) ) { throw new Error( label.error.invalidArguments ); } obj = element.create( "ul", {"class": "list", id: store.parentNode.id + "-datalist"}, target ); // Creating instance instance = new DataList( obj, ref[0], template ); if ( options instanceof Object) { utility.merge( instance, options ); } instance.store.datalists.push( instance ); // Rendering if not tied to an API or data is ready if ( instance.store.uri === null || instance.store.loaded ) { instance.refresh(); } return instance; }
javascript
function ( target, store, template, options ) { var ref = [store], obj, instance; if ( !( target instanceof Element ) || typeof store !== "object" || !regex.string_object.test( typeof template ) ) { throw new Error( label.error.invalidArguments ); } obj = element.create( "ul", {"class": "list", id: store.parentNode.id + "-datalist"}, target ); // Creating instance instance = new DataList( obj, ref[0], template ); if ( options instanceof Object) { utility.merge( instance, options ); } instance.store.datalists.push( instance ); // Rendering if not tied to an API or data is ready if ( instance.store.uri === null || instance.store.loaded ) { instance.refresh(); } return instance; }
[ "function", "(", "target", ",", "store", ",", "template", ",", "options", ")", "{", "var", "ref", "=", "[", "store", "]", ",", "obj", ",", "instance", ";", "if", "(", "!", "(", "target", "instanceof", "Element", ")", "||", "typeof", "store", "!==", "\"object\"", "||", "!", "regex", ".", "string_object", ".", "test", "(", "typeof", "template", ")", ")", "{", "throw", "new", "Error", "(", "label", ".", "error", ".", "invalidArguments", ")", ";", "}", "obj", "=", "element", ".", "create", "(", "\"ul\"", ",", "{", "\"class\"", ":", "\"list\"", ",", "id", ":", "store", ".", "parentNode", ".", "id", "+", "\"-datalist\"", "}", ",", "target", ")", ";", "instance", "=", "new", "DataList", "(", "obj", ",", "ref", "[", "0", "]", ",", "template", ")", ";", "if", "(", "options", "instanceof", "Object", ")", "{", "utility", ".", "merge", "(", "instance", ",", "options", ")", ";", "}", "instance", ".", "store", ".", "datalists", ".", "push", "(", "instance", ")", ";", "if", "(", "instance", ".", "store", ".", "uri", "===", "null", "||", "instance", ".", "store", ".", "loaded", ")", "{", "instance", ".", "refresh", "(", ")", ";", "}", "return", "instance", ";", "}" ]
Creates an instance of datalist @method factory @param {Object} target Element to receive the DataList @param {Object} store Data store to feed the DataList @param {Mixed} template Record field, template ( $.tpl ), or String, e.g. "<p>this is a {{field}} sample.</p>", fields are marked with {{ }} @param {Object} options Optional parameters to set on the DataList @return {Object} DataList instance
[ "Creates", "an", "instance", "of", "datalist" ]
07c147684bccd28868f377881eb80ffc285cd483
https://github.com/avoidwork/abaaso/blob/07c147684bccd28868f377881eb80ffc285cd483/src/datalist.js#L13-L38
train
avoidwork/abaaso
src/datalist.js
function () { if ( isNaN( this.pageSize ) ) { throw new Error( label.error.invalidArguments ); } return number.round( ( !this.filter ? this.total : this.filtered.length ) / this.pageSize, "up" ); }
javascript
function () { if ( isNaN( this.pageSize ) ) { throw new Error( label.error.invalidArguments ); } return number.round( ( !this.filter ? this.total : this.filtered.length ) / this.pageSize, "up" ); }
[ "function", "(", ")", "{", "if", "(", "isNaN", "(", "this", ".", "pageSize", ")", ")", "{", "throw", "new", "Error", "(", "label", ".", "error", ".", "invalidArguments", ")", ";", "}", "return", "number", ".", "round", "(", "(", "!", "this", ".", "filter", "?", "this", ".", "total", ":", "this", ".", "filtered", ".", "length", ")", "/", "this", ".", "pageSize", ",", "\"up\"", ")", ";", "}" ]
Calculates the total pages @method pages @private @return {Number} Total pages
[ "Calculates", "the", "total", "pages" ]
07c147684bccd28868f377881eb80ffc285cd483
https://github.com/avoidwork/abaaso/blob/07c147684bccd28868f377881eb80ffc285cd483/src/datalist.js#L47-L53
train
spreadshirt/rAppid.js-sprd
sprd/type/UploadDesign.js
function (fileName) { fileName = (fileName || "").toLowerCase(); var validExtensions = ["svg", "cdr", "eps", "ai"], fileExtension = fileName.substr(fileName.lastIndexOf('.') + 1); return validExtensions.indexOf(fileExtension) != -1; }
javascript
function (fileName) { fileName = (fileName || "").toLowerCase(); var validExtensions = ["svg", "cdr", "eps", "ai"], fileExtension = fileName.substr(fileName.lastIndexOf('.') + 1); return validExtensions.indexOf(fileExtension) != -1; }
[ "function", "(", "fileName", ")", "{", "fileName", "=", "(", "fileName", "||", "\"\"", ")", ".", "toLowerCase", "(", ")", ";", "var", "validExtensions", "=", "[", "\"svg\"", ",", "\"cdr\"", ",", "\"eps\"", ",", "\"ai\"", "]", ",", "fileExtension", "=", "fileName", ".", "substr", "(", "fileName", ".", "lastIndexOf", "(", "'.'", ")", "+", "1", ")", ";", "return", "validExtensions", ".", "indexOf", "(", "fileExtension", ")", "!=", "-", "1", ";", "}" ]
Checks if the file name matches a correct extension for a vector file. @param {String} fileName @returns {boolean}
[ "Checks", "if", "the", "file", "name", "matches", "a", "correct", "extension", "for", "a", "vector", "file", "." ]
b56f9f47fe01332f5bf885eaf4db59014f099019
https://github.com/spreadshirt/rAppid.js-sprd/blob/b56f9f47fe01332f5bf885eaf4db59014f099019/sprd/type/UploadDesign.js#L103-L109
train
tinwatchman/grawlix
spec/util-spec.js
function(pluginOptions, options) { options.isFactoryFunctionRun = true; return new GrawlixPlugin({ name: 'blank-plugin-2', init: function(opts) { opts.isLoaded = true; } }); }
javascript
function(pluginOptions, options) { options.isFactoryFunctionRun = true; return new GrawlixPlugin({ name: 'blank-plugin-2', init: function(opts) { opts.isLoaded = true; } }); }
[ "function", "(", "pluginOptions", ",", "options", ")", "{", "options", ".", "isFactoryFunctionRun", "=", "true", ";", "return", "new", "GrawlixPlugin", "(", "{", "name", ":", "'blank-plugin-2'", ",", "init", ":", "function", "(", "opts", ")", "{", "opts", ".", "isLoaded", "=", "true", ";", "}", "}", ")", ";", "}" ]
factory function plugin
[ "factory", "function", "plugin" ]
235cd9629992b97c62953b813d5034a9546211f1
https://github.com/tinwatchman/grawlix/blob/235cd9629992b97c62953b813d5034a9546211f1/spec/util-spec.js#L644-L652
train
LockateMe/cordova-plugin-minisodium
www/MiniSodium.js
function(ed25519Sk, callback){ if (typeof callback != 'function') throw new TypeError('callback must be a function'); try { isValidInput(ed25519Sk, 'ed25519Sk', MiniSodium.crypto_sign_SECRETKEYBYTES); } catch (e){ callback(e); return; } ed25519Sk = to_hex(ed25519Sk); var params = [ed25519Sk]; cordova.exec(resultHandlerFactory(callback), callback, 'MiniSodium', 'crypto_sign_ed25519_sk_to_curve25519', params); }
javascript
function(ed25519Sk, callback){ if (typeof callback != 'function') throw new TypeError('callback must be a function'); try { isValidInput(ed25519Sk, 'ed25519Sk', MiniSodium.crypto_sign_SECRETKEYBYTES); } catch (e){ callback(e); return; } ed25519Sk = to_hex(ed25519Sk); var params = [ed25519Sk]; cordova.exec(resultHandlerFactory(callback), callback, 'MiniSodium', 'crypto_sign_ed25519_sk_to_curve25519', params); }
[ "function", "(", "ed25519Sk", ",", "callback", ")", "{", "if", "(", "typeof", "callback", "!=", "'function'", ")", "throw", "new", "TypeError", "(", "'callback must be a function'", ")", ";", "try", "{", "isValidInput", "(", "ed25519Sk", ",", "'ed25519Sk'", ",", "MiniSodium", ".", "crypto_sign_SECRETKEYBYTES", ")", ";", "}", "catch", "(", "e", ")", "{", "callback", "(", "e", ")", ";", "return", ";", "}", "ed25519Sk", "=", "to_hex", "(", "ed25519Sk", ")", ";", "var", "params", "=", "[", "ed25519Sk", "]", ";", "cordova", ".", "exec", "(", "resultHandlerFactory", "(", "callback", ")", ",", "callback", ",", "'MiniSodium'", ",", "'crypto_sign_ed25519_sk_to_curve25519'", ",", "params", ")", ";", "}" ]
Ed25519 -> Curve25519 keypair conversion
[ "Ed25519", "-", ">", "Curve25519", "keypair", "conversion" ]
4527565db27c488deca5f949d562192526ef1748
https://github.com/LockateMe/cordova-plugin-minisodium/blob/4527565db27c488deca5f949d562192526ef1748/www/MiniSodium.js#L220-L233
train
LockateMe/cordova-plugin-minisodium
www/MiniSodium.js
function(str) { if (str instanceof Uint8Array) return str; if (!is_hex(str)) { throw new TypeError("The provided string doesn't look like hex data"); } var result = new Uint8Array(str.length / 2); for (var i = 0; i < str.length; i += 2) { result[i >>> 1] = parseInt(str.substr(i, 2), 16); } return result; }
javascript
function(str) { if (str instanceof Uint8Array) return str; if (!is_hex(str)) { throw new TypeError("The provided string doesn't look like hex data"); } var result = new Uint8Array(str.length / 2); for (var i = 0; i < str.length; i += 2) { result[i >>> 1] = parseInt(str.substr(i, 2), 16); } return result; }
[ "function", "(", "str", ")", "{", "if", "(", "str", "instanceof", "Uint8Array", ")", "return", "str", ";", "if", "(", "!", "is_hex", "(", "str", ")", ")", "{", "throw", "new", "TypeError", "(", "\"The provided string doesn't look like hex data\"", ")", ";", "}", "var", "result", "=", "new", "Uint8Array", "(", "str", ".", "length", "/", "2", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "str", ".", "length", ";", "i", "+=", "2", ")", "{", "result", "[", "i", ">>>", "1", "]", "=", "parseInt", "(", "str", ".", "substr", "(", "i", ",", "2", ")", ",", "16", ")", ";", "}", "return", "result", ";", "}" ]
Hexdecimal encoding helpers
[ "Hexdecimal", "encoding", "helpers" ]
4527565db27c488deca5f949d562192526ef1748
https://github.com/LockateMe/cordova-plugin-minisodium/blob/4527565db27c488deca5f949d562192526ef1748/www/MiniSodium.js#L472-L482
train
Dashron/roads
src/middleware/simpleRouter.js
buildRouterPath
function buildRouterPath(path, prefix) { if (!prefix) { prefix = ''; } if (prefix.length && path === '/') { return prefix; } return prefix + path; }
javascript
function buildRouterPath(path, prefix) { if (!prefix) { prefix = ''; } if (prefix.length && path === '/') { return prefix; } return prefix + path; }
[ "function", "buildRouterPath", "(", "path", ",", "prefix", ")", "{", "if", "(", "!", "prefix", ")", "{", "prefix", "=", "''", ";", "}", "if", "(", "prefix", ".", "length", "&&", "path", "===", "'/'", ")", "{", "return", "prefix", ";", "}", "return", "prefix", "+", "path", ";", "}" ]
Applies a prefix to paths of route files @todo I'm pretty sure there's an existing library that will do this more accurately @param {string} path - The HTTP path of a route @param {string} [prefix] - An optional prefix for the HTTP path
[ "Applies", "a", "prefix", "to", "paths", "of", "route", "files" ]
c089d79d8181063c7fae00432a79b7a79a7809d3
https://github.com/Dashron/roads/blob/c089d79d8181063c7fae00432a79b7a79a7809d3/src/middleware/simpleRouter.js#L19-L29
train
Dashron/roads
src/middleware/simpleRouter.js
compareRouteAndApplyArgs
function compareRouteAndApplyArgs (route, request_url, request_method) { if (route.method !== request_method) { return false; } let template = route.path.split('/'); if (template[0] === '') { template = template.slice(1); // Slice kills the emptystring before the leading slash } let actual = request_url.pathname.split('/'); if (actual[0] === '') { actual = actual.slice(1); // Slice kills the emptystring before the leading slash } if (template.length != actual.length) { return false; } for (let i = 0; i < template.length; i++) { let actual_part = actual[i]; let template_part = template[i]; // Process variables first if (template_part[0] === '#') { // # templates only accept numbers if (isNaN(Number(actual_part))) { return false; } applyArg(request_url, template_part.substring(1), Number(actual_part)); continue; } if (template_part[0] === '$') { // $ templates accept any non-slash alphanumeric character applyArg(request_url, template_part.substring(1), String(actual_part)); // Continue so that continue; } // Process exact matches second if (actual_part === template_part) { continue; } return false; } return true; }
javascript
function compareRouteAndApplyArgs (route, request_url, request_method) { if (route.method !== request_method) { return false; } let template = route.path.split('/'); if (template[0] === '') { template = template.slice(1); // Slice kills the emptystring before the leading slash } let actual = request_url.pathname.split('/'); if (actual[0] === '') { actual = actual.slice(1); // Slice kills the emptystring before the leading slash } if (template.length != actual.length) { return false; } for (let i = 0; i < template.length; i++) { let actual_part = actual[i]; let template_part = template[i]; // Process variables first if (template_part[0] === '#') { // # templates only accept numbers if (isNaN(Number(actual_part))) { return false; } applyArg(request_url, template_part.substring(1), Number(actual_part)); continue; } if (template_part[0] === '$') { // $ templates accept any non-slash alphanumeric character applyArg(request_url, template_part.substring(1), String(actual_part)); // Continue so that continue; } // Process exact matches second if (actual_part === template_part) { continue; } return false; } return true; }
[ "function", "compareRouteAndApplyArgs", "(", "route", ",", "request_url", ",", "request_method", ")", "{", "if", "(", "route", ".", "method", "!==", "request_method", ")", "{", "return", "false", ";", "}", "let", "template", "=", "route", ".", "path", ".", "split", "(", "'/'", ")", ";", "if", "(", "template", "[", "0", "]", "===", "''", ")", "{", "template", "=", "template", ".", "slice", "(", "1", ")", ";", "}", "let", "actual", "=", "request_url", ".", "pathname", ".", "split", "(", "'/'", ")", ";", "if", "(", "actual", "[", "0", "]", "===", "''", ")", "{", "actual", "=", "actual", ".", "slice", "(", "1", ")", ";", "}", "if", "(", "template", ".", "length", "!=", "actual", ".", "length", ")", "{", "return", "false", ";", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "template", ".", "length", ";", "i", "++", ")", "{", "let", "actual_part", "=", "actual", "[", "i", "]", ";", "let", "template_part", "=", "template", "[", "i", "]", ";", "if", "(", "template_part", "[", "0", "]", "===", "'#'", ")", "{", "if", "(", "isNaN", "(", "Number", "(", "actual_part", ")", ")", ")", "{", "return", "false", ";", "}", "applyArg", "(", "request_url", ",", "template_part", ".", "substring", "(", "1", ")", ",", "Number", "(", "actual_part", ")", ")", ";", "continue", ";", "}", "if", "(", "template_part", "[", "0", "]", "===", "'$'", ")", "{", "applyArg", "(", "request_url", ",", "template_part", ".", "substring", "(", "1", ")", ",", "String", "(", "actual_part", ")", ")", ";", "continue", ";", "}", "if", "(", "actual_part", "===", "template_part", ")", "{", "continue", ";", "}", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks to see if the route matches the request, and if true assigns any applicable url variables and returns the route @param {object} route - Route object from this simple router class @param {object} route.method - HTTP method associated with this route @param {object} route.path - HTTP path associated with this route @param {object} request_url - Parsed HTTP request url @param {string} request_method - HTTP request method
[ "Checks", "to", "see", "if", "the", "route", "matches", "the", "request", "and", "if", "true", "assigns", "any", "applicable", "url", "variables", "and", "returns", "the", "route" ]
c089d79d8181063c7fae00432a79b7a79a7809d3
https://github.com/Dashron/roads/blob/c089d79d8181063c7fae00432a79b7a79a7809d3/src/middleware/simpleRouter.js#L154-L204
train
Dashron/roads
src/middleware/simpleRouter.js
applyArg
function applyArg(request_url, template_part, actual_part) { if (typeof(request_url.args) === "undefined") { request_url.args = {}; } if (typeof request_url.args !== "object") { throw new Error("The request url's args have already been defined as a " + typeof request_url.args + " and we expected an object. For safety we are throwing this error instead of overwriting your existing data. Please use a different field name in your code"); } request_url.args[template_part] = actual_part; }
javascript
function applyArg(request_url, template_part, actual_part) { if (typeof(request_url.args) === "undefined") { request_url.args = {}; } if (typeof request_url.args !== "object") { throw new Error("The request url's args have already been defined as a " + typeof request_url.args + " and we expected an object. For safety we are throwing this error instead of overwriting your existing data. Please use a different field name in your code"); } request_url.args[template_part] = actual_part; }
[ "function", "applyArg", "(", "request_url", ",", "template_part", ",", "actual_part", ")", "{", "if", "(", "typeof", "(", "request_url", ".", "args", ")", "===", "\"undefined\"", ")", "{", "request_url", ".", "args", "=", "{", "}", ";", "}", "if", "(", "typeof", "request_url", ".", "args", "!==", "\"object\"", ")", "{", "throw", "new", "Error", "(", "\"The request url's args have already been defined as a \"", "+", "typeof", "request_url", ".", "args", "+", "\" and we expected an object. For safety we are throwing this error instead of overwriting your existing data. Please use a different field name in your code\"", ")", ";", "}", "request_url", ".", "args", "[", "template_part", "]", "=", "actual_part", ";", "}" ]
Assigns a value to the parsed request urls args parameter @param {object} request_url - The parsed url object @param {string} template_part - The template variable @param {*} actual_part - The url value
[ "Assigns", "a", "value", "to", "the", "parsed", "request", "urls", "args", "parameter" ]
c089d79d8181063c7fae00432a79b7a79a7809d3
https://github.com/Dashron/roads/blob/c089d79d8181063c7fae00432a79b7a79a7809d3/src/middleware/simpleRouter.js#L213-L223
train
felixrieseberg/windows-notification-state
lib/index.js
getNotificationState
function getNotificationState () { if (process.platform !== 'win32') { throw new Error('windows-notification-state only works on windows') } const QUERY_USER_NOTIFICATION_STATE = [ '', 'QUNS_NOT_PRESENT', 'QUNS_BUSY', 'QUNS_RUNNING_D3D_FULL_SCREEN', 'QUNS_PRESENTATION_MODE', 'QUNS_ACCEPTS_NOTIFICATIONS', 'QUNS_QUIET_TIME', 'QUNS_APP' ] const result = addon.getNotificationState() if (QUERY_USER_NOTIFICATION_STATE[result]) { return QUERY_USER_NOTIFICATION_STATE[result] } else { return 'UNKNOWN_ERROR' } }
javascript
function getNotificationState () { if (process.platform !== 'win32') { throw new Error('windows-notification-state only works on windows') } const QUERY_USER_NOTIFICATION_STATE = [ '', 'QUNS_NOT_PRESENT', 'QUNS_BUSY', 'QUNS_RUNNING_D3D_FULL_SCREEN', 'QUNS_PRESENTATION_MODE', 'QUNS_ACCEPTS_NOTIFICATIONS', 'QUNS_QUIET_TIME', 'QUNS_APP' ] const result = addon.getNotificationState() if (QUERY_USER_NOTIFICATION_STATE[result]) { return QUERY_USER_NOTIFICATION_STATE[result] } else { return 'UNKNOWN_ERROR' } }
[ "function", "getNotificationState", "(", ")", "{", "if", "(", "process", ".", "platform", "!==", "'win32'", ")", "{", "throw", "new", "Error", "(", "'windows-notification-state only works on windows'", ")", "}", "const", "QUERY_USER_NOTIFICATION_STATE", "=", "[", "''", ",", "'QUNS_NOT_PRESENT'", ",", "'QUNS_BUSY'", ",", "'QUNS_RUNNING_D3D_FULL_SCREEN'", ",", "'QUNS_PRESENTATION_MODE'", ",", "'QUNS_ACCEPTS_NOTIFICATIONS'", ",", "'QUNS_QUIET_TIME'", ",", "'QUNS_APP'", "]", "const", "result", "=", "addon", ".", "getNotificationState", "(", ")", "if", "(", "QUERY_USER_NOTIFICATION_STATE", "[", "result", "]", ")", "{", "return", "QUERY_USER_NOTIFICATION_STATE", "[", "result", "]", "}", "else", "{", "return", "'UNKNOWN_ERROR'", "}", "}" ]
Returns the name of the QUERY_USER_NOTIFICATION_STATE enum rather than a number. @returns {string} QUERY_USER_NOTIFICATION_STATE
[ "Returns", "the", "name", "of", "the", "QUERY_USER_NOTIFICATION_STATE", "enum", "rather", "than", "a", "number", "." ]
a8e0710997f1744eb8129e691513f235f681807e
https://github.com/felixrieseberg/windows-notification-state/blob/a8e0710997f1744eb8129e691513f235f681807e/lib/index.js#L22-L45
train