Change content dynamically when my module cron runs - javascript

I have a module named my_module and it uses for running cron. I am using hook_cron() to run cron in my module. I want to change the value of a javascript veriable when cron runs. This javascript variable has already present in the footer. I am using drupal 7. Can any one help me to write codes for this?

This code can get you started.
/**
* Implementation of hook_cron()
*/
function [YOUR_MODULE]_cron() {
variable_set('YOUR_VARIABLE', 'change this value to your liking');
}
/**
* Implementation of hook_init()
*/
function [YOUR_MODULE]_init() {
$yourVariable = variable_get('YOUR_VARIABLE', '');
drupal_add_js(array('YOUR_VARIABLE' => $yourVariable), 'setting');
}
Then in your javascript:
var myVar = Drupal.settings.YOUR_VARIABLE;
Docs:
hook_init()
hook_cron()
variable_get()
variable_set()

Related

Can you declare your own function in Discord JS?

Normally I just add to the command files or the index file easily but it's starting to look messy. Recently I got this leveling system working
if (!levels[message.author.id]) {
levels[message.author.id] = {
level: 1,
exp: 0
}
}
// Gives random EXP
let randomExp = Math.floor(Math.random() * 5 + 5);
// Adds the random EXP to their current EXP
levels[message.author.id].exp += randomExp;
// Checks their EXP and changes their level
for (x = 0; x < expLevels.length; x++) {
if (levels[message.author.id].exp > expLevels[x]) {
levels[message.author.id].level = x + 1;
message.channel.reply(`congratulations! You reached level ${levels[message.author.id].level + 1}!`);
}
}
fs.writeFile('./levels.json', JSON.stringify(levels), err => {
if (err) console.error(err);
});
if (levels[authorMessage.author.id].level >= 10) {
message.member.roles.remove('720109209479413761');
message.member.roles.add('719058151940292659');
}
I would like to be able to put this into its own function and then call it in the "message" section for every time someone sends a message. Is that possible to do? Or no since I need to have access to the "message" variable?
I'm used to C++ with functions where it's much easier to deal with. Does anyone know if it's possible to code a bot in C++ or is there no support? If there is a way if someone can point me in the right direction to start please let me know. Otherwise I can easily stay with JS.
I'm not sure if a discord framework for C++ exists, probably but I'm not sure.
You can of course define a function somewhere and call it in the onMessage event.
There are two ways that you could do that.
In the same file
In another file
Functions in the same file.
You can declare a function and then pass arguments to that function. You don't need to declare the type of argument that is being passed here. Source
function leveling(message) { // here you can include all parameters that you might need
// the rest of your code
}
Once you have a function you can call it like this.
leveling(message); // here we pass the values we need to the function
Functions in a different file.
The concept is the same, however we need to export the function in order to use it somewhere else. There are two ways to do this, either export only one function or export all functions, in the case of a dedicated functions file this is the easier option.
Note: In this example I name the file functions.js and place it in the same directory as the file I require it from.
module.exports = {
// we need to declare the name first, then add the function
leveling: function (message) {
// the rest of your code
}
// here we can add more functions, divided by a comma
}
// if you want to export only one function
// declare it normally and then export it
module.exports = leveling;
Calling functions.
To use this function we need to require it in the file we want to use it in. Here we also have two options.
Either require the whole file and get the function from there
const myfunctions = require('./functions.js'); // this is the relative path to the file
// get the function via the new constant
myfunctions.leveling(message);
Or use Object destructuring to get only what you need from the exported functions.
const { leveling } = require('./functions.js');
leveling(message);
Both of these options provide advantages and disadvantages but in the end they both do the same.

How do I refer to a JavaScript function defined in a different script in WinDbg?

I have a couple of JavaScript scripts to house my functions (for modularity and reuse). I load them both from the windbg script I'm running. From within one script, how do I call a function defined in the other?
This engine doesn't seem to support the import/export feature employed by browsers.
From within the debugger script, I have to use #$scriptContents to access JavaScript functions.
How do I accomplish something similar from within one of the JavaScript functions?
Experiment
I was hoping there would be some sort of global namespace for all JavaScript functions, but it appears not.
Consider
// t1.js
function func1() {
host.diagnostics.debugLog('func1()...\n');
}
and
// t2.js
function func2() {
host.diagnostics.debugLog('func2()...\n');
func1();
}
In my cdb session
0:000> .load jsprovider.dll
0:000> .scriptload t1.js
JavaScript script successfully loaded from 't1.js'
0:000> .scriptload t2.js
JavaScript script successfully loaded from 't2.js'
0:000> dx #$scriptContents.func1()
func1()...
#$scriptContents.func1()
0:000> dx #$scriptContents.func2()
func2()...
Error: 'func1' is not defined [at t2 (line 3 col 5)]
Edit
Per #Mosè Raguzzini's comment and this answer, I went looking for some way to reference "foreign" functions.
I eventually unearthed this
host.namespace.Debugger.State.DebuggerVariables.scriptContents
as a container for all functions. Is this documented somewhere? Is there no simpler way to get there? (I realize I can just assign a short variable to that object; I'm just suspicious this this is more of a backdoor into something with a very simple front door, but I don't know where the front door is.)
AFAIK all scripts are imported in global scope, so you can act as them are written in a single file, once all are loaded.
Example (REF to blabb answer)
common.js has a few functions that are normally reusable like
host.diagnostics.debugLog()
First load it using .scriptload
Then in other js files create a var to those functions and use it
contents of common function file
C:\>cat c:\wdscr\common.js
function log(instr) {
host.diagnostics.debugLog(instr + "\n");
}
function exec (cmdstr){
return host.namespace.Debugger.Utility.Control.ExecuteCommand(cmdstr);
}
a js file using the function from common.js
C:\>cat c:\wdscr\usecommon.js
function foo(){
var commonlog = host.namespace.Debugger.State.Scripts.common.Contents.log
var commonexec = host.namespace.Debugger.State.Scripts.common.Contents.exec
commonlog("we are using the logging function from the common.js file")
var blah = commonexec("lma #$exentry")
for(var a of blah) {
commonlog(a)
}
}
actual usage
C:\>cdb calc
Microsoft (R) Windows Debugger Version 10.0.16299.15 X86
0:000> .load jsprovider
0:000> .scriptload c:\wdscr\common.js
JavaScript script successfully loaded from 'c:\wdscr\common.js'
0:000> .scriptload c:\wdscr\usecommon.js
JavaScript script successfully loaded from 'c:\wdscr\usecommon.js'
0:000> dx #$scriptContents.foo()
we are using the logging function from the common.js file
start end module name
00f10000 00fd0000 calc (deferred)
#$scriptContents.foo()
0:000>
well you can write a javascript function that calls any function from any script sitting in any directory
using something like below (you may need to tweak it the POC worked on my machine for a .js that returned a string)
function runFuncFromAnyScript(dir,script,somefunc) {
var unl = ".scriptunload " + script
host.namespace.Debugger.Utility.Control.ExecuteCommand(unl)
var pre = ".scriptload "
var post = "dx #$scriptContents." + somefunc
var cmd = pre + dir + script
host.namespace.Debugger.Utility.Control.ExecuteCommand(cmd)
return host.namespace.Debugger.Utility.Control.ExecuteCommand(post)
}
used like
0:000> dx #$scriptContents.runFuncFromAnyScript("f:\\zzzz\\wdscript\\","mojo.js","hola_mojo(\"executethis\")" )
#$scriptContents.runFuncFromAnyScript("f:\\zzzz\\wdscript\\","mojo.js","hola_mojo(\"executethis\")" )
[0x0] : hola mojo this is javascript
[0x1] : hello mojo this is the argument you sent to me for execution I have executed your executethis
[0x2] : #$scriptContents.hola_mojo("executethis")

How to pass a variable retrieved from 1 protractor test script to another

I want to achieve the following:
Create a dynamic id for a customer in my createPlan.js
Store the ID in a global variable
Use this globalVariable in a separate file, sendforreview.js
Currently I'm using jasmine data provider but dynamically I'm not able to
do it every time after i run the first js file then i update the jasmine data
provider and then I run the next js file so that the plan number is fed as
input in the search textbox .
This is a simple logic but it'll be applicable across any application I guess.
createplan.js file:
var plannumberis, using = require('jasmine-data-provider');
describe("Plan Creation", () => {
using(leadEnters.leadinputs, (data, description) => {
it("Plan is generated and stored globally", () => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000;
browser.wait(EC.urlContains('WorkFlow/#/app/impPlan'));
browser.wait(EC.presenceOf(element(by.xpath("//div[#class='sweModal-body']"))), 160 * 10000);
var dialog = element(by.className("sweModal-body"));
expect(dialog.isDisplayed).toBeTruthy();
var dialog-text = element(by.className("sweModal-content"));
dialogtext.getText().then(function (text) {
console.log(text);
plannumberis=text.slice(20, 28);// --here i store the plan number in var
// plannumberis **
console.log("implementation plan id is :" + plan);
browser.wait(EC.presenceOf(element(by.css("button[class='btn btn-primary okBtn']"))));
element(by.css("button[class='btn btn-primary okBtn']")).click();
})
})
})
})
sendforreview.js
describe("STAGE 2:Developer Activities : Segment Checkout", () => {
using(DeveloperInputs.Devinputs, (data, description) => {
it("Developer checksout the required segments", () => {
searchPlanId.clickSearch();
searchPlanId.selectSearchTypeWithIndex(2);
searchPlanId.enterImplementationNo(data.PlanNumber);// --here i want to
// call theplannumber generated in the first js file.How to do this
browser.wait(EC.presenceOf(element(by.css("i[class='fa fa-search']"))), 10000);
searchPlanId.clickSearchButton();
developerActions.editFirstImplementation(plannumberis);
// Here I want to call the id generated in createplan.js
// So in jasmine data provider I'm manually updating
// this after I run the 1stjs file then pass it in second jsfile
})
})
})
You should be able to achieve this by using NodeJS's global variables keyword which make variables accessible to all files in the project.
file1.js
//delcare var
global.newGlobalVar = 'value we want in another file'
file2.js
//use the var
console.log(newGlobalVar)
However as it appears you are using loops in both your test files I cannot see how this approach will work for you
The issue you're having is that var plannumberis is on the module (file) scope, not the global scope. Your variable is only accessible within that spec file.
Some more from the docs:
In browsers, the top-level scope is the global scope. This means that within the browser var something will define a new global variable. In Node.js this is different. The top-level scope is not the global scope; var something inside a Node.js module will be local to that module.
The way to put something on the global scope is to put it on the global object.
global.plannumberis=text.slice(20, 28);
After that you can reference it from any module using plannumberis.
However, I cannot encourage your design decision here. Having interdepencencies between specs like this is highly discouraged. With the way you've designed it, if anyone ever tries to run sendforreview.js by itself, the test will fail in a confusing and seemingly-arbitrary manner. You should write your specs so that they are all independent of each other and can be run in any order.
In this particular case, you could accomplish that by combining the two files into a single spec.

fluent wait in nightwatch.js

please help me with implementing FluentWait using nightwatch.js
how can I use it??
in my project I have global.js containing:
waitForConditionPollInterval : 300,
waitForConditionTimeout : 5000,
but this is not FluentWait??
And the second question is how to use variables from global.js in test scripts ??
for example, if I have code like this:
this.typeLoginAndSubmit = function() {
browser
.waitForElementVisible(loginPageSelectors.loginField, 5000)
.setValue(loginPageSelectors.loginField, 'login')
.waitForElementVisible(loginPageSelectors.loginSubmit, 5000)
.click(loginPageSelectors.loginSubmit)
return browser;
the nightwatch methods like "waitForElementVisible" has forced me to give ms value ?? so how and when I can use global.js configuration??
You have to assign a variable to the js.
var global=require('global.js');
browser
.waitForElementVisible(loginPageSelectors.loginField, global.timeout);
or
just assign var timeout=5000; before all actions as the script you run is javascript
then use it
browser.waitForElementVisible(loginPageSelectors.loginField,timeout);

PhantomJS: require Script and set variables beforehand

I am using PhantomJS for page automation. For my script, I need to load another script which is also used on the actual client-side of my webpage. This script contains some parts where global variables - which are assumed to be set before the script is loaded - are used.
Now my problem is that I can't figure out how to set these variables before I require them within PhantomJS.
This (obviously) didn't do the trick:
variableX = 1024;
var moduleX = require('myScripts.js');
Now what's the proper and intended way ( if there is one) to do this?
If you prepare the testing script as a CommonJS module, you can require it and use its methods and variables in PhantomJS.
From the docs: http://phantomjs.org/release-1.7.html
As an example, supposed there is a script universe.js which contains the following code:
exports.answer = 42;
exports.start = function () {
console.log('Starting the universe....');
}
This module can be used in another script like the following:
var universe = require('./universe');
universe.start();
console.log('The answer is', universe.answer);
And if you want to assign global variables from such a module you can use the global object as in node.js:
exports.start = function () {
global.success = true;
console.log('Starting the universe....');
}

Categories