anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
componentDidMount() { this.getDataFromDb(); if (!this.state.intervalIsSet) { let interval = setInterval(this.getDataFromDb, 1000); this.setState({ intervalIsSet: interval }); } }
when component mounts, first thing it does is fetch all existing data in our db then we incorporate a polling logic so that we can easily see if our db has changed and implement those changes into our UI
updateMachineRecipeLocation(recipeURL) { if (!this.copyOriginFactory) { return; } let machineConfig = this.copyOriginFactory.workspace.environments[0].machines[0]; machineConfig.source.type = 'recipe'; machineConfig.source.location = recipeURL; this.updateFactory(); }
Update the machine recipe URL
function deletetrue_false(id) { let f = confirm("Are you Sure"); if (f == true) { firebase .database() .ref("Types") .child(_typeId) .child(id) .remove(); firebase .database() .ref("Test") .child(_courseID) .child("Levels") .child(_levelID) ....
Delete the true_false using id and update the table
canTransitionToStep(wizard, destinationIndex) { return this.isNavigable(wizard, destinationIndex); }
Imposes additional restrictions for `canGoToStep` in current navigation mode. The base implementation allows transition iff the given step is navigable from the navigation bar (see `isNavigable`). However, in some navigation modes `canTransitionToStep` can be more relaxed to allow navigation to certain steps by previou...
function configFromISO(config) { var i, l, string = config._i, match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), allowTime, dateFormat, timeFormat, tzFormat; if (match) { getParsingFlags(config).iso = true; for (i = 0, l = ...
date from iso format
function Obj() { //函数有自己的this const f = ()=>console.log(this); f(); }
o is the this
function cfnPatchBaselinePropsToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnPatchBaselinePropsValidator(properties).assertSuccess(); return { Name: cdk.stringToCloudFormation(properties.name), ApprovalRules: cfnPatchBaselineRuleGroupPro...
Renders the AWS CloudFormation properties of an `AWS::SSM::PatchBaseline` resource
function queuePhotos(file, index, length) { $.ajax({ url: "/queue_photos", type: 'POST', data: {filename: file.filename, data: file.data}, success: function(data, status, xhr) {}, complete: function(data, status, xhr) { if (index + 1 ==...
POST the photo name and data to /queue_photos route via an AJAX request
getOtherPlayerList() { let observable = new rxjs__WEBPACK_IMPORTED_MODULE_2__["Observable"](observer => { this.socket.on('serverUpdatePlayerList', (msg) => { var output = this.getAllOtherPlayersList(msg); observer.next(output); }); return () =>...
get the list of all players excluding current player
function _safely_install_sigint_listener() { const listeners = process.listeners(SIGINT); const existingListeners = []; for (let i = 0, length = listeners.length; i < length; i++) { const lstnr = listeners[i]; /* istanbul ignore else */ if (lstnr.name === '_tmp$sigint_listener') { existingListe...
Safely install SIGINT listener. NOTE: this will only work on OSX and Linux.
function hide(Id){ document.getElementById(Id).style.display = "none"; }
Function to change display property to none.
function Calendar_Class(ClassCSS){ jq( "."+ClassCSS ).datepicker(); }
cargar el calendario atraves de un clase jquery para funciones tienen que estar cargada la clase
practTableSearch(event) { event.preventDefault(); var searchText = event.currentTarget.value; var filter = searchText.toUpperCase(); var table = document.getElementById("ExamListTable"); var tr = table.getElementsByTagName("tr"); // Loop through all table rows, and hide those who don't m...
exam search by exam name
function rotateAndPaintImage ( context, image, angleInRad , bird ) { var TO_RADIANS = Math.PI/180; var yAdjuster = angleInRad < 0 ? (-angleInRad/5) : (-angleInRad/3); var xAdjuster = angleInRad > angleInRad/2.5 ? angleInRad/3 : 0 var middleX = bird.aabb.x + xAdjuster; var middle...
Helper function to rotate the bird depending on their vertical velocity
function start() { connection.query("SELECT * FROM products", function(err, res) { if (err) throw err; console.log( "--------------------------------------------------------------------------------" ); for (var i = 0; i < res.length; i++) { console.log( "ID: " + res[i].it...
Building the list of items
function findEvenIndex(arr) { if (arr.length < 1 || !arr) { return -1; } for (let i = 0; i < arr.length; i++) { if ( arr.slice(0, i).reduce((x, y) => x + y, 0) === arr.slice(i + 1).reduce((x, y) => x + y, 0) ) { return i; } } return...
You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return 1.
function processIncludes(includes,input) { var src = input.toString() ; var t = "return "+src ; var args = src.match(/.*\(([^)]*)\)/)[1] ; var re = /['"]!!!([^'"]*)['"]/g ; var m = [] ; while (1) { var mx = re.exec(t) ; if (mx) m.push(mx) ; else break ; } ...
$asyncbind has multiple uses, depending on the parameter list. It is in Function.prototype, so 'this' is always a function 1) If called with a single argument (this), it is used when defining an async function to ensure when it is invoked, the correct 'this' is present, just like "bind". For legacy reasons, 'this' is g...
function copyFromBufferString(n, list) { var p = list.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { ...
Copies a specified amount of characters from the list of buffered data chunks. This function is designed to be inlinable, so please take care when making changes to the function body.
_equal(a, b) { return a === b; }
This should be overriden.
getById (url, id) { url = `${url}/${id}?f=json`; return this.request(url, {method: 'GET'}); }
Get a record by id
function genCalcHash() { //document.write("<br>random_seed "+random_seed); //test random_seed value in this function. if(random_seed == false){//if random_seed not active //using original brainwallet function var hash = Crypto.SHA256($('#pass').val()); }else{ //using brainwallet with specifie...
sec_exponent = hash(passphrase) XOR hash(random_seed)
jump() { if (this.isJumping()) { return; } this.verticalVelocity = Constants.SKIER_JUMP_VELOCITY; }
Jump the skier, but do nothing if already jumping
function create_generation(population, fitnesses, mating_probability, mutation_probability) { mating_population = sample_population(population, fitnesses, mating_probability) parents = crossover(mating_population) preserved_population = preserve_top(population, fitnesses, (1 - mating_probability).toFixed(1)) //...
Buat generasi population = generate_population(5) fitness_values = calculate_population_fitness(population) mating_probability = 0.7 mutation_probability = 0.001 console.log(create_generation(population, fitness_values, mating_probability, mutation_probability))
function createCircle(map, center, place) { let circle = new google.maps.Circle({ map: map, center: {lat: center.placeLat, lng: center.placeLng}, strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35, radi...
draws a circle around a designated point to show locations needed to get to
function closeConnection() { //alert("closing"); if (socket != null) { socket.close(); } }
closes the connection, this is used once you leave the page/closes the tab/closes the browser
function displayLoadGraph(node_id) { if (! (node_id in nodes)) { consoleWarn("Cannot display load graph for unknown node:", node_id); return; } load_redraw = false; var node_name = node_id; var low_threshold = 0; var high_threshold = 100; var max_tps = 4.999; if ("state" ...
global, used for tooltips
function CreatePokemonCard (pkmn) { var output = ""; // create the output string if (pkmn.party) { output += "<div class='characterSheetPartyFormatter'>"; } else { output += "<div class='characterSheetFormatter'>"; } // pokemon name, type, and gender output += "<div cla...
================================================================================ Create Pokemon Card ================================================================================
function appendCurrency(input) { var curr = input.currencies; for (key in curr) { $("#from").append( "<option value = " + key + ">" + key + " " + curr[key] + "</option>" ); } for (key in curr) { $("#to").append( "<option value = " + key + ">" + key + " " + curr[key] + "</option>" ); ...
appending options in to and from
function initiateCall() { prepareCall(); navigator.getUserMedia({ "audio": false, "video": { mediaSource: "screen", width: 800, height: 600 } }, function(stream) { localVideoStream = stream; peerConn.addStream(localVideoStream); ...
run start(true) to initiate a call
function rstr2hex(input) { var hex_tab = '0123456789abcdef', output = '', x, i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); ...
Convert a raw string to a hex string
render() { return ( <Router> <div className="app"> <Switch> <Route path="/" exact render={() => <Home user={this.state.user} />} /> <Route path="/login" exact component={Login} /> <Route path="/register" exact component={Register} /> </Switch> </div> </Router> ); }
the router components to navigate through the pages
function onKeyUp(value) { 'use strict'; switch(value.keyCode) { case 81: // q objV1.userData.rotClockwise = false; break; case 69: // e objV1.userData.rotAntiClockwise = false; break; case 65: // a objV2.userData.rotClock...
Define o que acontece quando se deixa de pressionar certas teclas
function convertObjects(objects, list){ blank = [] for(var i=0; i<objects.length; i++) { obj = [] object = objects[i] obj['pk'] = object.pk for (var j=0; j<list.length; j ++) { obj.pu...
Reorder objects attributes so that that the table works. Should put this as a service/factory.
function loadPage() { getRandomVideo(false); setTimeout(function() { loadSidebar(); stopLogo(); loadScreen(); }, 500); }
loads the full page content
handleHidesOnOutsideEsc(show) { if (show) { this._escKeyHandler = ev => ev.key === 'Escape' && this.hide(); document.addEventListener('keyup', this._escKeyHandler); } else { document.removeEventListener('keyup', this._escKeyHandler); }...
add listeners for escape key press
function TUToggle(elementID) { // Find the desired element. If it doesn't exist, we do nothing. var actualElement = document.getElementById(elementID); if (actualElement !== undefined) { if (actualElement.style.display == 'none') { actualElement.style.display = ''; } else { ...
This method toggles the display of the element with the specified ID. It is fairly primitive, because it presumes that when displayed, the element uses the default display style.
function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = ...
Pluck off n bytes from an array of buffers. Length is the combined lengths of all the buffers in the list. This function is designed to be inlinable, so please take care when making changes to the function body.
function removeElement(elem) { if (elem.prev) elem.prev.next = elem.next; if (elem.next) elem.next.prev = elem.prev; if (elem.parent) { var childs = elem.parent.children; childs.splice(childs.lastIndexOf(elem), 1); } }
Remove an element from the dom
function firstAndLast(array){ for(var i = 0; i < array.length; i++){ if(array.length % 2 === 0){ return array[0] + array[array.length - 1]; } else{ return array[0] - array[array.length - 1]; } } }
the sum of the first and last elements of the array if there is an even number of elements the difference between the first and last elements of the array if there is an odd number of elements. You can assume the array contains at least one number.
function initPage() { var mainContent = document.getElementById('mainContent'); mainContent.innerHTML = "<h1>My Battles</h1>"; var createBattleButton = document.createElement('p'); createBattleButton.innerHTML = 'Begin a New Battle'; createBattleButton.setAttribute('id', 'createBattle'); var battleForm = document...
Add the basic UI items to the page
function checkCommentOwnership(req, res, next) { if (req.isAuthenticated()) { Comment.findById(req.params.comment_id, function(err, foundComment) { if (err) { console.log('Error with edit comment route ', err); res.redirect('back'); } else { // does user own the comment ...
middleware to check if a user owns the comment
function DatePicker( picker, settings ) { var calendar = this, elementValue = picker.$node[ 0 ].value, elementDataValue = picker.$node.data( 'value' ), valueString = elementDataValue || elementValue, formatString = elementDataValue ? settings.formatSubmit : settings.format cale...
The date picker constructor
function tag(name, attrs, selfclosing) { if (this.disableTags > 0) { return; } this.buffer += ('<' + name); if (attrs && attrs.length > 0) { var i = 0; var attrib; while ((attrib = attrs[i]) !== undefined) { this.buffer += (' ' + attrib[0] + '="' + attrib[1] + '"'); i++; } } ...
Helper function to produce an HTML tag.
function fetch(filename) { var att = atts[filename]; var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) + '?rev=' + doc._rev; return ajaxPromise(opts, { method: 'GET', url: genDBUrl(host, path), binary: true }).then(function (blob...
we fetch these manually in separate XHRs, because Sync Gateway would normally send it back as multipart/mixed, which we cannot parse. Also, this is more efficient than receiving attachments as base64encoded strings.
function storeActivity(nsp, activity) { db.activities.insert(doc, function(err, doc){ if (err) { console.log("[!] Error storing activity: "+err); } else { nsp.emit('network', {activity: doc}); } }); }
Store activity for /Network relay
function attachRefs() { ReactRef.attachRefs(this, this._currentElement); }
Helper to call ReactRef.attachRefs with this composite component, split out to avoid allocations in the transaction mountready queue.
handleKeydownOnHost(event) { if (event.altKey && event.keyCode === DOWN_ARROW) { this.dtPicker.open(); event.preventDefault(); } }
Open the picker when user hold alt + DOWN_ARROW
function parseHexUtf16(str, start, end) { var result = ''; while (start < end) { // UTF-16, so swizzle the bytes result += String.fromCharCode( (hexToInt(str.charCodeAt(start + 2)) << 12) | (hexToInt(str.charCodeAt(start + 3)) << 8) | (hexToInt(str.charCodeAt(start)) << 4) | he...
Example: pragma encoding=utf16; select hex('A'); returns '4100' notice that the 00 comes after the 41 (i.e. it's swizzled)
function greeting (hi, hello,hey,sup){ { return ('hi', hi) return ('hello', hello) return ('hey', hey) return ('sup', sup) } }
spread operator changes the elements into an array as individual separate arguments
function RSADoPublic(x) { return x.modPowInt(this.e, this.n); }
Perform raw public operation on "x": return x^e (mod n)
static restoreSelectedSwitchesInMainScreen(symbolsArr) { symbolsArr.forEach(function(symbol) { $(`#${symbol}`).prop("checked", true); }); }
After returning to main screen from other screen in the site
function FieldPath$1() { var fieldNames = []; for (var _i = 0; _i < arguments.length; _i++) { fieldNames[_i] = arguments[_i]; } validateNamedArrayAtLeastNumberOfElements('FieldPath', fieldNames, 'fieldNames', 1); for (var i = 0; i < fieldNames.length; ++i) { ...
Creates a FieldPath from the provided field names. If more than one field name is provided, the path will point to a nested field in a document.
function Guidewire_ExtractSrcFromURL() { var VarDocumentURL = window.WWHFrame.location; var TheParametersArray = VarDocumentURL.hash.split("&"); var thisParam; var FMSourceFile = "UNKNOWN_FRAMEMAKER_SOURCE_FILE"; k = TheParametersArray.length; for (i= 0 ; i < k; i++) { thisParam = unescape(TheParametersArray...
extracts the src=myfilename from the URL
function clearOpponentsHand() { $('.opponent-hand').empty(); }
clears opponents hand, to be used before refreshing players hand
function PivotContextMenu(parent){/* eslint-enable */this.parent=parent;this.parent.contextMenuModule=this;}
eslintdisable Constructor for render module
addContent(name, content) { //@TODO let word_map = new Map(); let word_count = new Map(); let map_filename = new Map(); this.words(content); map3.set(name,content); let word_offset = []; let match; while(match = WORD_REGEX.exec(content)){ if(!this.noise_words.has(match[0])){...
Add document named by string name with specified content to this instance. Update index in this with all nonnoise normalized words in content string.
function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; }
Support: IE<8 Manipulating tables requires a tbody
constructor(initList, initIndex){ this.todoList = initList; this.initList = initList; this.todoIndex = initIndex; this.todoItem = this.todoList.items[this.todoIndex]; }
THIS IS THE OBJECT IT WILL MANIPULATE
function isCrushed() {}
This is a dummy function to check if the function name has been altered by minification. If the function has been minified and NODE_ENV !== 'production', warn the user.
function mutate(population, mutation_probability) { for (var i = 0; i < population.length; i++) { random = Math.random() if (random < mutation_probability) { cur_chromosome = population[i] random = Math.round(Math.random() * (cur_chromosome - 1)) + 0 random_gen = cur_chromosome[Math.round(Ma...
Mutasi population = generate_population(5) mutation_probability = 0.0001 console.log(mutate(population, mutation_probability))
preload(scene) { }
Called when the game preloads assets for later use
function formatTrim(s) { out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) { switch (s[i]) { case ".": i0 = i1 = i; break; case "0": if (i0 === 0) i0 = i; i1 = i; break; default: if (i0 > 0) { if (!+s[i]) break out; i0 = 0; } break; } } return i0...
Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
function expand(url, params, variables) { var tmpl = parse(url), expanded = tmpl.expand(params); if (variables) { variables.push.apply(variables, tmpl.vars); } return expanded; }
URL Template v2.0.6 (
function resetScore() { if (lethal) { score = 0; lives = 2; } else { return; } }
this function stops the player spamming reset until they get favourable wires yet still allows to retain their score pressing reset after picking the correct wire
function writeOrBuffer(stream, state, chunk, encoding, cb) { chunk = decodeChunk(state, chunk, encoding); if (Buffer.isBuffer(chunk)) encoding = 'buffer'; var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous n...
if we're already writing something, then just put this in the queue, and wait our turn. Otherwise, call _write If we return false, then we need a drain event, so set that flag.
function configFromRFC2822(config) { var match = rfc2822.exec(preprocessRFC2822(config._i)); if (match) { var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]); if (!checkWeekday(match[1], parsedArray, config)) { r...
date and time from ref 2822 format
function crystalsRandomSel() { var C = Math.floor(Math.random() * 12) + 1; return C; }
random numbers selected for the crystals, between range 1 12
travelTo(gameObjectTravelling, finalPosition, time, parameters) { const _from = { x: gameObjectTravelling.position.x, y: gameObjectTravelling.position.y, z: gameObjectTravelling.position.z }; const _to = { x: finalPosition.x, y: finalPosition.y, z: finalPosition.z };...
TODO: add tweening register of what objects are travellng TODO: make function parameters an object and use proptypes or alternative to specify mandatory fields and have auto complete.
async function findByMatricula(matricula){ let estudiante = await db.Estudiante.findAll({ where: { matricula: matricula } }); return estudiante; }
Busca estudiante por matricula
function workspaceDisplay(){ console.log("data.workspacesAll: ", data.workspacesAll); let parking, transit; let workspaceIndex = []; //fix array iterations for (let i = 0; i < displayArray.length; i++) { if (disp...
Filter and Sort buttons Sort buttons can be done in Switch/Case with querySelectorAll Filter dropdowns needs to search through workspacesAll to populate values Need a submit button? Need to remember filter and sort values Need to display from a display array
function fixLogo() { var c = document.getElementsByTagName('td')[1]; // background to ibdof logo c.className = 'topbkg'; // replace the ibdof logo c.getElementsByTagName('img')[0].src = 'data:image/gif;base64,R0lGODlhaAFrAPcAAPr7/PT2/PT29PTy9Ozu7OTu9OTm5OTi5Nje5Nzd3NLa3NTT1MDW3MTS1MzO1MzNzMTOzMHO1L/KzMDG...
Prepare the header to receive styling Replace the ibdof logo gif with a background transparent version Note: cell addresses are relative to cell[0] == class 'bodyline'
function Arrayception(array, depth = 0) { var depth = 0 var maxdepth = 0 function checkArray(arr) { for (var i = 0; i < arr.length; i++) { if (!Array.isArray(arr[i]) && depth === 0) { depth++; if (depth > maxdepth) { maxdepth = depth ...
Given an array of arbitrarily nested arrays, return n, where n is the deepest level that contains a nonarray value. Examples Input Output array: [ [ 5 ], [ [ ] ] ] ==>2 array: [ 10, 20, 30, 40 ] ==>1 array: [ [ 10, 20 ], [ [ 30, [ 40 ] ] ] ] ==>4 array: [ ] ==>0 array: [ [ [ ] ] ] ==>0
function addDateStr(messageObj) { const errMsg = "Unable to parse date stamp in message object"; const months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; const d = new Date(message...
Add a humanreadable date string to a message object.
function getStatus(trigger,sampleData) { switch(trigger.op){ case "less": if (sampleData < trigger.val){ console.log("alarm trigged at",new Date(),"sampleData",sampleData,"less then trigger",trigger.val); return true; } break; case "larger": ...
Check if alarms are triggered
cancel() { this.state.cancelRender = true; }
Cancels any currently inprogress render.
function setWebhook() { var url = telegramUrl + "/setWebhook?url=" + webAppUrl; var response = UrlFetchApp.fetch(url); Logger.log(response.getContentText()); }
Set url to receive incoming Telegram updates to the webAppUrl of the published Google script
function App() { const announcementsList = useSelector((state) => state.announcementList.list); const [cookie, setCookie, removeCookie] = useCookies(['userToken']); useEffect(()=>{ document.title = "Virtual Notice Board"; }, []) return ( <div className = 'App'> <div cla...
Core of the application, specifies all the routes with React Router allowing website to be multi paged
function createDisposable(request, idx) { var disposed = false; return function() { if (disposed || request._disposed) { return; } disposed = true; request._callbacks[idx] = null; request._optimizedPaths[idx] = []; request._requestedPaths[idx...
Creates a more efficient closure of the things that are needed. So the request and the idx. Also prevents code duplication.
function valAtIndex (view, index) { return view.viewAtIndex(index).stringValue() }
A quick way to get the value of text fields in the alerts
function yAxis() { return d3.axisLeft(y) .tickSize(-width) .tickFormat("") }
Gridlines in y axis function
function checkLine( num ){ if( board.grid[0][num].bool && board.grid[1][num].bool &&board.grid[2][num].bool &&board.grid[3][num].bool &&board.grid[4][num].bool &&board.grid[5][num].bool &&board.grid[6][num].bool &&board.grid[7][num].bool &&board.grid[8][num].bool &&board.grid[9][num].bool ){ board.grid.forEach( f...
sorry I couldn't get forEach or every to work... it was probably because of varriable scoping issues
function replaceObjectElements(_this, counter) { var imgType; var displayType; var counter = counter; var newURL; // get dimensions of current svg var width = Math.floor(_this.outerWidth()); var height = Math.floor(_this.outerHeight()); var backgroundSiz...
Replace all 'object' elements with images of nick cage. Note this is best done with a background image.
function setUserInfo(request) { return { _id: request._id, username: request.username, email: request.email }; }
We don't want to use the entire user object to sign our JWTs that's a lot of information to eventually store in a cookie. Plus, we don't want to be returning huge blocks of what could be sensitive user information. We need control. Let's create a function to select the user information we want to pass through
handle () { console.log(this.creep.memory.role + ' is not valid role for ' + this.creep.name); }
Main entry into role, called for every creep with that role every tick. Must be overridden by Role subclasses.
function lineAtHeight(chunk, h) { var n = chunk.first; outer: do { for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { var child = chunk.children[i$1], ch = child.height; if (h < ch) { chunk = child; continue outer } h -= ch; n += child.chunkSize(); } return...
Find the line at the given vertical position, using the height information in the document tree.
function fetchStarred(login, nextPageUrl) { return { login, [CALL_API]: { types: [ STARRED_REQUEST, STARRED_SUCCESS, STARRED_FAILURE ], endpoint: nextPageUrl, schema: Schemas.REPO_ARRAY } } }
Fetches a page of starred repos by a particular user. Relies on the custom API middleware defined in ../middleware/api.js.
function cleanDocs(docs) { for (var i = 0; i < docs.length; i++) { var doc = docs[i]; if (doc._deleted) { delete doc._attachments; // ignore atts for deleted docs } else if (doc._attachments) { // filter out extraneous keys from _attachments var atts = Object.keys(doc._attachments...
clean docs given to us by the user
function changeorder( arr, ordernum ) { var thisorder = ordernum; var shufflelocations = new Array(); for (var i=0; i<arr.length; i++) { shufflelocations.push(i); } for (i=arr.length-1; i>=0; --i) { var loci = shufflelocations[i]; var locj = shufflelocations[thisorder%(i+1)]; thisorder = Math.floo...
We want to be able to alias the order of stimuli to a single number which can be stored and which can easily replicate a given stimulus order.
function getMapped(state, dispatch, ownProps) { const Connected = require('./index').default; expect(mockConnect).toBeCalled(); const [ mapStateToProps, mapDispatchToProps, mergeProps, ] = mockConnect.mock.calls[0]; expect(mapStateToProps) .toBeInstanceOf(Function); expect(mapDispatchToPro...
sorting order null > 'asc' > 'desc'
function adjust() { var height, originalHeight; if (mirrored !== ta) { initMirror(); } else { setWidth(); } if (!ta.value && options.placeholder) { // If the textarea is empty, copy the placeholder text into // the mirror control and use that for sizing so that we // don't...
Using mainly bare JS in this function because it is going to fire very often while typing, and needs to very efficient.
function colorgenerator() { let colours = [], i; for (i = 0; i < 372; i++){ colours[i] = 'hsl(' + i + ', 100%, 50%)'; if (i > 359) { colours[i] = 'hsl(0, 100%, 100%)'; } } colours = colours.toString(); //console.log(colours); root.style.setProperty("--...
Generates all the rainbow colours for the colour slider selector
function positionFromMove(mv,pos){ "use strict"; var pscp = pos.clone(), nm, i, p = pos.plyr, op, cap, mov; pscp.sow( [ pos.plyr, mv[0][1] ] ); pscp.plyr = pos.opposite( p ); pscp.possibleMoves = false; return pscp; }
return new muskPos by applying given mov to given pos
function selectHome() { $("#home").on("click", function () { $("#scheduleImg").addClass("hidden"); $(".contacts").addClass("hidden"); $(".emails").removeClass("hidden"); $(".nav").removeClass("hidden"); $(".files").addClass("hidden"); $("#search").addClass("hidden"); }); }
Hides and reveals the relevant elements when the home button is clicked
function clearScene() { context.save(); context.setTransform(h, 0.0, 0.0, -h, 0.0, h); context.clearRect(0, 0, w, h); context.restore(); }
This is Professor Beveridges from the rotating pacman lecture
getApplication (opportunityId, personId, forceReload) { var d = $q.defer(); if(!this.loadedOpportunityApplications[`${opportunityId}-${personId}`] || forceReload === true) { $http.get(`/api/opportunity_applications/${opportunityId}/${personId}`) .then(response => { var applicat...
Load opportunity applications from database
function observerON() { debug('Turning observer ON'); if (validPointer(mainObserver)) {mainObserver.observe(mainTargetNode, mainConfig);} }
Functions to log when we connect/disconnect main observer, for debugging
moons (lib){ for (var i=0;i<7;i++){ let moon = this.madeMoons[i]; var size = moon.s; lib.moveTo(moon.x, moon.y); lib.penRGB(moon.r, moon.g, moon.b); let movingLeft = true; let behind = false; if (moon.s < 6) { ...
moons: lib: code.org library Draws all the moons that are larger than or equal to 6 pixels in radius. Then, it moves them to the left before checking if it should change one into a small moon. Written by Keegan Brown
function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}
! ctxMenu v1.1.1 | (c) Nikolaj Kappler | !
function migrateLocalStore(txn, cb) { var localStore = txn.objectStore(LOCAL_STORE); var docStore = txn.objectStore(DOC_STORE); var seqStore = txn.objectStore(BY_SEQ_STORE); var cursor = docStore.openCursor(); cursor.onsuccess = function (event) { var cursor = event.target.result; ...
migration to version 3 (part 2)
function downloadAsSVG(fileName) { // use default name if not provided fileName = fileName || "output.svg"; // create a data url of the file var svgData = project.exportSVG({ asString: true }); var url = "data:image/svg+xml;utf8," + encodeURIComponent(svgData); // create a link to the data, and "cli...
a function to download the .svg file