language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function replaceString(oldS, newS, fullS) {
for (let i = 0; i < fullS.length; ++i) {
if (fullS.substring(i, i + oldS.length) === oldS) {
fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
}
}
return fullS;
} | function replaceString(oldS, newS, fullS) {
for (let i = 0; i < fullS.length; ++i) {
if (fullS.substring(i, i + oldS.length) === oldS) {
fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
}
}
return fullS;
} |
JavaScript | function moveFileToAnotherFolder(fileID, targetFolderID) {
let file = DriveApp.getFileById(fileID);
// Remove the file from all parent folders
let parents = file.getParents();
while (parents.hasNext()) {
let parent = parents.next();
parent.removeFile(file);
}
DriveApp.getFolderById(targetFolderID).addFile(file);
} | function moveFileToAnotherFolder(fileID, targetFolderID) {
let file = DriveApp.getFileById(fileID);
// Remove the file from all parent folders
let parents = file.getParents();
while (parents.hasNext()) {
let parent = parents.next();
parent.removeFile(file);
}
DriveApp.getFolderById(targetFolderID).addFile(file);
} |
JavaScript | function formatHours(unixTimestamp) {
let date = new Date(unixTimestamp * 1000);
// Hours part from the timestamp
let hours = '0' + date.getHours();
// Minutes part from the timestamp
let minutes = "0" + date.getMinutes();
// Will display time in 10:30:23 format
return hours.substr(-2) + ':' + minutes.substr(-2);
} | function formatHours(unixTimestamp) {
let date = new Date(unixTimestamp * 1000);
// Hours part from the timestamp
let hours = '0' + date.getHours();
// Minutes part from the timestamp
let minutes = "0" + date.getMinutes();
// Will display time in 10:30:23 format
return hours.substr(-2) + ':' + minutes.substr(-2);
} |
JavaScript | function isToday(dateString) {
let today = new Date();
let toCheck = new Date(dateString);
return toCheck.getDate() === today.getDate() && toCheck.getMonth() === today.getMonth() && toCheck.getFullYear() === today.getFullYear();
} | function isToday(dateString) {
let today = new Date();
let toCheck = new Date(dateString);
return toCheck.getDate() === today.getDate() && toCheck.getMonth() === today.getMonth() && toCheck.getFullYear() === today.getFullYear();
} |
JavaScript | function mathjs(msg) {
try {
let params = msg['text'].split(' ');
let expression = params[1];
let data = UrlFetchApp.fetch(calculatorUrlBase + '?expr=' + encodeURIComponent(expression));
telegramApi.sendMessage(msg, data.getContentText(), replyTo=true);
} catch(e) {
console.error('Error en convertCurrency');
console.error(e);
telegramApi.sendMessage(msg, 'No se ha podido realizar la operación.', replyTo=true);
}
} | function mathjs(msg) {
try {
let params = msg['text'].split(' ');
let expression = params[1];
let data = UrlFetchApp.fetch(calculatorUrlBase + '?expr=' + encodeURIComponent(expression));
telegramApi.sendMessage(msg, data.getContentText(), replyTo=true);
} catch(e) {
console.error('Error en convertCurrency');
console.error(e);
telegramApi.sendMessage(msg, 'No se ha podido realizar la operación.', replyTo=true);
}
} |
JavaScript | function refreshAccessToken() {
let options = {
'method': 'GET',
'headers': {
'X-ClientId': scriptProperties.getProperty('EmtIdClient'),
'passKey': scriptProperties.getProperty('EmtPassKey'),
}
}
let data = JSON.parse(UrlFetchApp.fetch(emtUrlBase + '/v2/mobilitylabs/user/login', options));
if(data.hasOwnProperty('data')) {
if(data['data'].length > 0) {
scriptProperties.setProperty('EMTAccessInfo', JSON.stringify(data['data'][0]));
return data['data'][0]['accessToken'];
} else {
return null;
}
} else {
return null;
}
} | function refreshAccessToken() {
let options = {
'method': 'GET',
'headers': {
'X-ClientId': scriptProperties.getProperty('EmtIdClient'),
'passKey': scriptProperties.getProperty('EmtPassKey'),
}
}
let data = JSON.parse(UrlFetchApp.fetch(emtUrlBase + '/v2/mobilitylabs/user/login', options));
if(data.hasOwnProperty('data')) {
if(data['data'].length > 0) {
scriptProperties.setProperty('EMTAccessInfo', JSON.stringify(data['data'][0]));
return data['data'][0]['accessToken'];
} else {
return null;
}
} else {
return null;
}
} |
JavaScript | function InputMixin(superClass) {
class InputElement extends superClass {
/**
* this description never gets picked up by the analyzer.
* so we lose some info about default values and the fact it is both property and attribute
*/
@property({ type: Boolean }) disabled = false
}
return InputElement;
} | function InputMixin(superClass) {
class InputElement extends superClass {
/**
* this description never gets picked up by the analyzer.
* so we lose some info about default values and the fact it is both property and attribute
*/
@property({ type: Boolean }) disabled = false
}
return InputElement;
} |
JavaScript | function createDreamTeam(members) {
var dreamTeam = '';
if (Array.isArray(members)) {
for (let i = members.length; i--;) {
if (typeof(members[i]) !== "string")
members.splice(i, 1);
}
for (let i = 0; i < members.length; i++) {
members[i] = members[i].trim().charAt(0).toUpperCase();
}
members.sort()
dreamTeam = members.join("");
return dreamTeam;
}
return false;
} | function createDreamTeam(members) {
var dreamTeam = '';
if (Array.isArray(members)) {
for (let i = members.length; i--;) {
if (typeof(members[i]) !== "string")
members.splice(i, 1);
}
for (let i = 0; i < members.length; i++) {
members[i] = members[i].trim().charAt(0).toUpperCase();
}
members.sort()
dreamTeam = members.join("");
return dreamTeam;
}
return false;
} |
JavaScript | function MenuBar() {
const { user, logout } = useContext(AuthContext);
// make the color on within the corresponding page
const pathname = window.location.pathname;
const path = pathname === "/" ? "home" : pathname.substr(1);
const [activeItem, setActiveItem] = useState(path);
const handleItemClick = (e, { name }) => setActiveItem(name);
// dont need render since this is a functional component, we just return
// render() {
// const { activeItem } = this.state
const menuBar = user ? (
<Menu pointing secondary size="massive" color="teal">
<Menu.Item
name={user.username}
active
// cool about component from semantic ui react:
// it is an integration, we can have it as a different component
as={Link}
// prop that will be on the link:
to="/"
/>
<Menu.Menu position="right">
<Menu.Item name="logout" onClick={logout} />
</Menu.Menu>
</Menu>
) : (
<Menu pointing secondary size="massive" color="teal">
<Menu.Item
name="home"
active={activeItem === "home"}
onClick={handleItemClick}
// cool about component from semantic ui react:
// it is an integration, we can have it as a different component
as={Link}
// prop that will be on the link:
to="/"
/>
<Menu.Menu position="right">
<Menu.Item
name="login"
active={activeItem === "login"}
onClick={handleItemClick}
as={Link}
to="/login"
/>
<Menu.Item
name="register"
active={activeItem === "register"}
onClick={handleItemClick}
as={Link}
to="/register"
/>
</Menu.Menu>
</Menu>
);
return menuBar;
} | function MenuBar() {
const { user, logout } = useContext(AuthContext);
// make the color on within the corresponding page
const pathname = window.location.pathname;
const path = pathname === "/" ? "home" : pathname.substr(1);
const [activeItem, setActiveItem] = useState(path);
const handleItemClick = (e, { name }) => setActiveItem(name);
// dont need render since this is a functional component, we just return
// render() {
// const { activeItem } = this.state
const menuBar = user ? (
<Menu pointing secondary size="massive" color="teal">
<Menu.Item
name={user.username}
active
// cool about component from semantic ui react:
// it is an integration, we can have it as a different component
as={Link}
// prop that will be on the link:
to="/"
/>
<Menu.Menu position="right">
<Menu.Item name="logout" onClick={logout} />
</Menu.Menu>
</Menu>
) : (
<Menu pointing secondary size="massive" color="teal">
<Menu.Item
name="home"
active={activeItem === "home"}
onClick={handleItemClick}
// cool about component from semantic ui react:
// it is an integration, we can have it as a different component
as={Link}
// prop that will be on the link:
to="/"
/>
<Menu.Menu position="right">
<Menu.Item
name="login"
active={activeItem === "login"}
onClick={handleItemClick}
as={Link}
to="/login"
/>
<Menu.Item
name="register"
active={activeItem === "register"}
onClick={handleItemClick}
as={Link}
to="/register"
/>
</Menu.Menu>
</Menu>
);
return menuBar;
} |
JavaScript | function LikeButton({ user, post: { id, likeCount, likes } }) {
const [liked, setLiked] = useState(false);
// how to use?
useEffect(() => {
// if we have a user and can find a like with that username, we've liked
if (user && likes.find((like) => like.username === user.username)) {
setLiked(true);
} else setLiked(false);
// parameter here? dependency array?
}, [user, likes]);
const [likePost] = useMutation(LIKE_POST_MUTATION, {
variables: { postId: id },
});
const LikeButton = user ? (
liked ? (
<Button color="red">
<Icon name="heart" />
</Button>
) : (
<Button color="red" basic>
<Icon name="heart" />
</Button>
)
) : (
<Button as={Link} to="/login" color="red" basic>
<Icon name="heart" />
</Button>
);
return (
<Button as="div" labelPosition="right" onClick={likePost}>
<MyPopup content={liked ? "Unlike" : "Like"}>{LikeButton}</MyPopup>
<Label as="div" basic color="red" pointing="left">
{likeCount}
</Label>
</Button>
);
} | function LikeButton({ user, post: { id, likeCount, likes } }) {
const [liked, setLiked] = useState(false);
// how to use?
useEffect(() => {
// if we have a user and can find a like with that username, we've liked
if (user && likes.find((like) => like.username === user.username)) {
setLiked(true);
} else setLiked(false);
// parameter here? dependency array?
}, [user, likes]);
const [likePost] = useMutation(LIKE_POST_MUTATION, {
variables: { postId: id },
});
const LikeButton = user ? (
liked ? (
<Button color="red">
<Icon name="heart" />
</Button>
) : (
<Button color="red" basic>
<Icon name="heart" />
</Button>
)
) : (
<Button as={Link} to="/login" color="red" basic>
<Icon name="heart" />
</Button>
);
return (
<Button as="div" labelPosition="right" onClick={likePost}>
<MyPopup content={liked ? "Unlike" : "Like"}>{LikeButton}</MyPopup>
<Label as="div" basic color="red" pointing="left">
{likeCount}
</Label>
</Button>
);
} |
JavaScript | update(_, { data: { register: userData } }) {
// console.log(result);
context.login(userData);
props.history.push("/");
} | update(_, { data: { register: userData } }) {
// console.log(result);
context.login(userData);
props.history.push("/");
} |
JavaScript | function generateToken(user) {
return jwt.sign(
{
id: user.id,
email: user.email,
username: user.username
},
SECRET_KEY, { expiresIn: '1h' }
);
} | function generateToken(user) {
return jwt.sign(
{
id: user.id,
email: user.email,
username: user.username
},
SECRET_KEY, { expiresIn: '1h' }
);
} |
JavaScript | function authReducer(state, action) {
// do something depending on the type of the action
switch (action.type) {
case "LOGIN":
return {
...state,
user: action.payload,
};
case "LOGOUT":
return {
...state,
user: null,
};
default:
return state;
}
} | function authReducer(state, action) {
// do something depending on the type of the action
switch (action.type) {
case "LOGIN":
return {
...state,
user: action.payload,
};
case "LOGOUT":
return {
...state,
user: null,
};
default:
return state;
}
} |
JavaScript | function randomDoubleLetters(pre, weight) {
let post = pre.toLowerCase()
.replace(/(?<= )./g, (match) => weight > Math.random() ? match.replace(2): match);
return post;
} | function randomDoubleLetters(pre, weight) {
let post = pre.toLowerCase()
.replace(/(?<= )./g, (match) => weight > Math.random() ? match.replace(2): match);
return post;
} |
JavaScript | function nonsenseCase(pre, weight) {
let post = pre.toLowerCase()
.replace(/(?<= )./g, (match) => weight > Math.random() ? match.toUpperCase(): match);
return post;
} | function nonsenseCase(pre, weight) {
let post = pre.toLowerCase()
.replace(/(?<= )./g, (match) => weight > Math.random() ? match.toUpperCase(): match);
return post;
} |
JavaScript | function randomKerning(pre, nonsenseWeight, spacingWeight, propensity) {
let post = pre
.replace(/ /g, () => spacingWeight > Math.random() ? " ".repeat( propensity > Math.random() ? Math.random() > 0.7 ? 3 : 2 : 0) : " ")
.replace(/./g, (match) => nonsenseWeight > Math.random() ? match + " " : match)
return post;
} | function randomKerning(pre, nonsenseWeight, spacingWeight, propensity) {
let post = pre
.replace(/ /g, () => spacingWeight > Math.random() ? " ".repeat( propensity > Math.random() ? Math.random() > 0.7 ? 3 : 2 : 0) : " ")
.replace(/./g, (match) => nonsenseWeight > Math.random() ? match + " " : match)
return post;
} |
JavaScript | function extraKilo(pre) {
// TODO: add more elements
let post = pre
.replace(/[\.\!]/g, " \u203C")
.replace(/you/g, "U")
.replace(/'/g, '');
return post;
} | function extraKilo(pre) {
// TODO: add more elements
let post = pre
.replace(/[\.\!]/g, " \u203C")
.replace(/you/g, "U")
.replace(/'/g, '');
return post;
} |
JavaScript | isPlayer(){
if (this.player){
return true
} else {
return false
}
} | isPlayer(){
if (this.player){
return true
} else {
return false
}
} |
JavaScript | save(){
// don't save if we arent a player
if (!this.isPlayer){
return
} else {
return submitPlayer(this)
}
} | save(){
// don't save if we arent a player
if (!this.isPlayer){
return
} else {
return submitPlayer(this)
}
} |
JavaScript | isAlive(){
if (this.hp > 0){
return true
} else {
return false
}
} | isAlive(){
if (this.hp > 0){
return true
} else {
return false
}
} |
JavaScript | gainXP(monster){
let xp = monster.xp;
this.xp += xp;
(monster.monies) ? this.addMonies(monster.monies) : this.addMonies(DEFAULT_MONIES_FOR_COMBAT);
if (this.xp >= this.tnl){
this.levelUp();
}
this.save();
return;
} | gainXP(monster){
let xp = monster.xp;
this.xp += xp;
(monster.monies) ? this.addMonies(monster.monies) : this.addMonies(DEFAULT_MONIES_FOR_COMBAT);
if (this.xp >= this.tnl){
this.levelUp();
}
this.save();
return;
} |
JavaScript | refreshStats(){
this.hp = this.maxHP;
this.sp = this.maxSP;
return;
} | refreshStats(){
this.hp = this.maxHP;
this.sp = this.maxSP;
return;
} |
JavaScript | function combat(player, monster){
let p = player;
let mon = monster;
let patk = player.atk
let matk = mon.atk;
let event = {}
event.mon = mon
let monDamageTaken = mon.takeDamage(patk)
// If we killed the monster
if(!mon.isAlive()){
p.gainXP(mon);
return {mon, monDamageTaken, p}
}
event.monDamageTaken = monDamageTaken;
let playerDamageTaken = p.takeDamage(matk);
// If the player died
if(!p.isAlive()){
p.kill();
event.totalXPLost = p.lastXPLost;
event.playerKilled = true;
}
event.playerDamageTaken = playerDamageTaken;
p.save();
return event
} | function combat(player, monster){
let p = player;
let mon = monster;
let patk = player.atk
let matk = mon.atk;
let event = {}
event.mon = mon
let monDamageTaken = mon.takeDamage(patk)
// If we killed the monster
if(!mon.isAlive()){
p.gainXP(mon);
return {mon, monDamageTaken, p}
}
event.monDamageTaken = monDamageTaken;
let playerDamageTaken = p.takeDamage(matk);
// If the player died
if(!p.isAlive()){
p.kill();
event.totalXPLost = p.lastXPLost;
event.playerKilled = true;
}
event.playerDamageTaken = playerDamageTaken;
p.save();
return event
} |
JavaScript | function submitPlayer(player){
if(player.name === "TestChar"){
return true
};
if(player){
window.localStorage.setItem("player", JSON.stringify(player))
return true
} else {
return false
}
} | function submitPlayer(player){
if(player.name === "TestChar"){
return true
};
if(player){
window.localStorage.setItem("player", JSON.stringify(player))
return true
} else {
return false
}
} |
JavaScript | async runCommandOnGroup(project, group, command) {
const projectConfig = this.configuration.projects.find(({ name }) => name === project);
if (!projectConfig)
throw `No project ${project} found.`;
const groupConfig = projectConfig.groups.find(({ name }) => name === group);
if (!groupConfig)
throw `No group ${group} found.`;
const services = groupConfig.services;
const commandResults = await Promise.all(services.map(service => this.runCommandOnService(project, service, command)));
const results = {};
commandResults.forEach((result, index) => results[services[index]] = result);
return results;
} | async runCommandOnGroup(project, group, command) {
const projectConfig = this.configuration.projects.find(({ name }) => name === project);
if (!projectConfig)
throw `No project ${project} found.`;
const groupConfig = projectConfig.groups.find(({ name }) => name === group);
if (!groupConfig)
throw `No group ${group} found.`;
const services = groupConfig.services;
const commandResults = await Promise.all(services.map(service => this.runCommandOnService(project, service, command)));
const results = {};
commandResults.forEach((result, index) => results[services[index]] = result);
return results;
} |
JavaScript | async runCommandOnService(project, service, command) {
const projectConfig = this.configuration.projects.find(({ name }) => name === project);
if (!projectConfig)
throw `No project ${project} found.`;
const serviceConfig = projectConfig.services.find(({ name }) => name === service);
if (!serviceConfig)
throw `No service ${service} found.`;
// don't run commands that are not defined
if (!serviceConfig.commands[command]) {
return null;
}
this.processes[project] = this.processes[project] || {};
this.processes[project][service] = this.processes[project][service] || [];
// don't run again services already running
if (command === 'start' && this.processes[project][service].length > 0) {
return null;
}
return await serviceConfig.commands[command]({
service: serviceConfig,
configuration: this.configuration,
processes: this.processes[project][service],
exec: (bashCommand, { splitLine = true } = { splitLine: true }) => this.exec(bashCommand, serviceConfig.path, splitLine),
run: (processName, bashCommand) => this.run(bashCommand, project, service, serviceConfig.path, processName),
awaitOutput: (process, expectedOutput, errorOutput, timeout) => new Promise((resolve, reject) => {
const timeoutReject = setTimeout(reject, timeout);
process.stdout.on('data', data => {
const convertedData = data.toString();
if (convertedData.match(expectedOutput)) {
resolve(convertedData);
clearTimeout(timeoutReject);
}
else if (convertedData.match(errorOutput)) {
reject(convertedData);
clearTimeout(timeoutReject);
}
});
}),
kill: () => {
this.processes[project][service].forEach(process => process.process.kill());
this.processes[project][service] = [];
},
cleanProcesses: () => {
this.processes[project][service] = [];
},
});
} | async runCommandOnService(project, service, command) {
const projectConfig = this.configuration.projects.find(({ name }) => name === project);
if (!projectConfig)
throw `No project ${project} found.`;
const serviceConfig = projectConfig.services.find(({ name }) => name === service);
if (!serviceConfig)
throw `No service ${service} found.`;
// don't run commands that are not defined
if (!serviceConfig.commands[command]) {
return null;
}
this.processes[project] = this.processes[project] || {};
this.processes[project][service] = this.processes[project][service] || [];
// don't run again services already running
if (command === 'start' && this.processes[project][service].length > 0) {
return null;
}
return await serviceConfig.commands[command]({
service: serviceConfig,
configuration: this.configuration,
processes: this.processes[project][service],
exec: (bashCommand, { splitLine = true } = { splitLine: true }) => this.exec(bashCommand, serviceConfig.path, splitLine),
run: (processName, bashCommand) => this.run(bashCommand, project, service, serviceConfig.path, processName),
awaitOutput: (process, expectedOutput, errorOutput, timeout) => new Promise((resolve, reject) => {
const timeoutReject = setTimeout(reject, timeout);
process.stdout.on('data', data => {
const convertedData = data.toString();
if (convertedData.match(expectedOutput)) {
resolve(convertedData);
clearTimeout(timeoutReject);
}
else if (convertedData.match(errorOutput)) {
reject(convertedData);
clearTimeout(timeoutReject);
}
});
}),
kill: () => {
this.processes[project][service].forEach(process => process.process.kill());
this.processes[project][service] = [];
},
cleanProcesses: () => {
this.processes[project][service] = [];
},
});
} |
JavaScript | run(bashCommand, project, service, fromPath, processName) {
const process = child_process_1.exec(bashCommand, {
cwd: fromPath,
});
const logs = [];
this.processes[project][service].push({ process, logs, name: processName });
process.stdout.on('data', data => {
logs.push(data.toString());
});
return process;
} | run(bashCommand, project, service, fromPath, processName) {
const process = child_process_1.exec(bashCommand, {
cwd: fromPath,
});
const logs = [];
this.processes[project][service].push({ process, logs, name: processName });
process.stdout.on('data', data => {
logs.push(data.toString());
});
return process;
} |
JavaScript | function parseTarget(targetType, target, configuration) {
targetType = targetType || 'group';
target = target || '';
let [parsedProject, parsedServiceOrGroup] = target.split(':');
const project = (parsedServiceOrGroup && parsedProject) || configuration.currentProject;
const serviceOrGroup = parsedServiceOrGroup || parsedProject || configuration.currentGroup;
if (!project) {
throw 'Project must be provided.';
}
if (!serviceOrGroup) {
throw 'Service or group must be provided.';
}
return {
targetType,
project,
serviceOrGroup,
};
} | function parseTarget(targetType, target, configuration) {
targetType = targetType || 'group';
target = target || '';
let [parsedProject, parsedServiceOrGroup] = target.split(':');
const project = (parsedServiceOrGroup && parsedProject) || configuration.currentProject;
const serviceOrGroup = parsedServiceOrGroup || parsedProject || configuration.currentGroup;
if (!project) {
throw 'Project must be provided.';
}
if (!serviceOrGroup) {
throw 'Service or group must be provided.';
}
return {
targetType,
project,
serviceOrGroup,
};
} |
JavaScript | function purgeCache(moduleName) {
// Traverse the cache looking for the files loaded by the specified module name
searchCache(moduleName, mod => {
delete require.cache[mod.id];
});
// Remove cached paths to the module.
Object.keys(module.constructor['_pathCache']).forEach(cacheKey => {
if (cacheKey.indexOf(moduleName) > 0) {
delete module.constructor['_pathCache'][cacheKey];
}
});
} | function purgeCache(moduleName) {
// Traverse the cache looking for the files loaded by the specified module name
searchCache(moduleName, mod => {
delete require.cache[mod.id];
});
// Remove cached paths to the module.
Object.keys(module.constructor['_pathCache']).forEach(cacheKey => {
if (cacheKey.indexOf(moduleName) > 0) {
delete module.constructor['_pathCache'][cacheKey];
}
});
} |
JavaScript | function searchCache(moduleName, callback) {
// Resolve the module identified by the specified name
let mod = require.resolve(moduleName);
// Check if the module has been resolved and found within the cache
if (mod && ((mod = require.cache[mod]) !== undefined)) {
// Recursively go over the results
(function traverse(mod) {
// Go over each of the module's children and traverse them
mod.children.forEach(child => {
traverse(child);
});
// Call the specified callback providing the found cached module
callback(mod);
}(mod));
}
} | function searchCache(moduleName, callback) {
// Resolve the module identified by the specified name
let mod = require.resolve(moduleName);
// Check if the module has been resolved and found within the cache
if (mod && ((mod = require.cache[mod]) !== undefined)) {
// Recursively go over the results
(function traverse(mod) {
// Go over each of the module's children and traverse them
mod.children.forEach(child => {
traverse(child);
});
// Call the specified callback providing the found cached module
callback(mod);
}(mod));
}
} |
JavaScript | async sendRequest(request) {
try {
const response = await request();
return response.data;
}
catch (e) {
if (!!e.response) {
throw e.response.data;
}
else {
throw `Could not connect to Minos server. Are you sure it's running?`;
}
}
} | async sendRequest(request) {
try {
const response = await request();
return response.data;
}
catch (e) {
if (!!e.response) {
throw e.response.data;
}
else {
throw `Could not connect to Minos server. Are you sure it's running?`;
}
}
} |
JavaScript | fetchLogs(project, service, processName, fromBeginning = true) {
return __asyncGenerator(this, arguments, function* fetchLogs_1() {
const ws = new WebSocket(`ws://localhost:${this.serverConfig.port}`);
ws.on('open', () => {
const message = {
path: 'logs',
project,
service,
process: processName,
fromBeginning,
};
ws.send(JSON.stringify(message));
});
const buffer = [];
ws.on('message', (message) => {
buffer.push(message);
});
while (true) {
yield yield __await(new Promise(resolve => {
if (buffer.length > 0) {
resolve(buffer.shift());
}
else {
let interval;
interval = setInterval(() => {
if (buffer.length > 0) {
resolve(buffer.shift());
clearInterval(interval);
}
}, 50);
}
}));
}
});
} | fetchLogs(project, service, processName, fromBeginning = true) {
return __asyncGenerator(this, arguments, function* fetchLogs_1() {
const ws = new WebSocket(`ws://localhost:${this.serverConfig.port}`);
ws.on('open', () => {
const message = {
path: 'logs',
project,
service,
process: processName,
fromBeginning,
};
ws.send(JSON.stringify(message));
});
const buffer = [];
ws.on('message', (message) => {
buffer.push(message);
});
while (true) {
yield yield __await(new Promise(resolve => {
if (buffer.length > 0) {
resolve(buffer.shift());
}
else {
let interval;
interval = setInterval(() => {
if (buffer.length > 0) {
resolve(buffer.shift());
clearInterval(interval);
}
}, 50);
}
}));
}
});
} |
JavaScript | async build(rootConfig) {
rootConfig.projects = rootConfig.projects || [];
rootConfig.server = rootConfig.server || {};
rootConfig.server.port = rootConfig.server.port || config_1.defaultServerConf.port;
const projects = await Promise.all(rootConfig.projects
.map(UserConfigBuilder.replaceHomeInPath)
.map(path => {
requireCache_1.purgeCache(path);
return path;
})
.map(this.getProjectConfig));
return Object.assign({}, rootConfig, { projects });
} | async build(rootConfig) {
rootConfig.projects = rootConfig.projects || [];
rootConfig.server = rootConfig.server || {};
rootConfig.server.port = rootConfig.server.port || config_1.defaultServerConf.port;
const projects = await Promise.all(rootConfig.projects
.map(UserConfigBuilder.replaceHomeInPath)
.map(path => {
requireCache_1.purgeCache(path);
return path;
})
.map(this.getProjectConfig));
return Object.assign({}, rootConfig, { projects });
} |
JavaScript | static serviceConfigWithDefaultValues(service) {
// path
service.path = UserConfigBuilder.replaceHomeInPath(service.path);
// repository
let { repository } = service;
if (!!repository) {
// replace shortcut
if (typeof repository === 'string') {
repository = {
url: repository,
};
}
repository = repository;
// default value for type
if (!repository.type) {
repository.type = config_1.defaultUserProjectConfig.repositoryType;
}
}
service.repository = repository;
// commands
service.commands = Object.assign({}, defaultCommands_1.default, service.commands);
return service;
} | static serviceConfigWithDefaultValues(service) {
// path
service.path = UserConfigBuilder.replaceHomeInPath(service.path);
// repository
let { repository } = service;
if (!!repository) {
// replace shortcut
if (typeof repository === 'string') {
repository = {
url: repository,
};
}
repository = repository;
// default value for type
if (!repository.type) {
repository.type = config_1.defaultUserProjectConfig.repositoryType;
}
}
service.repository = repository;
// commands
service.commands = Object.assign({}, defaultCommands_1.default, service.commands);
return service;
} |
JavaScript | function show_info(info){
var place = document.getElementById('infoDIV');
if (info == "GEN"){
var infoText = document.getElementById('General_info').innerHTML;
} else if (info == "FFT"){
var infoText = document.getElementById('FFT_info').innerHTML;
} else if (info == "RAW"){
var infoText = document.getElementById('raw_info').innerHTML;
} else if (info == "HEAT"){
var infoText = document.getElementById('HEAT_info').innerHTML;
}
place.innerHTML = infoText;
} | function show_info(info){
var place = document.getElementById('infoDIV');
if (info == "GEN"){
var infoText = document.getElementById('General_info').innerHTML;
} else if (info == "FFT"){
var infoText = document.getElementById('FFT_info').innerHTML;
} else if (info == "RAW"){
var infoText = document.getElementById('raw_info').innerHTML;
} else if (info == "HEAT"){
var infoText = document.getElementById('HEAT_info').innerHTML;
}
place.innerHTML = infoText;
} |
JavaScript | function Lin2LogSpace(max, n){
var start = Math.log(1), // First frequency
stop = Math.log(max), // Stop at last frequency
step = (stop-start)/n,
freqIndexes = [start];
for (i = 1; i<n; i++){
freqIndexes.push(freqIndexes[i-1] + step);
freqIndexes[i-1] = Math.round(Math.exp(freqIndexes[i-1]));
}
freqIndexes[i-1] = Math.round(Math.exp(freqIndexes[i-1]));
return freqIndexes
} | function Lin2LogSpace(max, n){
var start = Math.log(1), // First frequency
stop = Math.log(max), // Stop at last frequency
step = (stop-start)/n,
freqIndexes = [start];
for (i = 1; i<n; i++){
freqIndexes.push(freqIndexes[i-1] + step);
freqIndexes[i-1] = Math.round(Math.exp(freqIndexes[i-1]));
}
freqIndexes[i-1] = Math.round(Math.exp(freqIndexes[i-1]));
return freqIndexes
} |
JavaScript | function redraw_FFT_heat_plot(xMax){
svg3.svg.remove();
svg3.canvas.remove();
svg3 = init_FFT_heat_plot(nCols, freqLims);
} | function redraw_FFT_heat_plot(xMax){
svg3.svg.remove();
svg3.canvas.remove();
svg3 = init_FFT_heat_plot(nCols, freqLims);
} |
JavaScript | function gainer(value){
var out = value*(1+(1-gain)) - zeroer;
if (out<0){
return 0
} else {
return out
}
} | function gainer(value){
var out = value*(1+(1-gain)) - zeroer;
if (out<0){
return 0
} else {
return out
}
} |
JavaScript | function plot_heatmap(freq_matrix, xMax, yMax){
context = svg3.canvas.node().getContext("2d"),
image = context.createImageData(xMax, yMax);
for (var y = 0, p = 0; y < yMax; y++) {
for (var x = 0; x < xMax; x++) {
var c = d3.rgb(svg3.color(freq_matrix[x][y]));
image.data[p++] = c.r;
image.data[p++] = c.g;
image.data[p++] = c.b;
image.data[p++] = 256;
}
}
context.putImageData(image,0,0);
} | function plot_heatmap(freq_matrix, xMax, yMax){
context = svg3.canvas.node().getContext("2d"),
image = context.createImageData(xMax, yMax);
for (var y = 0, p = 0; y < yMax; y++) {
for (var x = 0; x < xMax; x++) {
var c = d3.rgb(svg3.color(freq_matrix[x][y]));
image.data[p++] = c.r;
image.data[p++] = c.g;
image.data[p++] = c.b;
image.data[p++] = 256;
}
}
context.putImageData(image,0,0);
} |
JavaScript | function start_microphone(stream){
var gain_node = audioContext.createGain();
gain_node.connect( audioContext.destination );
var microphone_stream = audioContext.createMediaStreamSource(stream);
// Enable increase and decrease of number of bins of FFT heatmap
document.getElementById('historyLength').addEventListener('change', function(){
if (this.value > nCols){ // Add extra columns to the matrix
var extra = this.value - nCols,
filler = new Uint8Array(nBins);
for (var i = 0; i<extra; i++){
freq_matrix.unshift(filler);
}
}
else{ // Delete columns of the matrix
var toDelete = nCols - this.value;
for (var i = 0; i<toDelete; i++){
freq_matrix.shift();
}
}
nCols = this.value
redraw_FFT_heat_plot(nCols, svg3)
plot_heatmap(freq_matrix, nCols, nBins);
});
// --- setup FFT
var script_processor_analysis_node = audioContext.createScriptProcessor(BUFF_SIZE, 1, 1);
script_processor_analysis_node.connect(gain_node);
var analyser_node = audioContext.createAnalyser();
analyser_node.smoothingTimeConstant = 0;
analyser_node.fftSize = BUFF_SIZE;
microphone_stream.connect(analyser_node);
// Initialize freq matrix for FFT heatmap
var nBins = analyser_node.frequencyBinCount/2;
var freq_matrix = new Array(nCols);
for (var i = 0; i<nCols; i++){
freq_matrix[i] = new Uint8Array(nBins);
}
var array_freq = new Uint8Array(nBins);
var smoothing_array = new Uint8Array(nBins);
var array_time_signal = new Uint8Array(BUFF_SIZE);
script_processor_analysis_node.onaudioprocess = function() {
if (microphone_stream.playbackState == microphone_stream.PLAYING_STATE) {
if (pause == 0){
// With no smoothing: update array_freq with the newest Frequency data
// With smoothing: Use smoothing array to update array_freq with an average of the two
if (smoothing == 0){
analyser_node.getByteFrequencyData(array_freq);
} else {
analyser_node.getByteFrequencyData(smoothing_array);
for (var i = 0; i<smoothing_array.length; i++){
array_freq[i] = (array_freq[i] + smoothing_array[i])/ 2;
}
}
// The latest buffer data
analyser_node.getByteTimeDomainData(array_time_signal);
// Add FFT results to frequency matrix
image_slice = [];
for (i = 0; i < CompressTo; i++) {
image_slice.unshift(array_freq[freqIndexes[i]]);
}
freq_matrix.shift(); // Remove oldest freq_bins_column
freq_matrix.push(image_slice); // Add new freq data
// draw the plots
plot_line(time, array_time_signal);
plot_heatmap(freq_matrix, nCols, nBins);
}
// FFT plot should get updated even when paused so you can switch views while paused.
if (FFTview == "stacked"){
plot_FFT_stacked(freqBins, array_freq, octaveIndexes);
} else {
plot_FFT_linear(freqBins, array_freq);
}
}
};
} | function start_microphone(stream){
var gain_node = audioContext.createGain();
gain_node.connect( audioContext.destination );
var microphone_stream = audioContext.createMediaStreamSource(stream);
// Enable increase and decrease of number of bins of FFT heatmap
document.getElementById('historyLength').addEventListener('change', function(){
if (this.value > nCols){ // Add extra columns to the matrix
var extra = this.value - nCols,
filler = new Uint8Array(nBins);
for (var i = 0; i<extra; i++){
freq_matrix.unshift(filler);
}
}
else{ // Delete columns of the matrix
var toDelete = nCols - this.value;
for (var i = 0; i<toDelete; i++){
freq_matrix.shift();
}
}
nCols = this.value
redraw_FFT_heat_plot(nCols, svg3)
plot_heatmap(freq_matrix, nCols, nBins);
});
// --- setup FFT
var script_processor_analysis_node = audioContext.createScriptProcessor(BUFF_SIZE, 1, 1);
script_processor_analysis_node.connect(gain_node);
var analyser_node = audioContext.createAnalyser();
analyser_node.smoothingTimeConstant = 0;
analyser_node.fftSize = BUFF_SIZE;
microphone_stream.connect(analyser_node);
// Initialize freq matrix for FFT heatmap
var nBins = analyser_node.frequencyBinCount/2;
var freq_matrix = new Array(nCols);
for (var i = 0; i<nCols; i++){
freq_matrix[i] = new Uint8Array(nBins);
}
var array_freq = new Uint8Array(nBins);
var smoothing_array = new Uint8Array(nBins);
var array_time_signal = new Uint8Array(BUFF_SIZE);
script_processor_analysis_node.onaudioprocess = function() {
if (microphone_stream.playbackState == microphone_stream.PLAYING_STATE) {
if (pause == 0){
// With no smoothing: update array_freq with the newest Frequency data
// With smoothing: Use smoothing array to update array_freq with an average of the two
if (smoothing == 0){
analyser_node.getByteFrequencyData(array_freq);
} else {
analyser_node.getByteFrequencyData(smoothing_array);
for (var i = 0; i<smoothing_array.length; i++){
array_freq[i] = (array_freq[i] + smoothing_array[i])/ 2;
}
}
// The latest buffer data
analyser_node.getByteTimeDomainData(array_time_signal);
// Add FFT results to frequency matrix
image_slice = [];
for (i = 0; i < CompressTo; i++) {
image_slice.unshift(array_freq[freqIndexes[i]]);
}
freq_matrix.shift(); // Remove oldest freq_bins_column
freq_matrix.push(image_slice); // Add new freq data
// draw the plots
plot_line(time, array_time_signal);
plot_heatmap(freq_matrix, nCols, nBins);
}
// FFT plot should get updated even when paused so you can switch views while paused.
if (FFTview == "stacked"){
plot_FFT_stacked(freqBins, array_freq, octaveIndexes);
} else {
plot_FFT_linear(freqBins, array_freq);
}
}
};
} |
JavaScript | _disconnect (payload) {
if (!payload.identifier) {
throw new Error('account param can\'t be empty.')
}
let wsKey = this._parseKey(payload.conn);
if (!(payload.identifier in this.connections)) {
throw new Error('This account is not connected');
}
if (!(wsKey in this.connections[payload.identifier])) {
throw new Error('No Connection found');
}
delete this.connections[payload.identifier][wsKey];
if (!this.getConnectionsFrom(payload.identifier).length) {
delete this.connections[payload.identifier];
}
} | _disconnect (payload) {
if (!payload.identifier) {
throw new Error('account param can\'t be empty.')
}
let wsKey = this._parseKey(payload.conn);
if (!(payload.identifier in this.connections)) {
throw new Error('This account is not connected');
}
if (!(wsKey in this.connections[payload.identifier])) {
throw new Error('No Connection found');
}
delete this.connections[payload.identifier][wsKey];
if (!this.getConnectionsFrom(payload.identifier).length) {
delete this.connections[payload.identifier];
}
} |
JavaScript | _connect (payload) {
if (!payload.identifier) {
throw new Error('payload param can\'t be empty.')
}
let wsKey = this._parseKey(payload.conn);
if (!(payload.identifier in this.connections)) {
this.connections[payload.identifier] = {}
}
this.connections[payload.identifier][wsKey] = payload.conn
} | _connect (payload) {
if (!payload.identifier) {
throw new Error('payload param can\'t be empty.')
}
let wsKey = this._parseKey(payload.conn);
if (!(payload.identifier in this.connections)) {
this.connections[payload.identifier] = {}
}
this.connections[payload.identifier][wsKey] = payload.conn
} |
JavaScript | _parseKey (conn) {
try {
return hash(stringify(conn));
} catch (e) {
throw new Error('Wrong Connection Object');
}
} | _parseKey (conn) {
try {
return hash(stringify(conn));
} catch (e) {
throw new Error('Wrong Connection Object');
}
} |
JavaScript | function fillOutSecurityPage(bot) {
var securityAnswer = '44133';
var horseman = bot.horseman;
return horseman.type('input#dcq_question_subjective_1', securityAnswer)
.wait(1327)
.click('input#dcq_submit')
.waitForNextPage()
.catch((err) => { console.log('Encountered an error when filling out the security page.'); throw err; })
} | function fillOutSecurityPage(bot) {
var securityAnswer = '44133';
var horseman = bot.horseman;
return horseman.type('input#dcq_question_subjective_1', securityAnswer)
.wait(1327)
.click('input#dcq_submit')
.waitForNextPage()
.catch((err) => { console.log('Encountered an error when filling out the security page.'); throw err; })
} |
JavaScript | function waitForItemToBecomeAvailable(botInfoList) {
/* The bot that will be used to keep polling for item availability */
let localBot = createBotFromBotInfo(botInfoList[0]);
return new Promise(async (resolve, reject) => {
let itemIsReady = false;
let currentBotIndex = 0;
// Loop until the item is available
let lookTries = 0;
while(!itemIsReady) {
try {
itemIsReady = await localBot.lookForItem();
} catch(err) {
console.log(err);
localBot = createBotFromBotInfo(botInfoList[currentBotIndex]);
}
lookTries++;
if((lookTries % 10) == 0) {
console.log('Looked for item ' + lookTries + ' times.');
currentBotIndex = (currentBotIndex + 1) % botInfoList.length;
localBot = createBotFromBotInfo(botInfoList[currentBotIndex]);
}
if(!itemIsReady){
await delay(15833);
}
}
if(itemIsReady) {
console.log('ITEM IS READY TO BUY!');
buyPromises = [];
for(i = 0; i < botInfoList.length; i++) {
buyPromises.push(buyItem(botInfoList[i]));
}
await Promise.all(buyPromises);
}
resolve(itemIsReady);
});
} | function waitForItemToBecomeAvailable(botInfoList) {
/* The bot that will be used to keep polling for item availability */
let localBot = createBotFromBotInfo(botInfoList[0]);
return new Promise(async (resolve, reject) => {
let itemIsReady = false;
let currentBotIndex = 0;
// Loop until the item is available
let lookTries = 0;
while(!itemIsReady) {
try {
itemIsReady = await localBot.lookForItem();
} catch(err) {
console.log(err);
localBot = createBotFromBotInfo(botInfoList[currentBotIndex]);
}
lookTries++;
if((lookTries % 10) == 0) {
console.log('Looked for item ' + lookTries + ' times.');
currentBotIndex = (currentBotIndex + 1) % botInfoList.length;
localBot = createBotFromBotInfo(botInfoList[currentBotIndex]);
}
if(!itemIsReady){
await delay(15833);
}
}
if(itemIsReady) {
console.log('ITEM IS READY TO BUY!');
buyPromises = [];
for(i = 0; i < botInfoList.length; i++) {
buyPromises.push(buyItem(botInfoList[i]));
}
await Promise.all(buyPromises);
}
resolve(itemIsReady);
});
} |
JavaScript | function buyItem(botInfo) {
let localBot = createBotFromBotInfo(botInfo);
return new Promise(async (resolve, reject) => {
let loggedIn = false;
let addedToCart = false;
let checkedOut = false;
let currentBotIndex = 0;
// Login
while(!loggedIn) {
try {
loggedIn = await localBot.login();
} catch(err) {
console.log(err);
localBot = createBotFromBotInfo(botInfo);
}
if(!loggedIn)
{
await delay(2000);
}
}
// Add the item to cart if logged in
if(loggedIn) {
console.log('Logged in.');
await delay(5270);
while(!addedToCart)
{
try {
addedToCart = await localBot.addItem();
} catch(err) {
console.log(err);
}
if(!addedToCart) {
await delay(2000);
}
}
}
// Checkout if the item was successfully added to the cart
if(addedToCart) {
console.log('Added item to cart.');
await delay(4161);
while(!checkedOut) {
try {
checkedOut = await localBot.checkout();
} catch(err) {
console.log(err);
}
if(!checkedOut) {
await delay(2000);
}
}
}
if(checkedOut) {
console.log('Successfully bought the item!');
try {
await localBot.logout();
console.log('Logged out.');
} catch(err) {
console.log(err);
}
}
resolve(checkedOut);
});
} | function buyItem(botInfo) {
let localBot = createBotFromBotInfo(botInfo);
return new Promise(async (resolve, reject) => {
let loggedIn = false;
let addedToCart = false;
let checkedOut = false;
let currentBotIndex = 0;
// Login
while(!loggedIn) {
try {
loggedIn = await localBot.login();
} catch(err) {
console.log(err);
localBot = createBotFromBotInfo(botInfo);
}
if(!loggedIn)
{
await delay(2000);
}
}
// Add the item to cart if logged in
if(loggedIn) {
console.log('Logged in.');
await delay(5270);
while(!addedToCart)
{
try {
addedToCart = await localBot.addItem();
} catch(err) {
console.log(err);
}
if(!addedToCart) {
await delay(2000);
}
}
}
// Checkout if the item was successfully added to the cart
if(addedToCart) {
console.log('Added item to cart.');
await delay(4161);
while(!checkedOut) {
try {
checkedOut = await localBot.checkout();
} catch(err) {
console.log(err);
}
if(!checkedOut) {
await delay(2000);
}
}
}
if(checkedOut) {
console.log('Successfully bought the item!');
try {
await localBot.logout();
console.log('Logged out.');
} catch(err) {
console.log(err);
}
}
resolve(checkedOut);
});
} |
JavaScript | function _needToIndexDocument(doc) {
var docInfo = _documentMap.get(doc);
// lastmodtime is not changed when undo is invoked.
// so we will use the generation count to determine if the document has changed
if ((docInfo) && (docInfo.generation === doc.history.generation)) {
// document has not changed since we indexed
return false;
}
return true;
} | function _needToIndexDocument(doc) {
var docInfo = _documentMap.get(doc);
// lastmodtime is not changed when undo is invoked.
// so we will use the generation count to determine if the document has changed
if ((docInfo) && (docInfo.generation === doc.history.generation)) {
// document has not changed since we indexed
return false;
}
return true;
} |
JavaScript | function _createLineCharacterCountIndex(text, lineSeparator) {
var lineNumber;
console.time('_createLineCharacterCountIndex');
// splitting is actually faster than using doc.getLine()
var lines = text.split(lineSeparator);
var lineSeparatorLength = lineSeparator.length;
var lineCharacterCountIndex = new Uint32Array(lines.length);
var lineCount = lines.length;
var totalCharacterCount = 0;
for (lineNumber = 0; lineNumber < lineCount; lineNumber++) {
totalCharacterCount += lines[lineNumber].length + lineSeparatorLength;
lineCharacterCountIndex[lineNumber] = totalCharacterCount;
}
console.timeEnd('_createLineCharacterCountIndex');
return lineCharacterCountIndex;
} | function _createLineCharacterCountIndex(text, lineSeparator) {
var lineNumber;
console.time('_createLineCharacterCountIndex');
// splitting is actually faster than using doc.getLine()
var lines = text.split(lineSeparator);
var lineSeparatorLength = lineSeparator.length;
var lineCharacterCountIndex = new Uint32Array(lines.length);
var lineCount = lines.length;
var totalCharacterCount = 0;
for (lineNumber = 0; lineNumber < lineCount; lineNumber++) {
totalCharacterCount += lines[lineNumber].length + lineSeparatorLength;
lineCharacterCountIndex[lineNumber] = totalCharacterCount;
}
console.timeEnd('_createLineCharacterCountIndex');
return lineCharacterCountIndex;
} |
JavaScript | function _indexDocument(doc) {
var docText = doc.getValue();
var docLineIndex = _createLineCharacterCountIndex(docText, doc.lineSeparator());
_documentMap.set(doc, {text: docText, index: docLineIndex, generation: doc.history.generation});
} | function _indexDocument(doc) {
var docText = doc.getValue();
var docLineIndex = _createLineCharacterCountIndex(docText, doc.lineSeparator());
_documentMap.set(doc, {text: docText, index: docLineIndex, generation: doc.history.generation});
} |
JavaScript | function _convertToRegularExpression(stringOrRegex, ignoreCase) {
if (typeof stringOrRegex === "string") {
return new RegExp(StringUtils.regexEscape(stringOrRegex), ignoreCase ? "igm" : "gm");
} else {
return new RegExp(stringOrRegex.source, ignoreCase ? "igm" : "gm");
}
} | function _convertToRegularExpression(stringOrRegex, ignoreCase) {
if (typeof stringOrRegex === "string") {
return new RegExp(StringUtils.regexEscape(stringOrRegex), ignoreCase ? "igm" : "gm");
} else {
return new RegExp(stringOrRegex.source, ignoreCase ? "igm" : "gm");
}
} |
JavaScript | function _createPosFromIndex(lineCharacterCountIndexArray, startSearchingWithLine, indexWithinDoc) {
var lineNumber;
var lineCount = lineCharacterCountIndexArray.length;
// linear search for line number turns out to be usually faster than binary search
// as matches tend to come relatively close together and we can boost the linear
// search performance using starting position since we often know our progress through the document.
for (lineNumber = startSearchingWithLine; lineNumber < lineCount; lineNumber++) {
// If the total character count at this line is greater than the index
// then the index must be somewhere on this line
if (lineCharacterCountIndexArray[lineNumber] > indexWithinDoc) {
var previousLineEndingCharacterIndex = lineNumber > 0 ? lineCharacterCountIndexArray[lineNumber - 1] : 0;
// create a Pos with the line number and the character offset relative to the beginning of this line
return {line: lineNumber, ch: indexWithinDoc - previousLineEndingCharacterIndex };
}
}
} | function _createPosFromIndex(lineCharacterCountIndexArray, startSearchingWithLine, indexWithinDoc) {
var lineNumber;
var lineCount = lineCharacterCountIndexArray.length;
// linear search for line number turns out to be usually faster than binary search
// as matches tend to come relatively close together and we can boost the linear
// search performance using starting position since we often know our progress through the document.
for (lineNumber = startSearchingWithLine; lineNumber < lineCount; lineNumber++) {
// If the total character count at this line is greater than the index
// then the index must be somewhere on this line
if (lineCharacterCountIndexArray[lineNumber] > indexWithinDoc) {
var previousLineEndingCharacterIndex = lineNumber > 0 ? lineCharacterCountIndexArray[lineNumber - 1] : 0;
// create a Pos with the line number and the character offset relative to the beginning of this line
return {line: lineNumber, ch: indexWithinDoc - previousLineEndingCharacterIndex };
}
}
} |
JavaScript | function _scanDocumentUsingRegularExpression(documentIndex, documentText, regex, fnEachMatch) {
var matchArray;
var lastMatchedLine = 0;
while ((matchArray = regex.exec(documentText)) !== null) {
var startPosition = _createPosFromIndex(documentIndex, lastMatchedLine, matchArray.index);
var endPosition = _createPosFromIndex(documentIndex, startPosition.line, regex.lastIndex);
lastMatchedLine = endPosition.line;
fnEachMatch(startPosition, endPosition, matchArray);
// This is to stop infinite loop. Some regular expressions can return 0 length match
// which will not advance the lastindex property. Ex ".*"
if (matchArray.index === regex.lastIndex) {
regex.lastIndex++;
}
}
} | function _scanDocumentUsingRegularExpression(documentIndex, documentText, regex, fnEachMatch) {
var matchArray;
var lastMatchedLine = 0;
while ((matchArray = regex.exec(documentText)) !== null) {
var startPosition = _createPosFromIndex(documentIndex, lastMatchedLine, matchArray.index);
var endPosition = _createPosFromIndex(documentIndex, startPosition.line, regex.lastIndex);
lastMatchedLine = endPosition.line;
fnEachMatch(startPosition, endPosition, matchArray);
// This is to stop infinite loop. Some regular expressions can return 0 length match
// which will not advance the lastindex property. Ex ".*"
if (matchArray.index === regex.lastIndex) {
regex.lastIndex++;
}
}
} |
JavaScript | function _indexFromPos(lineCharacterCountIndexArray, pos) {
var indexAtStartOfLine = 0;
if (pos.from.line > 0) {
// Start with the sum of the character count at the end of previous line
indexAtStartOfLine = lineCharacterCountIndexArray[pos.from.line - 1];
}
// Add the number of characters offset from the start and return
return indexAtStartOfLine + pos.from.ch;
} | function _indexFromPos(lineCharacterCountIndexArray, pos) {
var indexAtStartOfLine = 0;
if (pos.from.line > 0) {
// Start with the sum of the character count at the end of previous line
indexAtStartOfLine = lineCharacterCountIndexArray[pos.from.line - 1];
}
// Add the number of characters offset from the start and return
return indexAtStartOfLine + pos.from.ch;
} |
JavaScript | function _createSearchResult(docLineIndex, indexStart, indexEnd, startLine) {
if (typeof startLine === 'undefined') {
startLine = 0;
}
var fromPos = _createPosFromIndex(docLineIndex, startLine, indexStart);
var toPos = _createPosFromIndex(docLineIndex, fromPos.line, indexEnd);
return {from: fromPos, to: toPos};
} | function _createSearchResult(docLineIndex, indexStart, indexEnd, startLine) {
if (typeof startLine === 'undefined') {
startLine = 0;
}
var fromPos = _createPosFromIndex(docLineIndex, startLine, indexStart);
var toPos = _createPosFromIndex(docLineIndex, fromPos.line, indexEnd);
return {from: fromPos, to: toPos};
} |
JavaScript | function _compareMatchResultToPos(matchIndex, posIndex) {
if (matchIndex === posIndex) {
return 0;
} else if (matchIndex < posIndex) {
return -1;
} else {
return 1;
}
} | function _compareMatchResultToPos(matchIndex, posIndex) {
if (matchIndex === posIndex) {
return 0;
} else if (matchIndex < posIndex) {
return -1;
} else {
return 1;
}
} |
JavaScript | function _findResultIndexNearPos(regexIndexer, pos, reverse, fnCompare) {
var compare;
console.time("findNext");
var length = regexIndexer.getItemCount();
var upperBound = length - 1;
var lowerBound = 0;
var searchIndex;
while (lowerBound <= upperBound) {
searchIndex = Math.floor((upperBound + lowerBound) / 2);
compare = fnCompare(regexIndexer.getMatchIndexStart(searchIndex), pos);
if (compare === 0) {
console.timeEnd("findNext");
return searchIndex;
} else if (compare === -1) {
lowerBound = searchIndex + 1;
} else {
upperBound = searchIndex - 1;
}
}
console.timeEnd("findNext");
// no exact match, we are at the lower bound
// if going forward return the next index
if ((compare === -1) && (!reverse)) {
searchIndex += 1;
}
// no exact match, we are at the upper bound
// if going reverse return the next lower index
if ((compare === 1) && (reverse)) {
searchIndex -= 1;
}
// If we went beyond the length or start, there was no match and no next index to match
if ((searchIndex < 0) || (searchIndex >= length)) {
return false;
}
// no exact match, we are already at the closest match in the search direction
return searchIndex;
} | function _findResultIndexNearPos(regexIndexer, pos, reverse, fnCompare) {
var compare;
console.time("findNext");
var length = regexIndexer.getItemCount();
var upperBound = length - 1;
var lowerBound = 0;
var searchIndex;
while (lowerBound <= upperBound) {
searchIndex = Math.floor((upperBound + lowerBound) / 2);
compare = fnCompare(regexIndexer.getMatchIndexStart(searchIndex), pos);
if (compare === 0) {
console.timeEnd("findNext");
return searchIndex;
} else if (compare === -1) {
lowerBound = searchIndex + 1;
} else {
upperBound = searchIndex - 1;
}
}
console.timeEnd("findNext");
// no exact match, we are at the lower bound
// if going forward return the next index
if ((compare === -1) && (!reverse)) {
searchIndex += 1;
}
// no exact match, we are at the upper bound
// if going reverse return the next lower index
if ((compare === 1) && (reverse)) {
searchIndex -= 1;
}
// If we went beyond the length or start, there was no match and no next index to match
if ((searchIndex < 0) || (searchIndex >= length)) {
return false;
}
// no exact match, we are already at the closest match in the search direction
return searchIndex;
} |
JavaScript | function _makeGroupArray(array, groupSize) {
var _currentGroupIndex = -groupSize;
_.assign(array, {
nextGroupIndex: function () {
if (_currentGroupIndex < array.length - groupSize) {
_currentGroupIndex += groupSize;
} else {
_currentGroupIndex = -groupSize;
return false;
}
return _currentGroupIndex;
},
prevGroupIndex: function () {
if (_currentGroupIndex - groupSize > -1) {
_currentGroupIndex -= groupSize;
} else {
_currentGroupIndex = -groupSize;
return false;
}
return _currentGroupIndex;
},
setCurrentGroup: function (groupNumber) {_currentGroupIndex = groupNumber * groupSize; },
getGroupIndex: function (groupNumber) { return groupSize * groupNumber; },
getGroupValue: function (groupNumber, valueIndexWithinGroup) {return array[(groupSize * groupNumber) + valueIndexWithinGroup]; },
currentGroupIndex: function () { return _currentGroupIndex; },
currentGroupNumber: function () { return _currentGroupIndex / groupSize; },
groupSize: function () { return groupSize; },
itemCount: function () { return array.length / groupSize; },
});
return array;
} | function _makeGroupArray(array, groupSize) {
var _currentGroupIndex = -groupSize;
_.assign(array, {
nextGroupIndex: function () {
if (_currentGroupIndex < array.length - groupSize) {
_currentGroupIndex += groupSize;
} else {
_currentGroupIndex = -groupSize;
return false;
}
return _currentGroupIndex;
},
prevGroupIndex: function () {
if (_currentGroupIndex - groupSize > -1) {
_currentGroupIndex -= groupSize;
} else {
_currentGroupIndex = -groupSize;
return false;
}
return _currentGroupIndex;
},
setCurrentGroup: function (groupNumber) {_currentGroupIndex = groupNumber * groupSize; },
getGroupIndex: function (groupNumber) { return groupSize * groupNumber; },
getGroupValue: function (groupNumber, valueIndexWithinGroup) {return array[(groupSize * groupNumber) + valueIndexWithinGroup]; },
currentGroupIndex: function () { return _currentGroupIndex; },
currentGroupNumber: function () { return _currentGroupIndex / groupSize; },
groupSize: function () { return groupSize; },
itemCount: function () { return array.length / groupSize; },
});
return array;
} |
JavaScript | function _createRegexIndexer(docText, docLineIndex, query) {
// Start and End index of each match stored in array as:
// [0] = start index of first match
// [1] = end index of first match
// ...
// Each pair of start and end is considered a group when using the group array
var _startEndIndexArray = _makeGroupArray([], 2);
function nextMatch() {
var currentMatchIndex = _startEndIndexArray.nextGroupIndex();
if (currentMatchIndex === false) {
return false;
}
// TODO potentially could be optimized if we could pass in the prev match line for starting search
// However, seems very fast already for current use case
return _createSearchResult(docLineIndex, _startEndIndexArray[currentMatchIndex], _startEndIndexArray[currentMatchIndex + 1]);
}
function prevMatch() {
var currentMatchIndex = _startEndIndexArray.prevGroupIndex();
if (currentMatchIndex === false) {
return false;
}
return _createSearchResult(docLineIndex, _startEndIndexArray[currentMatchIndex], _startEndIndexArray[currentMatchIndex + 1]);
}
function getItemByMatchNumber(matchNumber) {
var groupIndex = _startEndIndexArray.getGroupIndex(matchNumber);
return _createSearchResult(docLineIndex, _startEndIndexArray[groupIndex], _startEndIndexArray[groupIndex + 1]);
}
function forEachMatch(fnMatch) {
var index;
var length = _startEndIndexArray.itemCount();
var lastLine = 0;
for (index = 0; index < length; index++) {
var groupIndex = _startEndIndexArray.getGroupIndex(index);
var fromPos = _createPosFromIndex(docLineIndex, lastLine, _startEndIndexArray[groupIndex]);
var toPos = _createPosFromIndex(docLineIndex, fromPos.line, _startEndIndexArray[groupIndex + 1]);
lastLine = toPos.line;
fnMatch(fromPos, toPos);
}
}
function getItemCount() {
return _startEndIndexArray.itemCount();
}
function getCurrentMatch() {
var currentMatchIndex = _startEndIndexArray.currentGroupIndex();
if (currentMatchIndex > -1) {
return _createSearchResult(docLineIndex, _startEndIndexArray[currentMatchIndex], _startEndIndexArray[currentMatchIndex + 1]);
}
}
function getMatchIndexStart(matchNumber) {
return _startEndIndexArray.getGroupValue(matchNumber, 0);
}
function getMatchIndexEnd(matchNumber) {
return _startEndIndexArray.getGroupValue(matchNumber, 1);
}
function setCurrentMatchNumber(number) {
_startEndIndexArray.setCurrentGroup(number);
}
function getCurrentMatchNumber() {
return _startEndIndexArray.currentGroupNumber();
}
function getFullResultInfo(matchNumber, query, docText) {
var groupIndex = _startEndIndexArray.getGroupIndex(matchNumber);
query.lastIndex = _startEndIndexArray[groupIndex];
var matchInfo = query.exec(docText);
var currentMatch = getCurrentMatch();
currentMatch.match = matchInfo;
return currentMatch;
}
function _createSearchResults(docText, query) {
console.time("exec");
var matchArray;
var index = 0;
while ((matchArray = query.exec(docText)) !== null) {
_startEndIndexArray[index++] = matchArray.index;
_startEndIndexArray[index++] = query.lastIndex;
// This is to stop infinite loop. Some regular expressions can return 0 length match
// which will not advance the lastindex property. Ex ".*"
if (matchArray.index === query.lastIndex) {
query.lastIndex++;
}
}
console.timeEnd("exec");
return _startEndIndexArray;
}
_createSearchResults(docText, query);
return {nextMatch : nextMatch,
prevMatch : prevMatch,
getItemByMatchNumber : getItemByMatchNumber,
getItemCount : getItemCount,
getCurrentMatch : getCurrentMatch,
setCurrentMatchNumber : setCurrentMatchNumber,
getMatchIndexStart : getMatchIndexStart,
getMatchIndexEnd : getMatchIndexEnd,
getCurrentMatchNumber : getCurrentMatchNumber,
getFullResultInfo : getFullResultInfo,
forEachMatch : forEachMatch
};
} | function _createRegexIndexer(docText, docLineIndex, query) {
// Start and End index of each match stored in array as:
// [0] = start index of first match
// [1] = end index of first match
// ...
// Each pair of start and end is considered a group when using the group array
var _startEndIndexArray = _makeGroupArray([], 2);
function nextMatch() {
var currentMatchIndex = _startEndIndexArray.nextGroupIndex();
if (currentMatchIndex === false) {
return false;
}
// TODO potentially could be optimized if we could pass in the prev match line for starting search
// However, seems very fast already for current use case
return _createSearchResult(docLineIndex, _startEndIndexArray[currentMatchIndex], _startEndIndexArray[currentMatchIndex + 1]);
}
function prevMatch() {
var currentMatchIndex = _startEndIndexArray.prevGroupIndex();
if (currentMatchIndex === false) {
return false;
}
return _createSearchResult(docLineIndex, _startEndIndexArray[currentMatchIndex], _startEndIndexArray[currentMatchIndex + 1]);
}
function getItemByMatchNumber(matchNumber) {
var groupIndex = _startEndIndexArray.getGroupIndex(matchNumber);
return _createSearchResult(docLineIndex, _startEndIndexArray[groupIndex], _startEndIndexArray[groupIndex + 1]);
}
function forEachMatch(fnMatch) {
var index;
var length = _startEndIndexArray.itemCount();
var lastLine = 0;
for (index = 0; index < length; index++) {
var groupIndex = _startEndIndexArray.getGroupIndex(index);
var fromPos = _createPosFromIndex(docLineIndex, lastLine, _startEndIndexArray[groupIndex]);
var toPos = _createPosFromIndex(docLineIndex, fromPos.line, _startEndIndexArray[groupIndex + 1]);
lastLine = toPos.line;
fnMatch(fromPos, toPos);
}
}
function getItemCount() {
return _startEndIndexArray.itemCount();
}
function getCurrentMatch() {
var currentMatchIndex = _startEndIndexArray.currentGroupIndex();
if (currentMatchIndex > -1) {
return _createSearchResult(docLineIndex, _startEndIndexArray[currentMatchIndex], _startEndIndexArray[currentMatchIndex + 1]);
}
}
function getMatchIndexStart(matchNumber) {
return _startEndIndexArray.getGroupValue(matchNumber, 0);
}
function getMatchIndexEnd(matchNumber) {
return _startEndIndexArray.getGroupValue(matchNumber, 1);
}
function setCurrentMatchNumber(number) {
_startEndIndexArray.setCurrentGroup(number);
}
function getCurrentMatchNumber() {
return _startEndIndexArray.currentGroupNumber();
}
function getFullResultInfo(matchNumber, query, docText) {
var groupIndex = _startEndIndexArray.getGroupIndex(matchNumber);
query.lastIndex = _startEndIndexArray[groupIndex];
var matchInfo = query.exec(docText);
var currentMatch = getCurrentMatch();
currentMatch.match = matchInfo;
return currentMatch;
}
function _createSearchResults(docText, query) {
console.time("exec");
var matchArray;
var index = 0;
while ((matchArray = query.exec(docText)) !== null) {
_startEndIndexArray[index++] = matchArray.index;
_startEndIndexArray[index++] = query.lastIndex;
// This is to stop infinite loop. Some regular expressions can return 0 length match
// which will not advance the lastindex property. Ex ".*"
if (matchArray.index === query.lastIndex) {
query.lastIndex++;
}
}
console.timeEnd("exec");
return _startEndIndexArray;
}
_createSearchResults(docText, query);
return {nextMatch : nextMatch,
prevMatch : prevMatch,
getItemByMatchNumber : getItemByMatchNumber,
getItemCount : getItemCount,
getCurrentMatch : getCurrentMatch,
setCurrentMatchNumber : setCurrentMatchNumber,
getMatchIndexStart : getMatchIndexStart,
getMatchIndexEnd : getMatchIndexEnd,
getCurrentMatchNumber : getCurrentMatchNumber,
getFullResultInfo : getFullResultInfo,
forEachMatch : forEachMatch
};
} |
JavaScript | function _createCursor() {
function _findNext(cursor) {
var match = cursor.regexIndexer.nextMatch();
if (!match) {
cursor.atOccurrence = false;
cursor.currentMatch = {line: cursor.doc.lineCount(), ch: 0};
return false;
}
return match;
}
function _findPrevious(cursor) {
var match = cursor.regexIndexer.prevMatch();
if (!match) {
cursor.atOccurrence = false;
cursor.currentMatch = {line: 0, ch: 0};
return false;
}
return match;
}
function _updateResultsIfNeeded(cursor) {
if (_needToIndexDocument(cursor.doc)) {
_indexDocument(cursor.doc);
cursor.resultsCurrent = false;
}
if (!cursor.resultsCurrent) {
cursor.scanDocumentAndStoreResultsInCursor();
}
}
function _setQuery(cursor, query) {
var newRegexQuery = _convertToRegularExpression(query, cursor.ignoreCase);
if ((cursor.query) && (cursor.query.source !== newRegexQuery.source)) {
// query has changed
cursor.resultsCurrent = false;
}
cursor.query = newRegexQuery;
}
/**
* Set the location of where the search cursor should be located
* @param {!Object} cursor The search cursor
* @param {!{line: number, ch: number}} pos The search cursor location
*/
function _setPos(cursor, pos) {
pos = pos || {line: 0, ch: 0};
cursor.currentMatch = {from: pos, to: pos};
}
// Return all public functions for the cursor
return _.assign(Object.create(null), {
/**
* Set or update the document and query properties
* @param {!{document: CodeMirror.Doc, searchQuery: string|RegExp, position: {line: number, ch: number}, ignoreCase: boolean}} properties
*/
setSearchDocumentAndQuery: function (properties) {
this.atOccurrence = false;
if (properties.ignoreCase) {this.ignoreCase = properties.ignoreCase; }
if (properties.document) {this.doc = properties.document; }
if (properties.searchQuery) {_setQuery(this, properties.searchQuery); }
if (properties.position) {_setPos(this, properties.position); }
},
/**
* Get the total number of characters in the document
* @return {number}
*/
getDocCharacterCount: function () {
_updateResultsIfNeeded(this);
var docLineIndex = _getDocumentIndex(this.doc);
return docLineIndex[docLineIndex.length - 1];
},
/**
* Get the total number of matches
* @return {number}
*/
getMatchCount: function () {
_updateResultsIfNeeded(this);
return this.regexIndexer.getItemCount();
},
/**
* Get the current match number counting from the first match.
* @return {number}
*/
getCurrentMatchNumber: function () {
_updateResultsIfNeeded(this);
return this.regexIndexer.getCurrentMatchNumber();
},
/**
* Find the next match in the indicated search direction
* @param {boolean} reverse true searches backwards. false searches forwards
* @return {{to: {line: number, ch: number}, from: {line: number, ch: number}}}
*/
find: function (reverse) {
_updateResultsIfNeeded(this);
var foundPosition;
if (!this.regexIndexer.getCurrentMatch()) {
// There is currently no match position
// This is our first time or we hit the top or end of document using next or prev
var docLineIndex = _getDocumentIndex(this.doc);
var matchIndex = _findResultIndexNearPos(this.regexIndexer, _indexFromPos(docLineIndex, this.currentMatch), reverse, _compareMatchResultToPos);
if (matchIndex) {
this.regexIndexer.setCurrentMatchNumber(matchIndex);
foundPosition = this.regexIndexer.getCurrentMatch();
}
}
if (!foundPosition) {
foundPosition = reverse ? _findPrevious(this) : _findNext(this);
}
if (foundPosition) {
this.currentMatch = foundPosition;
this.atOccurrence = !(!foundPosition);
}
return foundPosition;
},
/**
* Iterate over each result from searching the document calling the function with the start and end positions of each match
* @param {function({line: number, ch: number}, {line: number, ch: number})} fnResult
*/
forEachMatch: function (fnResult) {
_updateResultsIfNeeded(this);
this.regexIndexer.forEachMatch(fnResult);
},
/**
* Get the start and end positions plus the regular expression match array data
* @return {{to: {line: number, ch: number}, from: {line: number, ch: number}, match: Array}} returns start and end of match with the array of results
*/
getFullInfoForCurrentMatch: function () {
var docText = _getDocumentText(this.doc);
return this.regexIndexer.getFullResultInfo(this.regexIndexer.getCurrentMatchNumber(), this.query, docText);
},
/**
* Find the indexes of all matches based on the current search query
* The matches can then be navigated and retrieved using the functions of the search cursor.
*
* @return {number} the count of matches found.
*/
scanDocumentAndStoreResultsInCursor: function () {
if (_needToIndexDocument(this.doc)) {
_indexDocument(this.doc);
}
var docText = _getDocumentText(this.doc);
var docLineIndex = _getDocumentIndex(this.doc);
this.regexIndexer = _createRegexIndexer(docText, docLineIndex, this.query);
this.resultsCurrent = true;
return this.getMatchCount();
}
});
} | function _createCursor() {
function _findNext(cursor) {
var match = cursor.regexIndexer.nextMatch();
if (!match) {
cursor.atOccurrence = false;
cursor.currentMatch = {line: cursor.doc.lineCount(), ch: 0};
return false;
}
return match;
}
function _findPrevious(cursor) {
var match = cursor.regexIndexer.prevMatch();
if (!match) {
cursor.atOccurrence = false;
cursor.currentMatch = {line: 0, ch: 0};
return false;
}
return match;
}
function _updateResultsIfNeeded(cursor) {
if (_needToIndexDocument(cursor.doc)) {
_indexDocument(cursor.doc);
cursor.resultsCurrent = false;
}
if (!cursor.resultsCurrent) {
cursor.scanDocumentAndStoreResultsInCursor();
}
}
function _setQuery(cursor, query) {
var newRegexQuery = _convertToRegularExpression(query, cursor.ignoreCase);
if ((cursor.query) && (cursor.query.source !== newRegexQuery.source)) {
// query has changed
cursor.resultsCurrent = false;
}
cursor.query = newRegexQuery;
}
/**
* Set the location of where the search cursor should be located
* @param {!Object} cursor The search cursor
* @param {!{line: number, ch: number}} pos The search cursor location
*/
function _setPos(cursor, pos) {
pos = pos || {line: 0, ch: 0};
cursor.currentMatch = {from: pos, to: pos};
}
// Return all public functions for the cursor
return _.assign(Object.create(null), {
/**
* Set or update the document and query properties
* @param {!{document: CodeMirror.Doc, searchQuery: string|RegExp, position: {line: number, ch: number}, ignoreCase: boolean}} properties
*/
setSearchDocumentAndQuery: function (properties) {
this.atOccurrence = false;
if (properties.ignoreCase) {this.ignoreCase = properties.ignoreCase; }
if (properties.document) {this.doc = properties.document; }
if (properties.searchQuery) {_setQuery(this, properties.searchQuery); }
if (properties.position) {_setPos(this, properties.position); }
},
/**
* Get the total number of characters in the document
* @return {number}
*/
getDocCharacterCount: function () {
_updateResultsIfNeeded(this);
var docLineIndex = _getDocumentIndex(this.doc);
return docLineIndex[docLineIndex.length - 1];
},
/**
* Get the total number of matches
* @return {number}
*/
getMatchCount: function () {
_updateResultsIfNeeded(this);
return this.regexIndexer.getItemCount();
},
/**
* Get the current match number counting from the first match.
* @return {number}
*/
getCurrentMatchNumber: function () {
_updateResultsIfNeeded(this);
return this.regexIndexer.getCurrentMatchNumber();
},
/**
* Find the next match in the indicated search direction
* @param {boolean} reverse true searches backwards. false searches forwards
* @return {{to: {line: number, ch: number}, from: {line: number, ch: number}}}
*/
find: function (reverse) {
_updateResultsIfNeeded(this);
var foundPosition;
if (!this.regexIndexer.getCurrentMatch()) {
// There is currently no match position
// This is our first time or we hit the top or end of document using next or prev
var docLineIndex = _getDocumentIndex(this.doc);
var matchIndex = _findResultIndexNearPos(this.regexIndexer, _indexFromPos(docLineIndex, this.currentMatch), reverse, _compareMatchResultToPos);
if (matchIndex) {
this.regexIndexer.setCurrentMatchNumber(matchIndex);
foundPosition = this.regexIndexer.getCurrentMatch();
}
}
if (!foundPosition) {
foundPosition = reverse ? _findPrevious(this) : _findNext(this);
}
if (foundPosition) {
this.currentMatch = foundPosition;
this.atOccurrence = !(!foundPosition);
}
return foundPosition;
},
/**
* Iterate over each result from searching the document calling the function with the start and end positions of each match
* @param {function({line: number, ch: number}, {line: number, ch: number})} fnResult
*/
forEachMatch: function (fnResult) {
_updateResultsIfNeeded(this);
this.regexIndexer.forEachMatch(fnResult);
},
/**
* Get the start and end positions plus the regular expression match array data
* @return {{to: {line: number, ch: number}, from: {line: number, ch: number}, match: Array}} returns start and end of match with the array of results
*/
getFullInfoForCurrentMatch: function () {
var docText = _getDocumentText(this.doc);
return this.regexIndexer.getFullResultInfo(this.regexIndexer.getCurrentMatchNumber(), this.query, docText);
},
/**
* Find the indexes of all matches based on the current search query
* The matches can then be navigated and retrieved using the functions of the search cursor.
*
* @return {number} the count of matches found.
*/
scanDocumentAndStoreResultsInCursor: function () {
if (_needToIndexDocument(this.doc)) {
_indexDocument(this.doc);
}
var docText = _getDocumentText(this.doc);
var docLineIndex = _getDocumentIndex(this.doc);
this.regexIndexer = _createRegexIndexer(docText, docLineIndex, this.query);
this.resultsCurrent = true;
return this.getMatchCount();
}
});
} |
JavaScript | function createSearchCursor(properties) {
console.log("creating new search cursor");
var searchCursor = _createCursor();
searchCursor.setSearchDocumentAndQuery(properties);
return searchCursor;
} | function createSearchCursor(properties) {
console.log("creating new search cursor");
var searchCursor = _createCursor();
searchCursor.setSearchDocumentAndQuery(properties);
return searchCursor;
} |
JavaScript | function scanDocumentForMatches(properties) {
if (_needToIndexDocument(properties.document)) {
_indexDocument(properties.document);
}
var regex = _convertToRegularExpression(properties.searchQuery, properties.ignoreCase);
_scanDocumentUsingRegularExpression(_getDocumentIndex(properties.document), _getDocumentText(properties.document), regex, properties.fnEachMatch);
} | function scanDocumentForMatches(properties) {
if (_needToIndexDocument(properties.document)) {
_indexDocument(properties.document);
}
var regex = _convertToRegularExpression(properties.searchQuery, properties.ignoreCase);
_scanDocumentUsingRegularExpression(_getDocumentIndex(properties.document), _getDocumentText(properties.document), regex, properties.fnEachMatch);
} |
JavaScript | function delete_auxiliar(ID_Componente) {
for(item in $scope.lista_componentes){
if($scope.lista_componentes[item].ID_Componente == ID_Componente){
$scope.lista_componentes.splice(item,1);
}
}
} | function delete_auxiliar(ID_Componente) {
for(item in $scope.lista_componentes){
if($scope.lista_componentes[item].ID_Componente == ID_Componente){
$scope.lista_componentes.splice(item,1);
}
}
} |
JavaScript | function delete_auxiliar(ID_CYA) {
for(item in $scope.lista_cye_ajustados){
if($scope.lista_cye_ajustados[item].ID == ID_CYA){
$scope.lista_cye_ajustados.splice(item,1);
}
}
} | function delete_auxiliar(ID_CYA) {
for(item in $scope.lista_cye_ajustados){
if($scope.lista_cye_ajustados[item].ID == ID_CYA){
$scope.lista_cye_ajustados.splice(item,1);
}
}
} |
JavaScript | function existResponsable(Responsable) {
for(item in $scope.lista_responsables_seleccionados){
if($scope.lista_responsables_seleccionados[item].Responsable == Responsable)return true;
}
return false;
} | function existResponsable(Responsable) {
for(item in $scope.lista_responsables_seleccionados){
if($scope.lista_responsables_seleccionados[item].Responsable == Responsable)return true;
}
return false;
} |
JavaScript | function delete_auxiliar(ID_CYE) {
for(item in $scope.lista_criterios_y_estandares){
if($scope.lista_criterios_y_estandares[item].ID_CYE == ID_CYE){
$scope.lista_criterios_y_estandares.splice(item,1);
return;
}
}
} | function delete_auxiliar(ID_CYE) {
for(item in $scope.lista_criterios_y_estandares){
if($scope.lista_criterios_y_estandares[item].ID_CYE == ID_CYE){
$scope.lista_criterios_y_estandares.splice(item,1);
return;
}
}
} |
JavaScript | function renameFiles(names) {
const newNames = [];
const n = 1;
names.forEach((currentName) => {
let newCurrentName = currentName;
if (newNames.includes(currentName)) {
newCurrentName = `${currentName}(${n})`;
if (newNames.includes(newCurrentName)) {
newCurrentName = `${currentName}(${n + 1})`;
}
}
newNames.push(newCurrentName);
});
return (newNames);
} | function renameFiles(names) {
const newNames = [];
const n = 1;
names.forEach((currentName) => {
let newCurrentName = currentName;
if (newNames.includes(currentName)) {
newCurrentName = `${currentName}(${n})`;
if (newNames.includes(newCurrentName)) {
newCurrentName = `${currentName}(${n + 1})`;
}
}
newNames.push(newCurrentName);
});
return (newNames);
} |
JavaScript | function visible( element ) {
var visibility = element.css( "visibility" );
while ( visibility === "inherit" ) {
element = element.parent();
visibility = element.css( "visibility" );
}
return visibility !== "hidden";
} | function visible( element ) {
var visibility = element.css( "visibility" );
while ( visibility === "inherit" ) {
element = element.parent();
visibility = element.css( "visibility" );
}
return visibility !== "hidden";
} |
JavaScript | function Datepicker() {
this._curInst = null; // The current instance in use
this._keyEvent = false; // If the last event was a key event
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
this._appendClass = "ui-datepicker-append"; // The name of the append marker class
this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[ "" ] = { // Default regional settings
closeText: "Done", // Display text for close link
prevText: "Prev", // Display text for previous month link
nextText: "Next", // Display text for next month link
currentText: "Today", // Display text for current month link
monthNames: [ "January","February","March","April","May","June",
"July","August","September","October","November","December" ], // Names of months for drop-down and formatting
monthNamesShort: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], // For formatting
dayNames: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], // For formatting
dayNamesShort: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], // For formatting
dayNamesMin: [ "Su","Mo","Tu","We","Th","Fr","Sa" ], // Column headings for days starting at Sunday
weekHeader: "Wk", // Column header for week of the year
dateFormat: "mm/dd/yy", // See format options on parseDate
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
isRTL: false, // True if right-to-left language, false if left-to-right
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearSuffix: "" // Additional text to append to the year in the month headers
};
this._defaults = { // Global defaults for all the date picker instances
showOn: "focus", // "focus" for popup on focus,
// "button" for trigger button, or "both" for either
showAnim: "fadeIn", // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
appendText: "", // Display text following the input box, e.g. showing the format
buttonText: "...", // Text for trigger button
buttonImage: "", // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
gotoCurrent: false, // True if today link goes back to current selection instead
changeMonth: false, // True if month can be selected directly, false if only prev/next
changeYear: false, // True if year can be selected directly, false if only prev/next
yearRange: "c-10:c+10", // Range of years to display in drop-down,
// either relative to today's year (-nn:+nn), relative to currently displayed year
// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
showOtherMonths: false, // True to show dates in other months, false to leave blank
selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
showWeek: false, // True to show week of the year, false to not show it
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: "+10", // Short year values < this are in the current century,
// > this are in the previous century,
// string value starting with "+" for current year + value
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
duration: "fast", // Duration of display/closure
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
// [2] = cell title (optional), e.g. $.datepicker.noWeekends
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onChangeMonthYear: null, // Define a callback function when the month or year is changed
onClose: null, // Define a callback function when the datepicker is closed
numberOfMonths: 1, // Number of months to show at a time
showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
stepMonths: 1, // Number of months to step back/forward
stepBigMonths: 12, // Number of months to step back/forward for the big links
altField: "", // Selector for an alternate field to store selected dates into
altFormat: "", // The date format to use for the alternate field
constrainInput: true, // The input is constrained by the current date format
showButtonPanel: false, // True to show button panel, false to not show it
autoSize: false, // True to size the input for the date format, false to leave as is
disabled: false // The initial disabled state
};
$.extend( this._defaults, this.regional[ "" ] );
this.regional.en = $.extend( true, {}, this.regional[ "" ] );
this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
this.dpDiv = datepicker_bindHover( $( "<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>" ) );
} | function Datepicker() {
this._curInst = null; // The current instance in use
this._keyEvent = false; // If the last event was a key event
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
this._appendClass = "ui-datepicker-append"; // The name of the append marker class
this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[ "" ] = { // Default regional settings
closeText: "Done", // Display text for close link
prevText: "Prev", // Display text for previous month link
nextText: "Next", // Display text for next month link
currentText: "Today", // Display text for current month link
monthNames: [ "January","February","March","April","May","June",
"July","August","September","October","November","December" ], // Names of months for drop-down and formatting
monthNamesShort: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], // For formatting
dayNames: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], // For formatting
dayNamesShort: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], // For formatting
dayNamesMin: [ "Su","Mo","Tu","We","Th","Fr","Sa" ], // Column headings for days starting at Sunday
weekHeader: "Wk", // Column header for week of the year
dateFormat: "mm/dd/yy", // See format options on parseDate
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
isRTL: false, // True if right-to-left language, false if left-to-right
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearSuffix: "" // Additional text to append to the year in the month headers
};
this._defaults = { // Global defaults for all the date picker instances
showOn: "focus", // "focus" for popup on focus,
// "button" for trigger button, or "both" for either
showAnim: "fadeIn", // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
appendText: "", // Display text following the input box, e.g. showing the format
buttonText: "...", // Text for trigger button
buttonImage: "", // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
gotoCurrent: false, // True if today link goes back to current selection instead
changeMonth: false, // True if month can be selected directly, false if only prev/next
changeYear: false, // True if year can be selected directly, false if only prev/next
yearRange: "c-10:c+10", // Range of years to display in drop-down,
// either relative to today's year (-nn:+nn), relative to currently displayed year
// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
showOtherMonths: false, // True to show dates in other months, false to leave blank
selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
showWeek: false, // True to show week of the year, false to not show it
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: "+10", // Short year values < this are in the current century,
// > this are in the previous century,
// string value starting with "+" for current year + value
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
duration: "fast", // Duration of display/closure
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
// [2] = cell title (optional), e.g. $.datepicker.noWeekends
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onChangeMonthYear: null, // Define a callback function when the month or year is changed
onClose: null, // Define a callback function when the datepicker is closed
numberOfMonths: 1, // Number of months to show at a time
showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
stepMonths: 1, // Number of months to step back/forward
stepBigMonths: 12, // Number of months to step back/forward for the big links
altField: "", // Selector for an alternate field to store selected dates into
altFormat: "", // The date format to use for the alternate field
constrainInput: true, // The input is constrained by the current date format
showButtonPanel: false, // True to show button panel, false to not show it
autoSize: false, // True to size the input for the date format, false to leave as is
disabled: false // The initial disabled state
};
$.extend( this._defaults, this.regional[ "" ] );
this.regional.en = $.extend( true, {}, this.regional[ "" ] );
this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
this.dpDiv = datepicker_bindHover( $( "<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>" ) );
} |
JavaScript | function datepicker_bindHover( dpDiv ) {
var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
return dpDiv.on( "mouseout", selector, function() {
$( this ).removeClass( "ui-state-hover" );
if ( this.className.indexOf( "ui-datepicker-prev" ) !== -1 ) {
$( this ).removeClass( "ui-datepicker-prev-hover" );
}
if ( this.className.indexOf( "ui-datepicker-next" ) !== -1 ) {
$( this ).removeClass( "ui-datepicker-next-hover" );
}
} )
.on( "mouseover", selector, datepicker_handleMouseover );
} | function datepicker_bindHover( dpDiv ) {
var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
return dpDiv.on( "mouseout", selector, function() {
$( this ).removeClass( "ui-state-hover" );
if ( this.className.indexOf( "ui-datepicker-prev" ) !== -1 ) {
$( this ).removeClass( "ui-datepicker-prev-hover" );
}
if ( this.className.indexOf( "ui-datepicker-next" ) !== -1 ) {
$( this ).removeClass( "ui-datepicker-next-hover" );
}
} )
.on( "mouseover", selector, datepicker_handleMouseover );
} |
JavaScript | function makeUtcWrapper(d) {
function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
sourceObj[sourceMethod] = function() {
return targetObj[targetMethod].apply(targetObj, arguments);
};
}
var utc = {
date: d
};
// support strftime, if found
if (d.strftime != undefined) {
addProxyMethod(utc, "strftime", d, "strftime");
}
addProxyMethod(utc, "getTime", d, "getTime");
addProxyMethod(utc, "setTime", d, "setTime");
var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];
for (var p = 0; p < props.length; p++) {
addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
}
return utc;
} | function makeUtcWrapper(d) {
function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
sourceObj[sourceMethod] = function() {
return targetObj[targetMethod].apply(targetObj, arguments);
};
}
var utc = {
date: d
};
// support strftime, if found
if (d.strftime != undefined) {
addProxyMethod(utc, "strftime", d, "strftime");
}
addProxyMethod(utc, "getTime", d, "getTime");
addProxyMethod(utc, "setTime", d, "setTime");
var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];
for (var p = 0; p < props.length; p++) {
addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
}
return utc;
} |
JavaScript | logout(req, res) {
req.logout()
// mark the user as logged out for auth purposes
if (req.session)
req.session.authenticated = false
res.json({flag: true, data: '', message: 'Logout successfully'});
} | logout(req, res) {
req.logout()
// mark the user as logged out for auth purposes
if (req.session)
req.session.authenticated = false
res.json({flag: true, data: '', message: 'Logout successfully'});
} |
JavaScript | function people(req, res) {
var columns = res.locals.options.columns || ["name", "phone", "email", "created"],
delimiter = res.locals.options.delimiter,
date = null,
parts = res.locals.data.split(' ');
//parse well known time frames or default to a
if (parts[1] === 'last') { //last week
date = moment().subtract(1, 'week').format('YYYY-MM-DD');
} else if (parts[1] === 'yesterday') {
date = moment().subtract(1, 'day').format('YYYY-MM-DD');
} else if (parts[1] === 'two') { //two weeks ago
date = moment().subtract(2, 'week').format('YYYY-MM-DD');
} else if (res.locals.data) {
date = moment().subtract(parts[1], parts[2]).format('YYYY-MM-DD');
} else {
//this should not happen
}
peopleModel.since({
date: date
}).then(function(people) {
people = _.filter(people, function(person) { //filter out updates of existing records
return moment(person.created) > moment(date); //only get people created after the user's requested date
});
var output = _.map(_.sortBy(people, 'name'), function(person) { //sort by name and then convert objects into an array of strings
return person.toString(columns, delimiter);
}).join(res.locals.options.break); //convert the array of strings into a string
res.send(output || "Couldn't find anyone since then");
});
} | function people(req, res) {
var columns = res.locals.options.columns || ["name", "phone", "email", "created"],
delimiter = res.locals.options.delimiter,
date = null,
parts = res.locals.data.split(' ');
//parse well known time frames or default to a
if (parts[1] === 'last') { //last week
date = moment().subtract(1, 'week').format('YYYY-MM-DD');
} else if (parts[1] === 'yesterday') {
date = moment().subtract(1, 'day').format('YYYY-MM-DD');
} else if (parts[1] === 'two') { //two weeks ago
date = moment().subtract(2, 'week').format('YYYY-MM-DD');
} else if (res.locals.data) {
date = moment().subtract(parts[1], parts[2]).format('YYYY-MM-DD');
} else {
//this should not happen
}
peopleModel.since({
date: date
}).then(function(people) {
people = _.filter(people, function(person) { //filter out updates of existing records
return moment(person.created) > moment(date); //only get people created after the user's requested date
});
var output = _.map(_.sortBy(people, 'name'), function(person) { //sort by name and then convert objects into an array of strings
return person.toString(columns, delimiter);
}).join(res.locals.options.break); //convert the array of strings into a string
res.send(output || "Couldn't find anyone since then");
});
} |
JavaScript | function renderLicenseBadge(license) {
// If there is no license, return an empty string
if (license === "none") {
return "";
}
// If an MIT License is selected, format the URL like this...
else if (license === "MIT License") {
return `[](https://choosealicense.com/licenses/)`;
}
else if (license === "Apache License 2.0") {
return `[](https://choosealicense.com/licenses/)`;
}
// If one of the other licenses is selected, format the URL like this...
return `[](https://choosealicense.com/licenses/)`;
} | function renderLicenseBadge(license) {
// If there is no license, return an empty string
if (license === "none") {
return "";
}
// If an MIT License is selected, format the URL like this...
else if (license === "MIT License") {
return `[](https://choosealicense.com/licenses/)`;
}
else if (license === "Apache License 2.0") {
return `[](https://choosealicense.com/licenses/)`;
}
// If one of the other licenses is selected, format the URL like this...
return `[](https://choosealicense.com/licenses/)`;
} |
JavaScript | function alcargar (){
$("#nuevaEliminacionMaquinaria").hide();
$("#addNewRegistroMaquinariaProyecto").hide();
$(".contenidoDatosNuevosMaquinariaProyecto").hide();
} | function alcargar (){
$("#nuevaEliminacionMaquinaria").hide();
$("#addNewRegistroMaquinariaProyecto").hide();
$(".contenidoDatosNuevosMaquinariaProyecto").hide();
} |
JavaScript | function formatRepo (data) {
if(data.nombre){
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>"+ data.maIdentificacionAlquiler+' '+ data.nombre + " - " + data.alias + "</div>" +
"</div></div>";
}
return markup;
} | function formatRepo (data) {
if(data.nombre){
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>"+ data.maIdentificacionAlquiler+' '+ data.nombre + " - " + data.alias + "</div>" +
"</div></div>";
}
return markup;
} |
JavaScript | function llamarDataTableDatosMantenimiento(){
var idMaqui= $("#idMaquina").val();
var url = Routing.generate('datosmantenimientodata',{idMaquina: idMaqui});
$('#listaDatosMantenimientos').DataTable({
columnDefs: [
{
targets: [0, 1, 2, 3],
className: 'mdl-data-table__cell--non-numeric'
}
],
"pageLength": 10,
"lengthMenu": [20],
"dom": "ftp",
"processing": true,
"ajax": {
"url": url,
"type": 'GET'
},
"columns": [
{"data": "codigo"},
{"data": "nombre"},
{"data": "numeroOriginal"},
{"data": "numeroComercial"}
],
"language": {
"info": "Mostrando página _PAGE_ de _PAGES_",
"infoEmpty": "",
"emptyTable": "<center>No se encontraron registros</center>",
"paginate": {
"next": "Siguiente",
"previous": "Anterior"
},
"processing": "<p>Procesando petición...</p>",
"search": "<p>Buscar registros:</p>",
"lengthMenu": "Mostrar _MENU_ registros"
}
});
} | function llamarDataTableDatosMantenimiento(){
var idMaqui= $("#idMaquina").val();
var url = Routing.generate('datosmantenimientodata',{idMaquina: idMaqui});
$('#listaDatosMantenimientos').DataTable({
columnDefs: [
{
targets: [0, 1, 2, 3],
className: 'mdl-data-table__cell--non-numeric'
}
],
"pageLength": 10,
"lengthMenu": [20],
"dom": "ftp",
"processing": true,
"ajax": {
"url": url,
"type": 'GET'
},
"columns": [
{"data": "codigo"},
{"data": "nombre"},
{"data": "numeroOriginal"},
{"data": "numeroComercial"}
],
"language": {
"info": "Mostrando página _PAGE_ de _PAGES_",
"infoEmpty": "",
"emptyTable": "<center>No se encontraron registros</center>",
"paginate": {
"next": "Siguiente",
"previous": "Anterior"
},
"processing": "<p>Procesando petición...</p>",
"search": "<p>Buscar registros:</p>",
"lengthMenu": "Mostrar _MENU_ registros"
}
});
} |
JavaScript | function llamarDataTableExpedientesMantenimientos(){
var idMaqui= $("#idMaquina").val();
var url = Routing.generate('datosexpedientesmantenimientodata',{idMaquina: idMaqui});
$('#listaExpedienteMantenimientos').DataTable({
columnDefs: [
{
targets: [0, 1, 2,3],
className: 'mdl-data-table__cell--non-numeric'
}
],
"pageLength": 10,
"lengthMenu": [20],
"dom": "ftp",
"processing": true,
// "serverSide": true,
"ajax": {
"url": url,
"type": 'GET'
},
"columns": [
{"data": "id"},
{"data": "fecha"},
{"data": "tipomantenimiento"},
// {"data": "serie"},
{"data": "costo"},
{"data": "proyecto"}
],
"language": {
"info": "Mostrando página _PAGE_ de _PAGES_",
"infoEmpty": "",
"emptyTable": "<center>No se encontraron registros</center>",
"paginate": {
"next": "Siguiente",
"previous": "Anterior"
},
"processing": "<p>Procesando petición...</p>",
"search": "<p>Buscar registros:</p>",
"lengthMenu": "Mostrar _MENU_ registros"
}
});
} | function llamarDataTableExpedientesMantenimientos(){
var idMaqui= $("#idMaquina").val();
var url = Routing.generate('datosexpedientesmantenimientodata',{idMaquina: idMaqui});
$('#listaExpedienteMantenimientos').DataTable({
columnDefs: [
{
targets: [0, 1, 2,3],
className: 'mdl-data-table__cell--non-numeric'
}
],
"pageLength": 10,
"lengthMenu": [20],
"dom": "ftp",
"processing": true,
// "serverSide": true,
"ajax": {
"url": url,
"type": 'GET'
},
"columns": [
{"data": "id"},
{"data": "fecha"},
{"data": "tipomantenimiento"},
// {"data": "serie"},
{"data": "costo"},
{"data": "proyecto"}
],
"language": {
"info": "Mostrando página _PAGE_ de _PAGES_",
"infoEmpty": "",
"emptyTable": "<center>No se encontraron registros</center>",
"paginate": {
"next": "Siguiente",
"previous": "Anterior"
},
"processing": "<p>Procesando petición...</p>",
"search": "<p>Buscar registros:</p>",
"lengthMenu": "Mostrar _MENU_ registros"
}
});
} |
JavaScript | function formatRepoM (data) {
if(data.nombre){
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>"+ data.maIdentificacionAlquiler+' '+ data.nombre + " - " + data.alias + "</div>" +
"</div></div>";
}
return markup;
} | function formatRepoM (data) {
if(data.nombre){
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>"+ data.maIdentificacionAlquiler+' '+ data.nombre + " - " + data.alias + "</div>" +
"</div></div>";
}
return markup;
} |
JavaScript | async function postBoxComment(token, event) {
const postURL = "https://api.box.com/2.0/comments/";
const config = {
headers: { Authorization: `Bearer ${token}` },
};
const bodyParameters = {
message: event.Body,
item: {
type: "file",
id: 783120462102,
},
};
try {
const response = await axios.post(postURL, bodyParameters, config);
return response.data;
} catch (err) {
console.log(err.message);
}
} | async function postBoxComment(token, event) {
const postURL = "https://api.box.com/2.0/comments/";
const config = {
headers: { Authorization: `Bearer ${token}` },
};
const bodyParameters = {
message: event.Body,
item: {
type: "file",
id: 783120462102,
},
};
try {
const response = await axios.post(postURL, bodyParameters, config);
return response.data;
} catch (err) {
console.log(err.message);
}
} |
JavaScript | async function fetchSyncService(name) {
let sync_services = [];
//Fetch existing sync services and return if one matches our env variable
try {
sync_services = await client.sync.services.list();
// If we previously created this service, just return it
let sync_service = sync_services.filter((sync_service) => {
if (sync_service.friendlyName == name) {
return sync_service;
}
});
// If we don't have one, create and return it
if (sync_service.length == 0) {
sync_service = await client.sync.services.create({
friendlyName: name,
});
}
// Because we get an array from filter, let's convert to an Object
let sync_service_obj = {};
if (Array.isArray(sync_service)) {
sync_service_obj = Object.assign(sync_service[0]);
} else {
sync_service_obj = sync_service;
}
return sync_service_obj;
} catch (err) {
return Promise.reject(err);
}
} | async function fetchSyncService(name) {
let sync_services = [];
//Fetch existing sync services and return if one matches our env variable
try {
sync_services = await client.sync.services.list();
// If we previously created this service, just return it
let sync_service = sync_services.filter((sync_service) => {
if (sync_service.friendlyName == name) {
return sync_service;
}
});
// If we don't have one, create and return it
if (sync_service.length == 0) {
sync_service = await client.sync.services.create({
friendlyName: name,
});
}
// Because we get an array from filter, let's convert to an Object
let sync_service_obj = {};
if (Array.isArray(sync_service)) {
sync_service_obj = Object.assign(sync_service[0]);
} else {
sync_service_obj = sync_service;
}
return sync_service_obj;
} catch (err) {
return Promise.reject(err);
}
} |
JavaScript | async function fetchSyncMap(syncservicesid, uniquename) {
let sync_maps = [];
try {
sync_maps = await client.sync.services(syncservicesid).syncMaps.list();
// If we previously created this map, just return it
let sync_map = sync_maps.filter((sync_map) => {
if (sync_map.uniqueName == uniquename) {
return sync_map;
}
});
// If we don't have a map, create and return it
if (sync_map.length === 0) {
sync_map = await client.sync
.services(syncservicesid)
.syncMaps.create({ uniqueName: uniquename });
}
// Because we get an array from filter, let's convert to an Object
let sync_map_obj = {};
if (Array.isArray(sync_map)) {
sync_map_obj = Object.assign(sync_map[0]);
} else {
sync_map_obj = sync_map;
}
return sync_map_obj;
} catch (err) {
return Promise.reject(err);
}
} | async function fetchSyncMap(syncservicesid, uniquename) {
let sync_maps = [];
try {
sync_maps = await client.sync.services(syncservicesid).syncMaps.list();
// If we previously created this map, just return it
let sync_map = sync_maps.filter((sync_map) => {
if (sync_map.uniqueName == uniquename) {
return sync_map;
}
});
// If we don't have a map, create and return it
if (sync_map.length === 0) {
sync_map = await client.sync
.services(syncservicesid)
.syncMaps.create({ uniqueName: uniquename });
}
// Because we get an array from filter, let's convert to an Object
let sync_map_obj = {};
if (Array.isArray(sync_map)) {
sync_map_obj = Object.assign(sync_map[0]);
} else {
sync_map_obj = sync_map;
}
return sync_map_obj;
} catch (err) {
return Promise.reject(err);
}
} |
JavaScript | async function createOrupdateMapItem(syncservicesid, syncmapsid, key, data) {
let sync_map_item = {};
try {
let mapitem = await fetchMapItem(syncservicesid, syncmapsid, key);
if (mapitem == "Map Item Not Found") {
sync_map_item = await client.sync
.services(syncservicesid)
.syncMaps(syncmapsid)
.syncMapItems.create({ key: key, data: data });
} else {
sync_map_item = await client.sync
.services(syncservicesid)
.syncMaps(syncmapsid)
.syncMapItems(key)
.update({ key: key, data: data });
}
return sync_map_item;
} catch (err) {
return Promise.reject(err);
}
} | async function createOrupdateMapItem(syncservicesid, syncmapsid, key, data) {
let sync_map_item = {};
try {
let mapitem = await fetchMapItem(syncservicesid, syncmapsid, key);
if (mapitem == "Map Item Not Found") {
sync_map_item = await client.sync
.services(syncservicesid)
.syncMaps(syncmapsid)
.syncMapItems.create({ key: key, data: data });
} else {
sync_map_item = await client.sync
.services(syncservicesid)
.syncMaps(syncmapsid)
.syncMapItems(key)
.update({ key: key, data: data });
}
return sync_map_item;
} catch (err) {
return Promise.reject(err);
}
} |
JavaScript | async function readTokens(provider) {
try {
let syncservice = await sync.fetchSyncService(process.env.SYNC_NAME);
let syncmap = await sync.fetchSyncMap(
syncservice.sid,
process.env.SYNC_NAME
);
let syncmapitem = await sync.fetchMapItem(
syncservice.sid,
syncmap.sid,
provider
);
return syncmapitem;
} catch (err) {
console.log(err);
return Promise.reject(err);
}
} | async function readTokens(provider) {
try {
let syncservice = await sync.fetchSyncService(process.env.SYNC_NAME);
let syncmap = await sync.fetchSyncMap(
syncservice.sid,
process.env.SYNC_NAME
);
let syncmapitem = await sync.fetchMapItem(
syncservice.sid,
syncmap.sid,
provider
);
return syncmapitem;
} catch (err) {
console.log(err);
return Promise.reject(err);
}
} |
JavaScript | async function writeTokens(provider, res, grant_type) {
// Timestamp
const date = new Date();
const timestamp = date.toISOString();
let tokendata = await readTokens(provider);
let currenttokens = tokendata.data;
// Google only sends a refresh token on 1st consent so we
// need to keep it around in order to get a new access token
let refresh =
provider == "google" && grant_type == "refresh_token"
? currenttokens.refresh_token
: res.refresh_token;
// Define the Tokens we need to write
let newtokens = {
...currenttokens,
access_token: res.access_token,
refresh_token: refresh,
expires_in: res.expires_in,
timestamp: timestamp,
};
// Write tokens to SyncMap
try {
let syncservice = await sync.fetchSyncService(process.env.SYNC_NAME);
let syncmap = await sync.fetchSyncMap(
syncservice.sid,
process.env.SYNC_NAME
);
let syncmapitem = await sync.createOrupdateMapItem(
syncservice.sid,
syncmap.sid,
provider,
newtokens
);
return syncmapitem;
} catch (err) {
console.log(err);
return Promise.reject(err);
}
} | async function writeTokens(provider, res, grant_type) {
// Timestamp
const date = new Date();
const timestamp = date.toISOString();
let tokendata = await readTokens(provider);
let currenttokens = tokendata.data;
// Google only sends a refresh token on 1st consent so we
// need to keep it around in order to get a new access token
let refresh =
provider == "google" && grant_type == "refresh_token"
? currenttokens.refresh_token
: res.refresh_token;
// Define the Tokens we need to write
let newtokens = {
...currenttokens,
access_token: res.access_token,
refresh_token: refresh,
expires_in: res.expires_in,
timestamp: timestamp,
};
// Write tokens to SyncMap
try {
let syncservice = await sync.fetchSyncService(process.env.SYNC_NAME);
let syncmap = await sync.fetchSyncMap(
syncservice.sid,
process.env.SYNC_NAME
);
let syncmapitem = await sync.createOrupdateMapItem(
syncservice.sid,
syncmap.sid,
provider,
newtokens
);
return syncmapitem;
} catch (err) {
console.log(err);
return Promise.reject(err);
}
} |
JavaScript | function fillAlphabet(cipherFunction, shift, direction) {
var result = "";
for (var i = 97; i < 123; i++) {
var code = cipherFunction(String.fromCharCode(i), shift, direction);
result += "<span class='letter-" + i + "'>" + code + " </span>";
}
return result;
} | function fillAlphabet(cipherFunction, shift, direction) {
var result = "";
for (var i = 97; i < 123; i++) {
var code = cipherFunction(String.fromCharCode(i), shift, direction);
result += "<span class='letter-" + i + "'>" + code + " </span>";
}
return result;
} |
JavaScript | function fillMessage(message, cipherFunction, shift, direction) {
var codeMessage = cipherFunction(testMessage, shift, direction);
var result = codeMessage.split("").map(function(character) {
var charCode = character.toLowerCase().charCodeAt(0);
return "<span class=letter-"+ charCode + ">" + character + "</span>";
});
return result.join("");
} | function fillMessage(message, cipherFunction, shift, direction) {
var codeMessage = cipherFunction(testMessage, shift, direction);
var result = codeMessage.split("").map(function(character) {
var charCode = character.toLowerCase().charCodeAt(0);
return "<span class=letter-"+ charCode + ">" + character + "</span>";
});
return result.join("");
} |
JavaScript | function caesarLetter(letter, shift, direction) {
if (direction === "right") {
shift = -shift;
}
if (/[^a-z]/i.test(letter)) {
return letter;
} else {
var charCode = letter.charCodeAt(0);
var asciiShift = 65; // Capital letters
if (/[a-z]/.test(letter)) { // lowercase letters
asciiShift = 97
}
charCode = charCode - asciiShift; // nomalize charCode to 0-26
charCode = (charCode - shift) % 26; // keep charCode in smaller than 26
if (charCode < 0) { // keep charCode a positive value
charCode += 26
}
charCode = charCode + asciiShift; // return charCode to correct ascii Value
return String.fromCharCode(charCode);
}
} | function caesarLetter(letter, shift, direction) {
if (direction === "right") {
shift = -shift;
}
if (/[^a-z]/i.test(letter)) {
return letter;
} else {
var charCode = letter.charCodeAt(0);
var asciiShift = 65; // Capital letters
if (/[a-z]/.test(letter)) { // lowercase letters
asciiShift = 97
}
charCode = charCode - asciiShift; // nomalize charCode to 0-26
charCode = (charCode - shift) % 26; // keep charCode in smaller than 26
if (charCode < 0) { // keep charCode a positive value
charCode += 26
}
charCode = charCode + asciiShift; // return charCode to correct ascii Value
return String.fromCharCode(charCode);
}
} |
JavaScript | function caesarShift(message, shift, direction) {
var messageArray = message.split("");
var result = "";
messageArray.forEach(function(letter){
result += caesarLetter(letter, shift, direction);
});
return result;
} | function caesarShift(message, shift, direction) {
var messageArray = message.split("");
var result = "";
messageArray.forEach(function(letter){
result += caesarLetter(letter, shift, direction);
});
return result;
} |
JavaScript | function subReceitasDespesas(receitas,despesas){
const somaR = somaReceitaDespesas(receitas); // METODO QUE RETORNA A SOMA DAS RECEITAS
const somaD = somaReceitaDespesas(despesas) // METODO QUE RETORNA A SOMA DAS DESPESAS
return somaR - somaD;
} | function subReceitasDespesas(receitas,despesas){
const somaR = somaReceitaDespesas(receitas); // METODO QUE RETORNA A SOMA DAS RECEITAS
const somaD = somaReceitaDespesas(despesas) // METODO QUE RETORNA A SOMA DAS DESPESAS
return somaR - somaD;
} |
JavaScript | function Banner() {
// We need the movie
const [movie, setMovie] = useState([]);
useEffect(() => {
async function fetchRandomMovie() {
const randomMovieResponse = await instance.get(requests.fetchNetflixOriginals);
// Randomly select one movie
let movieArr = randomMovieResponse.data.results;
let randomIndex = Math.floor(Math.random() * movieArr.length);
let randomMovie = movieArr[randomIndex];
setMovie(randomMovie);
return randomMovieResponse;
}
fetchRandomMovie();
}, [])
/**
* This function truncates the movie description to some what easier looking!
* @param {String} text This is the description of the movie
* @param {Integer} limit This is the limit after which we want to truncate
* @returns the description, truncated or not depending on the limit given
*/
function truncateDescription(text, limit) {
let result = '';
if (text != null && text.length > limit) {
result = text.substring(0, limit - 1) + "...";
} else {
result = text;
}
return result;
}
let baseUrl = "https://image.tmdb.org/t/p/";
let fileSize = "original";
return (
<header className="Banner" style={{ backgroundSize: "cover", backgroundImage: `url(${baseUrl}${fileSize}${movie?.backdrop_path})`, backgroundPosition: "center center" }}>
<div className="Banner__contents">
<h1 className="Banner__title">{movie?.title || movie?.name || movie?.orginal_name}</h1>
<div className="Banner_buttons">
<button className="Banner__button">Play</button>
<button className="Banner__button">My list</button>
</div>
<h1 className="Banner__description">{truncateDescription(movie?.overview, 200)}</h1>
</div>
{/* This div is to create that fading effect of the banner with the content */}
<div className="Banner__bottomFading"></div>
</header>
)
} | function Banner() {
// We need the movie
const [movie, setMovie] = useState([]);
useEffect(() => {
async function fetchRandomMovie() {
const randomMovieResponse = await instance.get(requests.fetchNetflixOriginals);
// Randomly select one movie
let movieArr = randomMovieResponse.data.results;
let randomIndex = Math.floor(Math.random() * movieArr.length);
let randomMovie = movieArr[randomIndex];
setMovie(randomMovie);
return randomMovieResponse;
}
fetchRandomMovie();
}, [])
/**
* This function truncates the movie description to some what easier looking!
* @param {String} text This is the description of the movie
* @param {Integer} limit This is the limit after which we want to truncate
* @returns the description, truncated or not depending on the limit given
*/
function truncateDescription(text, limit) {
let result = '';
if (text != null && text.length > limit) {
result = text.substring(0, limit - 1) + "...";
} else {
result = text;
}
return result;
}
let baseUrl = "https://image.tmdb.org/t/p/";
let fileSize = "original";
return (
<header className="Banner" style={{ backgroundSize: "cover", backgroundImage: `url(${baseUrl}${fileSize}${movie?.backdrop_path})`, backgroundPosition: "center center" }}>
<div className="Banner__contents">
<h1 className="Banner__title">{movie?.title || movie?.name || movie?.orginal_name}</h1>
<div className="Banner_buttons">
<button className="Banner__button">Play</button>
<button className="Banner__button">My list</button>
</div>
<h1 className="Banner__description">{truncateDescription(movie?.overview, 200)}</h1>
</div>
{/* This div is to create that fading effect of the banner with the content */}
<div className="Banner__bottomFading"></div>
</header>
)
} |
JavaScript | function truncateDescription(text, limit) {
let result = '';
if (text != null && text.length > limit) {
result = text.substring(0, limit - 1) + "...";
} else {
result = text;
}
return result;
} | function truncateDescription(text, limit) {
let result = '';
if (text != null && text.length > limit) {
result = text.substring(0, limit - 1) + "...";
} else {
result = text;
}
return result;
} |
JavaScript | function Row(props) {
/* States: short time memory to intialise the movies array */
const [movies, setMovies] = useState([]); /* intially it is going to be an empty array */
/* When the Row loads we need to load the movie information */
useEffect(() => {
/**
* This is asynchronous function to get the movies data
*/
async function fetchData() {
let fetchURL = props.fetchUrl;
/**
* Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected
*/
const apiResponse = await instance.get(fetchURL);
setMovies(apiResponse.data.results);
return apiResponse;
}
fetchData();
return () => {
console.log(`Cleanup process after every content change is done`);
}
}, [props.fetchUrl]) /* Every time the fetchUrl changes we need to reload the userEffect to get the dynamic data */
const baseUrl = "https://image.tmdb.org/t/p/";
const fileSize = "original";
return (
<div className="Row">
<h2>{props.title}</h2>
<div className="Row__container">
{movies.map(movie => (
// if there is any change or re-rendering required, instead of the whole row, it is going to render that particular movie, based on the movie.id which is unique
<img key={movie.id} className={`onePoster ${props.isLargeRow && "oneLargePoster"}`} src={`${baseUrl}${fileSize}${props.isLargeRow ? movie.poster_path : movie.backdrop_path}`} alt={movie.name} />
))}
</div>
</div>
)
} | function Row(props) {
/* States: short time memory to intialise the movies array */
const [movies, setMovies] = useState([]); /* intially it is going to be an empty array */
/* When the Row loads we need to load the movie information */
useEffect(() => {
/**
* This is asynchronous function to get the movies data
*/
async function fetchData() {
let fetchURL = props.fetchUrl;
/**
* Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected
*/
const apiResponse = await instance.get(fetchURL);
setMovies(apiResponse.data.results);
return apiResponse;
}
fetchData();
return () => {
console.log(`Cleanup process after every content change is done`);
}
}, [props.fetchUrl]) /* Every time the fetchUrl changes we need to reload the userEffect to get the dynamic data */
const baseUrl = "https://image.tmdb.org/t/p/";
const fileSize = "original";
return (
<div className="Row">
<h2>{props.title}</h2>
<div className="Row__container">
{movies.map(movie => (
// if there is any change or re-rendering required, instead of the whole row, it is going to render that particular movie, based on the movie.id which is unique
<img key={movie.id} className={`onePoster ${props.isLargeRow && "oneLargePoster"}`} src={`${baseUrl}${fileSize}${props.isLargeRow ? movie.poster_path : movie.backdrop_path}`} alt={movie.name} />
))}
</div>
</div>
)
} |
JavaScript | async function fetchData() {
let fetchURL = props.fetchUrl;
/**
* Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected
*/
const apiResponse = await instance.get(fetchURL);
setMovies(apiResponse.data.results);
return apiResponse;
} | async function fetchData() {
let fetchURL = props.fetchUrl;
/**
* Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected
*/
const apiResponse = await instance.get(fetchURL);
setMovies(apiResponse.data.results);
return apiResponse;
} |
JavaScript | function lint(textarea)
{
var tabInUse = document.getElementById(currentTab);
// Adding the keypress to the tab's name attribute
tabInUse.value = textarea.value;
switch (event.key)
{
case "Tab":
event.preventDefault();
textarea.setRangeText(" ");
textarea.setSelectionRange(
textarea.selectionStart + 2,
textarea.selectionStart + 2
);
break;
case "Enter":
event.preventDefault();
indent(textarea);
break;
case "{":
event.preventDefault();
textarea.setRangeText("{\n \n}");
// Placing cursor in between the brackets
textarea.setSelectionRange(
textarea.selectionStart + 4,
textarea.selectionStart + 4
);
break;
}
} | function lint(textarea)
{
var tabInUse = document.getElementById(currentTab);
// Adding the keypress to the tab's name attribute
tabInUse.value = textarea.value;
switch (event.key)
{
case "Tab":
event.preventDefault();
textarea.setRangeText(" ");
textarea.setSelectionRange(
textarea.selectionStart + 2,
textarea.selectionStart + 2
);
break;
case "Enter":
event.preventDefault();
indent(textarea);
break;
case "{":
event.preventDefault();
textarea.setRangeText("{\n \n}");
// Placing cursor in between the brackets
textarea.setSelectionRange(
textarea.selectionStart + 4,
textarea.selectionStart + 4
);
break;
}
} |
JavaScript | function indent(textarea)
{
// Index 0 of text until where the text cursor is
var text = textarea.value.substr(0, textarea.selectionStart);
// Getting the start of the current line
var newlineCheck;
while (true)
{
if (text === "") break;
newlineCheck = text[text.length - 1].match(/\n/g);
if (newlineCheck == null)
text = text.substr(0, text.length - 1);
else
break;
}
// Getting the amount of spaces for indentation
var startOfLineIndex = text.length;
var spaces = "";
while (textarea.value[startOfLineIndex] == " ")
{
spaces += " ";
startOfLineIndex++;
}
// Putting the indent on the screen
textarea.setRangeText("\n" + spaces);
textarea.setSelectionRange(
textarea.selectionStart + spaces.length + 1,
textarea.selectionStart + spaces.length + 1
);
// Indent if we expect that a statement's block of code will be written
// i.e. indent after Python if ...: or C++ if ()
// Getting the keyword
var keyword = "";
while (startOfLineIndex <= textarea.value.length - 1)
{
// Current character we're looking at
var currentCharacter = textarea.value[startOfLineIndex];
if (currentCharacter != " " && currentCharacter != "(" && currentCharacter.match(/\n/g) == null)
{
keyword += currentCharacter;
startOfLineIndex++;
}
else
break;
}
var keywords = ["if", "while", "for"];
if (keywords.includes(keyword))
{
textarea.setRangeText(" ");
textarea.setSelectionRange(
textarea.selectionStart + 2,
textarea.selectionStart + 2
);
}
} | function indent(textarea)
{
// Index 0 of text until where the text cursor is
var text = textarea.value.substr(0, textarea.selectionStart);
// Getting the start of the current line
var newlineCheck;
while (true)
{
if (text === "") break;
newlineCheck = text[text.length - 1].match(/\n/g);
if (newlineCheck == null)
text = text.substr(0, text.length - 1);
else
break;
}
// Getting the amount of spaces for indentation
var startOfLineIndex = text.length;
var spaces = "";
while (textarea.value[startOfLineIndex] == " ")
{
spaces += " ";
startOfLineIndex++;
}
// Putting the indent on the screen
textarea.setRangeText("\n" + spaces);
textarea.setSelectionRange(
textarea.selectionStart + spaces.length + 1,
textarea.selectionStart + spaces.length + 1
);
// Indent if we expect that a statement's block of code will be written
// i.e. indent after Python if ...: or C++ if ()
// Getting the keyword
var keyword = "";
while (startOfLineIndex <= textarea.value.length - 1)
{
// Current character we're looking at
var currentCharacter = textarea.value[startOfLineIndex];
if (currentCharacter != " " && currentCharacter != "(" && currentCharacter.match(/\n/g) == null)
{
keyword += currentCharacter;
startOfLineIndex++;
}
else
break;
}
var keywords = ["if", "while", "for"];
if (keywords.includes(keyword))
{
textarea.setRangeText(" ");
textarea.setSelectionRange(
textarea.selectionStart + 2,
textarea.selectionStart + 2
);
}
} |
JavaScript | async onlineShoppingNavigation() {
for (let i = 0; i < await this.productNavigationCategories.childElementCount; i++) {//productNavigationCategories.length
await t
.click(this.productNavigationCategories.child(i))//.find('a'))
.navigateTo(`https://www.lidlonline.es/`);
}
} | async onlineShoppingNavigation() {
for (let i = 0; i < await this.productNavigationCategories.childElementCount; i++) {//productNavigationCategories.length
await t
.click(this.productNavigationCategories.child(i))//.find('a'))
.navigateTo(`https://www.lidlonline.es/`);
}
} |
JavaScript | async goto(relativeUrl = null) {
if (relativeUrl) {
// navigate via relative paths
await t.navigateTo(`${this.url}${relativeUrl}`);
} else {
// get url from page object
await t.navigateTo(this.url);
}
} | async goto(relativeUrl = null) {
if (relativeUrl) {
// navigate via relative paths
await t.navigateTo(`${this.url}${relativeUrl}`);
} else {
// get url from page object
await t.navigateTo(this.url);
}
} |
JavaScript | async findPostByPaging(postTitle) {
if(await this.postTitleExists(postTitle)) {
return true;
} else if(await this.prevPageLink.exists) {
await t.click(this.prevPageLink);
await this.findPostByPaging(postTitle); // call recursively till found...
} else {
// post not found
return false;
}
} | async findPostByPaging(postTitle) {
if(await this.postTitleExists(postTitle)) {
return true;
} else if(await this.prevPageLink.exists) {
await t.click(this.prevPageLink);
await this.findPostByPaging(postTitle); // call recursively till found...
} else {
// post not found
return false;
}
} |
JavaScript | static waitForUserWidget(widgetId, add) {
return new Promise((resolve, reject) => {
// Tests an account data event, returning true if it's in the state
// we're waiting for it to be in
function eventInIntendedState(ev) {
if (!ev || !ev.getContent()) return false;
if (add) {
return ev.getContent()[widgetId] !== undefined;
} else {
return ev.getContent()[widgetId] === undefined;
}
}
const startingAccountDataEvent = MatrixClientPeg.get().getAccountData('m.widgets');
if (eventInIntendedState(startingAccountDataEvent)) {
resolve();
return;
}
function onAccountData(ev) {
const currentAccountDataEvent = MatrixClientPeg.get().getAccountData('m.widgets');
if (eventInIntendedState(currentAccountDataEvent)) {
MatrixClientPeg.get().removeListener('accountData', onAccountData);
clearTimeout(timerId);
resolve();
}
}
const timerId = setTimeout(() => {
MatrixClientPeg.get().removeListener('accountData', onAccountData);
reject(new Error("Timed out waiting for widget ID " + widgetId + " to appear"));
}, WIDGET_WAIT_TIME);
MatrixClientPeg.get().on('accountData', onAccountData);
});
} | static waitForUserWidget(widgetId, add) {
return new Promise((resolve, reject) => {
// Tests an account data event, returning true if it's in the state
// we're waiting for it to be in
function eventInIntendedState(ev) {
if (!ev || !ev.getContent()) return false;
if (add) {
return ev.getContent()[widgetId] !== undefined;
} else {
return ev.getContent()[widgetId] === undefined;
}
}
const startingAccountDataEvent = MatrixClientPeg.get().getAccountData('m.widgets');
if (eventInIntendedState(startingAccountDataEvent)) {
resolve();
return;
}
function onAccountData(ev) {
const currentAccountDataEvent = MatrixClientPeg.get().getAccountData('m.widgets');
if (eventInIntendedState(currentAccountDataEvent)) {
MatrixClientPeg.get().removeListener('accountData', onAccountData);
clearTimeout(timerId);
resolve();
}
}
const timerId = setTimeout(() => {
MatrixClientPeg.get().removeListener('accountData', onAccountData);
reject(new Error("Timed out waiting for widget ID " + widgetId + " to appear"));
}, WIDGET_WAIT_TIME);
MatrixClientPeg.get().on('accountData', onAccountData);
});
} |
JavaScript | function eventInIntendedState(ev) {
if (!ev || !ev.getContent()) return false;
if (add) {
return ev.getContent()[widgetId] !== undefined;
} else {
return ev.getContent()[widgetId] === undefined;
}
} | function eventInIntendedState(ev) {
if (!ev || !ev.getContent()) return false;
if (add) {
return ev.getContent()[widgetId] !== undefined;
} else {
return ev.getContent()[widgetId] === undefined;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.