Creating a common file by combining two similar functions - javascript

I have two functions that are mostly similar in different files and I want to combine them into one file but as can be seen in the code, some product properties are different from each other and I want to handle this dynamically. What is the correct way to do this?
File-1:
function run(args) {
try {
var sitePreferences = require("sitePreferences");
var pinterestHelpers = require("~/cartridge/scripts/helpers/pinterestHelpers");
var maxRowLength = sitePreferences.get("pinterestProductFeedMaxRow");
var hostName = require("dw/system/Site").current.httpsHostName;
var products = pinterestHelpers.onBeforeStep(args);
var fileNumber = 1;
var lineCount = 1;
pinterestHelpers.removeFiles(args);
var csvObject = pinterestHelpers.createCsvFile(fileNumber, args);
var csv = csvObject.csv;
var fileCreationResponse;
var fileWriter = csvObject.fileWriter;
while (products.hasNext()) {
var currentProductObject = products.next();
var priceObject = pinterestHelpers.getPrice(currentProductObject);
var product = {};
if (pinterestHelpers.shouldBeExported(currentProductObject)) {
if (maxRowLength !== lineCount) {
product.id = pinterestHelpers.getId(currentProductObject);
product.title = pinterestHelpers.getTitle(currentProductObject);
product.description = pinterestHelpers.getDescription(currentProductObject);
product.link = pinterestHelpers.getLink(currentProductObject, hostName);
product.image_link = pinterestHelpers.getImageLink(currentProductObject);
product.price = priceObject && priceObject.list ? priceObject.list : "";
product.availability = pinterestHelpers.getAvailability(currentProductObject);
product.item_group_id = pinterestHelpers.getItemGroupID(currentProductObject);
product.additional_image_link = pinterestHelpers.getAdditionalImageLink(currentProductObject);
product.brand = pinterestHelpers.getBrand(currentProductObject);
product.google_product_category = pinterestHelpers.getGoogleCategoryByProduct(currentProductObject);
product.sale_price = priceObject && priceObject.sale ? priceObject.sale : "";
product.color = pinterestHelpers.getColor(currentProductObject);
product.age_group = pinterestHelpers.getCustomAttribute(currentProductObject, "age_group", "Adult");
product.gender = pinterestHelpers.getCustomAttribute(currentProductObject, "gender", "unisex");
product.condition = pinterestHelpers.getCustomAttribute(currentProductObject, "condition", "new");
product.variant_names = pinterestHelpers.getSize(currentProductObject);
product.variant_values = pinterestHelpers.getColor(currentProductObject);
product.product_type = pinterestHelpers.getProductType(currentProductObject);
product.material = pinterestHelpers.getCustomAttribute(currentProductObject, "material");
product.pattern = pinterestHelpers.getCustomAttribute(currentProductObject, "pattern");
product.shipping = pinterestHelpers.getShipping(currentProductObject, priceObject).group;
product.adult = pinterestHelpers.getCustomAttribute(currentProductObject, "adult", "FALSE");
csv.writeNext([
product.id,
product.title,
product.description,
product.link,
product.image_link,
product.price,
product.availability,
product.item_group_id,
product.variant_names,
product.variant_values,
product.additional_image_link,
product.brand,
product.product_type,
product.sale_price,
product.age_group,
product.color,
product.gender,
product.material,
product.pattern,
product.shipping,
product.adult,
product.condition,
product.google_product_category
]);
lineCount++;
} else {
fileNumber++;
lineCount = 1;
fileCreationResponse = pinterestHelpers.createCsvFile(fileNumber, args);
csv = fileCreationResponse.csv;
}
}
}
products.close();
csv.close();
fileWriter.close();
Logger.info("Pinterest feed exported at {0}", pinterestHelpers.getFeedURL(args, fileCreationResponse.fileName));
return new Status(Status.OK, 'OK', 'Export successful');
} catch (e) {
return new Status(Status.ERROR, 'ERROR', 'Failed to export the feed: ' + e);
}
}
exports.Run = run;
File-2:
function run(args) {
try {
var snapchatHelpers = require("~/cartridge/scripts/helpers/snapchatHelpers");
var maxRowLength = sitePreferences.get("snapchatProductFeedMaxRow");
var hostName = require("dw/system/Site").current.httpsHostName;
var products = snapchatHelpers.onBeforeStep(args);
var fileNumber = 1;
var lineCount = 1;
snapchatHelpers.removeFiles(args);
var csvObject = snapchatHelpers.createCsvFile(fileNumber, args);
var csv = csvObject.csv;
var fileCreationResponse;
var fileWriter = csvObject.fileWriter;
while (products.hasNext()) {
var currentProductObject = products.next();
var priceObject = snapchatHelpers.getPrice(currentProductObject);
var product = {};
if (snapchatHelpers.shouldBeExported(currentProductObject)) {
if (maxRowLength !== lineCount) {
//Required Product Metadata
product.id = snapchatHelpers.getId(currentProductObject);
product.title = snapchatHelpers.getTitle(currentProductObject);
product.description = snapchatHelpers.getDescription(currentProductObject);
product.link = snapchatHelpers.getLink(currentProductObject, hostName);
product.imageLink = snapchatHelpers.getImageLink(currentProductObject);
product.price = priceObject && priceObject.list ? priceObject.list : "";
product.availability = snapchatHelpers.getAvailability(currentProductObject);
product.item_group_id = snapchatHelpers.getItemGroupID(currentProductObject);
product.additional_image_link = snapchatHelpers.getAdditionalImageLink(currentProductObject);
product.brand = snapchatHelpers.getBrand(currentProductObject);
product.google_product_category = snapchatHelpers.getGoogleCategoryByProduct(currentProductObject);
product.sale_price = priceObject && priceObject.sale ? priceObject.sale : "";
product.color = snapchatHelpers.getColor(currentProductObject);
product.age_group = snapchatHelpers.getCustomAttribute(currentProductObject, "age_group", "Adult");
product.gender = snapchatHelpers.getCustomAttribute(currentProductObject, "gender", "Unisex");
product.condition = snapchatHelpers.getCustomAttribute(currentProductObject, "condition", "New");
//Optional Product Metadata
product.product_type = snapchatHelpers.getProductType(currentProductObject);
product.adult = snapchatHelpers.getCustomAttribute(currentProductObject, "adult", "No");
product.size = snapchatHelpers.getSize(currentProductObject);
product.sale_price_effective_date = priceObject && priceObject.startDate ? StringUtils.format("{0}/{1}", priceObject.startDate, priceObject.endDate) : "";
csv.writeNext([
product.id,
product.title,
product.description,
product.link,
product.imageLink,
product.availability,
product.price,
product.brand,
product.age_group,
product.color,
product.condition,
product.gender,
product.item_group_id,
product.google_product_category,
product.product_type,
product.adult,
product.size,
product.additional_image_link,
product.sale_price,
product.sale_price_effective_date
]);
lineCount++;
} else {
fileNumber++;
lineCount = 1;
fileCreationResponse = snapchatHelpers.createCsvFile(fileNumber, args);
csv = fileCreationResponse.csv;
}
}
}
products.close();
csv.close();
fileWriter.close();
Logger.info("Facebook feed exported at {0}", snapchatHelpers.getFeedURL(args, fileCreationResponse.fileName));
return new Status(Status.OK, 'OK', 'Export successful');
} catch (e) {
return new Status(Status.ERROR, 'ERROR', 'Failed to export the feed: ' + e);
}
}
exports.Run = run;
Using inheritance with an Object oriented structure seems logical at first, but since we are working with javascript, I would like to implement it if there is a simpler way by sacrificing object oriented.

Related

Multithread node.js instagram parser

Working on node.js instagram parser. At the moment I have 1 thread with proxy working code, but I'm not sure how to make multithread architecture:
'use strict';
var InstagramPrivateAPI = {};
InstagramPrivateAPI = {};
InstagramPrivateAPI.V1 = require(__dirname + '/client/v1');
InstagramPrivateAPI.Helpers = require(__dirname + '/helpers');
var acc = require(__dirname + "/client/v1/account");
var med = require(__dirname + "/client/v1/media")
var Promise = require('../bluebird');
var _ = require('../lodash/');
module.exports = InstagramPrivateAPI;
var Client = require('instagram-private-api').V1;
var device = new Client.Device('maksgmn');
var storage = new Client.CookieFileStorage(__dirname + '/cookies/maksgmn.json');
var session = new Client.Session(device, storage);
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var fs = require('fs');
var proxyArray = fs.readFileSync('proxy.txt').toString().split("\n");
var usernamesArray = fs.readFileSync('usernames.txt').toString().split("\n");
var proxy = "http://" + proxyArray[getRandomInt(0,proxyArray.length)]
var username = usernamesArray[getRandomInt(0,usernamesArray.length)]
console.log(proxy)
console.log(username)
Client.Request.setProxy(proxy);
acc.searchForUser(session, username) //поиск id пользователя
.then(function(profile) {
return profile.id
})
.then(function(someId) { //получение промиса lenta
var feed = new Client.Feed.UserMedia(session, someId);
var lenta = Promise.mapSeries(_.range(0, 1), function() {
return feed.get();
}).then(function(lenta) {
return {id: someId, fd : lenta}
})
return lenta
})
.then(function(results) { //обработка промиса и получение ленты пользователя
// result should be Media[][]
var media1 = _.flatten(results.fd);
var urls1 = _.map(media1, function(medium) {
//var arr1 = medium.params.images[0].url;
var arr1 = []
try {
arr1 = medium.params.images[0].url
} catch (err) {
//console.log("lala")
}
return arr1;
//console.log(medium.params.carouselMedia.images[0].url)
})
//console.log(urls1)
return {id : results.id, linksNoCarousel : urls1, med : media1}
})
.then(function(res){
var urls2 = _.map(res.med, function(medium) {
var arr2 = []
try {
arr2 = medium.params.images[0][0].url
//console.log(arr2)
} catch (err) {
}
return arr2
})
for (var i = 0; i < 5; i++) {
if (typeof res.linksNoCarousel[i] == "undefined")
res.linksNoCarousel[i] = urls2[i];
}
var arr3 = []
for (var i = 0; i < 5; i++) {
arr3[i] = res.linksNoCarousel[i]
}
return {id : res.id, links : arr3}
})
.then(function(mediaAndId) {
acc = acc.getById(session, mediaAndId.id)
.then(function(account) {
//console.log(account.params)
let avatar = account.params.profilePicUrl;
let fullName = account.params.fullName;
let bio = account.params.biography;
let media0 = mediaAndId.links[0];
let media1 = mediaAndId.links[1];
let media2 = mediaAndId.links[2];
let media3 = mediaAndId.links[3];
let media4 = mediaAndId.links[4];
console.log(avatar);
console.log(fullName);
console.log(bio);
console.log(media0);
console.log(media1);
console.log(media2);
console.log(media3);
console.log(media4);
})
})
I would like it to work like multithread to be much more faster with proxies. As far as I'm working with node.js 2nd day, asking that question: how to do that?

I would like to analyze the image with tensorflw.js - nodejs

mobilenet.js
var loadFrozenModel = require('#tensorflow/tfjs-converter');
var NamedTensorMap = require('#tensorflow/tfjs-converter');
var tfc = require('#tensorflow/tfjs-core');
var IMAGENET_CLASSES = require('./imagenet_classes');
const GOOGLE_CLOUD_STORAGE_DIR = 'https://storage.googleapis.com/tfjs-models/savedmodel/';
const MODEL_FILE_URL = 'mobilenet_v1_1.0_224/optimized_model.pb';
const WEIGHT_MANIFEST_FILE_URL = 'mobilenet_v1_1.0_224/weights_manifest.json';
const INPUT_NODE_NAME = 'input';
const OUTPUT_NODE_NAME = 'MobilenetV1/Predictions/Reshape_1';
const PREPROCESS_DIVISOR = tfc.scalar(255 / 2);
class MobileNet {
constructor() {}
async load() {
this.model = await loadFrozenModel(
GOOGLE_CLOUD_STORAGE_DIR + MODEL_FILE_URL,
GOOGLE_CLOUD_STORAGE_DIR + WEIGHT_MANIFEST_FILE_URL);
}
dispose() {
if (this.model) {
this.model.dispose();
}
}
predict(input) {
const preprocessedInput = tfc.div(
tfc.sub(input.asType('float32'), PREPROCESS_DIVISOR),
PREPROCESS_DIVISOR);
const reshapedInput =
preprocessedInput.reshape([1, ...preprocessedInput.shape]);
const dict = {};
dict[INPUT_NODE_NAME] = reshapedInput;
return this.model.execute(dict, OUTPUT_NODE_NAME);
}
getTopKClasses(predictions, topK) {
const values = predictions.dataSync();
predictions.dispose();
let predictionList = [];
for (let i = 0; i < values.length; i++) {
predictionList.push({value: values[i], index: i});
}
predictionList = predictionList
.sort((a, b) => {
return b.value - a.value;
})
.slice(0, topK);
return predictionList.map(x => {
return {label: IMAGENET_CLASSES[x.index], value: x.value};
});
}
}
module.exports = MobileNet;
test.js
var tfc = require('#tensorflow/tfjs-core');
var MobileNet = require('./mobilenet');
var fs = require('fs');
var image = require('get-image-data')
var i = 0;
var meta;
image('./cat.jpg', function(err, getImageData){
if(err) throw err;
console.log('start to image data ');
console.log(i++);
console.log("meta : " + getImageData.data.length);
console.log("getImageData :"+getImageData);
const mobileNet = new MobileNet();
console.time('Loading of model');
// await mobileNet.load();
console.timeEnd('Loading of model');
console.log("maybee this is error on the data type");
const pixels = tfc.fromPixels(image);
console.time('First prediction');
let result = mobileNet.predict(pixels);
const topK = mobileNet.getTopKClasses(result, 5);
console.timeEnd('First prediction');
resultElement.innerText = '';
topK.forEach(x => {
resultElement.innerText += `${x.value.toFixed(3)}: ${x.label}\n`;
});
console.time('Subsequent predictions');
result = mobileNet.predict(pixels);
mobileNet.getTopKClasses(result, 5);
console.timeEnd('Subsequent predictions');
mobileNet.dispose();
});
I want to analyze the image using the tensorflow.js.
But it doesn't work.
ReferenceError: ImageData is not defined
at MathBackendCPU.fromPixels (/Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/#tensorflow/tfjs-core/dist/kernels/backend_cpu.js:75:31)
at Engine.fromPixels (/Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/#tensorflow/tfjs-core/dist/engine.js:292:29)
at ArrayOps.fromPixels (/Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/#tensorflow/tfjs-core/dist/ops/array_ops.js:195:41)
at /Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/#tensorflow/tfjs-core/dist/ops/operation.js:11:61
at Object.Tracking.tidy (/Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/#tensorflow/tfjs-core/dist/tracking.js:36:22)
at Object.descriptor.value [as fromPixels] (/Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/#tensorflow/tfjs-core/dist/ops/operation.js:11:26)
at /Users/leeyongmin/Documents/tfjs-converter-master-2/demo/test.js:26:22
at /Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/get-image-data/index.js:18:7
at load (/Users/leeyongmin/Documents/tfjs-converter-master-2/demo/node_modules/get-image/server.js:18:5)
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)

How do I call a vendor library from my main.js?

I have a basic electron app where I am trying to use vendor supplied js library. The example they supplied provides a static html page which includes their custom library and an example js file. This is the html
<HTML>
<HEAD>
<TITLE> MWD Library </TITLE>
</HEAD>
<BODY>
<h2>MWD Library Example</h2>
<input id="authAndConnect" type="button" value="authenticate and connect to stream" onclick="authenticateAndConnectToStream()" /></br></br>
<input id="clickMe" type="button" value="place position" onclick="placePosition()" /></br></br>
<input id="unsubscribeMe" type="button" value="unsubscribe" onclick="unsubscribe()" />
<input id="streamError" type="button" value="reconn to stream" onclick="reconnectToStream()" />
<input id="historicalData" type="button" value="historical data for GOLD" onclick="getHistoricalData()" />
<input id="goldExpiries" type="button" value="expiries for GOLD" onclick="getCurrentGoldExpiries()" /></br></br>
<input id="userTrades" type="button" value="active&completed trades" onclick="getUserTrades()" />
</BODY>
<SCRIPT SRC="jquery.ajax.js"></SCRIPT>
<SCRIPT SRC="mwdlib.js"></SCRIPT>
<SCRIPT SRC="app.js"></SCRIPT>
</HTML>
In the example above the button click calls authenticateAndConnectToStream in their example apps.js
//DEMO
//provide API key
MWDLibrary.config("dwR4jXn9ng9U2TbaPG2TzP1FTMqWMOuSrCWSK5vRIW7N9hefYEapvkXuYfVhzmdyFypxdayfkUT07HltIs4pwT0FIqEJ6PyzUz0mIqGj1GtmAlyeuVmSC5IcjO4gz14q");
//authenticate on MarketsWorld
var getAuthTokenParams = {email:"rtmarchionne#gmail.com", password:"Pitts4318AEM"};
var authenticateAndConnectToStream = function(){
MWDLibrary.getAuthDetails(getAuthTokenParams, function(authDetails) {
//optional: get older data
var marketsToSubscribeTo = ['GOLD', 'AUDNZD'];
for (var i = 0; i < marketsToSubscribeTo.length; i++){
MWDLibrary.getHistoricalData(marketsToSubscribeTo[i], function(response) {
console.log(response);
}, function(errorMessage) {
console.log(errorMessage);
});
}
//now you can connect to stream
MWDLibrary.connect(marketsToSubscribeTo, function() {
addMarketsListeners();
}, function(errorMessage) {
console.log(errorMessage);
});
}, function(errorMessage) {
console.log(errorMessage);
});
};
I want to call the same methods that start with MWDLibrary. from my main js like MWDLibrary.config("dwR4jXn9")
My main.js:
const electron = require('electron')
var path = require('path');
var countdown = require(path.resolve( __dirname, "./tradescaler.js" ) );
var mwd = require(path.resolve( __dirname, "./mwdlib.js" ) );
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const ipc = electron.ipcMain
let mainWindow
app.on('ready', _ => {
mainWindow = new BrowserWindow({
height: 360,
width: 700,
title: "TradeScaler Beta - Creative Solutions",
//frame: false,
alwaysOnTop: true,
autoHideMenuBar: true,
backgroundColor: "#FF7E47",
})
mainWindow.loadURL('file://' + __dirname + '/tradescaler.html')
mainWindow
//mainWindow.setAlwaysOnTop(true, 'screen');
mainWindow.on('closed', _ => {
mainWindow = null
})
})
ipc.on('countdown-start', _ => {
console.log('caught it!');
MWDLibrary.config();
countdown(count => {
mainWindow.webContents.send('countdown', count)
})
})
In my main.js above I get an error that says MWDLibrary is not defined.
Is it the structure of the library that is the problem? do i have to pass a window or modify the library?
Here is the library I'm trying to use:
(function(window){
'use strict';
function init(){
var MWDLibrary = {};
var transferProtocol = "https://"
var streamTransferProtocol = "https://"
var baseTLD = "www.marketsworld.com"
var basePort = ""
var streamBaseTLD = "www.marketsworld.com"
var streamPort = ""
var authToken = "";
var publicId = "";
var userLevel = "user";
var apiKey = "-";
var streamUrl = "";
var streamToken = "";
var subscribedChannels = [];
var streamEvents = {};
var offersWithExpiries = [];
var filteredExpiries = {};
var positions = {};
var evtSource;
MWDLibrary.config = function(apiUserKey){
apiKey = apiUserKey;
}
MWDLibrary.expiries = function(market){
return filteredExpiries[market];
}
MWDLibrary.connect = function(channelsToSubscribeTo, successHandler, errorHandler){
//console.log("Connecting...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var dispatchUrl = streamTransferProtocol+streamBaseTLD+streamPort+'/api/dispatcher';
getJSON(dispatchUrl, apiKey, authToken, function(data){
var data_from_json = JSON.parse(data);
if(data_from_json.url){
var url = data_from_json.url+'/announce?callback=__callback&publicToken='+publicId+'&userLevel='+userLevel+'&_='+(new Date().getTime() / 1000);
getJSON(url, apiKey, authToken, function(data) {
var data_from_json = JSON.parse(data);
if(data_from_json.url){
streamUrl = data_from_json.url.substring(0,data_from_json.url.lastIndexOf("/user"));
streamToken = data_from_json.url.split("token=")[1];
MWDLibrary.subscribe(channelsToSubscribeTo, function(subscribeResponseData) {
evtSource = new EventSource(streamTransferProtocol+data_from_json.url);
evtSource.onopen = sseOpen;
evtSource.onmessage = sseMessage;
evtSource.onerror = sseError;
successHandler('connected');
return;
}, function(errorMessage) {
errorHandler(errorMessage);
return;
});
}
else{
//console.log(data);
errorHandler('Something went wrong.');
return;
}
}, function(status) {
//console.log(status);
errorHandler(status);
return;
});
}
else{
//console.log(data);
errorHandler('Something went wrong.');
return;
}
}, function(status) {
//console.log(status);
errorHandler(status);
return;
});
}
MWDLibrary.subscribe = function(channelsToSubscribeTo, successHandler, errorHandler){
//console.log("Subscribing...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var channels = 'ALL|TEST|private.'+publicId;
if (channelsToSubscribeTo.length > 0){
var auxChannels = '';
if(subscribedChannels.length > 0){
channels = subscribedChannels[0];
for(var j = 1; j < subscribedChannels.length; j++){
channels = channels +'|'+subscribedChannels[j];
}
}
for(var i = 0; i < channelsToSubscribeTo.length; i++)
{
if(subscribedChannels.indexOf(channelsToSubscribeTo[i])==-1){
auxChannels = auxChannels+'|'+channelsToSubscribeTo[i]+'|'+channelsToSubscribeTo[i]+'.game#1';
}
}
channels = channels+auxChannels;
}
else{
if (subscribedChannels.length == 0)
{
channels = channels+'|GOLD|GOLD.game#1';
}
else{
channels = subscribedChannels[0];
for (var j = 1; j < subscribedChannels.length; j++){
channels = channels + '|' + subscribedChannels[j];
}
}
}
var subscribeUrl = streamTransferProtocol+streamUrl+'/user/stream/subscribe?callback=__callback&token='+streamToken+'&channels='+escape(channels)+'&_='+(new Date().getTime() / 1000);
//subscribe to channels
getJSON(subscribeUrl, apiKey, authToken, function(subscribeData) {
var subscribeData_from_json = JSON.parse(subscribeData);
subscribedChannels = subscribeData_from_json.channels;
//console.log(subscribedChannels);
for (var i = 0; i < subscribedChannels.length; i++)
{
if (subscribedChannels[i] == 'ALL')
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['heartbeat'] = new CustomEvent('ALL.heartbeat', {'detail':'-'});
streamEvents[subscribedChannels[i]]['status'] = new CustomEvent('ALL.status', {'detail':'-'});
continue;
}
if (subscribedChannels[i].lastIndexOf('private') > -1)
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['positions'] = new CustomEvent('PRIVATE.positions', {'detail':'-'});
streamEvents[subscribedChannels[i]]['balance'] = new CustomEvent('PRIVATE.balance', {'detail':'-'});
continue;
}
if (subscribedChannels[i].lastIndexOf('game') > -1)
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['expiry'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.expiry', {'detail':'-'});
streamEvents[subscribedChannels[i]]['spread'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.spread', {'detail':'-'});
streamEvents[subscribedChannels[i]]['payout'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.payout', {'detail':'-'});
streamEvents[subscribedChannels[i]]['offer'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.offer', {'detail':'-'});
continue;
}
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['value'] = new CustomEvent(subscribedChannels[i]+'.value', {'detail':'-'});
}
successHandler(subscribeData_from_json);
}, function(status) {
errorHandler(status);
});
}
MWDLibrary.unsubscribe = function(channelsToUnsubscribeFrom, successHandler, errorHandler){
//console.log("Unsubscribing...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
if(channelsToUnsubscribeFrom.length == 0){
errorHandler("Please select markets to unsubscribe from.");
return;
}
var channels = channelsToUnsubscribeFrom[0]+'|'+channelsToUnsubscribeFrom[0]+'.game#1';
for(var i = 1; i < channelsToUnsubscribeFrom.length; i++)
{
channels = channels+'|'+channelsToUnsubscribeFrom[i]+'|'+channelsToUnsubscribeFrom[i]+'.game#1';
}
var subscribeUrl = streamTransferProtocol+streamUrl+'/user/stream/unsubscribe?callback=__callback&token='+streamToken+'&channels='+escape(channels)+'&_='+(new Date().getTime() / 1000);
//subscribe to channels
getJSON(subscribeUrl, apiKey, authToken, function(unsubscribeData) {
var unsubscribeData_from_json = JSON.parse(unsubscribeData);
var unsubscribedChannels = unsubscribeData_from_json.channels;
for(var i = 0; i < unsubscribedChannels.length; i++)
{
var index = subscribedChannels.indexOf(unsubscribedChannels[i]);
if(index != -1) {
subscribedChannels.splice(index, 1);
}
}
//console.log(subscribedChannels);
successHandler(unsubscribeData_from_json);
}, function(status) {
errorHandler(status);
});
}
MWDLibrary.getAuthDetails = function(params, successHandler, errorHandler){
//console.log("getting auth token...");
var url = transferProtocol+baseTLD+basePort+'/api/v2/sessions';
postJSON(url, apiKey, authToken, params, function(data) {
var data_from_json = JSON.parse(data);
if (!data_from_json.error){
authToken = data_from_json.api_session_token.token;
publicId = data_from_json.api_session_token.user.public_id;
successHandler(data_from_json.api_session_token);
return;
}
else{
errorHandler(data_from_json.error);
return;
}
}, function(status) {
errorHandler(status);
return;
});
}
MWDLibrary.placePosition = function(params, successHandler, errorHandler){
//console.log("placing a position...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var url = transferProtocol+baseTLD+basePort+'/api/v2/positions';
if(params.market == ''){
errorHandler('Market code is missing.');
return;
}
var position = positions[params.market];
if(!position || position.market_value <= 0){
errorHandler('No data for this market.');
return;
}
if(!params.offer_id || params.offer_id == ''){
errorHandler('Offer id is missing.');
return;
}
if(!params.resolution_at || params.resolution_at <= 0){
errorHandler('Expiry time is missing.');
return;
}
if(!params.type || params.type == ''){
errorHandler('Position type is missing.');
return;
}
if(!params.wager || params.wager <= 0){
errorHandler('Wager is missing.');
return;
}
position.offer_id = params.offer_id;
position.resolution_at = params.resolution_at;
position.type = params.type;
position.wager = params.wager;
//console.log(position);
postJSON(url, apiKey, authToken, position, function(data) {
var data_from_json = JSON.parse(data);
if (!data_from_json.error){
successHandler(data_from_json);
return;
}
else{
errorHandler(data_from_json.error);
return;
}
}, function(status) {
errorHandler(status+' - make sure all parameters are set correctly and wait 10 seconds between bets');
return;
});
}
MWDLibrary.getMarkets = function(successHandler, errorHandler){
//console.log("getting markets list...");
getJSON(transferProtocol+baseTLD+basePort+'/api/v2/markets.json', apiKey, authToken, function(data) {
var data_from_json = JSON.parse(data);
for (var i = 0; i < data_from_json.length; i++) {
var status = "closed";
if (data_from_json[i].market.next_open_time > data_from_json[i].market.next_close_time)
{
status = "open";
}
data_from_json[i].market.status = status;
}
successHandler(data_from_json);
}, function(status) {
errorHandler(status);
});
}
var sortedOffersWithExpiries = offers.sort(compareOffersBtOrder);
for (var i=0; i<sortedOffersWithExpiries.length;i++)
{
expiryValue = 0;
expiryResult = 0;
var expiriesCopy = sortedOffersWithExpiries[i].expiries;
for (var index = 0; index<expiriesCopy.length;index++)
{
expiryValue = expiriesCopy[index]
if (expiryValue > lastExpiry)
{
expiryResult = expiryValue
break
}
}
if (expiryResult != 0)
{
var tuple = {};
tuple.timestamp = expiryValue/1000;
tuple.offerId = sortedOffersWithExpiries[i].offer;
tuple.cutout = sortedOffersWithExpiries[i].cutout;
expiriesFinalList.push(tuple);
lastExpiry = expiryValue
}
}
return expiriesFinalList;
}
function compareOffersBtOrder(a,b) {
if (a.order < b.order)
return -1;
if (a.order > b.order)
return 1;
return 0;
}
})/*(window)-->*/;
You're missing the .js file extension at the end of mwdlib
And you may need to require it using the full system path, instead of a relative one.
var mwd = require(path.resolve( __dirname, "./mwdlib.js" ) );

dynamically added input text field and get values to php and send to mysql

I have created like attachment and I have some problem to develop. The text boxes in bottom are dynamically created when add Article button pressed and now I want to update that "Added Article Details" section insert into mysql database some times have 5 rows sometime 2 rows and 1 row also wants to add. I named text box 1,2,3,4,5,6....... how to solve
My Javascript
function added_artic() {
if (added_art) {
document.getElementById('added_article').style.cssText = "display:block;";
var art_name = document.getElementsByName('article_name')[0].value;
var app = document.getElementsByName('appearance')[0].value;
var weight = document.getElementsByName('weight')[0].value;
var netWeight = document.getElementsByName('net_weight')[0].value;
var qty = document.getElementsByName('qty')[0].value;
var test = document.getElementsByName('test')[0].selectedOptions[0].text;
var added = document.getElementById("added");
var i_artname = document.createElement('input');
i_artname.value = art_name;
i_artname.name = "art_name" + art_name_id++;
i_artname.id = "txt_added";
i_artname.disabled = true;
added.appendChild(i_artname);
var i_app = document.createElement('input');
i_app.value = app;
i_app.name = "app" + app_id++;
i_app.id = "txt_added";
i_app.disabled = true;
added.appendChild(i_app);
var i_weight = document.createElement('input');
i_weight.value = weight;
i_weight.name = "weight" + weight_id++;
i_weight.id = "txt_added";
i_weight.className = "cal_weight";
i_weight.disabled = true;
added.appendChild(i_weight);
var i_netweight = document.createElement('input');
i_netweight.value = netWeight;
i_netweight.name = "netWeight" + netWeight_id++;
i_netweight.id = "txt_added";
i_netweight.className = "cal_netWeight";
i_netweight.disabled = true;
added.appendChild(i_netweight);
var i_qty = document.createElement('input');
i_qty.value = qty;
i_qty.name = "qty" + qty_id++;
i_qty.id = "txt_added";
i_qty.className = "cal_qty";
i_qty.disabled = true;
added.appendChild(i_qty);
var i_test = document.createElement('input');
i_test.value = test;
i_test.name = "test" + test_id++;
i_test.id = "txt_added";
i_test.className = "cal_test";
i_test.disabled = true;
added.appendChild(i_test);
var remove_btn = document.createElement('input');
remove_btn.type = "button";
remove_btn.value = "";
remove_btn.id = "remove_btn";
remove_btn.onclick = function ()
{
i_artname.parentElement.removeChild(i_artname);
i_app.parentElement.removeChild(i_app);
i_weight.parentElement.removeChild(i_weight);
i_netweight.parentElement.removeChild(i_netweight);
i_qty.parentElement.removeChild(i_qty);
i_test.parentElement.removeChild(i_test);
edit_btn.parentElement.removeChild(edit_btn);
this.parentElement.removeChild(this);
get_total();
if (!document.getElementsByName("test1")[0] && !document.getElementsByName("test2")[0] && !document.getElementsByName("test3")[0] && !document.getElementsByName("test4")[0] && !document.getElementsByName("test5")[0] && !document.getElementsByName("test6")[0] && !document.getElementsByName("test7")[0] && !document.getElementsByName("test8")[0] && !document.getElementsByName("test9")[0] && !document.getElementsByName("test10")[0])
{
document.getElementById('added_article').style.cssText = "display:none;";
}
}
added.appendChild(remove_btn);
var edit_btn = document.createElement('input');
edit_btn.type = "button";
edit_btn.value = "";
edit_btn.id = "edit_btn";
var a = 'weight' + (weight_id - 1);
var b = 'netWeight' + (netWeight_id - 1);
var c = 'qty' + (qty_id - 1);
edit_btn.onclick = function ()
{
document.getElementsByName(a)[0].disabled = false;
document.getElementsByName(b)[0].disabled = false;
document.getElementsByName(c)[0].disabled = false;
edit_btn.style.cssText = "background-image: url('images/update.png');";
edit_btn.onclick = function ()
{
document.getElementsByName(a)[0].disabled = true;
document.getElementsByName(b)[0].disabled = true;
document.getElementsByName(c)[0].disabled = true;
edit_btn.style.cssText = "background-image: url('images/edit.png');";
get_total();
};
};
added.appendChild(edit_btn);
document.getElementsByName('article_name')[0].value = "Article Name";
document.getElementsByName('appearance')[0].value = "Appearance";
document.getElementsByName('weight')[0].value = "";
document.getElementsByName('net_weight')[0].value = "";
document.getElementsByName('qty')[0].value = "";
document.getElementsByName('test')[0].value = "Select You Tested Karatage type";
}
}
my Project screen shot -

How do I display the contents of js file retrieved from the server (using ajax and jquery) in my webpage?

Well I am trying to load and execute a js file using the following jquery function
$.getScript(url, function( data, textStatus, jqxhr ) {
console.log( textStatus ); // Success
console.log( jqxhr.responseText ); // 200
console.log( data);
console.log( "Load was performed." );
});
Well the requirement for me is to display the contents of js retrieved from server in my webpage. How do I do it?
Fiddle Demo to get js file
function get_html_translation_table (table, quote_style) {
var entities = {},
hash_map = {},
decimal;
var constMappingTable = {},
constMappingQuoteStyle = {};
var useTable = {},
useQuoteStyle = {};
// Translate arguments
constMappingTable[0] = 'HTML_SPECIALCHARS';
constMappingTable[1] = 'HTML_ENTITIES';
constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
constMappingQuoteStyle[2] = 'ENT_COMPAT';
constMappingQuoteStyle[3] = 'ENT_QUOTES';
useTable = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
throw new Error("Table: " + useTable + ' not supported');
// return false;
}
entities['38'] = '&';
if (useTable === 'HTML_ENTITIES') {
entities['160'] = ' '; entities['161'] = '¡'; entities['162'] = '¢'; entities['163'] = '£'; entities['164'] = '¤'; entities['165'] = '¥'; entities['166'] = '¦'; entities['167'] = '§'; entities['168'] = '¨'; entities['169'] = '©'; entities['170'] = 'ª'; entities['171'] = '«'; entities['172'] = '¬'; entities['173'] = '­'; entities['174'] = '®'; entities['175'] = '¯'; entities['176'] = '°'; entities['177'] = '±'; entities['178'] = '²'; entities['179'] = '³'; entities['180'] = '´'; entities['181'] = 'µ'; entities['182'] = '¶'; entities['183'] = '·'; entities['184'] = '¸'; entities['185'] = '¹'; entities['186'] = 'º'; entities['187'] = '»'; entities['188'] = '¼'; entities['189'] = '½'; entities['190'] = '¾'; entities['191'] = '¿'; entities['192'] = 'À'; entities['193'] = 'Á'; entities['194'] = 'Â'; entities['195'] = 'Ã'; entities['196'] = 'Ä'; entities['197'] = 'Å'; entities['198'] = 'Æ'; entities['199'] = 'Ç'; entities['200'] = 'È'; entities['201'] = 'É'; entities['202'] = 'Ê'; entities['203'] = 'Ë'; entities['204'] = 'Ì'; entities['205'] = 'Í'; entities['206'] = 'Î'; entities['207'] = 'Ï'; entities['208'] = 'Ð'; entities['209'] = 'Ñ'; entities['210'] = 'Ò'; entities['211'] = 'Ó'; entities['212'] = 'Ô'; entities['213'] = 'Õ'; entities['214'] = 'Ö'; entities['215'] = '×'; entities['216'] = 'Ø'; entities['217'] = 'Ù'; entities['218'] = 'Ú'; entities['219'] = 'Û'; entities['220'] = 'Ü'; entities['221'] = 'Ý'; entities['222'] = 'Þ'; entities['223'] = 'ß'; entities['224'] = 'à'; entities['225'] = 'á'; entities['226'] = 'â'; entities['227'] = 'ã'; entities['228'] = 'ä'; entities['229'] = 'å'; entities['230'] = 'æ'; entities['231'] = 'ç'; entities['232'] = 'è'; entities['233'] = 'é'; entities['234'] = 'ê'; entities['235'] = 'ë'; entities['236'] = 'ì'; entities['237'] = 'í'; entities['238'] = 'î'; entities['239'] = 'ï'; entities['240'] = 'ð'; entities['241'] = 'ñ'; entities['242'] = 'ò'; entities['243'] = 'ó'; entities['244'] = 'ô'; entities['245'] = 'õ'; entities['246'] = 'ö'; entities['247'] = '÷'; entities['248'] = 'ø'; entities['249'] = 'ù'; entities['250'] = 'ú'; entities['251'] = 'û'; entities['252'] = 'ü'; entities['253'] = 'ý'; entities['254'] = 'þ'; entities['255'] = 'ÿ';
}
if (useQuoteStyle !== 'ENT_NOQUOTES') {
entities['34'] = '"';
}
if (useQuoteStyle === 'ENT_QUOTES') {
entities['39'] = ''';
}
entities['60'] = '<';
entities['62'] = '>';
// ascii decimals to real symbols
for (decimal in entities) {
if (entities.hasOwnProperty(decimal)) {
hash_map[String.fromCharCode(decimal)] = entities[decimal];
}
}
return hash_map;
}
function htmlentities (string, quote_style, charset, double_encode) {
var hash_map = get_html_translation_table('HTML_ENTITIES', quote_style),
symbol = '';
string = string == null ? '' : string + '';
if (!hash_map) {
return false;
}
if (quote_style && quote_style === 'ENT_QUOTES') {
hash_map["'"] = ''';
}
if (!!double_encode || double_encode == null) {
for (symbol in hash_map) {
if (hash_map.hasOwnProperty(symbol)) {
string = string.split(symbol).join(hash_map[symbol]);
}
}
} else {
string = string.replace(/([\s\S]*?)(&(?:#\d+|#x[\da-f]+|[a-zA-Z][\da-z]*);|$)/g, function (ignore, text, entity) {
for (symbol in hash_map) {
if (hash_map.hasOwnProperty(symbol)) {
text = text.split(symbol).join(hash_map[symbol]);
}
}
return text + entity;
});
}
return string;
}
$(function(){
$("#getjs").click(function(){
var url="http://fiddle.jshell.net/js/codemirror/lib/codemirror.js";
$.ajax({
url: url,
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
$("#container").html("<pre>"+htmlentities(data) + "</pre>")
});
});
})
Does this not work?
<textarea id="ta" style="border:0;"></textarea>
$.getScript( url, function( data, textStatus, jqxhr ) {
$("#ta").val(data);
});
You can use phpjs's file_get_contents function to get the content of a javascript file
http://phpjs.org/functions/file_get_contents/

Categories

Resources