language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
static waitForRoomWidget(widgetId, roomId, add) { return new Promise((resolve, reject) => { // Tests a list of state events, returning true if it's in the state // we're waiting for it to be in function eventsInIntendedState(evList) { const widgetPresent = evList.some((ev) => { return ev.getContent() && ev.getContent()['id'] === widgetId; }); if (add) { return widgetPresent; } else { return !widgetPresent; } } const room = MatrixClientPeg.get().getRoom(roomId); // TODO: Enable support for m.widget event type (https://github.com/vector-im/riot-web/issues/13111) const startingWidgetEvents = room.currentState.getStateEvents('im.vector.modular.widgets'); if (eventsInIntendedState(startingWidgetEvents)) { resolve(); return; } function onRoomStateEvents(ev) { if (ev.getRoomId() !== roomId) return; // TODO: Enable support for m.widget event type (https://github.com/vector-im/riot-web/issues/13111) const currentWidgetEvents = room.currentState.getStateEvents('im.vector.modular.widgets'); if (eventsInIntendedState(currentWidgetEvents)) { MatrixClientPeg.get().removeListener('RoomState.events', onRoomStateEvents); clearTimeout(timerId); resolve(); } } const timerId = setTimeout(() => { MatrixClientPeg.get().removeListener('RoomState.events', onRoomStateEvents); reject(new Error("Timed out waiting for widget ID " + widgetId + " to appear")); }, WIDGET_WAIT_TIME); MatrixClientPeg.get().on('RoomState.events', onRoomStateEvents); }); }
static waitForRoomWidget(widgetId, roomId, add) { return new Promise((resolve, reject) => { // Tests a list of state events, returning true if it's in the state // we're waiting for it to be in function eventsInIntendedState(evList) { const widgetPresent = evList.some((ev) => { return ev.getContent() && ev.getContent()['id'] === widgetId; }); if (add) { return widgetPresent; } else { return !widgetPresent; } } const room = MatrixClientPeg.get().getRoom(roomId); // TODO: Enable support for m.widget event type (https://github.com/vector-im/riot-web/issues/13111) const startingWidgetEvents = room.currentState.getStateEvents('im.vector.modular.widgets'); if (eventsInIntendedState(startingWidgetEvents)) { resolve(); return; } function onRoomStateEvents(ev) { if (ev.getRoomId() !== roomId) return; // TODO: Enable support for m.widget event type (https://github.com/vector-im/riot-web/issues/13111) const currentWidgetEvents = room.currentState.getStateEvents('im.vector.modular.widgets'); if (eventsInIntendedState(currentWidgetEvents)) { MatrixClientPeg.get().removeListener('RoomState.events', onRoomStateEvents); clearTimeout(timerId); resolve(); } } const timerId = setTimeout(() => { MatrixClientPeg.get().removeListener('RoomState.events', onRoomStateEvents); reject(new Error("Timed out waiting for widget ID " + widgetId + " to appear")); }, WIDGET_WAIT_TIME); MatrixClientPeg.get().on('RoomState.events', onRoomStateEvents); }); }
JavaScript
function eventsInIntendedState(evList) { const widgetPresent = evList.some((ev) => { return ev.getContent() && ev.getContent()['id'] === widgetId; }); if (add) { return widgetPresent; } else { return !widgetPresent; } }
function eventsInIntendedState(evList) { const widgetPresent = evList.some((ev) => { return ev.getContent() && ev.getContent()['id'] === widgetId; }); if (add) { return widgetPresent; } else { return !widgetPresent; } }
JavaScript
static removeStickerpickerWidgets() { const client = MatrixClientPeg.get(); if (!client) { throw new Error('User not logged in'); } const widgets = client.getAccountData('m.widgets'); if (!widgets) return; const userWidgets = widgets.getContent() || {}; Object.entries(userWidgets).forEach(([key, widget]) => { if (widget.content && widget.content.type === 'm.stickerpicker') { delete userWidgets[key]; } }); return client.setAccountData('m.widgets', userWidgets); }
static removeStickerpickerWidgets() { const client = MatrixClientPeg.get(); if (!client) { throw new Error('User not logged in'); } const widgets = client.getAccountData('m.widgets'); if (!widgets) return; const userWidgets = widgets.getContent() || {}; Object.entries(userWidgets).forEach(([key, widget]) => { if (widget.content && widget.content.type === 'm.stickerpicker') { delete userWidgets[key]; } }); return client.setAccountData('m.widgets', userWidgets); }
JavaScript
UNSAFE_componentWillReceiveProps(newProps) { if (newProps.serverConfig.hsUrl === this.props.serverConfig.hsUrl && newProps.serverConfig.isUrl === this.props.serverConfig.isUrl) return; this._replaceClient(newProps.serverConfig); // Handle cases where the user enters "https://tambulilabs.com" for their server // from the advanced option - we should default to FREE at that point. const serverType = ServerType.getTypeFromServerConfig(newProps.serverConfig); if (serverType !== this.state.serverType) { // Reset the phase to default phase for the server type. this.setState({ serverType, phase: this.getDefaultPhaseForServerType(serverType), }); } }
UNSAFE_componentWillReceiveProps(newProps) { if (newProps.serverConfig.hsUrl === this.props.serverConfig.hsUrl && newProps.serverConfig.isUrl === this.props.serverConfig.isUrl) return; this._replaceClient(newProps.serverConfig); // Handle cases where the user enters "https://tambulilabs.com" for their server // from the advanced option - we should default to FREE at that point. const serverType = ServerType.getTypeFromServerConfig(newProps.serverConfig); if (serverType !== this.state.serverType) { // Reset the phase to default phase for the server type. this.setState({ serverType, phase: this.getDefaultPhaseForServerType(serverType), }); } }
JavaScript
function checkDir(fullPath) { var parts = fullPath.split('/'); parts.length -= 1; var cur = ''; parts.forEach(function (part) { cur += part + '/'; if (!exists(cur, true)) { fs.mkdirSync(cur); } }); }
function checkDir(fullPath) { var parts = fullPath.split('/'); parts.length -= 1; var cur = ''; parts.forEach(function (part) { cur += part + '/'; if (!exists(cur, true)) { fs.mkdirSync(cur); } }); }
JavaScript
function exists(file, isDir) { try { return fs.statSync(file)[isDir ? 'isDirectory' : 'isFile'](); } catch (e) { return false; } }
function exists(file, isDir) { try { return fs.statSync(file)[isDir ? 'isDirectory' : 'isFile'](); } catch (e) { return false; } }
JavaScript
resolveId(importee, importer) { if (importee === "virtual-module") { return importee; // this signals that rollup should not ask other plugins or check the file system to find this id } return null; // other ids should be handled as usually }
resolveId(importee, importer) { if (importee === "virtual-module") { return importee; // this signals that rollup should not ask other plugins or check the file system to find this id } return null; // other ids should be handled as usually }
JavaScript
function combineFiles() { let teamRender = render(teamMembers); //read each employee type file try { writeFileAsync(outputPath, teamRender); } catch (err) { console.log; } }
function combineFiles() { let teamRender = render(teamMembers); //read each employee type file try { writeFileAsync(outputPath, teamRender); } catch (err) { console.log; } }
JavaScript
function taskStateReducer(taskState) { return (state, action) => { return { ...state, tasks: state.task.map(task => task.id === action.id ? { ...task, state: taskState } : task ), }; }; }
function taskStateReducer(taskState) { return (state, action) => { return { ...state, tasks: state.task.map(task => task.id === action.id ? { ...task, state: taskState } : task ), }; }; }
JavaScript
function Hook(fn, options) { if (!this) return new Hook(fn, options); options = options || {}; this.options = options; // Used for testing only. Ignore this. Don't touch. this.config = {}; // pre-commit configuration from the `package.json`. this.json = {}; // Actual content of the `package.json`. this.npm = ''; // The location of the `npm` binary. this.git = ''; // The location of the `git` binary. this.root = ''; // The root location of the .git folder. this.status = ''; // Contents of the `git status`. this.exit = fn; // Exit function. this.initialize(); }
function Hook(fn, options) { if (!this) return new Hook(fn, options); options = options || {}; this.options = options; // Used for testing only. Ignore this. Don't touch. this.config = {}; // pre-commit configuration from the `package.json`. this.json = {}; // Actual content of the `package.json`. this.npm = ''; // The location of the `npm` binary. this.git = ''; // The location of the `git` binary. this.root = ''; // The root location of the .git folder. this.status = ''; // Contents of the `git status`. this.exit = fn; // Exit function. this.initialize(); }
JavaScript
function containerQuery(selector, test, stylesheet) { var tag = document.querySelectorAll(selector) var style = '' var count = 0 for (var i=0; i<tag.length; i++) { var attr = (selector+test).replace(/\W+/g, '') if (test(tag[i])) { var css = stylesheet.replace(/:self|\$this/g, '[data-' + attr + '="' + count + '"]') tag[i].setAttribute('data-' + attr, count) style += css count++ } } return style }
function containerQuery(selector, test, stylesheet) { var tag = document.querySelectorAll(selector) var style = '' var count = 0 for (var i=0; i<tag.length; i++) { var attr = (selector+test).replace(/\W+/g, '') if (test(tag[i])) { var css = stylesheet.replace(/:self|\$this/g, '[data-' + attr + '="' + count + '"]') tag[i].setAttribute('data-' + attr, count) style += css count++ } } return style }
JavaScript
function printID() { console.log("start ID: " + absminID); console.log("end ID: " + absmaxID); mkdirp('./'+searchTerm, function(err) { // path was created unless there was error }); mkdirp('./'+searchTerm+'_meta', function(err) { // path was created unless there was error }); mt = new bn(absmaxID); getIG(); }
function printID() { console.log("start ID: " + absminID); console.log("end ID: " + absmaxID); mkdirp('./'+searchTerm, function(err) { // path was created unless there was error }); mkdirp('./'+searchTerm+'_meta', function(err) { // path was created unless there was error }); mt = new bn(absmaxID); getIG(); }
JavaScript
render() { if (_.isEmpty(this.props.categories) || _.isEmpty(this.props.posts)) return <div> Loading . . . </div>; let { categories, posts } = this.props; const { sortList, selectedSortOption, selectedFilterOption } = this.state; if (selectedFilterOption !== 'all') posts = posts.filter(post => post.category === selectedFilterOption); posts = _.orderBy(posts, [selectedSortOption], ['desc']); return ( <div className="home-view"> <div className="header"> BLOG POST </div> <div className="content display-flex justify-center"> <div className="filter-col" > <div className="filter-list"> <div className={this._computeClassName(selectedFilterOption, 'all')} onClick={()=> this._filterByCategory("all")}> All </div> {categories && (categories.map((category, index) => ( <div className={this._computeClassName(selectedFilterOption, category.name)} onClick={()=> this._filterByCategory(category.name)} key={index}> {_.startCase(_.toLower(category.name))} </div> )))} </div> </div> <div className="post-col" > <div className="post-list"> {!this._areAllPostsDeleted(posts) && (posts.map((post, index) => ( <div className="post-item" key={index} hidden={post.deleted} onClick={()=> this._viewPost(post.id)}> <div className="post-wrapper"> <div className="post-title"> {post.title} </div> <div className="author-name"><i> By : </i>{post.author} </div> <div> {post.body} </div> <div><i> Created at : </i>{util.ts2Time(post.timestamp)} </div> <div className="right-align"> <span onClick={(event)=> {event.preventDefault(); event.stopPropagation(); this.changeVote(post.id, "downVote")}} > <VoteDown size={50}/> </span> vote({post.voteScore}) <span onClick={(event)=> {event.preventDefault(); event.stopPropagation(); this.changeVote(post.id, "upVote")}} > <VoteUp size={50}/> </span> </div> <div className="right-align"> Comments : {this._computeCommentCount(post.id)}</div> </div> </div> )))} {this._areAllPostsDeleted(posts) && ( <div className="add-post-place-holder" onClick={() => this.props.history.push("/addpost")}> Add some blog ... </div> )} </div> </div> <div className="sort-col" > <div className="sort-list"> {sortList && (sortList.map((sortItem, index) => ( <div className={this._computeClassName(selectedSortOption, sortItem.field)} onClick={()=> this._sortPost(sortItem.field)} key={index}> Sort by {sortItem.label} </div> )))} </div> </div> </div> <div> <div className="add-icon" onClick={() => this.props.history.push("/addpost")}> <PlusCircle size={75}/> </div> </div> </div> ); }
render() { if (_.isEmpty(this.props.categories) || _.isEmpty(this.props.posts)) return <div> Loading . . . </div>; let { categories, posts } = this.props; const { sortList, selectedSortOption, selectedFilterOption } = this.state; if (selectedFilterOption !== 'all') posts = posts.filter(post => post.category === selectedFilterOption); posts = _.orderBy(posts, [selectedSortOption], ['desc']); return ( <div className="home-view"> <div className="header"> BLOG POST </div> <div className="content display-flex justify-center"> <div className="filter-col" > <div className="filter-list"> <div className={this._computeClassName(selectedFilterOption, 'all')} onClick={()=> this._filterByCategory("all")}> All </div> {categories && (categories.map((category, index) => ( <div className={this._computeClassName(selectedFilterOption, category.name)} onClick={()=> this._filterByCategory(category.name)} key={index}> {_.startCase(_.toLower(category.name))} </div> )))} </div> </div> <div className="post-col" > <div className="post-list"> {!this._areAllPostsDeleted(posts) && (posts.map((post, index) => ( <div className="post-item" key={index} hidden={post.deleted} onClick={()=> this._viewPost(post.id)}> <div className="post-wrapper"> <div className="post-title"> {post.title} </div> <div className="author-name"><i> By : </i>{post.author} </div> <div> {post.body} </div> <div><i> Created at : </i>{util.ts2Time(post.timestamp)} </div> <div className="right-align"> <span onClick={(event)=> {event.preventDefault(); event.stopPropagation(); this.changeVote(post.id, "downVote")}} > <VoteDown size={50}/> </span> vote({post.voteScore}) <span onClick={(event)=> {event.preventDefault(); event.stopPropagation(); this.changeVote(post.id, "upVote")}} > <VoteUp size={50}/> </span> </div> <div className="right-align"> Comments : {this._computeCommentCount(post.id)}</div> </div> </div> )))} {this._areAllPostsDeleted(posts) && ( <div className="add-post-place-holder" onClick={() => this.props.history.push("/addpost")}> Add some blog ... </div> )} </div> </div> <div className="sort-col" > <div className="sort-list"> {sortList && (sortList.map((sortItem, index) => ( <div className={this._computeClassName(selectedSortOption, sortItem.field)} onClick={()=> this._sortPost(sortItem.field)} key={index}> Sort by {sortItem.label} </div> )))} </div> </div> </div> <div> <div className="add-icon" onClick={() => this.props.history.push("/addpost")}> <PlusCircle size={75}/> </div> </div> </div> ); }
JavaScript
render() { const { comment, deleteComment } = this.props; const { isCommentModalOpen } = this.state; if (_.isEmpty(comment) || comment.deleted) { return <div className="" />; } else { return ( <div className="comment-card display-flex"> <div className="actions"> <DeleteButton onClick={()=> deleteComment(comment.id)} size={35} style={this.buttonStyle}/> <EditButton onClick={()=> this.setState({ isCommentModalOpen:true })} size={35} style={this.buttonStyle}/> </div> <div className="comment"> <div> <b>{comment.author}</b> says, {comment.body} </div> <div> <i>Created at</i> {util.ts2Time(comment.timestamp)}</div> </div> <div className="vote"> <VoteUp onClick={()=> this.changeVote(comment.id, "upVote")} size={35} style={this.upDownArrowStyle}/> <div> Vote({comment.voteScore})</div> <VoteDown onClick={()=> this.changeVote(comment.id, "downVote")} size={35} style={this.upDownArrowStyle}/> </div> <Modal className='modal' overlayClassName='overlay' isOpen={isCommentModalOpen} onRequestClose={this.closeModal} contentLabel='Modal'> {(isCommentModalOpen && <EditComment comment={comment} closeModal={()=> this.setState({isCommentModalOpen: false})}/> )} </Modal> </div> ); } }
render() { const { comment, deleteComment } = this.props; const { isCommentModalOpen } = this.state; if (_.isEmpty(comment) || comment.deleted) { return <div className="" />; } else { return ( <div className="comment-card display-flex"> <div className="actions"> <DeleteButton onClick={()=> deleteComment(comment.id)} size={35} style={this.buttonStyle}/> <EditButton onClick={()=> this.setState({ isCommentModalOpen:true })} size={35} style={this.buttonStyle}/> </div> <div className="comment"> <div> <b>{comment.author}</b> says, {comment.body} </div> <div> <i>Created at</i> {util.ts2Time(comment.timestamp)}</div> </div> <div className="vote"> <VoteUp onClick={()=> this.changeVote(comment.id, "upVote")} size={35} style={this.upDownArrowStyle}/> <div> Vote({comment.voteScore})</div> <VoteDown onClick={()=> this.changeVote(comment.id, "downVote")} size={35} style={this.upDownArrowStyle}/> </div> <Modal className='modal' overlayClassName='overlay' isOpen={isCommentModalOpen} onRequestClose={this.closeModal} contentLabel='Modal'> {(isCommentModalOpen && <EditComment comment={comment} closeModal={()=> this.setState({isCommentModalOpen: false})}/> )} </Modal> </div> ); } }
JavaScript
render() { const { categories, posts, comments } = this.props; const { commentSortOption, commentValidationResults, isPostModalOpen, selectedCommentSortOption, } = this.state; const post = posts.filter( post => post.id === this.props.match.params.postid )[0]; const commentsForThisPost = comments[this.props.match.params.postid] || []; const enabledCommentsForThisPost = commentsForThisPost.filter( comment => !comment.deleted ); const areCommentsSortSortable = enabledCommentsForThisPost.length !== 0; const sortedCommentsList = _.orderBy( enabledCommentsForThisPost, [selectedCommentSortOption], ['desc'] ); //Negative use case //In the case if user is viewing a deleted post if (_.isEmpty(post) || post.deleted) { return ( <div className="view-post-view"> <div className="header display-flex justify-space-between"> <div> {' '}<Link to="/"> <BackButton size={42.5} style={this.buttonStyle} /> </Link> </div> <div className="header-text"> POST DELETED</div> <div /> </div> </div> ); } //Positive use case //In the case if user is viewing a post return ( <div className="view-post-view"> {/* Header */} <div className="header display-flex justify-space-between"> <div> <Link to="/"> <BackButton size={42.5} style={this.buttonStyle} /> </Link> </div> <div className="header-text"> POST </div> <div> <DeleteButton size={50} style={this.buttonStyle} span onClick={()=> this.props.deletePost(post.id)}/> <EditButton size={50} style={this.buttonStyle} onClick={()=> this.setState({isPostModalOpen: true})}/> </div> </div> {/* Body */} <div className="view-post-content"> {/* Detailed post */} <div className="post-title">{post.title} </div> <div className="post-detail">{post.body} </div> <div className="post-detail"><i>Owner : </i>{post.author} </div> <div className="post-detail"><i>Created at</i> : {util.ts2Time(post.timestamp)} </div> <div className="vote"> <VoteUp onClick={()=> this.changeVote(post.id, "upVote")} size={50} style={this.upDownArrowStyle}/> <div className="post-detail">votes({post.voteScore}) </div> <VoteDown onClick={()=> this.changeVote(post.id, "downVote")} size={50} style={this.upDownArrowStyle}/> </div> <br/> <br/> <div className="comment-sub-header">COMMENTS</div> {/* Form to add new comment */} <form className="add-comment-form" onSubmit={this._submitForm}> <textarea rows="4" cols="50" type="multi" name="body" placeholder="body for comment ..." className="form-el"/> <div className="invalid-indicator"> <span hidden={!commentValidationResults.isBodyInvalid} className="invalid-form-entry"> Invalid Comment</span> </div> <input type="text" name="author" placeholder="author" className="form-el"/> <div className="invalid-indicator"> <span hidden={!commentValidationResults.isOwnerInvalid} className="invalid-form-entry"> Invalid author name </span> </div> <button className="form-button" > Add </button> </form> <br/> <br/> {/* Comment sort options: Visible only if there are comments to sort */} {areCommentsSortSortable && ( <div className="comment-sort-col display-flex" > {commentSortOption.map((sortOption, index) => ( <div key={index} onClick={()=> this._sortComments(sortOption.field)} className={this._computeClassName(selectedCommentSortOption, sortOption.field)}> <span className="sort-item"> Sort by {sortOption.label} </span> </div> ))} </div> )} {/* List of comments */} <div className="comments"> {!_.isEmpty(sortedCommentsList) && ( sortedCommentsList.map((item, index) => <CommentCard comment={item} key={index} /> ) )} </div> <Modal id="editPostModal" className='modal' overlayClassName='overlay' isOpen={isPostModalOpen} onRequestClose={this.closeModal} contentLabel='Modal'> {(isPostModalOpen && <EditPost post={post} closeModal={()=> this.setState({isPostModalOpen: false})} /> )} </Modal> </div> </div> ); }
render() { const { categories, posts, comments } = this.props; const { commentSortOption, commentValidationResults, isPostModalOpen, selectedCommentSortOption, } = this.state; const post = posts.filter( post => post.id === this.props.match.params.postid )[0]; const commentsForThisPost = comments[this.props.match.params.postid] || []; const enabledCommentsForThisPost = commentsForThisPost.filter( comment => !comment.deleted ); const areCommentsSortSortable = enabledCommentsForThisPost.length !== 0; const sortedCommentsList = _.orderBy( enabledCommentsForThisPost, [selectedCommentSortOption], ['desc'] ); //Negative use case //In the case if user is viewing a deleted post if (_.isEmpty(post) || post.deleted) { return ( <div className="view-post-view"> <div className="header display-flex justify-space-between"> <div> {' '}<Link to="/"> <BackButton size={42.5} style={this.buttonStyle} /> </Link> </div> <div className="header-text"> POST DELETED</div> <div /> </div> </div> ); } //Positive use case //In the case if user is viewing a post return ( <div className="view-post-view"> {/* Header */} <div className="header display-flex justify-space-between"> <div> <Link to="/"> <BackButton size={42.5} style={this.buttonStyle} /> </Link> </div> <div className="header-text"> POST </div> <div> <DeleteButton size={50} style={this.buttonStyle} span onClick={()=> this.props.deletePost(post.id)}/> <EditButton size={50} style={this.buttonStyle} onClick={()=> this.setState({isPostModalOpen: true})}/> </div> </div> {/* Body */} <div className="view-post-content"> {/* Detailed post */} <div className="post-title">{post.title} </div> <div className="post-detail">{post.body} </div> <div className="post-detail"><i>Owner : </i>{post.author} </div> <div className="post-detail"><i>Created at</i> : {util.ts2Time(post.timestamp)} </div> <div className="vote"> <VoteUp onClick={()=> this.changeVote(post.id, "upVote")} size={50} style={this.upDownArrowStyle}/> <div className="post-detail">votes({post.voteScore}) </div> <VoteDown onClick={()=> this.changeVote(post.id, "downVote")} size={50} style={this.upDownArrowStyle}/> </div> <br/> <br/> <div className="comment-sub-header">COMMENTS</div> {/* Form to add new comment */} <form className="add-comment-form" onSubmit={this._submitForm}> <textarea rows="4" cols="50" type="multi" name="body" placeholder="body for comment ..." className="form-el"/> <div className="invalid-indicator"> <span hidden={!commentValidationResults.isBodyInvalid} className="invalid-form-entry"> Invalid Comment</span> </div> <input type="text" name="author" placeholder="author" className="form-el"/> <div className="invalid-indicator"> <span hidden={!commentValidationResults.isOwnerInvalid} className="invalid-form-entry"> Invalid author name </span> </div> <button className="form-button" > Add </button> </form> <br/> <br/> {/* Comment sort options: Visible only if there are comments to sort */} {areCommentsSortSortable && ( <div className="comment-sort-col display-flex" > {commentSortOption.map((sortOption, index) => ( <div key={index} onClick={()=> this._sortComments(sortOption.field)} className={this._computeClassName(selectedCommentSortOption, sortOption.field)}> <span className="sort-item"> Sort by {sortOption.label} </span> </div> ))} </div> )} {/* List of comments */} <div className="comments"> {!_.isEmpty(sortedCommentsList) && ( sortedCommentsList.map((item, index) => <CommentCard comment={item} key={index} /> ) )} </div> <Modal id="editPostModal" className='modal' overlayClassName='overlay' isOpen={isPostModalOpen} onRequestClose={this.closeModal} contentLabel='Modal'> {(isPostModalOpen && <EditPost post={post} closeModal={()=> this.setState({isPostModalOpen: false})} /> )} </Modal> </div> </div> ); }
JavaScript
render() { const { comment } = this.props; const { validationResults } = this.state; if (_.isEmpty(comment)) return <div />; return ( <div className="edit-comment display-flex justify-center"> <form className="edit-comment-form" onSubmit={this._submitForm} ref={(formEl) => { this.formEl = formEl; }}> <legend className="edit-comment-sub-header"> EDIT COMMENT </legend> <textarea rows="4" cols="50" type="multi" name="body" placeholder="body for comment ..." defaultValue={comment.body}/> <span hidden={!validationResults.isBodyInvalid} className="invalid-form-entry"> Invalid comment</span> <div className="justify-space-between display-flex form-button-wrapper"> <div onClick={this._submitForm} className="form-button"> Update </div> <div onClick={this._closeModel} className="form-button"> Cancel </div> </div> </form> </div> ); }
render() { const { comment } = this.props; const { validationResults } = this.state; if (_.isEmpty(comment)) return <div />; return ( <div className="edit-comment display-flex justify-center"> <form className="edit-comment-form" onSubmit={this._submitForm} ref={(formEl) => { this.formEl = formEl; }}> <legend className="edit-comment-sub-header"> EDIT COMMENT </legend> <textarea rows="4" cols="50" type="multi" name="body" placeholder="body for comment ..." defaultValue={comment.body}/> <span hidden={!validationResults.isBodyInvalid} className="invalid-form-entry"> Invalid comment</span> <div className="justify-space-between display-flex form-button-wrapper"> <div onClick={this._submitForm} className="form-button"> Update </div> <div onClick={this._closeModel} className="form-button"> Cancel </div> </div> </form> </div> ); }
JavaScript
render() { const { post } = this.props; const { validationResults } = this.state; if (_.isEmpty(post)) return <div />; return ( <div className="edit-post display-flex justify-center"> <form className="edit-post-form" onSubmit={this._submitForm} ref={(formEl) => { this.formEl = formEl; }}> <legend className="edit-post-sub-header"> EDIT POST </legend> <input type="text" name="title" defaultValue={post.title} placeholder="title for post ..."/> <span hidden={!validationResults.isTitleInvalid} className="invalid-form-entry"> Invalid Title </span> <textarea rows="4" cols="50" type="multi" name="body" placeholder="body for post ..." defaultValue={post.body}/> <span hidden={!validationResults.isBodyInvalid} className="invalid-form-entry"> Invalid Post</span> <div className="justify-space-between display-flex form-button-wrapper"> <div onClick={this._submitForm} className="form-button"> Update </div> <div onClick={this._closeModel} className="form-button"> Cancel </div> </div> </form> </div> ); }
render() { const { post } = this.props; const { validationResults } = this.state; if (_.isEmpty(post)) return <div />; return ( <div className="edit-post display-flex justify-center"> <form className="edit-post-form" onSubmit={this._submitForm} ref={(formEl) => { this.formEl = formEl; }}> <legend className="edit-post-sub-header"> EDIT POST </legend> <input type="text" name="title" defaultValue={post.title} placeholder="title for post ..."/> <span hidden={!validationResults.isTitleInvalid} className="invalid-form-entry"> Invalid Title </span> <textarea rows="4" cols="50" type="multi" name="body" placeholder="body for post ..." defaultValue={post.body}/> <span hidden={!validationResults.isBodyInvalid} className="invalid-form-entry"> Invalid Post</span> <div className="justify-space-between display-flex form-button-wrapper"> <div onClick={this._submitForm} className="form-button"> Update </div> <div onClick={this._closeModel} className="form-button"> Cancel </div> </div> </form> </div> ); }
JavaScript
render() { const {categories} = this.props; const {validationResults} = this.state; return ( <div className="add-post"> <div className="header"> ADD NEW POST </div> <div className="form-wrapper"> <form className="add-post-form" onSubmit={this._submitForm} ref={(formEl) => { this.formEl = formEl; }} > <input type="text" name="title" placeholder="Title for post ..." className="form-el"/> <div className="invalid-indicator"> <span hidden={!validationResults.isTitleInvalid} className="invalid-form-entry"> Invalid Title </span> </div> <textarea rows="50" cols="50" type="multi" name="body" placeholder="Body for post ..." className="form-el"/> <div className="invalid-indicator"> <span hidden={!validationResults.isBodyInvalid} className="invalid-form-entry"> Invalid Post</span> </div> <input type="text" name="owner" placeholder="Author" className="form-el"/> <div className="invalid-indicator"> <span hidden={!validationResults.isOwnerInvalid} className="invalid-form-entry"> Invalid author name </span> </div> <select name="category" defaultValue={"Category..."} className="form-el"> <option value={"Category..."} disabled className="form-el"> Category... </option> {!_.isEmpty(categories) && ( categories.map((item, index) => <option key={index} value={item.name} className="form-el"> {_.startCase(_.toLower(item.name))} </option> ) )} </select> <div className="invalid-indicator"> <span hidden={!validationResults.isCategoryInvalid} className="invalid-form-entry"> Invalid Category</span> </div> <div className="justify-space-between display-flex form-button-wrapper"> <span onClick={() => this.props.history.push("/")} className="form-button"> Cancel </span> <span onClick={this._submitForm} className="form-button"> Post </span> </div> </form> </div> </div> ); }
render() { const {categories} = this.props; const {validationResults} = this.state; return ( <div className="add-post"> <div className="header"> ADD NEW POST </div> <div className="form-wrapper"> <form className="add-post-form" onSubmit={this._submitForm} ref={(formEl) => { this.formEl = formEl; }} > <input type="text" name="title" placeholder="Title for post ..." className="form-el"/> <div className="invalid-indicator"> <span hidden={!validationResults.isTitleInvalid} className="invalid-form-entry"> Invalid Title </span> </div> <textarea rows="50" cols="50" type="multi" name="body" placeholder="Body for post ..." className="form-el"/> <div className="invalid-indicator"> <span hidden={!validationResults.isBodyInvalid} className="invalid-form-entry"> Invalid Post</span> </div> <input type="text" name="owner" placeholder="Author" className="form-el"/> <div className="invalid-indicator"> <span hidden={!validationResults.isOwnerInvalid} className="invalid-form-entry"> Invalid author name </span> </div> <select name="category" defaultValue={"Category..."} className="form-el"> <option value={"Category..."} disabled className="form-el"> Category... </option> {!_.isEmpty(categories) && ( categories.map((item, index) => <option key={index} value={item.name} className="form-el"> {_.startCase(_.toLower(item.name))} </option> ) )} </select> <div className="invalid-indicator"> <span hidden={!validationResults.isCategoryInvalid} className="invalid-form-entry"> Invalid Category</span> </div> <div className="justify-space-between display-flex form-button-wrapper"> <span onClick={() => this.props.history.push("/")} className="form-button"> Cancel </span> <span onClick={this._submitForm} className="form-button"> Post </span> </div> </form> </div> </div> ); }
JavaScript
function Body (tempc, tempspeed, temangle, tempscale, Xtemp, Ytemp, tempSize, tempTrans) { this.pos = new Array(2); this.mouse = new Array(2); this.pos[0] = Xtemp; this.pos[1] = Ytemp; this.Xpos = Xtemp; this.Ypos = Ytemp; this.c = tempc; this.speed = tempspeed; this.size = tempSize; this.angle = temangle; this.t_scale = tempscale; this.transX = tempTrans; this.mouse[0] = 0.0; this.mouse[1] = 0.0; }
function Body (tempc, tempspeed, temangle, tempscale, Xtemp, Ytemp, tempSize, tempTrans) { this.pos = new Array(2); this.mouse = new Array(2); this.pos[0] = Xtemp; this.pos[1] = Ytemp; this.Xpos = Xtemp; this.Ypos = Ytemp; this.c = tempc; this.speed = tempspeed; this.size = tempSize; this.angle = temangle; this.t_scale = tempscale; this.transX = tempTrans; this.mouse[0] = 0.0; this.mouse[1] = 0.0; }
JavaScript
function mouseWheel() { if (Scale > 0 && Scale < 50) { Scale = Scale + event.delta/abs(event.delta) *0.4 ; } else { if (Scale <0.0){ Scale = 1.0; }; if (Scale > 50.0) { Scale = 49.0; }; } console.log(Scale,event.delta, event ); }
function mouseWheel() { if (Scale > 0 && Scale < 50) { Scale = Scale + event.delta/abs(event.delta) *0.4 ; } else { if (Scale <0.0){ Scale = 1.0; }; if (Scale > 50.0) { Scale = 49.0; }; } console.log(Scale,event.delta, event ); }
JavaScript
function calcularModa(lista) { const listaC = {}; lista.map( function (elemento) { if (listaC[elemento]) { listaC[elemento] += 1; } else { listaC[elemento] = 1; } } ); const listaArray = Object.entries(listaC).sort( function (elementoA, elementoB) { return elementoA[1] - elementoB[1]; } ); const moda = listaArray[listaArray.length - 1]; return moda; }
function calcularModa(lista) { const listaC = {}; lista.map( function (elemento) { if (listaC[elemento]) { listaC[elemento] += 1; } else { listaC[elemento] = 1; } } ); const listaArray = Object.entries(listaC).sort( function (elementoA, elementoB) { return elementoA[1] - elementoB[1]; } ); const moda = listaArray[listaArray.length - 1]; return moda; }
JavaScript
function activate(context) { // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated console.log('Congratulations, the extension "vscode-stormalf-term" is now active!'); //terminal example myterm.myterm(context); // The command has been defined in the package.json file // Now provide the implementation of the command with registerCommand // The commandId parameter must match the command field in package.json let disposable = vscode.commands.registerCommand("vscode-stormalf-term.helloWorld", () => { // The code you place here will be executed every time your command is executed // Display a message box to the user vscode.window.showInformationMessage("Hello World from stormalf-term!"); myfirst.first(); }); context.subscriptions.push(disposable); }
function activate(context) { // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated console.log('Congratulations, the extension "vscode-stormalf-term" is now active!'); //terminal example myterm.myterm(context); // The command has been defined in the package.json file // Now provide the implementation of the command with registerCommand // The commandId parameter must match the command field in package.json let disposable = vscode.commands.registerCommand("vscode-stormalf-term.helloWorld", () => { // The code you place here will be executed every time your command is executed // Display a message box to the user vscode.window.showInformationMessage("Hello World from stormalf-term!"); myfirst.first(); }); context.subscriptions.push(disposable); }
JavaScript
function applyValidationOnSubsetCheck (instanceProperties) { const baseCheckSubsetOf = instanceProperties.checkSubsetOf instanceProperties.checkSubsetOf = function (targetSchema) { var isSourceSchemaInvalid = this.hasErrors var isTargetSchemaInvalid = targetSchema.hasErrors switch (true) { case isSourceSchemaInvalid && isTargetSchemaInvalid: return { isSubset: false, reason: 'source and target schemas are invalid' } case isSourceSchemaInvalid: return { isSubset: false, reason: 'source schema is invalid' } case isTargetSchemaInvalid: return { isSubset: false, reason: 'target schema is invalid' } default: return baseCheckSubsetOf.call(this, targetSchema) } } }
function applyValidationOnSubsetCheck (instanceProperties) { const baseCheckSubsetOf = instanceProperties.checkSubsetOf instanceProperties.checkSubsetOf = function (targetSchema) { var isSourceSchemaInvalid = this.hasErrors var isTargetSchemaInvalid = targetSchema.hasErrors switch (true) { case isSourceSchemaInvalid && isTargetSchemaInvalid: return { isSubset: false, reason: 'source and target schemas are invalid' } case isSourceSchemaInvalid: return { isSubset: false, reason: 'source schema is invalid' } case isTargetSchemaInvalid: return { isSubset: false, reason: 'target schema is invalid' } default: return baseCheckSubsetOf.call(this, targetSchema) } } }
JavaScript
static updateActivity() { let streamInfo = this.getMostRecentStreamInfo(); if (streamInfo) { this.discordClient.user.setActivity(streamInfo.user_name, { "url": `https://twitch.tv/${streamInfo.user_name.toLowerCase()}`, "type": "STREAMING" }); console.log(chalk.cyan('[' + DateTime.utc().toFormat(timeFormat) + '][StreamActivity]'), chalk.white(`Update current activity: watching ${streamInfo.user_name}.`)); } else { console.log(chalk.cyan('[' + DateTime.utc().toFormat(timeFormat) + '][StreamActivity]'), chalk.white('Cleared current activity.')); this.discordClient.user.setActivity(null); } }
static updateActivity() { let streamInfo = this.getMostRecentStreamInfo(); if (streamInfo) { this.discordClient.user.setActivity(streamInfo.user_name, { "url": `https://twitch.tv/${streamInfo.user_name.toLowerCase()}`, "type": "STREAMING" }); console.log(chalk.cyan('[' + DateTime.utc().toFormat(timeFormat) + '][StreamActivity]'), chalk.white(`Update current activity: watching ${streamInfo.user_name}.`)); } else { console.log(chalk.cyan('[' + DateTime.utc().toFormat(timeFormat) + '][StreamActivity]'), chalk.white('Cleared current activity.')); this.discordClient.user.setActivity(null); } }
JavaScript
function showVoteResults() { let factID = $('.facts').find('.container').find('p').attr('data-id'), t; $.ajax({ type: 'POST', url: 'ajax_facts.php', data: { factID }, success: function(data) { // results[0] => upvotes // results[1] => downvotes let results = JSON.parse(data); // Change text value. $('.facts-results').find('.upvotes').find('.score').find('span').html(results[0] + '%'); $('.facts-results').find('.downvotes').find('.score').find('span').html(results[1] + '%'); // Modify width of result bars according to the real results let count_upvotes = 50; let count_downvotes = 50; t = setInterval(() => { $('.facts-results').find('.upvotes').css('width', count_upvotes + '%'); $('.facts-results').find('.downvotes').css('width', count_downvotes + '%'); if(count_upvotes < results[0]) count_upvotes++; if(count_upvotes > results[0]) count_upvotes--; if(count_upvotes == results[0]) clearInterval(t); count_downvotes = 100 - count_upvotes; }, 10) $('.facts-results').addClass('show-flex'); } }); setTimeout(() => { $('.facts-results').removeClass('show-flex'); $.ajax({ type: 'POST', url: 'ajax_facts.php', success: function(data) { $('.facts').find('.container').html(data); } }); }, 3000); }
function showVoteResults() { let factID = $('.facts').find('.container').find('p').attr('data-id'), t; $.ajax({ type: 'POST', url: 'ajax_facts.php', data: { factID }, success: function(data) { // results[0] => upvotes // results[1] => downvotes let results = JSON.parse(data); // Change text value. $('.facts-results').find('.upvotes').find('.score').find('span').html(results[0] + '%'); $('.facts-results').find('.downvotes').find('.score').find('span').html(results[1] + '%'); // Modify width of result bars according to the real results let count_upvotes = 50; let count_downvotes = 50; t = setInterval(() => { $('.facts-results').find('.upvotes').css('width', count_upvotes + '%'); $('.facts-results').find('.downvotes').css('width', count_downvotes + '%'); if(count_upvotes < results[0]) count_upvotes++; if(count_upvotes > results[0]) count_upvotes--; if(count_upvotes == results[0]) clearInterval(t); count_downvotes = 100 - count_upvotes; }, 10) $('.facts-results').addClass('show-flex'); } }); setTimeout(() => { $('.facts-results').removeClass('show-flex'); $.ajax({ type: 'POST', url: 'ajax_facts.php', success: function(data) { $('.facts').find('.container').html(data); } }); }, 3000); }
JavaScript
function EthernetTransport(opts) { if (!(this instanceof EthernetTransport)) { return new EthernetTransport(opts); } this.configuration = opts.configuration; this.controller = ""; switch (Controllers[this.configuration.controller].driver) { case Controllers.WIZ5100.driver: this.controller = Controllers.WIZ5100; break; case Controllers.ENC28J60.driver: this.controller = Controllers.ENC28J60; break; case Controllers.YUN.driver: this.controller = Controllers.YUN; break; default: throw new Error("No valid Ethernet controller defined"); } }
function EthernetTransport(opts) { if (!(this instanceof EthernetTransport)) { return new EthernetTransport(opts); } this.configuration = opts.configuration; this.controller = ""; switch (Controllers[this.configuration.controller].driver) { case Controllers.WIZ5100.driver: this.controller = Controllers.WIZ5100; break; case Controllers.ENC28J60.driver: this.controller = Controllers.ENC28J60; break; case Controllers.YUN.driver: this.controller = Controllers.YUN; break; default: throw new Error("No valid Ethernet controller defined"); } }
JavaScript
function bytediffFormatter(data) { var difference = (data.savings > 0) ? ' smaller.' : ' larger.'; return data.fileName + ' went from ' + (data.startSize / 1000).toFixed(2) + ' kB to ' + (data.endSize / 1000).toFixed(2) + ' kB' + ' and is ' + formatPercent(1 - data.percent, 2) + '%' + difference; }
function bytediffFormatter(data) { var difference = (data.savings > 0) ? ' smaller.' : ' larger.'; return data.fileName + ' went from ' + (data.startSize / 1000).toFixed(2) + ' kB to ' + (data.endSize / 1000).toFixed(2) + ' kB' + ' and is ' + formatPercent(1 - data.percent, 2) + '%' + difference; }
JavaScript
function notify(){ notifier.notify({ sound: 'Bottle', contentImage: path.join(__dirname, 'gulp.png'), icon: path.join(__dirname, 'gulp.png'), title: 'Gulp Build', subtitle: 'Deployed to the build folder', message: 'gulp serve-dev --sync' }); }
function notify(){ notifier.notify({ sound: 'Bottle', contentImage: path.join(__dirname, 'gulp.png'), icon: path.join(__dirname, 'gulp.png'), title: 'Gulp Build', subtitle: 'Deployed to the build folder', message: 'gulp serve-dev --sync' }); }
JavaScript
function parseError(e) { let sqlError = (e.source || e); if (e.code && e.code.indexOf('MONGO') === 0) { e.ns = 'STORE.MONGO'; } e.ns = 'STORE.mongo'; switch (sqlError.name) { case 'ValidatorError': e.code = 'STORE.DATA'; break; case 'VersionError': e.code = 'STORE.DATA_VERSION'; break; default: e.code = 'DATABASE_ERROR'; } return true; }
function parseError(e) { let sqlError = (e.source || e); if (e.code && e.code.indexOf('MONGO') === 0) { e.ns = 'STORE.MONGO'; } e.ns = 'STORE.mongo'; switch (sqlError.name) { case 'ValidatorError': e.code = 'STORE.DATA'; break; case 'VersionError': e.code = 'STORE.DATA_VERSION'; break; default: e.code = 'DATABASE_ERROR'; } return true; }
JavaScript
function initialize() { var myLatlng = new google.maps.LatLng(40.7833806,-74.0758533); // Change your location var mapOptions = { zoom: 5, // Change zoom value scrollwheel: false, // Change to "true" to enable users scale map on scroll center: myLatlng } var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); var marker = new google.maps.Marker({ position: myLatlng, map: map, title: 'Your business is here!' // Change the pinpoint popup text }); }
function initialize() { var myLatlng = new google.maps.LatLng(40.7833806,-74.0758533); // Change your location var mapOptions = { zoom: 5, // Change zoom value scrollwheel: false, // Change to "true" to enable users scale map on scroll center: myLatlng } var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); var marker = new google.maps.Marker({ position: myLatlng, map: map, title: 'Your business is here!' // Change the pinpoint popup text }); }
JavaScript
function groupAssets (assets, assetPath) { var exampleName = path.basename(assetPath, path.extname(assetPath)); if (!assets[exampleName]) { assets[exampleName] = []; } assets[exampleName].push(assetPath); return assets; }
function groupAssets (assets, assetPath) { var exampleName = path.basename(assetPath, path.extname(assetPath)); if (!assets[exampleName]) { assets[exampleName] = []; } assets[exampleName].push(assetPath); return assets; }
JavaScript
function buildExamples () { var examples = {}; var metadata = grunt.file.expand([ 'src/**/examples/*', 'demo/examples/*' ]).reduce(groupAssets, {}); // Iterate over grouped file paths to build example objects that contain // markup, javascript, and less content for loading via rxExample // // Objects should result in an something that looks like: // { // markup: '...', // javascript: '...', // Optional // less: '...' // Optional // } for (key in metadata) { if (examples[key]) { throw new Error(`Examples for '${key}' already defined.`); } var example = {}; metadata[key].forEach(function (filePath) { var fileContent = grunt.file.read(filePath); var ext = path.extname(filePath); switch (ext) { case '.html': example.markup = fileContent; break; case '.js': example.javascript = fileContent; break; case '.less': example.less = fileContent; break; default: throw new Error(`Unknown file extension: ${ext}`); break; } }); examples[key] = example; } return examples; }//findExamples
function buildExamples () { var examples = {}; var metadata = grunt.file.expand([ 'src/**/examples/*', 'demo/examples/*' ]).reduce(groupAssets, {}); // Iterate over grouped file paths to build example objects that contain // markup, javascript, and less content for loading via rxExample // // Objects should result in an something that looks like: // { // markup: '...', // javascript: '...', // Optional // less: '...' // Optional // } for (key in metadata) { if (examples[key]) { throw new Error(`Examples for '${key}' already defined.`); } var example = {}; metadata[key].forEach(function (filePath) { var fileContent = grunt.file.read(filePath); var ext = path.extname(filePath); switch (ext) { case '.html': example.markup = fileContent; break; case '.js': example.javascript = fileContent; break; case '.less': example.less = fileContent; break; default: throw new Error(`Unknown file extension: ${ext}`); break; } }); examples[key] = example; } return examples; }//findExamples
JavaScript
_hoverOverAction () { browser.actions().mouseMove(this.eleAction).perform(); // I know what you're thinking -- don't. Just leave it. // Otherwise, tooltips in tables in Chrome will not actually appear. browser.actions().mouseMove(this.eleAction).perform(); }
_hoverOverAction () { browser.actions().mouseMove(this.eleAction).perform(); // I know what you're thinking -- don't. Just leave it. // Otherwise, tooltips in tables in Chrome will not actually appear. browser.actions().mouseMove(this.eleAction).perform(); }
JavaScript
function selectNodeText (elementNode) { var range = document.createRange(); var selection = $window.getSelection(); // Unselect everything selection.removeAllRanges(); // Add all transcluded text to the range range.selectNodeContents(elementNode); // Apply text selection to window selection.addRange(range); }//selectNodeText()
function selectNodeText (elementNode) { var range = document.createRange(); var selection = $window.getSelection(); // Unselect everything selection.removeAllRanges(); // Add all transcluded text to the range range.selectNodeContents(elementNode); // Apply text selection to window selection.addRange(range); }//selectNodeText()
JavaScript
function execCopy (passFn, failFn) { try { if (document.execCommand('copy')) { _.isFunction(passFn) && passFn(); } else { _.isFunction(failFn) && failFn(); } } catch (e) { _.isFunction(failFn) && failFn(e); } }//execCopy
function execCopy (passFn, failFn) { try { if (document.execCommand('copy')) { _.isFunction(passFn) && passFn(); } else { _.isFunction(failFn) && failFn(); } } catch (e) { _.isFunction(failFn) && failFn(e); } }//execCopy
JavaScript
function xorFilter () { return function (a, b) { console.warn( 'DEPRECATED: xor - Please use rxXor. ' + 'xor will be removed in EncoreUI 4.0.0' ); return rxXorFilter()(a, b); }; }//xorFilter
function xorFilter () { return function (a, b) { console.warn( 'DEPRECATED: xor - Please use rxXor. ' + 'xor will be removed in EncoreUI 4.0.0' ); return rxXorFilter()(a, b); }; }//xorFilter
JavaScript
function ApplyFilter () { return function (list, filter) { console.warn( 'DEPRECATED: Apply - Please use rxApply. ' + 'Apply will be removed in EncoreUI 4.0.0' ); return rxApplyFilter()(list, filter); }; }//ApplyFilter
function ApplyFilter () { return function (list, filter) { console.warn( 'DEPRECATED: Apply - Please use rxApply. ' + 'Apply will be removed in EncoreUI 4.0.0' ); return rxApplyFilter()(list, filter); }; }//ApplyFilter
JavaScript
function removeFloat () { isFloating = false; _.each(header.find('tr'), function (tr) { var row = angular.element(tr); if (row.hasClass('rx-floating-header')) { // Cleanup classes/CSS row.removeClass('rx-floating-header'); row.css({ top: null }); _.each(row.find('th'), function (th) { var cell = angular.element(th); cell.css({ width: null }); }); } else { /* Filler Row */ row.remove(); } }); }//removeFloat()
function removeFloat () { isFloating = false; _.each(header.find('tr'), function (tr) { var row = angular.element(tr); if (row.hasClass('rx-floating-header')) { // Cleanup classes/CSS row.removeClass('rx-floating-header'); row.css({ top: null }); _.each(row.find('th'), function (th) { var cell = angular.element(th); cell.css({ width: null }); }); } else { /* Filler Row */ row.remove(); } }); }//removeFloat()
JavaScript
function reapplyFloat () { if (isFloating) { removeFloat(); applyFloat(); } }//reapplyFloat()
function reapplyFloat () { if (isFloating) { removeFloat(); applyFloat(); } }//reapplyFloat()
JavaScript
function update () { var maxHeight = table[0].offsetHeight; if (rxDOMHelper.shouldFloat(table, maxHeight)) { // If we're not floating, start floating if (!isFloating) { applyFloat(); } } else { // If we're floating, stop floating if (isFloating) { removeFloat(); } } }//update()
function update () { var maxHeight = table[0].offsetHeight; if (rxDOMHelper.shouldFloat(table, maxHeight)) { // If we're not floating, start floating if (!isFloating) { applyFloat(); } } else { // If we're floating, stop floating if (isFloating) { removeFloat(); } } }//update()
JavaScript
function findModule (category, name) { if (_.isUndefined(name)) { return; } function parseMarkdown (text) { return markdown(text); } var globBase = ['src', category, name].join('/'); var _srcFiles = grunt.file.expand([ globBase + '.module.js', // category manifests globBase + '/' + name + '.module.js', // component manifests (legacy) globBase + '/scripts/!(*.spec).js' // Load additional scripts ]); var _tplFiles = grunt.file.expand([ globBase + '/*.tpl.html' ]); var _tplJsFiles = grunt.file.expand([ 'templates/' + name + '/templates/*.html' ]); var _docMdFiles = grunt.file.expand(globBase + '/*.md'); var _docJsFiles = grunt.file.expand([ globBase + '/docs/*.js', globBase + '/docs/examples/**/*.js' ]); var _docHtmlFiles = grunt.file.expand(globBase + '/docs/*.html'); var _docLessFiles = grunt.file.expand(globBase + '/*.less'); var _moduleName = ['encore', 'ui']; if (category == 'components') { _moduleName.push(name); } else { _moduleName.push(category); } // Fetch Module Metadata var metadataJson = globBase + '/docs/' + name + '.meta.json'; var metadata = {}; if (grunt.file.exists(metadataJson)) { metadata = grunt.file.readJSON(metadataJson); } // Using Metadata as a base, add on additional information var module = _.defaults(metadata, { name: name, moduleName: enquote(_moduleName.join('.')), category: category, description: '', stability: 'prototype', // should be set by <module>.meta.json keywords: [], // should be set by <module>.meta.json displayName: name, // should be set by <module>.meta.json isLegacy: false, // TODO: to be removed with last of components hasApi: true, isCategory: (category == name), srcFiles: _srcFiles, tplFiles: _tplFiles, tplJsFiles: _tplJsFiles, docs: { // TODO: replace with <rx-example> md: _docMdFiles.map(grunt.file.read).map(parseMarkdown).join('\n'), js: _docJsFiles.map(grunt.file.read).join('\n'), html: _docHtmlFiles.map(grunt.file.read).join('\n'), less: _docLessFiles.map(grunt.file.read).join('\n') } }); grunt.config('config.modules', grunt.config('config.modules').concat(module)); }//findModule
function findModule (category, name) { if (_.isUndefined(name)) { return; } function parseMarkdown (text) { return markdown(text); } var globBase = ['src', category, name].join('/'); var _srcFiles = grunt.file.expand([ globBase + '.module.js', // category manifests globBase + '/' + name + '.module.js', // component manifests (legacy) globBase + '/scripts/!(*.spec).js' // Load additional scripts ]); var _tplFiles = grunt.file.expand([ globBase + '/*.tpl.html' ]); var _tplJsFiles = grunt.file.expand([ 'templates/' + name + '/templates/*.html' ]); var _docMdFiles = grunt.file.expand(globBase + '/*.md'); var _docJsFiles = grunt.file.expand([ globBase + '/docs/*.js', globBase + '/docs/examples/**/*.js' ]); var _docHtmlFiles = grunt.file.expand(globBase + '/docs/*.html'); var _docLessFiles = grunt.file.expand(globBase + '/*.less'); var _moduleName = ['encore', 'ui']; if (category == 'components') { _moduleName.push(name); } else { _moduleName.push(category); } // Fetch Module Metadata var metadataJson = globBase + '/docs/' + name + '.meta.json'; var metadata = {}; if (grunt.file.exists(metadataJson)) { metadata = grunt.file.readJSON(metadataJson); } // Using Metadata as a base, add on additional information var module = _.defaults(metadata, { name: name, moduleName: enquote(_moduleName.join('.')), category: category, description: '', stability: 'prototype', // should be set by <module>.meta.json keywords: [], // should be set by <module>.meta.json displayName: name, // should be set by <module>.meta.json isLegacy: false, // TODO: to be removed with last of components hasApi: true, isCategory: (category == name), srcFiles: _srcFiles, tplFiles: _tplFiles, tplJsFiles: _tplJsFiles, docs: { // TODO: replace with <rx-example> md: _docMdFiles.map(grunt.file.read).map(parseMarkdown).join('\n'), js: _docJsFiles.map(grunt.file.read).join('\n'), html: _docHtmlFiles.map(grunt.file.read).join('\n'), less: _docLessFiles.map(grunt.file.read).join('\n') } }); grunt.config('config.modules', grunt.config('config.modules').concat(module)); }//findModule
JavaScript
function titleizeFilter () { return function (inputString) { console.warn( 'DEPRECATED: titleize - Please use rxTitleize. ' + 'titleize will be removed in EncoreUI 4.0.0' ); return rxTitleizeFilter()(inputString); }; }
function titleizeFilter () { return function (inputString) { console.warn( 'DEPRECATED: titleize - Please use rxTitleize. ' + 'titleize will be removed in EncoreUI 4.0.0' ); return rxTitleizeFilter()(inputString); }; }
JavaScript
function rxPaginateFilter (rxPageTracker, rxPaginateUtils) { return function (items, pager) { if (!pager) { pager = rxPageTracker.createInstance(); } if (pager.showAll) { pager.total = items.length; return items; } if (items) { pager.total = items.length; // We were previously on the last page, but enough items were deleted // to reduce the total number of pages. We should now jump to whatever the // new last page is // When loading items over the network, our first few times through here // will have totalPages===0. We do the _.max to ensure that // we never set pageNumber to -1 if (pager.pageNumber + 1 > pager.totalPages) { if (!pager.isLastPage()) { pager.goToLastPage(); } } var firstLast = rxPaginateUtils.firstAndLast(pager.currentPage(), pager.itemsPerPage, items.length); return items.slice(firstLast.first, firstLast.last); } }; }//rxPaginateFilter
function rxPaginateFilter (rxPageTracker, rxPaginateUtils) { return function (items, pager) { if (!pager) { pager = rxPageTracker.createInstance(); } if (pager.showAll) { pager.total = items.length; return items; } if (items) { pager.total = items.length; // We were previously on the last page, but enough items were deleted // to reduce the total number of pages. We should now jump to whatever the // new last page is // When loading items over the network, our first few times through here // will have totalPages===0. We do the _.max to ensure that // we never set pageNumber to -1 if (pager.pageNumber + 1 > pager.totalPages) { if (!pager.isLastPage()) { pager.goToLastPage(); } } var firstLast = rxPaginateUtils.firstAndLast(pager.currentPage(), pager.itemsPerPage, items.length); return items.slice(firstLast.first, firstLast.last); } }; }//rxPaginateFilter
JavaScript
function PaginateFilter (rxPageTracker, rxPaginateUtils) { return function (items, pager) { console.warn( 'DEPRECATED: Paginate - Please use rxPaginate. ' + 'Paginate will be removed in EncoreUI 4.0.0' ); return rxPaginateFilter(rxPageTracker, rxPaginateUtils)(items, pager); }; }//PaginateFilter
function PaginateFilter (rxPageTracker, rxPaginateUtils) { return function (items, pager) { console.warn( 'DEPRECATED: Paginate - Please use rxPaginate. ' + 'Paginate will be removed in EncoreUI 4.0.0' ); return rxPaginateFilter(rxPageTracker, rxPaginateUtils)(items, pager); }; }//PaginateFilter
JavaScript
function addtonewMarkers(latLng, map) { var len = newMarkers.length; var marker = new google.maps.Marker({ position: latLng, map: map, animation: google.maps.Animation.DROP, icon: markerIcon }); marker.addListener('click', function(e) { var len = newMarkers.length; for (var i = 0; i < len; i++) { if(newMarkers[i].position == e.latLng){ var tempmark = newMarkers[i]; newMarkers[i] = newMarkers[len-1]; newMarkers[len-1] = tempmark; newMarkers[len-1].setMap(null); newMarkers.pop(); len--; } } console.log(newMarkers); }); newMarkers.push(marker); }
function addtonewMarkers(latLng, map) { var len = newMarkers.length; var marker = new google.maps.Marker({ position: latLng, map: map, animation: google.maps.Animation.DROP, icon: markerIcon }); marker.addListener('click', function(e) { var len = newMarkers.length; for (var i = 0; i < len; i++) { if(newMarkers[i].position == e.latLng){ var tempmark = newMarkers[i]; newMarkers[i] = newMarkers[len-1]; newMarkers[len-1] = tempmark; newMarkers[len-1].setMap(null); newMarkers.pop(); len--; } } console.log(newMarkers); }); newMarkers.push(marker); }
JavaScript
function scanBarcode() { window.plugins.barcodeScanner.scan( function(result) { if (result.text == "280720550") // Produto 1 { document.getElementById("scan-titulo").textContent="PRODUTO ENCONTRADO"; document.getElementById('produto-img-1').src="img/produto1.png" document.getElementById("produto-txt-1").textContent="Apple iPad Mini Wi-Fi"; document.getElementById("produto-txt-2").textContent="Valor: R$ 3.499,00"; document.getElementById("produto-txt-3").textContent="Cor: Cinza Espacial"; document.getElementById("produto-txt-4").textContent="S.O: iOS"; document.getElementById("produto-txt-5").textContent="Processador: A12 Bionic"; document.getElementById("produto-txt-6").textContent="Memoria Interna: 64GB"; document.getElementById("produto-txt-7").textContent="Memoria Ram: ---"; document.getElementById("produto-txt-8").textContent="Tela: 7.9"; document.getElementById("produto-txt-9").textContent="Camera: 8MP"; } else if (result.text == "989895555") // Produto 2 { document.getElementById("scan-titulo").textContent="PRODUTO ENCONTRADO"; document.getElementById('produto-img-1').src="img/produto2.png" document.getElementById("produto-txt-1").textContent="Samsung Galaxy J8 Dual Chip"; document.getElementById("produto-txt-2").textContent="Valor: R$ 1.888,00"; document.getElementById("produto-txt-3").textContent="Cor: Preto"; document.getElementById("produto-txt-4").textContent="S.O: Android 9 Pie"; document.getElementById("produto-txt-5").textContent="Processador: Octa Core"; document.getElementById("produto-txt-6").textContent="Memoria Interna: 64GB"; document.getElementById("produto-txt-7").textContent="Memoria Ram: 4GB"; document.getElementById("produto-txt-8").textContent="Tela: 6"; document.getElementById("produto-txt-9").textContent="Camera: 16MP"; } else if (result.text == "85236987") // Produto 3 { document.getElementById("scan-titulo").textContent="PRODUTO ENCONTRADO"; document.getElementById('produto-img-1').src="img/produto3.png" document.getElementById("produto-txt-1").textContent="Motorola One XT1941"; document.getElementById("produto-txt-2").textContent="Valor: R$ 1.099,00"; document.getElementById("produto-txt-3").textContent="Cor: Preto"; document.getElementById("produto-txt-4").textContent="S.O: Android 8 Oreo"; document.getElementById("produto-txt-5").textContent="Processador: Octa Core"; document.getElementById("produto-txt-6").textContent="Memoria Interna: 64GB"; document.getElementById("produto-txt-7").textContent="Memoria Ram: 4GB"; document.getElementById("produto-txt-8").textContent="Tela: 6"; document.getElementById("produto-txt-9").textContent="Camera: 13MP"; } else if (result.text == "85369877444") // Produto 4 { document.getElementById("scan-titulo").textContent="PRODUTO ENCONTRADO"; document.getElementById('produto-img-1').src="img/produto4.png" document.getElementById("produto-txt-1").textContent="Asus Zenfone Max Pro M1"; document.getElementById("produto-txt-2").textContent="Valor: R$ 1.199,00"; document.getElementById("produto-txt-3").textContent="Cor: Azul Espacial"; document.getElementById("produto-txt-4").textContent="S.O: Android 8.1 Oreo"; document.getElementById("produto-txt-5").textContent="Processador: Octa Core"; document.getElementById("produto-txt-6").textContent="Memoria Interna: 64GB"; document.getElementById("produto-txt-7").textContent="Memoria Ram: 4GB"; document.getElementById("produto-txt-8").textContent="Tela: 6"; document.getElementById("produto-txt-9").textContent="Camera: 16MP"; } else // Produto não econtrado { document.getElementById("scan-titulo").textContent="PRODUTO NÃO ENCONTRADO"; document.getElementById('produto-img-1').src="img/notfound.png" document.getElementById("produto-txt-1").textContent=""; document.getElementById("produto-txt-2").textContent=""; document.getElementById("produto-txt-3").textContent=""; document.getElementById("produto-txt-4").textContent=""; document.getElementById("produto-txt-5").textContent=""; document.getElementById("produto-txt-6").textContent=""; document.getElementById("produto-txt-7").textContent=""; document.getElementById("produto-txt-8").textContent=""; document.getElementById("produto-txt-9").textContent=""; } }, function(error) { alert("Erro ao escanear: " + error); } ); }
function scanBarcode() { window.plugins.barcodeScanner.scan( function(result) { if (result.text == "280720550") // Produto 1 { document.getElementById("scan-titulo").textContent="PRODUTO ENCONTRADO"; document.getElementById('produto-img-1').src="img/produto1.png" document.getElementById("produto-txt-1").textContent="Apple iPad Mini Wi-Fi"; document.getElementById("produto-txt-2").textContent="Valor: R$ 3.499,00"; document.getElementById("produto-txt-3").textContent="Cor: Cinza Espacial"; document.getElementById("produto-txt-4").textContent="S.O: iOS"; document.getElementById("produto-txt-5").textContent="Processador: A12 Bionic"; document.getElementById("produto-txt-6").textContent="Memoria Interna: 64GB"; document.getElementById("produto-txt-7").textContent="Memoria Ram: ---"; document.getElementById("produto-txt-8").textContent="Tela: 7.9"; document.getElementById("produto-txt-9").textContent="Camera: 8MP"; } else if (result.text == "989895555") // Produto 2 { document.getElementById("scan-titulo").textContent="PRODUTO ENCONTRADO"; document.getElementById('produto-img-1').src="img/produto2.png" document.getElementById("produto-txt-1").textContent="Samsung Galaxy J8 Dual Chip"; document.getElementById("produto-txt-2").textContent="Valor: R$ 1.888,00"; document.getElementById("produto-txt-3").textContent="Cor: Preto"; document.getElementById("produto-txt-4").textContent="S.O: Android 9 Pie"; document.getElementById("produto-txt-5").textContent="Processador: Octa Core"; document.getElementById("produto-txt-6").textContent="Memoria Interna: 64GB"; document.getElementById("produto-txt-7").textContent="Memoria Ram: 4GB"; document.getElementById("produto-txt-8").textContent="Tela: 6"; document.getElementById("produto-txt-9").textContent="Camera: 16MP"; } else if (result.text == "85236987") // Produto 3 { document.getElementById("scan-titulo").textContent="PRODUTO ENCONTRADO"; document.getElementById('produto-img-1').src="img/produto3.png" document.getElementById("produto-txt-1").textContent="Motorola One XT1941"; document.getElementById("produto-txt-2").textContent="Valor: R$ 1.099,00"; document.getElementById("produto-txt-3").textContent="Cor: Preto"; document.getElementById("produto-txt-4").textContent="S.O: Android 8 Oreo"; document.getElementById("produto-txt-5").textContent="Processador: Octa Core"; document.getElementById("produto-txt-6").textContent="Memoria Interna: 64GB"; document.getElementById("produto-txt-7").textContent="Memoria Ram: 4GB"; document.getElementById("produto-txt-8").textContent="Tela: 6"; document.getElementById("produto-txt-9").textContent="Camera: 13MP"; } else if (result.text == "85369877444") // Produto 4 { document.getElementById("scan-titulo").textContent="PRODUTO ENCONTRADO"; document.getElementById('produto-img-1').src="img/produto4.png" document.getElementById("produto-txt-1").textContent="Asus Zenfone Max Pro M1"; document.getElementById("produto-txt-2").textContent="Valor: R$ 1.199,00"; document.getElementById("produto-txt-3").textContent="Cor: Azul Espacial"; document.getElementById("produto-txt-4").textContent="S.O: Android 8.1 Oreo"; document.getElementById("produto-txt-5").textContent="Processador: Octa Core"; document.getElementById("produto-txt-6").textContent="Memoria Interna: 64GB"; document.getElementById("produto-txt-7").textContent="Memoria Ram: 4GB"; document.getElementById("produto-txt-8").textContent="Tela: 6"; document.getElementById("produto-txt-9").textContent="Camera: 16MP"; } else // Produto não econtrado { document.getElementById("scan-titulo").textContent="PRODUTO NÃO ENCONTRADO"; document.getElementById('produto-img-1').src="img/notfound.png" document.getElementById("produto-txt-1").textContent=""; document.getElementById("produto-txt-2").textContent=""; document.getElementById("produto-txt-3").textContent=""; document.getElementById("produto-txt-4").textContent=""; document.getElementById("produto-txt-5").textContent=""; document.getElementById("produto-txt-6").textContent=""; document.getElementById("produto-txt-7").textContent=""; document.getElementById("produto-txt-8").textContent=""; document.getElementById("produto-txt-9").textContent=""; } }, function(error) { alert("Erro ao escanear: " + error); } ); }
JavaScript
function promptUser() { // parseInt changes to a number. passLength = parseInt(prompt("Choose a password length between 8-128 charectors")); // If the user does not choose a password between 8 and 128, they will receive another prompt to choose a number. // Possible selection = the password being generated. // Each line includes possible selection with each of the four options being added or subtracted from it. if (passLength < 8 || passLength > 128) { prompt("Please choose a whole number between 8 and 128 charectors"); } if (confirm("Would you like to use upper case letters?")) { possibleSelection = possibleSelection + upperCase } if (confirm("Would you like to use lower case letters?")){ possibleSelection = possibleSelection + lowerCase } if (confirm("Would you like to use special charectors?")){ possibleSelection = possibleSelection + specialCharector } if (confirm("Would you like to use number values?")){ possibleSelection = possibleSelection + numberValue } // function stops running when 'return' prompt is inserted at the end. return }
function promptUser() { // parseInt changes to a number. passLength = parseInt(prompt("Choose a password length between 8-128 charectors")); // If the user does not choose a password between 8 and 128, they will receive another prompt to choose a number. // Possible selection = the password being generated. // Each line includes possible selection with each of the four options being added or subtracted from it. if (passLength < 8 || passLength > 128) { prompt("Please choose a whole number between 8 and 128 charectors"); } if (confirm("Would you like to use upper case letters?")) { possibleSelection = possibleSelection + upperCase } if (confirm("Would you like to use lower case letters?")){ possibleSelection = possibleSelection + lowerCase } if (confirm("Would you like to use special charectors?")){ possibleSelection = possibleSelection + specialCharector } if (confirm("Would you like to use number values?")){ possibleSelection = possibleSelection + numberValue } // function stops running when 'return' prompt is inserted at the end. return }
JavaScript
function regenerateFromeDCT(decodedImage) { decodedImage._decoder.components = []; const frame = decodedImage._decoder.frames[0]; for (let i = 0; i < frame.componentsOrder.length; i++) { const component = frame.components[frame.componentsOrder[i]]; decodedImage._decoder.components.push({ lines: decodedImage._decoder.buildComponentData(frame, component), scaleX: component.h / frame.maxH, scaleY: component.v / frame.maxV }); } decodedImage._decoder.copyToImageData({ width: decodedImage.width, height: decodedImage.height, data: decodedImage.data }); }
function regenerateFromeDCT(decodedImage) { decodedImage._decoder.components = []; const frame = decodedImage._decoder.frames[0]; for (let i = 0; i < frame.componentsOrder.length; i++) { const component = frame.components[frame.componentsOrder[i]]; decodedImage._decoder.components.push({ lines: decodedImage._decoder.buildComponentData(frame, component), scaleX: component.h / frame.maxH, scaleY: component.v / frame.maxV }); } decodedImage._decoder.copyToImageData({ width: decodedImage.width, height: decodedImage.height, data: decodedImage.data }); }
JavaScript
function dot(b) { if (decimalPoint == "") { enter = entered = b; first+= enter; entered+= enter; decimalPoint = "."; dotCounter = 0; return first; } else { return first; } }
function dot(b) { if (decimalPoint == "") { enter = entered = b; first+= enter; entered+= enter; decimalPoint = "."; dotCounter = 0; return first; } else { return first; } }
JavaScript
function PE(b) { decimalPoint = "."; dotCounter = 15; var cons = b; if (peSign == "") { if (operatorSign != "" && first == "" + operatorSign) { first = (cons = "PI") ? Math.PI: Math.E; } else if (operatorSign != "" && first > 0 || first < 0) { first = (cons == "PI") ? first + "*" + Math.PI: first + "*" + Math.E; } else if (first != "" && operatorSign != "") { first += (cons = "PI") ? Math.PI: Math.E; } else if (operatorSign == "" && first != "") { first = (cons == "PI") ? first + "*" + Math.PI: first + "*" + Math.E; } else { first = (cons == "PI") ? Math.PI: Math.E; } } else if (first !== "") { first = (cons == "PI") ? first + "*" + Math.PI: first + "*" + Math.E; } else { first = (cons == "PI") ? Math.PI: Math.E; } return first; }
function PE(b) { decimalPoint = "."; dotCounter = 15; var cons = b; if (peSign == "") { if (operatorSign != "" && first == "" + operatorSign) { first = (cons = "PI") ? Math.PI: Math.E; } else if (operatorSign != "" && first > 0 || first < 0) { first = (cons == "PI") ? first + "*" + Math.PI: first + "*" + Math.E; } else if (first != "" && operatorSign != "") { first += (cons = "PI") ? Math.PI: Math.E; } else if (operatorSign == "" && first != "") { first = (cons == "PI") ? first + "*" + Math.PI: first + "*" + Math.E; } else { first = (cons == "PI") ? Math.PI: Math.E; } } else if (first !== "") { first = (cons == "PI") ? first + "*" + Math.PI: first + "*" + Math.E; } else { first = (cons == "PI") ? Math.PI: Math.E; } return first; }
JavaScript
function mathematics() { if (math == "sqr") { result = firstI * firstI; } else if (math == "cube") { result = firstI * firstI * firstI; } else if (math == "Sqrt") { result = Math.sqrt(firstI); } else if (math == "cubert") { result = Math.cbrt(firstI); } else if (math == "negpos") { result = firstI * -1; } else if (math == "sine") { result = Math.sin(firstI); } else if (math == "cosine") { result = Math.cos(firstI); } else if (math == "tangent") { result = Math.tan(firstI); } else if (math == "ln") { result = Math.log(firstI); } else if (math == "logTen") { result = Math.log10(firstI); } else if (math == "rand") { result = Math.round(firstI); }else if (math == "res") { result = 1 / firstI; } else if (math == "fact") { n = firstI; firstI = 1; while (n > 1){ firstI *= n; n -= 1; } result = firstI; } decimalPoint = (Math.round(result) == result) ? "": "."; }
function mathematics() { if (math == "sqr") { result = firstI * firstI; } else if (math == "cube") { result = firstI * firstI * firstI; } else if (math == "Sqrt") { result = Math.sqrt(firstI); } else if (math == "cubert") { result = Math.cbrt(firstI); } else if (math == "negpos") { result = firstI * -1; } else if (math == "sine") { result = Math.sin(firstI); } else if (math == "cosine") { result = Math.cos(firstI); } else if (math == "tangent") { result = Math.tan(firstI); } else if (math == "ln") { result = Math.log(firstI); } else if (math == "logTen") { result = Math.log10(firstI); } else if (math == "rand") { result = Math.round(firstI); }else if (math == "res") { result = 1 / firstI; } else if (math == "fact") { n = firstI; firstI = 1; while (n > 1){ firstI *= n; n -= 1; } result = firstI; } decimalPoint = (Math.round(result) == result) ? "": "."; }
JavaScript
function maths(a) { math = a; try { if (operatorSign == "+") { prep(); firstI = first - second; mathematics(); first = second + "+" + result; } else if (operatorSign == "-") { prep(); firstI = second - first; mathematics(); first = second + "-" + "(" + result + ")"; } else if (operatorSign == "*") { prep(); firstI = first / second; mathematics(); first = second + "*" + result; } else if (operatorSign == "/") { prep(); firstI = second / first; mathematics(); first = second + "/" + result; } else { firstI = first; mathematics(); first = result; } return first; } catch (first ) { first = second + operatorSign; return first; } }
function maths(a) { math = a; try { if (operatorSign == "+") { prep(); firstI = first - second; mathematics(); first = second + "+" + result; } else if (operatorSign == "-") { prep(); firstI = second - first; mathematics(); first = second + "-" + "(" + result + ")"; } else if (operatorSign == "*") { prep(); firstI = first / second; mathematics(); first = second + "*" + result; } else if (operatorSign == "/") { prep(); firstI = second / first; mathematics(); first = second + "/" + result; } else { firstI = first; mathematics(); first = result; } return first; } catch (first ) { first = second + operatorSign; return first; } }
JavaScript
function digit(b) { opsCheck = 0; dotCounter++; if (first == Infinity || first == NaN) { first = 0; } peSign = "pes"; entered = b; if (rootNpower_Sign != "") { first = (first === "0" && entered !== ".") ? entered: first + entered; return secondI + firstI + rootNpower_Sign + first; } else { first = (first === "0" && entered !== ".") ? entered: first + entered; theanswer = eval(first) + ""; if (theanswer.length > 14) { theanswer = Math.abs((theanswer*1).toPrecision(14)); } document.getElementById("display1").innerHTML = first; return theanswer; } }
function digit(b) { opsCheck = 0; dotCounter++; if (first == Infinity || first == NaN) { first = 0; } peSign = "pes"; entered = b; if (rootNpower_Sign != "") { first = (first === "0" && entered !== ".") ? entered: first + entered; return secondI + firstI + rootNpower_Sign + first; } else { first = (first === "0" && entered !== ".") ? entered: first + entered; theanswer = eval(first) + ""; if (theanswer.length > 14) { theanswer = Math.abs((theanswer*1).toPrecision(14)); } document.getElementById("display1").innerHTML = first; return theanswer; } }
JavaScript
function themes(thm) { theme = thm; el = document.getElementsByClassName("div"); if (theme == 1) { el[0].id="theme1"; } else if (theme == 2) { el[0].id="theme2"; } else if (theme == 3) { el[0].id="theme3"; } else { el[0].id="theme4"; } }
function themes(thm) { theme = thm; el = document.getElementsByClassName("div"); if (theme == 1) { el[0].id="theme1"; } else if (theme == 2) { el[0].id="theme2"; } else if (theme == 3) { el[0].id="theme3"; } else { el[0].id="theme4"; } }
JavaScript
function operators(b) { peSign = ""; if (opsCheck == 0) { opsCheck = 1; document.getElementById("display1").innerHTML = first; try { if (rootNpower_Sign == "^") { if (operatorSign == "+") { pow(); answer = result + second; } else if (operatorSign == "-") { pow(); answer = second - result; } else if (operatorSign == "*") { pow(); answer = result * second; } else if (operatorSign == "/") { pow(); answer = second / result; } else { pow(); answer = result; } } else if (rootNpower_Sign == "√") { if (operatorSign == "+") { roots(); answer = second + result; } else if (operatorSign == "-") { roots(); answer = second - result; } else if (operatorSign == "*") { roots(); answer = result * second; } else if (operatorSign == "/") { roots(); answer = second / result; } else { roots(); answer = result; } } else if (a == "%") { answer = second % first; } else { operatorSign = b; first += operatorSign; decimalPoint = ""; } rootNpower_Sign = ""; operatorSign = b; firstI = ""; second = answer; first = answer + operatorSign; decimalPoint = ""; document.getElementById("display1").innerHTML = first; return eval(second); } catch(x) { if (first != "<span class='red'>Press ON to start</span>") { operatorSign = b; second = eval(first); first += operatorSign; decimalPoint = ""; } else { first = "<span class='red'>Press ON to start</span>" ; } document.getElementById("display1").innerHTML = first; return (second == undefined ) ? 0 : eval(second); } } else { operatorSign = b; first += ""; first = first.substr(0, first.length - 1); first = first + operatorSign; document.getElementById("display1").innerHTML = first; return (second == undefined ) ? 0 : eval(second); } }
function operators(b) { peSign = ""; if (opsCheck == 0) { opsCheck = 1; document.getElementById("display1").innerHTML = first; try { if (rootNpower_Sign == "^") { if (operatorSign == "+") { pow(); answer = result + second; } else if (operatorSign == "-") { pow(); answer = second - result; } else if (operatorSign == "*") { pow(); answer = result * second; } else if (operatorSign == "/") { pow(); answer = second / result; } else { pow(); answer = result; } } else if (rootNpower_Sign == "√") { if (operatorSign == "+") { roots(); answer = second + result; } else if (operatorSign == "-") { roots(); answer = second - result; } else if (operatorSign == "*") { roots(); answer = result * second; } else if (operatorSign == "/") { roots(); answer = second / result; } else { roots(); answer = result; } } else if (a == "%") { answer = second % first; } else { operatorSign = b; first += operatorSign; decimalPoint = ""; } rootNpower_Sign = ""; operatorSign = b; firstI = ""; second = answer; first = answer + operatorSign; decimalPoint = ""; document.getElementById("display1").innerHTML = first; return eval(second); } catch(x) { if (first != "<span class='red'>Press ON to start</span>") { operatorSign = b; second = eval(first); first += operatorSign; decimalPoint = ""; } else { first = "<span class='red'>Press ON to start</span>" ; } document.getElementById("display1").innerHTML = first; return (second == undefined ) ? 0 : eval(second); } } else { operatorSign = b; first += ""; first = first.substr(0, first.length - 1); first = first + operatorSign; document.getElementById("display1").innerHTML = first; return (second == undefined ) ? 0 : eval(second); } }
JavaScript
inject (app) { this.app = app; const target = Object.getPrototypeOf(this.app); for (const method of Object.getOwnPropertyNames(Object.getPrototypeOf(this))) { if (target.hasOwnProperty(method)) { continue; } this.app[method] = this[method].bind(this); } }
inject (app) { this.app = app; const target = Object.getPrototypeOf(this.app); for (const method of Object.getOwnPropertyNames(Object.getPrototypeOf(this))) { if (target.hasOwnProperty(method)) { continue; } this.app[method] = this[method].bind(this); } }
JavaScript
function gulpSymlink(dest, options) { options = typeof options == 'object' ? options : {} options.force = options.force === undefined ? false : options.force if (!dest) { throw new PluginError({plugin: PLUGIN_NAME, message: "Missing destination link"}) } if(dest instanceof Array) { //copy array because we'll shift values var destinations = dest.slice() } var stream = through.obj(function(source, enc, callback) { var self = this, symlink //resolving absolute path from source source.path = p.resolve(source.cwd, source.path) // source.relative = p.relative(source.cwd, source.path) //Array of destinations is passed symlink = destinations !== undefined ? destinations.shift() : dest //if dest is a function simply call it symlink = typeof dest == 'function' ? dest(source) : symlink //is the previous result a File instance ? symlink = symlink instanceof File ? symlink : new File({path: symlink}) //resolving absolute path from dest symlink.path = p.resolve(symlink.cwd, symlink.path) //relative path between source and link var relative_symlink_source = p.relative(p.dirname(symlink.path), source.path) //check if the destination path exists var exists = existsSync(symlink.path) //No force option, we can't override! if(exists && !options.force) { this.emit('error', new PluginError({plugin: PLUGIN_NAME, message: 'Destination file exists ('+dest+') - use force option to replace'})) this.push(source) return callback() } //remove destination if force option if(exists && options.force === true) rm.sync(symlink.path) //I'm aware that this is bad \o/ //create destination directories if(!fs.existsSync(p.dirname(symlink.path))) mkdirp.sync(p.dirname(symlink.path)) //this is a windows check as specified in http://nodejs.org/api/fs.html#fs_fs_symlink_srcpath_dstpath_type_callback source.stat = fs.statSync(source.path) fs.symlink(options.relative ? relative_symlink_source : source.path, symlink.path, source.stat.isDirectory() ? 'dir' : 'file', function(err) { if(err) self.emit('error', new PluginError({plugin: PLUGIN_NAME, message: err})) else gutil.log(PLUGIN_NAME + ':', gutil.colors.yellow(symlink.path), '→', gutil.colors.blue(options.relative ? relative_symlink_source : source.path)) self.push(source) callback() }) }) return stream }
function gulpSymlink(dest, options) { options = typeof options == 'object' ? options : {} options.force = options.force === undefined ? false : options.force if (!dest) { throw new PluginError({plugin: PLUGIN_NAME, message: "Missing destination link"}) } if(dest instanceof Array) { //copy array because we'll shift values var destinations = dest.slice() } var stream = through.obj(function(source, enc, callback) { var self = this, symlink //resolving absolute path from source source.path = p.resolve(source.cwd, source.path) // source.relative = p.relative(source.cwd, source.path) //Array of destinations is passed symlink = destinations !== undefined ? destinations.shift() : dest //if dest is a function simply call it symlink = typeof dest == 'function' ? dest(source) : symlink //is the previous result a File instance ? symlink = symlink instanceof File ? symlink : new File({path: symlink}) //resolving absolute path from dest symlink.path = p.resolve(symlink.cwd, symlink.path) //relative path between source and link var relative_symlink_source = p.relative(p.dirname(symlink.path), source.path) //check if the destination path exists var exists = existsSync(symlink.path) //No force option, we can't override! if(exists && !options.force) { this.emit('error', new PluginError({plugin: PLUGIN_NAME, message: 'Destination file exists ('+dest+') - use force option to replace'})) this.push(source) return callback() } //remove destination if force option if(exists && options.force === true) rm.sync(symlink.path) //I'm aware that this is bad \o/ //create destination directories if(!fs.existsSync(p.dirname(symlink.path))) mkdirp.sync(p.dirname(symlink.path)) //this is a windows check as specified in http://nodejs.org/api/fs.html#fs_fs_symlink_srcpath_dstpath_type_callback source.stat = fs.statSync(source.path) fs.symlink(options.relative ? relative_symlink_source : source.path, symlink.path, source.stat.isDirectory() ? 'dir' : 'file', function(err) { if(err) self.emit('error', new PluginError({plugin: PLUGIN_NAME, message: err})) else gutil.log(PLUGIN_NAME + ':', gutil.colors.yellow(symlink.path), '→', gutil.colors.blue(options.relative ? relative_symlink_source : source.path)) self.push(source) callback() }) }) return stream }
JavaScript
_initConnection() { this._connection = mysql.createConnection({ host: this.host, port: this.port, user: this.username, password: this.password, database: this.database, timezone: 'local', typeCast: this._typeCast }); this._connection.on('error', this._onError); this._connection.connect(); if (this.charset !== null) { this.exec('SET NAMES ' + this.quoteValue(this.charset)); } super._initConnection(); }
_initConnection() { this._connection = mysql.createConnection({ host: this.host, port: this.port, user: this.username, password: this.password, database: this.database, timezone: 'local', typeCast: this._typeCast }); this._connection.on('error', this._onError); this._connection.connect(); if (this.charset !== null) { this.exec('SET NAMES ' + this.quoteValue(this.charset)); } super._initConnection(); }
JavaScript
_loadTableSchema(name) { var table = new TableSchema(); this._resolveTableNames(table, name); return this._findColumns(table).then(() => { return this._findConstraints(table); }, () => { table = null; }).then(() => { return table; }); }
_loadTableSchema(name) { var table = new TableSchema(); this._resolveTableNames(table, name); return this._findColumns(table).then(() => { return this._findConstraints(table); }, () => { table = null; }).then(() => { return table; }); }
JavaScript
_resolveTableNames(table, name) { var parts = name.replace(/`/g, '').split('.'); if (parts.length > 1) { table.schemaName = parts[0]; table.name = parts[1]; table.fullName = table.schemaName + '.' + table.name; } else { table.fullName = table.name = parts[0]; } }
_resolveTableNames(table, name) { var parts = name.replace(/`/g, '').split('.'); if (parts.length > 1) { table.schemaName = parts[0]; table.name = parts[1]; table.fullName = table.schemaName + '.' + table.name; } else { table.fullName = table.name = parts[0]; } }
JavaScript
_loadColumnSchema(info) { var column = this._createColumnSchema(); column.name = info.Field; column.allowNull = info.Null === 'YES'; column.isPrimaryKey = info.Key.indexOf('PRI') !== -1; column.autoIncrement = info.Extra.toLowerCase().indexOf('auto_increment') !== -1; column.comment = info.Comment; column.dbType = info.Type; column.unsigned = column.dbType.indexOf('unsigned') !== -1; column.type = this.constructor.TYPE_STRING; var type = null; var matches = /^(\w+)(?:\(([^\)]+)\))?/.exec(column.dbType); if (matches !== null) { type = matches[1]; if (_has(this.typeMap, type)) { column.type = this.typeMap[type]; } if (matches[2]) { var values = matches[2].split(','); if (type === 'enum') { _each(values, (value, i) => { values[i] = _trim(value, '\''); }); column.enumValues = values; } else { column.size = parseInt(values[0]); column.precision = parseInt(values[0]); if (values[1]) { column.scale = parseInt(values[1]); } if (column.size === 1 && type === 'bit') { column.type = 'boolean'; } else if (type === 'bit') { if (column.size > 32) { column.type = 'bigint'; } else if (column.size === 32) { column.type = 'integer'; } } } } } column.jsType = type === 'bit' ? 'string' : this._getColumnJsType(column); if (!column.isPrimaryKey) { if (column.type === 'timestamp' && info.Default === 'CURRENT_TIMESTAMP') { column.defaultValue = new Expression('CURRENT_TIMESTAMP'); } else if (type === 'bit') { column.defaultValue = _trimStart(_trimEnd(info.Default, '\''), 'b\''); } else { column.defaultValue = column.typecast(info.Default); } } return column; }
_loadColumnSchema(info) { var column = this._createColumnSchema(); column.name = info.Field; column.allowNull = info.Null === 'YES'; column.isPrimaryKey = info.Key.indexOf('PRI') !== -1; column.autoIncrement = info.Extra.toLowerCase().indexOf('auto_increment') !== -1; column.comment = info.Comment; column.dbType = info.Type; column.unsigned = column.dbType.indexOf('unsigned') !== -1; column.type = this.constructor.TYPE_STRING; var type = null; var matches = /^(\w+)(?:\(([^\)]+)\))?/.exec(column.dbType); if (matches !== null) { type = matches[1]; if (_has(this.typeMap, type)) { column.type = this.typeMap[type]; } if (matches[2]) { var values = matches[2].split(','); if (type === 'enum') { _each(values, (value, i) => { values[i] = _trim(value, '\''); }); column.enumValues = values; } else { column.size = parseInt(values[0]); column.precision = parseInt(values[0]); if (values[1]) { column.scale = parseInt(values[1]); } if (column.size === 1 && type === 'bit') { column.type = 'boolean'; } else if (type === 'bit') { if (column.size > 32) { column.type = 'bigint'; } else if (column.size === 32) { column.type = 'integer'; } } } } } column.jsType = type === 'bit' ? 'string' : this._getColumnJsType(column); if (!column.isPrimaryKey) { if (column.type === 'timestamp' && info.Default === 'CURRENT_TIMESTAMP') { column.defaultValue = new Expression('CURRENT_TIMESTAMP'); } else if (type === 'bit') { column.defaultValue = _trimStart(_trimEnd(info.Default, '\''), 'b\''); } else { column.defaultValue = column.typecast(info.Default); } } return column; }
JavaScript
_findColumns(table) { var sql = 'SHOW FULL COLUMNS FROM ' + this.quoteTableName(table.fullName); return this.db.createCommand(sql).queryAll().then(columns => { if (columns === false) { return Promise.reject(new SqlQueryException('Can not get metadata of table `' + table.name + '`')); } _each(columns, info => { var column = this._loadColumnSchema(info); table.columns[column.name] = column; if (column.isPrimaryKey) { table.primaryKey.push(column.name); if (column.autoIncrement) { table.sequenceName = ''; } } }); return Promise.resolve(); }).catch(exception => { // @todo Php code: //var previous = e.getPrevious(); //if (previous instanceof \PDOException && previous.getCode() == '42S02') { // table does not exist //} //throw e; console.warn(exception.toString()); return Promise.reject(); }); }
_findColumns(table) { var sql = 'SHOW FULL COLUMNS FROM ' + this.quoteTableName(table.fullName); return this.db.createCommand(sql).queryAll().then(columns => { if (columns === false) { return Promise.reject(new SqlQueryException('Can not get metadata of table `' + table.name + '`')); } _each(columns, info => { var column = this._loadColumnSchema(info); table.columns[column.name] = column; if (column.isPrimaryKey) { table.primaryKey.push(column.name); if (column.autoIncrement) { table.sequenceName = ''; } } }); return Promise.resolve(); }).catch(exception => { // @todo Php code: //var previous = e.getPrevious(); //if (previous instanceof \PDOException && previous.getCode() == '42S02') { // table does not exist //} //throw e; console.warn(exception.toString()); return Promise.reject(); }); }
JavaScript
_getCreateTableSql(table) { var sql = 'SHOW CREATE TABLE ' + this.quoteSimpleTableName(table.name); return this.db.createCommand(sql).queryOne().then(row => { if (row === false) { return Promise.reject(new SqlQueryException('Can not get CREATE TABLE sql for table `' + table.name + '`')); } return _has(row, 'Create Table') ? row['Create Table'] : _values(row)[1]; }); }
_getCreateTableSql(table) { var sql = 'SHOW CREATE TABLE ' + this.quoteSimpleTableName(table.name); return this.db.createCommand(sql).queryOne().then(row => { if (row === false) { return Promise.reject(new SqlQueryException('Can not get CREATE TABLE sql for table `' + table.name + '`')); } return _has(row, 'Create Table') ? row['Create Table'] : _values(row)[1]; }); }
JavaScript
_findConstraints(table) { return this._getCreateTableSql(table).then(sql => { var regexp = /FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/i; var processKeys = strKeys => { var arrKeys = strKeys.replace(/`/g, '').split(','); _each(arrKeys, (key, i) => { arrKeys[i] = _trim(key); }); return arrKeys; }; table.foreignKeys = table.foreignKeys || []; var k = 0; var index = -1; while (true) { var previousIndex = index; index = sql.indexOf('FOREIGN KEY', index + 1); var foreignPart = sql.substr(previousIndex, (index > 0 ? index : sql.length) - previousIndex); var matches = regexp.exec(foreignPart); if (matches !== null) { var fks = processKeys(matches[1]); var pks = processKeys(matches[3]); var constraint = { 0: matches[2].replace(/`/g, '') }; for (var i = 0, l = fks.length; i < l; i++) { constraint[fks[i]] = pks[i]; } table.foreignKeys[k++] = constraint; } if (index === -1) { break; } } }); }
_findConstraints(table) { return this._getCreateTableSql(table).then(sql => { var regexp = /FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/i; var processKeys = strKeys => { var arrKeys = strKeys.replace(/`/g, '').split(','); _each(arrKeys, (key, i) => { arrKeys[i] = _trim(key); }); return arrKeys; }; table.foreignKeys = table.foreignKeys || []; var k = 0; var index = -1; while (true) { var previousIndex = index; index = sql.indexOf('FOREIGN KEY', index + 1); var foreignPart = sql.substr(previousIndex, (index > 0 ? index : sql.length) - previousIndex); var matches = regexp.exec(foreignPart); if (matches !== null) { var fks = processKeys(matches[1]); var pks = processKeys(matches[3]); var constraint = { 0: matches[2].replace(/`/g, '') }; for (var i = 0, l = fks.length; i < l; i++) { constraint[fks[i]] = pks[i]; } table.foreignKeys[k++] = constraint; } if (index === -1) { break; } } }); }
JavaScript
findUniqueIndexes(table) { return this._getCreateTableSql(table).then(sql => { var uniqueIndexes = []; var regexp = /UNIQUE KEY\s+([^\(\s]+)\s*\(([^\(\)]+)\)/i; var processKeys = strKeys => { var arrKeys = strKeys.replace(/`/g, '').split(','); _each(arrKeys, (key, i) => { arrKeys[i] = _trim(key); }); return arrKeys; }; var index = -1; while (true) { var previousIndex = index; index = sql.indexOf('UNIQUE KEY', index + 1); var foreignPart = sql.substr(previousIndex, (index > 0 ? index : sql.length) - previousIndex); var matches = regexp.exec(foreignPart); if (matches !== null) { var indexName = matches[1].replace(/`/, ''); uniqueIndexes[indexName] = processKeys(matches[2]); } if (index === -1) { break; } } return Promise.resolve(uniqueIndexes); }); }
findUniqueIndexes(table) { return this._getCreateTableSql(table).then(sql => { var uniqueIndexes = []; var regexp = /UNIQUE KEY\s+([^\(\s]+)\s*\(([^\(\)]+)\)/i; var processKeys = strKeys => { var arrKeys = strKeys.replace(/`/g, '').split(','); _each(arrKeys, (key, i) => { arrKeys[i] = _trim(key); }); return arrKeys; }; var index = -1; while (true) { var previousIndex = index; index = sql.indexOf('UNIQUE KEY', index + 1); var foreignPart = sql.substr(previousIndex, (index > 0 ? index : sql.length) - previousIndex); var matches = regexp.exec(foreignPart); if (matches !== null) { var indexName = matches[1].replace(/`/, ''); uniqueIndexes[indexName] = processKeys(matches[2]); } if (index === -1) { break; } } return Promise.resolve(uniqueIndexes); }); }
JavaScript
_findTableNames(schema) { schema = schema || ''; var sql = 'SHOW TABLES'; if (schema !== '') { sql += ' FROM ' + this.quoteSimpleTableName(schema); } return this.db.createCommand(sql).queryColumn(); }
_findTableNames(schema) { schema = schema || ''; var sql = 'SHOW TABLES'; if (schema !== '') { sql += ' FROM ' + this.quoteSimpleTableName(schema); } return this.db.createCommand(sql).queryColumn(); }
JavaScript
renameColumn(table, oldName, newName) { var quoteTable = this.db.quoteTableName(table); var sql = 'SHOW CREATE TABLE ' + quoteTable; return this.db.createCommand(sql).queryOne().then(row => { if (row === null) { throw new ApplicationException('Unable to find column `' + oldName + '` in table `' + table + '`.'); } var sql = row['Create Table'] || _values(row)[1]; var options = ''; _each(sql.split('\n'), sqlLine => { if (options) { return; } var matches = /^\s*`(.*?)`\s+(.*?),?/g.exec(sqlLine); if (matches !== null && matches[1] === oldName) { options = matches[1]; } }); // try to give back a SQL anyway return 'ALTER TABLE ' + quoteTable + ' CHANGE ' + this.db.quoteColumnName(oldName) + ' ' + this.db.quoteColumnName(newName) + (options ? ' ' + options : ''); }); }
renameColumn(table, oldName, newName) { var quoteTable = this.db.quoteTableName(table); var sql = 'SHOW CREATE TABLE ' + quoteTable; return this.db.createCommand(sql).queryOne().then(row => { if (row === null) { throw new ApplicationException('Unable to find column `' + oldName + '` in table `' + table + '`.'); } var sql = row['Create Table'] || _values(row)[1]; var options = ''; _each(sql.split('\n'), sqlLine => { if (options) { return; } var matches = /^\s*`(.*?)`\s+(.*?),?/g.exec(sqlLine); if (matches !== null && matches[1] === oldName) { options = matches[1]; } }); // try to give back a SQL anyway return 'ALTER TABLE ' + quoteTable + ' CHANGE ' + this.db.quoteColumnName(oldName) + ' ' + this.db.quoteColumnName(newName) + (options ? ' ' + options : ''); }); }
JavaScript
resetSequence(tableName, value) { value = value || null; var table = this.db.getTableSchema(tableName); if (table === null) { throw new InvalidParamException('Table not found: `' + tableName + '`'); } if (table.sequenceName === null) { throw new InvalidParamException('There is no sequence associated with table `' + tableName + '`.'); } var quoteTableName = this.db.quoteTableName(tableName); if (value === null) { var sql = 'SELECT MAX(`' + _first(table.primaryKey) + '`) FROM ' + quoteTableName; return this.db.createCommand(sql).queryScalar().then(value => { return 'ALTER TABLE ' + quoteTableName + ' AUTO_INCREMENT=' + (value + 1); }); } return Promise.resolve('ALTER TABLE ' + quoteTableName + ' AUTO_INCREMENT=' + parseInt(value)); }
resetSequence(tableName, value) { value = value || null; var table = this.db.getTableSchema(tableName); if (table === null) { throw new InvalidParamException('Table not found: `' + tableName + '`'); } if (table.sequenceName === null) { throw new InvalidParamException('There is no sequence associated with table `' + tableName + '`.'); } var quoteTableName = this.db.quoteTableName(tableName); if (value === null) { var sql = 'SELECT MAX(`' + _first(table.primaryKey) + '`) FROM ' + quoteTableName; return this.db.createCommand(sql).queryScalar().then(value => { return 'ALTER TABLE ' + quoteTableName + ' AUTO_INCREMENT=' + (value + 1); }); } return Promise.resolve('ALTER TABLE ' + quoteTableName + ' AUTO_INCREMENT=' + parseInt(value)); }
JavaScript
checkIntegrity(check, schema, table) { check = check || true; schema = schema || ''; table = table || ''; return Promise.resolve('SET FOREIGN_KEY_CHECKS = ' + (check ? 1 : 0)); }
checkIntegrity(check, schema, table) { check = check || true; schema = schema || ''; table = table || ''; return Promise.resolve('SET FOREIGN_KEY_CHECKS = ' + (check ? 1 : 0)); }
JavaScript
listen() { this.io.on('connection', (socket) => { this.events.forEach((event, key) => { socket.on(key, event.execute(this.io, socket)); }); }); this.io.listen(this.port); this.onReady(); }
listen() { this.io.on('connection', (socket) => { this.events.forEach((event, key) => { socket.on(key, event.execute(this.io, socket)); }); }); this.io.listen(this.port); this.onReady(); }
JavaScript
registerSubscribe(name, subcribe) { if (this.type == RedisClientType.SUBSCRIBER) { this.subscribe.set(name, subcribe); this.instance.subscribe(name); } }
registerSubscribe(name, subcribe) { if (this.type == RedisClientType.SUBSCRIBER) { this.subscribe.set(name, subcribe); this.instance.subscribe(name); } }
JavaScript
function convertToTensor(data) { // Wrapping these calculations in a tidy will dispose any // intermediate tensors. return tf.tidy(() => { // Step 1. Shuffle the data tf.util.shuffle(data); // Step 2. Convert data to Tensor const inputs = data.map(d => d.open) const labels = data.map(d => d.close); const inputTensor = tf.tensor2d(inputs, [inputs.length, 1]); const labelTensor = tf.tensor2d(labels, [labels.length, 1]); //Step 3. Normalize the data to the range 0 - 1 using min-max scaling const inputMax = inputTensor.max(); const inputMin = inputTensor.min(); const labelMax = labelTensor.max(); const labelMin = labelTensor.min(); const normalizedInputs = inputTensor.sub(inputMin).div(inputMax.sub(inputMin)); const normalizedLabels = labelTensor.sub(labelMin).div(labelMax.sub(labelMin)); return { inputs: normalizedInputs, labels: normalizedLabels, // Return the min/max bounds so we can use them later. inputMax, inputMin, labelMax, labelMin, } }); }
function convertToTensor(data) { // Wrapping these calculations in a tidy will dispose any // intermediate tensors. return tf.tidy(() => { // Step 1. Shuffle the data tf.util.shuffle(data); // Step 2. Convert data to Tensor const inputs = data.map(d => d.open) const labels = data.map(d => d.close); const inputTensor = tf.tensor2d(inputs, [inputs.length, 1]); const labelTensor = tf.tensor2d(labels, [labels.length, 1]); //Step 3. Normalize the data to the range 0 - 1 using min-max scaling const inputMax = inputTensor.max(); const inputMin = inputTensor.min(); const labelMax = labelTensor.max(); const labelMin = labelTensor.min(); const normalizedInputs = inputTensor.sub(inputMin).div(inputMax.sub(inputMin)); const normalizedLabels = labelTensor.sub(labelMin).div(labelMax.sub(labelMin)); return { inputs: normalizedInputs, labels: normalizedLabels, // Return the min/max bounds so we can use them later. inputMax, inputMin, labelMax, labelMin, } }); }
JavaScript
function updateCodeView(newKey) { $('#pattern-name').val(names[newKey]); let code = sources[newKey].trim(); if (defaultSourceKeys.indexOf(newKey) >= 0) { // Prevent editing default patterns code = '# Code editing and renaming disabled on default patterns. Click "New Pattern" to create and edit a copy of this pattern.\n\n' + code; codeMirror.setOption('readOnly', true); $('#pattern-name').prop('disabled', true); } else { codeMirror.setOption('readOnly', false); $('#pattern-name').prop('disabled', false); } codeMirror.setValue(code); }
function updateCodeView(newKey) { $('#pattern-name').val(names[newKey]); let code = sources[newKey].trim(); if (defaultSourceKeys.indexOf(newKey) >= 0) { // Prevent editing default patterns code = '# Code editing and renaming disabled on default patterns. Click "New Pattern" to create and edit a copy of this pattern.\n\n' + code; codeMirror.setOption('readOnly', true); $('#pattern-name').prop('disabled', true); } else { codeMirror.setOption('readOnly', false); $('#pattern-name').prop('disabled', false); } codeMirror.setValue(code); }
JavaScript
function _getBranch(inputs) { const { args } = inputs; try { return args.branch || ""; } catch (error) { throw new Error( `There was an error getting the branch name from git: ${error}` ); } }
function _getBranch(inputs) { const { args } = inputs; try { return args.branch || ""; } catch (error) { throw new Error( `There was an error getting the branch name from git: ${error}` ); } }
JavaScript
function _getSHA(inputs) { const { args } = inputs; try { return args.sha || ""; } catch (error) { throw new Error( `There was an error getting the commit SHA from git: ${error}` ); } }
function _getSHA(inputs) { const { args } = inputs; try { return args.sha || ""; } catch (error) { throw new Error( `There was an error getting the commit SHA from git: ${error}` ); } }
JavaScript
function screen4_relockCell(){ screen4_killPulses(); exportRoot.screen4.arrow1.visible=false; exportRoot.screen4.arrow2.visible=false; //lock the cell! screen4_cell_locked=true; screen4_cell.gotoAndStop(0); //cell starts at its first state (locked) //anim of insulin key appearing... don't do if all g cells are invisible if(!g1.visible && !g2.visible && !g3.visible && !g4.visible) return; else exportRoot.screen4.gotoAndPlay("newInsulin"); }
function screen4_relockCell(){ screen4_killPulses(); exportRoot.screen4.arrow1.visible=false; exportRoot.screen4.arrow2.visible=false; //lock the cell! screen4_cell_locked=true; screen4_cell.gotoAndStop(0); //cell starts at its first state (locked) //anim of insulin key appearing... don't do if all g cells are invisible if(!g1.visible && !g2.visible && !g3.visible && !g4.visible) return; else exportRoot.screen4.gotoAndPlay("newInsulin"); }
JavaScript
function begin_pulseObj(obj) { obj.startSX = obj.scaleX; obj.startSY = obj.scaleY; createjs.Tween.get(obj, {loop:true}).to({ scaleX: obj.scaleX*1.1, scaleY: obj.scaleY*1.1 }, 250, createjs.Ease.none).wait(250).to({ scaleX: obj.startSX, scaleY: obj.startSY }, 250, createjs.Ease.none).wait(250); }
function begin_pulseObj(obj) { obj.startSX = obj.scaleX; obj.startSY = obj.scaleY; createjs.Tween.get(obj, {loop:true}).to({ scaleX: obj.scaleX*1.1, scaleY: obj.scaleY*1.1 }, 250, createjs.Ease.none).wait(250).to({ scaleX: obj.startSX, scaleY: obj.startSY }, 250, createjs.Ease.none).wait(250); }
JavaScript
function begin_pulseObj(obj) { obj.startSX = obj.scaleX; obj.startSY = obj.scaleY; createjs.Tween.get(obj, {loop:true}).to({ scaleX: obj.scaleX*1.1, scaleY: obj.scaleY*1.1 }, 250, createjs.Ease.none).wait(250).to({ scaleX: obj.scaleX, scaleY: obj.scaleY }, 250, createjs.Ease.none).wait(250); }
function begin_pulseObj(obj) { obj.startSX = obj.scaleX; obj.startSY = obj.scaleY; createjs.Tween.get(obj, {loop:true}).to({ scaleX: obj.scaleX*1.1, scaleY: obj.scaleY*1.1 }, 250, createjs.Ease.none).wait(250).to({ scaleX: obj.scaleX, scaleY: obj.scaleY }, 250, createjs.Ease.none).wait(250); }
JavaScript
async function submit(agent, name, systemid, signal, settings) { expect(settings).to.have.property('apikey').that.is.a('string'); const signalid = typeof signal == 'string' ? signal : undefined; const signalobj = typeof signal == 'object' ? signal : undefined; const uri = settings[name]; const parsed = _.isString(uri) && url.parse(uri); const body = await new Promise((ready, error) => { if (!settings.transmit || !parsed) { console.log(uri || '', JSON.stringify({ apikey: settings.apikey, systemid: systemid, signalid: signalid, signal: signalobj }, null, 2)); ready(JSON.stringify({ ok: 1, signal: _.extend({ signalid: signalid }, signalobj) })); } else if (parsed.protocol == 'https:' || parsed.protocol == 'http:') { const client = parsed.protocol == 'https:' ? https : http; const request = client.request(_.defaults({ method: 'POST', headers: {'User-Agent': 'mtrader/' + version}, agent: parsed.protocol == 'https:' && agent }, parsed), res => { try { if (res.statusCode >= 300) throw Error("Unexpected response code " + res.statusCode); if (!~res.headers['content-type'].indexOf('/json')) throw Error("Unexpected response type " + res.headers['content-type']); const data = []; res.setEncoding('utf8'); res.on('data', chunk => { data.push(chunk); }); res.on('end', () => { ready(data.join('')); }); } catch(err) { error(err); } }).on('error', error); logger.log(uri); request.end(JSON.stringify({ apikey: settings.apikey, systemid: systemid, signalid: signalid, signal: signalobj })); } else if (parsed.protocol == 'file:') { const data = JSON.stringify({signalid, signal: signalobj}, null, ' '); fs.writeFile(parsed.pathname, data, err => err ? error(err) : ready(JSON.stringify({ ok: 1, signal: merge({ signalid: signalid || signalobj.xreplace || Math.floor(Math.random() * 100000000), conditionalUponSignal: signalobj && signalobj.conditionalUponSignal && {signalid: signalobj.conditionalUponSignal.signalid || Math.floor(Math.random() * 100000000)} }, signalobj) }))); } else { throw Error("Unknown protocol " + uri); } }); const res = JSON.parse(body); if (parsed.protocol != 'file:') logger.debug("collective2", name, JSON.stringify(signal), JSON.stringify(res)); else logger.trace("collective2", name, JSON.stringify(signal), JSON.stringify(res)); if (res.title) logger.log(res.title, res.signalid || ''); else if (res.error && res.error.title) logger.error(res.error.title, res.signalid || ''); if (name == 'cancelSignal' && _.property(['error', 'title'])(res) && res.error.title.indexOf('Signal already cancel')) return res; else if (!+res.ok) throw Error(res.message || res.error && res.error.message || JSON.stringify(res)); else return res; }
async function submit(agent, name, systemid, signal, settings) { expect(settings).to.have.property('apikey').that.is.a('string'); const signalid = typeof signal == 'string' ? signal : undefined; const signalobj = typeof signal == 'object' ? signal : undefined; const uri = settings[name]; const parsed = _.isString(uri) && url.parse(uri); const body = await new Promise((ready, error) => { if (!settings.transmit || !parsed) { console.log(uri || '', JSON.stringify({ apikey: settings.apikey, systemid: systemid, signalid: signalid, signal: signalobj }, null, 2)); ready(JSON.stringify({ ok: 1, signal: _.extend({ signalid: signalid }, signalobj) })); } else if (parsed.protocol == 'https:' || parsed.protocol == 'http:') { const client = parsed.protocol == 'https:' ? https : http; const request = client.request(_.defaults({ method: 'POST', headers: {'User-Agent': 'mtrader/' + version}, agent: parsed.protocol == 'https:' && agent }, parsed), res => { try { if (res.statusCode >= 300) throw Error("Unexpected response code " + res.statusCode); if (!~res.headers['content-type'].indexOf('/json')) throw Error("Unexpected response type " + res.headers['content-type']); const data = []; res.setEncoding('utf8'); res.on('data', chunk => { data.push(chunk); }); res.on('end', () => { ready(data.join('')); }); } catch(err) { error(err); } }).on('error', error); logger.log(uri); request.end(JSON.stringify({ apikey: settings.apikey, systemid: systemid, signalid: signalid, signal: signalobj })); } else if (parsed.protocol == 'file:') { const data = JSON.stringify({signalid, signal: signalobj}, null, ' '); fs.writeFile(parsed.pathname, data, err => err ? error(err) : ready(JSON.stringify({ ok: 1, signal: merge({ signalid: signalid || signalobj.xreplace || Math.floor(Math.random() * 100000000), conditionalUponSignal: signalobj && signalobj.conditionalUponSignal && {signalid: signalobj.conditionalUponSignal.signalid || Math.floor(Math.random() * 100000000)} }, signalobj) }))); } else { throw Error("Unknown protocol " + uri); } }); const res = JSON.parse(body); if (parsed.protocol != 'file:') logger.debug("collective2", name, JSON.stringify(signal), JSON.stringify(res)); else logger.trace("collective2", name, JSON.stringify(signal), JSON.stringify(res)); if (res.title) logger.log(res.title, res.signalid || ''); else if (res.error && res.error.title) logger.error(res.error.title, res.signalid || ''); if (name == 'cancelSignal' && _.property(['error', 'title'])(res) && res.error.title.indexOf('Signal already cancel')) return res; else if (!+res.ok) throw Error(res.message || res.error && res.error.message || JSON.stringify(res)); else return res; }
JavaScript
function help(collect) { return collect({info:'help'}).then(_.first).then(help => { return [{ name: 'optimize', usage: 'optimize(options)', description: "Searches possible parameter values to find a higher score", properties: ['score', 'parameters'], options: _.extend({}, help.options, { solution_count: { usage: '<number of results>', description: "Number of solutions to include in result" }, sample_duration: { usage: 'P1Y', description: "Duration of each sample" }, sample_count: { usage: '<number of samples>', description: "Number of samples to search before searching the entire date range (begin-end)" }, sample_population_size: { usage: '<number of candidates>', description: "Number of candidates to test and mutate together in each sample" }, sample_termination: { usage: 'PT1M', description: "Amount of time spent searching for sample solutions" }, eval_validity: { usage: '<expression>', description: "Expression (or array) that invalidates candidates by returning 0 or null" }, eval_variables: { type: 'map', usage: '<expression>', description: "Variable used to help compute the eval_score. The expression can be any combination of field, constants, and function calls connected by an operator or operators.", seeAlso: ['expression', 'common-functions', 'lookback-functions', 'indicator-functions', 'rolling-functions'] }, eval_score: { usage: '<expression>', description: "Expression that determines the score for a sample" }, parameter_values: { usage: '{name: [value,..],..}', description: "Possible parameter values for each each parameter name" }, population_size: { usage: '<number of candidates>', description: "Number of candidates to test and mutate together" }, optimize_termination: { usage: 'PT5M', description: "Amount of time spent searching for a solution before the best yet is used" }, termination: { usage: 'PT5M', description: "Amount of time spent searching for a solution before the best yet is used" } }) }]; }); }
function help(collect) { return collect({info:'help'}).then(_.first).then(help => { return [{ name: 'optimize', usage: 'optimize(options)', description: "Searches possible parameter values to find a higher score", properties: ['score', 'parameters'], options: _.extend({}, help.options, { solution_count: { usage: '<number of results>', description: "Number of solutions to include in result" }, sample_duration: { usage: 'P1Y', description: "Duration of each sample" }, sample_count: { usage: '<number of samples>', description: "Number of samples to search before searching the entire date range (begin-end)" }, sample_population_size: { usage: '<number of candidates>', description: "Number of candidates to test and mutate together in each sample" }, sample_termination: { usage: 'PT1M', description: "Amount of time spent searching for sample solutions" }, eval_validity: { usage: '<expression>', description: "Expression (or array) that invalidates candidates by returning 0 or null" }, eval_variables: { type: 'map', usage: '<expression>', description: "Variable used to help compute the eval_score. The expression can be any combination of field, constants, and function calls connected by an operator or operators.", seeAlso: ['expression', 'common-functions', 'lookback-functions', 'indicator-functions', 'rolling-functions'] }, eval_score: { usage: '<expression>', description: "Expression that determines the score for a sample" }, parameter_values: { usage: '{name: [value,..],..}', description: "Possible parameter values for each each parameter name" }, population_size: { usage: '<number of candidates>', description: "Number of candidates to test and mutate together" }, optimize_termination: { usage: 'PT5M', description: "Amount of time spent searching for a solution before the best yet is used" }, termination: { usage: 'PT5M', description: "Amount of time spent searching for a solution before the best yet is used" } }) }]; }); }
JavaScript
async function optimize(collect, prng, options) { expect(options).to.have.property('parameter_values'); expect(options).to.have.property('eval_score'); const started = Date.now(); const count = options.solution_count || 1; const pnames = _.keys(options.parameter_values); const pvalues = pnames.map(name => options.parameter_values[name]); const space = await createSearchSpace(pnames, options); return searchParameters(collect, prng, pnames, count, space, options).then(solutions => { if (_.isEmpty(solutions)) throw Error("Could not create population for " + options.label); const duration = moment.duration(_.max(_.pluck(solutions, 'foundAt')) - started); if (!_.isEmpty(solutions) && solutions[0].pindex.length) logger.log("Found local extremum", options.label || '\b', solutions[0].pindex.map((idx, i) => pvalues[i][idx]).join(','), "in", duration.humanize(), solutions[0].score); else if (!_.isEmpty(solutions)) logger.debug("Evaluated", options.label || '\b', solutions[0].score); return solutions.map((solution, i) => ({ score: solution.score, parameters: _.object(pnames, solution.pindex.map((idx, i) => pvalues[i][idx]) ) })); }).then(results => { if (options.solution_count) return results; else return _.first(results); }); }
async function optimize(collect, prng, options) { expect(options).to.have.property('parameter_values'); expect(options).to.have.property('eval_score'); const started = Date.now(); const count = options.solution_count || 1; const pnames = _.keys(options.parameter_values); const pvalues = pnames.map(name => options.parameter_values[name]); const space = await createSearchSpace(pnames, options); return searchParameters(collect, prng, pnames, count, space, options).then(solutions => { if (_.isEmpty(solutions)) throw Error("Could not create population for " + options.label); const duration = moment.duration(_.max(_.pluck(solutions, 'foundAt')) - started); if (!_.isEmpty(solutions) && solutions[0].pindex.length) logger.log("Found local extremum", options.label || '\b', solutions[0].pindex.map((idx, i) => pvalues[i][idx]).join(','), "in", duration.humanize(), solutions[0].score); else if (!_.isEmpty(solutions)) logger.debug("Evaluated", options.label || '\b', solutions[0].score); return solutions.map((solution, i) => ({ score: solution.score, parameters: _.object(pnames, solution.pindex.map((idx, i) => pvalues[i][idx]) ) })); }).then(results => { if (options.solution_count) return results; else return _.first(results); }); }
JavaScript
function searchParameters(collect, prng, pnames, count, space, options) { const terminateAt = options.optimize_termination && moment().add(moment.duration(options.optimize_termination)).valueOf(); const pvalues = pnames.map(name => options.parameter_values[name]); const size = options.population_size || Math.max( Math.min(Math.ceil(pvalues.map(_.size).reduce((a,b)=>a+b,0)/2), MAX_POPULATION), _.max(pvalues.map(_.size)), count * 2, MIN_POPULATION); const createPopulation = options.sample_duration || options.sample_count ? sampleSolutions(collect, prng, pnames, space, size, options) : initialPopulation(prng, pnames, space, size, options); return Promise.resolve(createPopulation).then(async(population) => { if (population.length === 0) return []; if (population.length > 1) logger.debug("Initial population of", population.length, options.label || '\b'); const fitnessFn = await fitness(collect, options, pnames); const mutationFn = mutation.bind(this, prng, pvalues, space); return adapt(fitnessFn, mutationFn, pnames, terminateAt, options, population, size); }).then(solutions => { return _.sortBy(solutions.reverse(), 'score').slice(-count).reverse(); }); }
function searchParameters(collect, prng, pnames, count, space, options) { const terminateAt = options.optimize_termination && moment().add(moment.duration(options.optimize_termination)).valueOf(); const pvalues = pnames.map(name => options.parameter_values[name]); const size = options.population_size || Math.max( Math.min(Math.ceil(pvalues.map(_.size).reduce((a,b)=>a+b,0)/2), MAX_POPULATION), _.max(pvalues.map(_.size)), count * 2, MIN_POPULATION); const createPopulation = options.sample_duration || options.sample_count ? sampleSolutions(collect, prng, pnames, space, size, options) : initialPopulation(prng, pnames, space, size, options); return Promise.resolve(createPopulation).then(async(population) => { if (population.length === 0) return []; if (population.length > 1) logger.debug("Initial population of", population.length, options.label || '\b'); const fitnessFn = await fitness(collect, options, pnames); const mutationFn = mutation.bind(this, prng, pvalues, space); return adapt(fitnessFn, mutationFn, pnames, terminateAt, options, population, size); }).then(solutions => { return _.sortBy(solutions.reverse(), 'score').slice(-count).reverse(); }); }
JavaScript
async function createSearchSpace(pnames, options) { const hash = {}; const pvalues = pnames.map(name => options.parameter_values[name]); const parser = new Parser({ constant(value) { return _.constant(value); }, variable(name) { const idx = pnames.indexOf(name); if (idx >= 0) return pindex => pvalues[idx][pindex[idx]]; const p = _.property(name); const value = p(options.parameters) || p(options.parameters); return _.constant(value); }, expression(expr, name, args) { if (common.has(name)) return common(name, args, options); else throw Error("Cannot use " + name + " in eval_validity"); } }); const validity = await parser.parseCriteriaList(options.eval_validity); const invalid = ctx => !!validity.find(fn => !fn(ctx)); return candidate => { const key = candidate.pindex.join(','); if (hash[key] || invalid(candidate.pindex)) return false; hash[key] = candidate; return true; }; }
async function createSearchSpace(pnames, options) { const hash = {}; const pvalues = pnames.map(name => options.parameter_values[name]); const parser = new Parser({ constant(value) { return _.constant(value); }, variable(name) { const idx = pnames.indexOf(name); if (idx >= 0) return pindex => pvalues[idx][pindex[idx]]; const p = _.property(name); const value = p(options.parameters) || p(options.parameters); return _.constant(value); }, expression(expr, name, args) { if (common.has(name)) return common(name, args, options); else throw Error("Cannot use " + name + " in eval_validity"); } }); const validity = await parser.parseCriteriaList(options.eval_validity); const invalid = ctx => !!validity.find(fn => !fn(ctx)); return candidate => { const key = candidate.pindex.join(','); if (hash[key] || invalid(candidate.pindex)) return false; hash[key] = candidate; return true; }; }
JavaScript
function sampleSolutions(collect, prng, pnames, space, size, options) { const begin = moment(options.begin); const end = moment(options.end || options.now); if (!begin.isValid()) throw Error("Invalid begin date: " + options.begin); if (!end.isValid()) throw Error("Invalid end date: " + options.end); const until = options.sample_duration ? moment(end).subtract(moment.duration(options.sample_duration)) : begin; const count = options.sample_count || 1; const period = createDuration(begin, until, count); const unit = getDurationUnit(period, count); const duration = options.sample_duration ? moment.duration(options.sample_duration) : moment.duration(end.diff(begin)); if (duration && duration.asMilliseconds()<=0) throw Error("Invalid duration: " + options.sample_duration); const period_units = Math.max(period.as(unit), 0); const pvalues = pnames.map(name => options.parameter_values[name]); const termination = options.sample_termination || options.optimize_termination && moment.duration(moment.duration(options.optimize_termination).asSeconds()/3000).toISOString(); const optionset = _.range(count).map(() => { let periodBegin = period_units ? moment(begin).add(Math.round(prng() * period_units), unit) : begin let periodEnd = moment(periodBegin).add(duration); if (!periodEnd.isBefore(end)) { periodEnd = end; if (periodBegin.isAfter(begin)) { periodBegin = moment(end).subtract(duration); } } return _.defaults({ optimize_termination: termination, begin: periodBegin.format(), end: periodEnd.format(), population_size: options.sample_population_size || options.population_size }, _.omit(options, ['sample_duration', 'sample_count'])); }); const space_factory = period_units ? createSearchSpace : _.constant(space); return Promise.all(optionset.map(async(opts) => { const sample_space = await space_factory(pnames, options); return searchParameters(collect, prng, pnames, opts.population_size, sample_space, opts); })).then(results => { const parameters = _.pick(options.parameters, pnames); const pool = _.compact(_.flatten(_.zip.apply(_, results))); const sorted = period_units ? pool : _.sortBy(pool.reverse(), 'score').reverse(); const population = sorted.reduce((population, solution) => { const candidate = {pindex: solution.pindex}; if (population.length < size && (!period_units || space(candidate))) { population.push(candidate); } return population; }, []); const seed = _.isEmpty(parameters) ? null : {pindex: pvalues.map((values, p) => values.indexOf(parameters[pnames[p]]))}; if (seed && space(seed)) { population.push(seed); } const mutate = mutation(prng, pvalues, space, population); for (let i=0; i/2<size && population.length < size; i++) { const mutant = mutate(seed); if (mutant) population.push(mutant); } return population; }); }
function sampleSolutions(collect, prng, pnames, space, size, options) { const begin = moment(options.begin); const end = moment(options.end || options.now); if (!begin.isValid()) throw Error("Invalid begin date: " + options.begin); if (!end.isValid()) throw Error("Invalid end date: " + options.end); const until = options.sample_duration ? moment(end).subtract(moment.duration(options.sample_duration)) : begin; const count = options.sample_count || 1; const period = createDuration(begin, until, count); const unit = getDurationUnit(period, count); const duration = options.sample_duration ? moment.duration(options.sample_duration) : moment.duration(end.diff(begin)); if (duration && duration.asMilliseconds()<=0) throw Error("Invalid duration: " + options.sample_duration); const period_units = Math.max(period.as(unit), 0); const pvalues = pnames.map(name => options.parameter_values[name]); const termination = options.sample_termination || options.optimize_termination && moment.duration(moment.duration(options.optimize_termination).asSeconds()/3000).toISOString(); const optionset = _.range(count).map(() => { let periodBegin = period_units ? moment(begin).add(Math.round(prng() * period_units), unit) : begin let periodEnd = moment(periodBegin).add(duration); if (!periodEnd.isBefore(end)) { periodEnd = end; if (periodBegin.isAfter(begin)) { periodBegin = moment(end).subtract(duration); } } return _.defaults({ optimize_termination: termination, begin: periodBegin.format(), end: periodEnd.format(), population_size: options.sample_population_size || options.population_size }, _.omit(options, ['sample_duration', 'sample_count'])); }); const space_factory = period_units ? createSearchSpace : _.constant(space); return Promise.all(optionset.map(async(opts) => { const sample_space = await space_factory(pnames, options); return searchParameters(collect, prng, pnames, opts.population_size, sample_space, opts); })).then(results => { const parameters = _.pick(options.parameters, pnames); const pool = _.compact(_.flatten(_.zip.apply(_, results))); const sorted = period_units ? pool : _.sortBy(pool.reverse(), 'score').reverse(); const population = sorted.reduce((population, solution) => { const candidate = {pindex: solution.pindex}; if (population.length < size && (!period_units || space(candidate))) { population.push(candidate); } return population; }, []); const seed = _.isEmpty(parameters) ? null : {pindex: pvalues.map((values, p) => values.indexOf(parameters[pnames[p]]))}; if (seed && space(seed)) { population.push(seed); } const mutate = mutation(prng, pvalues, space, population); for (let i=0; i/2<size && population.length < size; i++) { const mutant = mutate(seed); if (mutant) population.push(mutant); } return population; }); }
JavaScript
function initialPopulation(prng, pnames, space, size, options) { const parameters = _.pick(options.parameters, pnames); const pvalues = pnames.map(name => options.parameter_values[name]); const population = []; const seed = _.isEmpty(parameters) ? null : { pindex: pvalues.map((values, p) => values.indexOf(parameters[pnames[p]])) }; if (seed && space(seed)) { population.push(seed); } const mutate = mutation(prng, pvalues, space); for (let i=0; i<size*2 && population.length < size; i++) { const mutant = mutate(seed); if (mutant) population.push(mutant); } return population; }
function initialPopulation(prng, pnames, space, size, options) { const parameters = _.pick(options.parameters, pnames); const pvalues = pnames.map(name => options.parameter_values[name]); const population = []; const seed = _.isEmpty(parameters) ? null : { pindex: pvalues.map((values, p) => values.indexOf(parameters[pnames[p]])) }; if (seed && space(seed)) { population.push(seed); } const mutate = mutation(prng, pvalues, space); for (let i=0; i<size*2 && population.length < size; i++) { const mutant = mutate(seed); if (mutant) population.push(mutant); } return population; }
JavaScript
async function fitness(collect, options, pnames) { const pvalues = pnames.map(name => options.parameter_values[name]); const score_column = getScoreColumn(options); const transient = _.isBoolean(options.transient) ? options.transient : await isLookbackParameter(pnames, options); return function(candidate) { const params = _.object(pnames, candidate.pindex.map((idx, p) => pvalues[p][idx])); const parameters = _.defaults(params, options.parameters); const label = pnames.length ? (options.label ? options.label + ' ' : '') + candidate.pindex.map((idx,i) => { return options.parameter_values[pnames[i]][idx]; }).join(',') : options.label; const picked = ['portfolio', 'columns', 'variables', 'parameters', 'filter', 'precedence', 'order', 'pad_leading', 'reset_every', 'tail', 'transient']; const opts = _.defaults({ tail: 1, transient: transient, label: label, portfolio: [_.pick(options, picked)], columns: {[score_column]: options.eval_score}, variables: options.eval_variables, parameters: parameters }, _.omit(options, picked)); return collect(opts) .then(_.last).then(_.property(score_column)).then(score => { return _.extend(candidate, { score: score || 0 }); }); }; }
async function fitness(collect, options, pnames) { const pvalues = pnames.map(name => options.parameter_values[name]); const score_column = getScoreColumn(options); const transient = _.isBoolean(options.transient) ? options.transient : await isLookbackParameter(pnames, options); return function(candidate) { const params = _.object(pnames, candidate.pindex.map((idx, p) => pvalues[p][idx])); const parameters = _.defaults(params, options.parameters); const label = pnames.length ? (options.label ? options.label + ' ' : '') + candidate.pindex.map((idx,i) => { return options.parameter_values[pnames[i]][idx]; }).join(',') : options.label; const picked = ['portfolio', 'columns', 'variables', 'parameters', 'filter', 'precedence', 'order', 'pad_leading', 'reset_every', 'tail', 'transient']; const opts = _.defaults({ tail: 1, transient: transient, label: label, portfolio: [_.pick(options, picked)], columns: {[score_column]: options.eval_score}, variables: options.eval_variables, parameters: parameters }, _.omit(options, picked)); return collect(opts) .then(_.last).then(_.property(score_column)).then(score => { return _.extend(candidate, { score: score || 0 }); }); }; }
JavaScript
function adapt(fitness, mutation, pnames, terminateAt, options, population, size) { const check = interrupt(true); const maxEliteSize = Math.max(options.solution_count || 1, Math.floor(size/2)); const generation = size - maxEliteSize || 1; let elite = []; // elite solutions best one last const solutions = []; // unsorted solutions with a score const candidates = population.slice(0); // solutions without a score let strength = 0; let counter = 0; let until = Promise.resolve(); const rank = candidate => { return fitness(candidate).then(solution => { candidates.splice(candidates.indexOf(candidate), 1); solutions.push(solution); }).then(async() => { if (!solutions.length || await check()) return; const population = solutions.concat(elite); const top = _.sortBy(population, 'score').slice(-maxEliteSize); const additions = _.difference(top, elite); const better = _.difference(_.pluck(top, 'score'), _.pluck(elite, 'score')).length; if (better || counter % generation === 0) { const best = _.last(top); if (best.pindex.length) logger.debug("Optimize", options.label || '\b', options.begin, "G" + Math.floor(counter/generation), "P" + (elite.length+candidates.length), "M" + Math.round(strength * pnames.length), best.pindex.map((idx,i) => { return options.parameter_values[pnames[i]][idx]; }).join(','), ':', best.score); } if (better) { const now = Date.now(); additions.forEach(solution => solution.foundAt = now); elite = top; strength = 0; } if (!terminateAt || terminateAt > Date.now()) { const ranking = []; while (!ranking.length && strength < generation/pnames.length*2) { const mutate = mutation(elite, strength); for (let i=0; i<size*2 && elite.length+candidates.length<size; i++) { const mutant = mutate(additions[i], _.last(elite)); if (mutant) { candidates.push(mutant); ranking.push(rank(mutant)); } } strength += 1/generation/pnames.length; } if (ranking.length) { until = until.then(() => Promise.all(ranking)); } } counter += solutions.length; solutions.splice(0, solutions.length); }); }; until = until.then(() => Promise.all(candidates.map(rank))); const wait = promise => promise.then(async() => { if (promise != until && !await check()) return wait(until); else return elite.slice(0).reverse(); }); return wait(until); }
function adapt(fitness, mutation, pnames, terminateAt, options, population, size) { const check = interrupt(true); const maxEliteSize = Math.max(options.solution_count || 1, Math.floor(size/2)); const generation = size - maxEliteSize || 1; let elite = []; // elite solutions best one last const solutions = []; // unsorted solutions with a score const candidates = population.slice(0); // solutions without a score let strength = 0; let counter = 0; let until = Promise.resolve(); const rank = candidate => { return fitness(candidate).then(solution => { candidates.splice(candidates.indexOf(candidate), 1); solutions.push(solution); }).then(async() => { if (!solutions.length || await check()) return; const population = solutions.concat(elite); const top = _.sortBy(population, 'score').slice(-maxEliteSize); const additions = _.difference(top, elite); const better = _.difference(_.pluck(top, 'score'), _.pluck(elite, 'score')).length; if (better || counter % generation === 0) { const best = _.last(top); if (best.pindex.length) logger.debug("Optimize", options.label || '\b', options.begin, "G" + Math.floor(counter/generation), "P" + (elite.length+candidates.length), "M" + Math.round(strength * pnames.length), best.pindex.map((idx,i) => { return options.parameter_values[pnames[i]][idx]; }).join(','), ':', best.score); } if (better) { const now = Date.now(); additions.forEach(solution => solution.foundAt = now); elite = top; strength = 0; } if (!terminateAt || terminateAt > Date.now()) { const ranking = []; while (!ranking.length && strength < generation/pnames.length*2) { const mutate = mutation(elite, strength); for (let i=0; i<size*2 && elite.length+candidates.length<size; i++) { const mutant = mutate(additions[i], _.last(elite)); if (mutant) { candidates.push(mutant); ranking.push(rank(mutant)); } } strength += 1/generation/pnames.length; } if (ranking.length) { until = until.then(() => Promise.all(ranking)); } } counter += solutions.length; solutions.splice(0, solutions.length); }); }; until = until.then(() => Promise.all(candidates.map(rank))); const wait = promise => promise.then(async() => { if (promise != until && !await check()) return wait(until); else return elite.slice(0).reverse(); }); return wait(until); }
JavaScript
function mutation(prng, pvalues, space, solutions, strength) { const empty = _.isEmpty(solutions); const one = solutions && solutions.length == 1; const mutations = pvalues.map((values,i) => { const vals = empty || one ? _.range(values.length) : _.map(solutions, sol => sol.pindex[i]); const avg = one ? solutions[0].pindex[i] : vals.reduce((a,b) => a + b) / vals.length; const stdev = vals.length>1 ? statkit.std(vals) : 0; const window = Math.min(stdev + (strength || 0), Math.ceil(values.length/2)); return function(value) { const val = arguments.length ? value : avg; const target = statkit.norminv(prng()) * window + val; const abs = Math.abs(target % (values.length * 2)); return abs >= values.length ? Math.ceil(values.length * 2 - abs) - 1 : Math.floor(abs); }; }); return function(...solutions) { const result = solutions.reduce((result, solution) => { if (result || !solution) return result; const mutated = {pindex: mutations.map((fn, i) => fn(solution.pindex[i]))}; if (space(mutated)) return mutated; }, null); if (result) return result; const candidate = {pindex: mutations.map(fn => fn())}; if (space(candidate)) return candidate; else return null; }; }
function mutation(prng, pvalues, space, solutions, strength) { const empty = _.isEmpty(solutions); const one = solutions && solutions.length == 1; const mutations = pvalues.map((values,i) => { const vals = empty || one ? _.range(values.length) : _.map(solutions, sol => sol.pindex[i]); const avg = one ? solutions[0].pindex[i] : vals.reduce((a,b) => a + b) / vals.length; const stdev = vals.length>1 ? statkit.std(vals) : 0; const window = Math.min(stdev + (strength || 0), Math.ceil(values.length/2)); return function(value) { const val = arguments.length ? value : avg; const target = statkit.norminv(prng()) * window + val; const abs = Math.abs(target % (values.length * 2)); return abs >= values.length ? Math.ceil(values.length * 2 - abs) - 1 : Math.floor(abs); }; }); return function(...solutions) { const result = solutions.reduce((result, solution) => { if (result || !solution) return result; const mutated = {pindex: mutations.map((fn, i) => fn(solution.pindex[i]))}; if (space(mutated)) return mutated; }, null); if (result) return result; const candidate = {pindex: mutations.map(fn => fn())}; if (space(candidate)) return candidate; else return null; }; }
JavaScript
function createDuration(begin, end, count) { const duration = moment.duration(end.diff(begin)); const unit = getDurationUnit(duration, count); return moment.duration(duration.as(unit), unit); }
function createDuration(begin, end, count) { const duration = moment.duration(end.diff(begin)); const unit = getDurationUnit(duration, count); return moment.duration(duration.as(unit), unit); }
JavaScript
async function isLookbackParameter(pnames, options) { const parser = new Parser({ constant(value) { return {}; }, variable(name) { return {variables:[name]}; }, expression(expr, name, args) { const lookbacks = lookback.has(name) && [name]; return args.reduce((memo, arg) => { const lookbackParams = lookbacks && _.intersection(pnames, arg.variables); return { variables: _.union(memo.variables, arg.variables), lookbacks: _.union(lookbacks, memo.lookbacks, arg.lookbacks), lookbackParams: _.union(lookbackParams, memo.lookbackParams, arg.lookbackParams) }; }, {}); } }); const parsed = await parser.parse(_.flatten(_.compact([ _.values(options.columns), _.values(options.variables), options.criteria, options.filter, options.precedence, options.order ]))); const lookbackParams = _.uniq(_.flatten(_.compact(parsed.map(item => item.lookbackParams)))); if (lookbackParams.length) return true; // don't persist parameter values else return false; }
async function isLookbackParameter(pnames, options) { const parser = new Parser({ constant(value) { return {}; }, variable(name) { return {variables:[name]}; }, expression(expr, name, args) { const lookbacks = lookback.has(name) && [name]; return args.reduce((memo, arg) => { const lookbackParams = lookbacks && _.intersection(pnames, arg.variables); return { variables: _.union(memo.variables, arg.variables), lookbacks: _.union(lookbacks, memo.lookbacks, arg.lookbacks), lookbackParams: _.union(lookbackParams, memo.lookbackParams, arg.lookbackParams) }; }, {}); } }); const parsed = await parser.parse(_.flatten(_.compact([ _.values(options.columns), _.values(options.variables), options.criteria, options.filter, options.precedence, options.order ]))); const lookbackParams = _.uniq(_.flatten(_.compact(parsed.map(item => item.lookbackParams)))); if (lookbackParams.length) return true; // don't persist parameter values else return false; }
JavaScript
function availableHeapSize(cache) { const sample = Object.values(cache).filter(entry => entry.heap_before < entry.heap_after); const heap_growth_rate = sample.reduce((total, entry) => { return total + entry.heap_after - entry.heap_before; }, 0) / sample.length; if (!sample.length || !heap_growth_rate) return Infinity; const usage = process.memoryUsage(); const heap_avail = (heap_limit || usage.heapTotal) - usage.heapUsed; return Math.floor(heap_avail/heap_growth_rate); }
function availableHeapSize(cache) { const sample = Object.values(cache).filter(entry => entry.heap_before < entry.heap_after); const heap_growth_rate = sample.reduce((total, entry) => { return total + entry.heap_after - entry.heap_before; }, 0) / sample.length; if (!sample.length || !heap_growth_rate) return Infinity; const usage = process.memoryUsage(); const heap_avail = (heap_limit || usage.heapTotal) - usage.heapUsed; return Math.floor(heap_avail/heap_growth_rate); }
JavaScript
function help(bestsignals) { return bestsignals({info:'help'}).then(_.first).then(help => { return [{ name: 'strategize', usage: 'strategize(options)', description: "Modifies a strategy looks for improvements to its score", properties: ['solution_variable','strategy_variable'].concat(help.properties), options: _.extend({}, help.options, { strategy_variable: { usage: '<variable name>', description: "The variable name to use when testing various strategies" }, conjunction_cost: { usage: '<number>', description: "Minimum amount the score must increase by before adding 'AND' operator" }, conjunctions_only: { usage: 'true', description: "If more disjunctions are prohibited (no 'OR' operators)" }, disjunction_cost: { usage: '<number>', description: "Minimum amount the score must increase by to add another 'OR' operator" }, disjunctions_only: { usage: 'true', description: "If more conjunctions are prohibited (no 'AND' operators)" }, follow_signals_only: { usage: 'true', description: "If the strategy should never counter the signal direction" }, from_scratch: { usage: 'true', description: "If the existing strategy should not be immediately considered" }, max_operands: { usage: '<number>', description: "Maximum amount of operands between AND/OR conjunctions/disjunctions" }, termination: { usage: 'PT5M', description: "Amount of time spent searching for a solution before the best yet is used" }, directional: { usage: 'true|false', description: "If a signal's direction is significant on its own" } }) }]; }); }
function help(bestsignals) { return bestsignals({info:'help'}).then(_.first).then(help => { return [{ name: 'strategize', usage: 'strategize(options)', description: "Modifies a strategy looks for improvements to its score", properties: ['solution_variable','strategy_variable'].concat(help.properties), options: _.extend({}, help.options, { strategy_variable: { usage: '<variable name>', description: "The variable name to use when testing various strategies" }, conjunction_cost: { usage: '<number>', description: "Minimum amount the score must increase by before adding 'AND' operator" }, conjunctions_only: { usage: 'true', description: "If more disjunctions are prohibited (no 'OR' operators)" }, disjunction_cost: { usage: '<number>', description: "Minimum amount the score must increase by to add another 'OR' operator" }, disjunctions_only: { usage: 'true', description: "If more conjunctions are prohibited (no 'AND' operators)" }, follow_signals_only: { usage: 'true', description: "If the strategy should never counter the signal direction" }, from_scratch: { usage: 'true', description: "If the existing strategy should not be immediately considered" }, max_operands: { usage: '<number>', description: "Maximum amount of operands between AND/OR conjunctions/disjunctions" }, termination: { usage: 'PT5M', description: "Amount of time spent searching for a solution before the best yet is used" }, directional: { usage: 'true|false', description: "If a signal's direction is significant on its own" } }) }]; }); }
JavaScript
function strategize(bestsignals, prng, options) { const now = Date.now(); const parser = createParser(); const termAt = options.termination && moment().add(moment.duration(options.termination)).valueOf(); const strategize = strategizeLegs.bind(this, bestsignals, prng, parser, termAt, now); const strategy_var = options.strategy_variable; return strategize(options, {[strategy_var]: options}) .then(signals => combine(signals, options)) .then(best => { const strategy = best.variables[strategy_var]; logger.info("Strategize", options.label || '\b', strategy, best.score); return best; }); }
function strategize(bestsignals, prng, options) { const now = Date.now(); const parser = createParser(); const termAt = options.termination && moment().add(moment.duration(options.termination)).valueOf(); const strategize = strategizeLegs.bind(this, bestsignals, prng, parser, termAt, now); const strategy_var = options.strategy_variable; return strategize(options, {[strategy_var]: options}) .then(signals => combine(signals, options)) .then(best => { const strategy = best.variables[strategy_var]; logger.info("Strategize", options.label || '\b', strategy, best.score); return best; }); }
JavaScript
async function strategizeLegs(bestsignals, prng, parser, termAt, started, options, signals) { const scores = {}; const strategy_var = options.strategy_variable; const latest = signals[strategy_var]; const latest_expr = latest.variables[strategy_var]; const strategy = await parser(isBlankStrategy(latest_expr, options) ? '' : latest_expr); const from_scratch = options.from_scratch || !strategy.legs.length; const incremental = strategy.legs.length; const searchFn = searchLeg.bind(this, bestsignals, prng, parser, termAt); const all = strategizeAll.bind(this, bestsignals, searchFn, parser, started, options); const some = strategizeSome.bind(this, bestsignals, prng, searchFn, parser, termAt, started, options); return Promise.resolve(from_scratch ? all(scores, merge({signals}, {signals:{ [strategy_var]: {variables:{[strategy_var]:''}} }})) : null).then(reset => { if (!incremental) return reset; else if (!reset) return some(scores, signals); else return evaluate(bestsignals, scores, strategy.expr, latest) .then(latestScore => { const cost = getStrategyCost(strategy.expr, options); const better = reset[strategy_var]; if (latestScore - cost < better.score - better.cost) return reset; if (latestScore - cost == better.score - better.cost) return merge(signals, {[strategy_var]: {score: latestScore}}); logger.log("Strategize", options.label || '\b', "from scratch was not good enough", better.variables[strategy_var], better.score); return some(scores, signals); }); }); }
async function strategizeLegs(bestsignals, prng, parser, termAt, started, options, signals) { const scores = {}; const strategy_var = options.strategy_variable; const latest = signals[strategy_var]; const latest_expr = latest.variables[strategy_var]; const strategy = await parser(isBlankStrategy(latest_expr, options) ? '' : latest_expr); const from_scratch = options.from_scratch || !strategy.legs.length; const incremental = strategy.legs.length; const searchFn = searchLeg.bind(this, bestsignals, prng, parser, termAt); const all = strategizeAll.bind(this, bestsignals, searchFn, parser, started, options); const some = strategizeSome.bind(this, bestsignals, prng, searchFn, parser, termAt, started, options); return Promise.resolve(from_scratch ? all(scores, merge({signals}, {signals:{ [strategy_var]: {variables:{[strategy_var]:''}} }})) : null).then(reset => { if (!incremental) return reset; else if (!reset) return some(scores, signals); else return evaluate(bestsignals, scores, strategy.expr, latest) .then(latestScore => { const cost = getStrategyCost(strategy.expr, options); const better = reset[strategy_var]; if (latestScore - cost < better.score - better.cost) return reset; if (latestScore - cost == better.score - better.cost) return merge(signals, {[strategy_var]: {score: latestScore}}); logger.log("Strategize", options.label || '\b', "from scratch was not good enough", better.variables[strategy_var], better.score); return some(scores, signals); }); }); }
JavaScript
async function strategizeSome(bestsignals, prng, searchLeg, parser, termAt, started, options, scores, signals) { const check = interrupt(true); const strategy_var = options.strategy_variable; const latest = signals[strategy_var]; const latest_expr = latest.variables[strategy_var]; const strategy = await parser(isBlankStrategy(latest_expr, options) ? '' : latest_expr); if (!strategy.legs.length) return strategizeAll(bestsignals, searchLeg, parser, started, options, scores, {signals}); const isolations = strategy.legs.length > 1 && strategy.legs.map((leg, i) => { return spliceExpr(strategy.legs, i, 1).join(' OR '); }); return evaluate(bestsignals, scores, strategy.expr, latest) .then(latestScore => Promise.all(strategy.legs.map((leg, i) => { if (strategy.legs.length == 1) return latestScore; const withoutIt = isolations[i]; return evaluate(bestsignals, scores, withoutIt, latest).then(score => latestScore - score); })).then(async(contribs) => { if (await check()) return msignals; const label = options.label || '\b'; logger.log("Strategize", label, "base", latest.variables[strategy_var], latestScore); const cost = getStrategyCost(strategy.expr, options); const msignals = merge(signals, {[strategy_var]:{score:latestScore, cost}}); const full = options.conjunctions_only || options.max_operands && options.max_operands <= countOperands(strategy.expr); const idx = chooseContribution(prng, options.disjunction_cost, contribs, full ? 0 : 1); if (idx < strategy.legs.length) logger.trace("Strategize", label, "contrib", strategy.legs[idx].expr, contribs[idx]); const searchFn = searchLeg.bind(this, 1, {}); // just try to improve one thing return strategizeContribs(searchFn, msignals, strategy, contribs[idx], idx, options) .then(signals => { const better = signals[strategy_var]; const new_expr = better.variables[strategy_var]; if (!new_expr) { logger.warn("Strategize", options.label || '\b', "failed to make sense of", latest_expr); return strategizeAll(bestsignals, searchLeg, parser, started, options, scores, {signals}); } if (latestScore - cost < better.score - better.cost) return signals; else return msignals; // better was not significantly so }); })); }
async function strategizeSome(bestsignals, prng, searchLeg, parser, termAt, started, options, scores, signals) { const check = interrupt(true); const strategy_var = options.strategy_variable; const latest = signals[strategy_var]; const latest_expr = latest.variables[strategy_var]; const strategy = await parser(isBlankStrategy(latest_expr, options) ? '' : latest_expr); if (!strategy.legs.length) return strategizeAll(bestsignals, searchLeg, parser, started, options, scores, {signals}); const isolations = strategy.legs.length > 1 && strategy.legs.map((leg, i) => { return spliceExpr(strategy.legs, i, 1).join(' OR '); }); return evaluate(bestsignals, scores, strategy.expr, latest) .then(latestScore => Promise.all(strategy.legs.map((leg, i) => { if (strategy.legs.length == 1) return latestScore; const withoutIt = isolations[i]; return evaluate(bestsignals, scores, withoutIt, latest).then(score => latestScore - score); })).then(async(contribs) => { if (await check()) return msignals; const label = options.label || '\b'; logger.log("Strategize", label, "base", latest.variables[strategy_var], latestScore); const cost = getStrategyCost(strategy.expr, options); const msignals = merge(signals, {[strategy_var]:{score:latestScore, cost}}); const full = options.conjunctions_only || options.max_operands && options.max_operands <= countOperands(strategy.expr); const idx = chooseContribution(prng, options.disjunction_cost, contribs, full ? 0 : 1); if (idx < strategy.legs.length) logger.trace("Strategize", label, "contrib", strategy.legs[idx].expr, contribs[idx]); const searchFn = searchLeg.bind(this, 1, {}); // just try to improve one thing return strategizeContribs(searchFn, msignals, strategy, contribs[idx], idx, options) .then(signals => { const better = signals[strategy_var]; const new_expr = better.variables[strategy_var]; if (!new_expr) { logger.warn("Strategize", options.label || '\b', "failed to make sense of", latest_expr); return strategizeAll(bestsignals, searchLeg, parser, started, options, scores, {signals}); } if (latestScore - cost < better.score - better.cost) return signals; else return msignals; // better was not significantly so }); })); }
JavaScript
async function strategizeAll(bestsignals, searchLeg, parser, started, options, scores, state) { _.defaults(state, {exhausted: [false], scores: []}); const strategy_var = options.strategy_variable; const latest = state.signals[strategy_var]; const latest_expr = latest.variables[strategy_var]; const strategy = await parser(isBlankStrategy(latest_expr, options) ? '' : latest_expr); const isolations = strategy.legs.length > 1 && strategy.legs.map((leg, i) => { return spliceExpr(strategy.legs, i, 1).join(' OR '); }); const leg_count = Math.max(strategy.legs.length+(options.conjunctions_only?0:1),1); return Promise.all(_.range(leg_count).map(idx => { if (state.exhausted[idx]) return state; const searchLegFn = searchLeg.bind(this, 100, state.scores[idx] = state.scores[idx] || {}); return Promise.resolve(!strategy.legs.length ? 0 : strategy.legs.length == 1 ? latest.score : evaluate(bestsignals, scores, isolations[idx], latest).then(score => latest.score - score)) .then(contrib => strategizeContribs(searchLegFn, state.signals, strategy, contrib, idx, options)) .then(async(signals) => { const same = _.isEqual(signals, state.signals); const new_expr = same ? latest_expr : signals[strategy_var].variables[strategy_var]; const new_strategy = same ? strategy : await parser(new_expr); const next_exhausted = same ? state.exhausted.slice(0) : new Array(new_strategy.legs.length+1); const next_scores = []; if (new_strategy.legs.length >= strategy.legs.length) { next_exhausted[idx] = same; // legs was not dropped next_scores[idx] = state.scores[idx]; } if (idx < new_strategy.legs.length) { const full = options.conjunctions_only || options.max_operands && options.max_operands <= countOperands(new_expr); next_exhausted[new_strategy.legs.length] = full; } return {signals, exhausted: next_exhausted, scores: next_scores}; }); })).then(all => { const different = all.filter(se => !_.isEqual(se.signals, state.signals)); const se = _.last(_.sortBy(different, se => { const better = se.signals[strategy_var]; return better.score - better.cost; })); if (se) return se; return { signals: state.signals, exhausted: all.map((se, i) => se.exhausted[i]), scores: all.map((se, i) => se.scores[i]) }; }).then(state => { const better = state.signals[strategy_var]; const new_expr = better.variables[strategy_var]; if (!new_expr) throw Error(`Strategize ${options.label} failed to come up with a strategy`); if (_.every(state.exhausted)) return state.signals; const elapse = moment.duration(Date.now() - started).humanize(); logger.log("Strategize", options.label || '\b', new_expr, "after", elapse, better.score); return strategizeAll(bestsignals, searchLeg, parser, started, options, scores, state); }); }
async function strategizeAll(bestsignals, searchLeg, parser, started, options, scores, state) { _.defaults(state, {exhausted: [false], scores: []}); const strategy_var = options.strategy_variable; const latest = state.signals[strategy_var]; const latest_expr = latest.variables[strategy_var]; const strategy = await parser(isBlankStrategy(latest_expr, options) ? '' : latest_expr); const isolations = strategy.legs.length > 1 && strategy.legs.map((leg, i) => { return spliceExpr(strategy.legs, i, 1).join(' OR '); }); const leg_count = Math.max(strategy.legs.length+(options.conjunctions_only?0:1),1); return Promise.all(_.range(leg_count).map(idx => { if (state.exhausted[idx]) return state; const searchLegFn = searchLeg.bind(this, 100, state.scores[idx] = state.scores[idx] || {}); return Promise.resolve(!strategy.legs.length ? 0 : strategy.legs.length == 1 ? latest.score : evaluate(bestsignals, scores, isolations[idx], latest).then(score => latest.score - score)) .then(contrib => strategizeContribs(searchLegFn, state.signals, strategy, contrib, idx, options)) .then(async(signals) => { const same = _.isEqual(signals, state.signals); const new_expr = same ? latest_expr : signals[strategy_var].variables[strategy_var]; const new_strategy = same ? strategy : await parser(new_expr); const next_exhausted = same ? state.exhausted.slice(0) : new Array(new_strategy.legs.length+1); const next_scores = []; if (new_strategy.legs.length >= strategy.legs.length) { next_exhausted[idx] = same; // legs was not dropped next_scores[idx] = state.scores[idx]; } if (idx < new_strategy.legs.length) { const full = options.conjunctions_only || options.max_operands && options.max_operands <= countOperands(new_expr); next_exhausted[new_strategy.legs.length] = full; } return {signals, exhausted: next_exhausted, scores: next_scores}; }); })).then(all => { const different = all.filter(se => !_.isEqual(se.signals, state.signals)); const se = _.last(_.sortBy(different, se => { const better = se.signals[strategy_var]; return better.score - better.cost; })); if (se) return se; return { signals: state.signals, exhausted: all.map((se, i) => se.exhausted[i]), scores: all.map((se, i) => se.scores[i]) }; }).then(state => { const better = state.signals[strategy_var]; const new_expr = better.variables[strategy_var]; if (!new_expr) throw Error(`Strategize ${options.label} failed to come up with a strategy`); if (_.every(state.exhausted)) return state.signals; const elapse = moment.duration(Date.now() - started).humanize(); logger.log("Strategize", options.label || '\b', new_expr, "after", elapse, better.score); return strategizeAll(bestsignals, searchLeg, parser, started, options, scores, state); }); }
JavaScript
function strategizeContribs(searchLeg, signals, strategy, contrib, idx, options) { const label = options.label || '\b'; const strategy_var = options.strategy_variable; const latest = signals[strategy_var]; const empty = !strategy.legs.length; return strategizeLeg(searchLeg, signals, strategy, idx, options) .then(leg_signals => { const best = leg_signals[strategy_var]; const new_expr = best.variables[strategy_var]; const better = empty || best.score - best.cost > latest.score - latest.cost; const better_contrib = better ? best.score - latest.score + contrib : contrib; const drop = idx < strategy.legs.length && strategy.legs.length > 1 && better_contrib < options.disjunction_cost; const drop_expr = drop && spliceExpr(strategy.legs, idx, 1).join(' OR '); if (drop) return _.extend({}, signals, {[strategy_var]: merge(latest, { score: latest.score - contrib, cost: getStrategyCost(drop_expr, options), variables:{[strategy_var]: drop_expr} })}); return better ? leg_signals : signals; }); }
function strategizeContribs(searchLeg, signals, strategy, contrib, idx, options) { const label = options.label || '\b'; const strategy_var = options.strategy_variable; const latest = signals[strategy_var]; const empty = !strategy.legs.length; return strategizeLeg(searchLeg, signals, strategy, idx, options) .then(leg_signals => { const best = leg_signals[strategy_var]; const new_expr = best.variables[strategy_var]; const better = empty || best.score - best.cost > latest.score - latest.cost; const better_contrib = better ? best.score - latest.score + contrib : contrib; const drop = idx < strategy.legs.length && strategy.legs.length > 1 && better_contrib < options.disjunction_cost; const drop_expr = drop && spliceExpr(strategy.legs, idx, 1).join(' OR '); if (drop) return _.extend({}, signals, {[strategy_var]: merge(latest, { score: latest.score - contrib, cost: getStrategyCost(drop_expr, options), variables:{[strategy_var]: drop_expr} })}); return better ? leg_signals : signals; }); }
JavaScript
async function strategizeLeg(searchLeg, signals, strategy, idx, options) { const leg_var = options.leg_variable; // move leg into temporary variable const strategy_var = options.strategy_variable; const latest = signals[strategy_var]; const empty = !strategy.legs.length; const scratch = idx >= strategy.legs.length; const used = empty ? [] : await getReferences(latest.variables[strategy_var], options); const operands = idx < strategy.legs.length ? countOperands(strategy.legs[idx].expr) : 0; const other_operands = empty ? 0 : countOperands(strategy.expr) - operands; const opts = merge(latest, { score: latest.score || 0, cost: scratch ? 0 : getStrategyCost(strategy.legs[idx].expr, options), disjunction_cost: empty ? 0 : options.disjunction_cost, strategy_variable: leg_var, max_operands: options.max_operands && options.max_operands - other_operands, variables: { [strategy_var]: spliceExpr(strategy.legs, idx, 1, leg_var).join(' OR '), [leg_var]: scratch ? '' : strategy.legs[idx].expr } }); return searchLeg(signals, opts).then(leg_signals => _.mapObject(leg_signals, (best, name) => { if (signals[name] && name != leg_var) return best; const new_leg = best.variables[leg_var]; const new_expr = spliceExpr(strategy.legs, idx, 1, new_leg).join(' OR '); return _.defaults({ cost: getStrategyCost(new_expr, options), strategy_variable: strategy_var, max_operands: options.max_operands, variables: _.defaults({ [strategy_var]: new_expr }, _.omit(best.variables, leg_var)) }, best); })).then(leg_signals => _.defaults({ [strategy_var]: leg_signals[leg_var] }, _.omit(leg_signals, leg_var))); }
async function strategizeLeg(searchLeg, signals, strategy, idx, options) { const leg_var = options.leg_variable; // move leg into temporary variable const strategy_var = options.strategy_variable; const latest = signals[strategy_var]; const empty = !strategy.legs.length; const scratch = idx >= strategy.legs.length; const used = empty ? [] : await getReferences(latest.variables[strategy_var], options); const operands = idx < strategy.legs.length ? countOperands(strategy.legs[idx].expr) : 0; const other_operands = empty ? 0 : countOperands(strategy.expr) - operands; const opts = merge(latest, { score: latest.score || 0, cost: scratch ? 0 : getStrategyCost(strategy.legs[idx].expr, options), disjunction_cost: empty ? 0 : options.disjunction_cost, strategy_variable: leg_var, max_operands: options.max_operands && options.max_operands - other_operands, variables: { [strategy_var]: spliceExpr(strategy.legs, idx, 1, leg_var).join(' OR '), [leg_var]: scratch ? '' : strategy.legs[idx].expr } }); return searchLeg(signals, opts).then(leg_signals => _.mapObject(leg_signals, (best, name) => { if (signals[name] && name != leg_var) return best; const new_leg = best.variables[leg_var]; const new_expr = spliceExpr(strategy.legs, idx, 1, new_leg).join(' OR '); return _.defaults({ cost: getStrategyCost(new_expr, options), strategy_variable: strategy_var, max_operands: options.max_operands, variables: _.defaults({ [strategy_var]: new_expr }, _.omit(best.variables, leg_var)) }, best); })).then(leg_signals => _.defaults({ [strategy_var]: leg_signals[leg_var] }, _.omit(leg_signals, leg_var))); }
JavaScript
function searchLeg(bestsignals, prng, parser, terminateAt, max_attempts, scores, signals, latest) { const check = interrupt(true); _.defaults(scores, {bestsignal: {}, evaluate: {}}); const bestsignalFn = bestsignal.bind(this, bestsignals, terminateAt, scores.bestsignal); const evaluateFn = evaluate.bind(this, bestsignals, scores.evaluate); const max_operands = latest.max_operands; const strategy_var = latest.strategy_variable; const strategy = latest.variables[strategy_var]; const moreStrategiesFn = moreStrategies.bind(this, prng, evaluateFn, parser, max_operands); const empty = !strategy || strategy == latest.signal_variable; let leg_signals = _.extend({}, signals, {[strategy_var]: latest}); let attempts = 1; const next = search.bind(this, bestsignalFn, moreStrategiesFn); const cb = async(next_signals) => { const best = next_signals[strategy_var]; const next_expr = best.variables[strategy_var]; const disjunction_cost = latest.disjunction_cost; const better = empty ? best.score > best.cost + disjunction_cost : latest.score - latest.cost < best.score - best.cost; if (better || attempts >= max_attempts || await check() || Date.now() > terminateAt) return Promise.resolve(next_signals); attempts = _.isEqual(next_signals, leg_signals) ? attempts + 1 : 0; leg_signals = next_signals; return next(next_signals, latest, cb); }; return next(leg_signals, latest, cb); }
function searchLeg(bestsignals, prng, parser, terminateAt, max_attempts, scores, signals, latest) { const check = interrupt(true); _.defaults(scores, {bestsignal: {}, evaluate: {}}); const bestsignalFn = bestsignal.bind(this, bestsignals, terminateAt, scores.bestsignal); const evaluateFn = evaluate.bind(this, bestsignals, scores.evaluate); const max_operands = latest.max_operands; const strategy_var = latest.strategy_variable; const strategy = latest.variables[strategy_var]; const moreStrategiesFn = moreStrategies.bind(this, prng, evaluateFn, parser, max_operands); const empty = !strategy || strategy == latest.signal_variable; let leg_signals = _.extend({}, signals, {[strategy_var]: latest}); let attempts = 1; const next = search.bind(this, bestsignalFn, moreStrategiesFn); const cb = async(next_signals) => { const best = next_signals[strategy_var]; const next_expr = best.variables[strategy_var]; const disjunction_cost = latest.disjunction_cost; const better = empty ? best.score > best.cost + disjunction_cost : latest.score - latest.cost < best.score - best.cost; if (better || attempts >= max_attempts || await check() || Date.now() > terminateAt) return Promise.resolve(next_signals); attempts = _.isEqual(next_signals, leg_signals) ? attempts + 1 : 0; leg_signals = next_signals; return next(next_signals, latest, cb); }; return next(leg_signals, latest, cb); }
JavaScript
function search(bestsignal, moreStrategies, signals, options, cb) { const strategy_var = options.strategy_variable; const latest = signals[strategy_var]; return moreStrategies(latest) .then(strategies => Promise.all(strategies.map(st => bestsignal(st, latest)))) .then(solutions => _.last(_.sortBy(solutions, sol => sol.score - sol.cost))) .then(async(solution) => { if (!solution || solution.revisited) { return cb(signals); } else if (latest.variables[strategy_var] && _.has(latest, 'score') && solution.score - solution.cost <= latest.score - latest.cost) { const strategy = solution.variables[strategy_var]; logger.debug("Strategize", options.label || '\b', "leg", strategy, solution.score); return cb(signals); } else { const formatted = await formatSolution(solution, latest, '_'); const improved = merge(latest, formatted); const next_signals = _.defaults({ [formatted.solution_variable]: solution, [strategy_var]: improved }, signals); const strategy = improved.variables[strategy_var]; logger.log("Strategize", options.label || '\b', "leg", strategy, solution.score); return cb(next_signals); } }); }
function search(bestsignal, moreStrategies, signals, options, cb) { const strategy_var = options.strategy_variable; const latest = signals[strategy_var]; return moreStrategies(latest) .then(strategies => Promise.all(strategies.map(st => bestsignal(st, latest)))) .then(solutions => _.last(_.sortBy(solutions, sol => sol.score - sol.cost))) .then(async(solution) => { if (!solution || solution.revisited) { return cb(signals); } else if (latest.variables[strategy_var] && _.has(latest, 'score') && solution.score - solution.cost <= latest.score - latest.cost) { const strategy = solution.variables[strategy_var]; logger.debug("Strategize", options.label || '\b', "leg", strategy, solution.score); return cb(signals); } else { const formatted = await formatSolution(solution, latest, '_'); const improved = merge(latest, formatted); const next_signals = _.defaults({ [formatted.solution_variable]: solution, [strategy_var]: improved }, signals); const strategy = improved.variables[strategy_var]; logger.log("Strategize", options.label || '\b', "leg", strategy, solution.score); return cb(next_signals); } }); }