Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
can somebody help for my code which is written in python, i want to write it in javascript but im in trouble, i dont know how.
python code
cities={}
for line in open("linnadkaugustega.txt", "r", encoding="UTF-8"):
m=line.strip().split()
abim=[word.split(":") for word in m[1:]]
cities[m[0]]={}
for couple in abim:
cities[m[0]][couple[0]]=int(couple[1])
print(cities);
and i tried in javascript but that doesen't work
function tere(){
console.log("Tere");
$.get('read.txt', function(data) {
cities={};
var lines = (data.trim()).split();
abim=[var word.split(":") for word in m[1:]]
cities[m[0]]={};
for var couple in abim
cities[m[0]][couple[0]]=couple[1];
console.log(cities);
}, 'text');
}
tere();
can somebody help me ?
You have syntax issues translating from python to js. Heres how arrays work...
if you have an array litteral in javascript
var cities = [];
Then we would add to the array by calling push
cities.push('Portland');
...
cities.push('New York');
we can then iterate over the array by calling forEach on the array object.
cities.forEach(function (city, index){
//do work on each city
console.log(city);
});
// Portland
// New York
A few things:
.split() in JS does something different than split in python when no separator is given. To split a line into words, you'll need to split on whitespaces explicitly
you're missing the for loop over the lines of the file. Python uses the iterator syntax for reading from the file, in JavaScript an ajax request loads the whole file and you'll need to split it in lines yourself.
JavaScript does not have that m[1:] syntax, you'll need to use the .slice() method instead
JavaScript does not have array/list comprehensions. You will need to use an explicit loop, or the map method of arrays
your loop syntax is too pythonic. In JavaScript, for loops need parenthesis and an index variable.
So this should do (supposed you have the jQuery library loaded and it finds the file):
$.get('read.txt', function(data) {
var cities = {};
var lines = data.split("\n");
for (var i=0; i<lines.length; i++) {
var line = lines[i];
var m = line.trim().split(/\s+/);
var abim = m.slice(1).map(function(word) {
return word.split(":");
});
var obj = cities[m[0]] = {};
for (var j=0; j<abim.length; j++) {
var couple = abim[j];
obj[couple[0]] = couple[1];
}
}
console.log(cities);
}, 'text');
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So, hello. I edited the entire thing.
app.get('/', async (req, res) => {
let results = await db.collection("malwarepad-website").find("6047667ff156cb8135bdaa88").toArray()
//var resultsConverted = results.toString();
//let resultsFinal = resultsConverted.split('"');
console.log(results)
res.render('index.ejs', { startText: results });
})
In the above code I want to only keep the second part of it specified better in this image: https://i.stack.imgur.com/Wi031.png
I want to create a variable containing the following:
Hello, and welcome to my website. I don't know how you found me but yo...
I already have a constant containing the search results, but it is this:
[
{
_id: 6047667ff156cb8135bdaa88,
mainPage: "Hello, and welcome to my website. I don't know how you found me but you're welcome :)."
}
]
Thanks for the understanding :)
a = a.split("\"")[1]
If you mean extracting what's inside double quotations, you have two methods:
1 - Use Regular Expressions:
You can use regular expression /.*"(.*)".*/ which tries to capture everything inside parentheses. You can use exec method. like :
const importantPart = /.*"(.*)".*/.exec(a)[1] (a is your variable)
2 - Using indexOf string methods
In JavaScript strings have two useful methods: indexOf and lastIndexOf. In addition to a substring.
You can use these to extract the important part:
a.substring(a.indexOf('"') + 1, a.lastIndexOf('"'))
There are several solutions. One could be:
const a = 'odshniudfskdjnfdsjnf"Important part"fererferferef';
let a_splitted = a.split('"');
console.log(a_splitted[1]);
You can use regular expressions to extract the part that you need.
const a = 'odshniudfskdjnfdsjnf"Important part"fererferferef';
let result = a.match(/\"(.*)\"/);
console.log(result[1]);
There are a lot of what-ifs though.
const a = 'odshniudfskdjnfdsjnf"Important part"fererferferef';
let regex = /(?<=\")(.*?)(?=\")/;
let result = regex.exec(a)[0];
console.log(result);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
https://jsfiddle.net/a/2L4t9saq/217/ is my fiddle
most of the code you can ignore, here is the function:
var modGrid = function(code){
var arr = code
console.log(arr)
for(var n=1;n<gridx+1;n++){
for(var i = 1; i<gridy+1; i++){
var garbledMess = "[x="+i+"][y="+n+"]"
var idea = arr[0]
arr.shift()
$(garbledMess).css("background-color",idea)
}
}
}
the syntax error is as follows:
Uncaught TypeError: arr.shift is not a function
at modGrid ((index):44)
at window.onload ((index):81)
since the modGrid function takes in an array (in the case of my code an array of 4 elements) the .shift() function should be removing the first option in the array, it worked before i added some more code, but now it is apparently not a function
many thanks
since the modGrid function takes in an array
It is designed to take an array, but that isn't what you are passing it.
You are passing it a string, another string, a number and another number.
modGrid('rgba(255,0,0,1)','rgba(0,255,0,1)',2,1);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Can anybody provide the java script for the below JSON. I tried in many way, but could not add the field "set"
{
"student":[
"set",
[
{
"name":"abcd",
"id":"1234"
}
]
]
}
So your javaScript variable would be an objecthaving property/key name student of array type. Now student has two elements set a string and an object, other element is also an array, has an element of object type. This element has two properties/keys name and id.
var required = {};
required.student = [];
required.student.push("set");
var innerArray = [];
var innerObj = {};
innerObj.name = "abcd";
innerObj.id = "1234";
innerArray.push(innerObj);
required.student.push(innerArray);
document.write('<pre> ' + JSON.stringify(required,0, 3) + '</pre>');
JSON.parse(jsonString);
Is a pure JavaScript approach so long as you can require a reasonably modern browser.
See also https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I'm not sure what you are trying to do, but...
If you just want to have the JSON object you described available in your JavaScript code, you can just put it into a variable.
var json = {
"student":[
"set",
[
{
"name":"abcd",
"id":"1234"
}
]
]
};
// Testing the object:
// Print the JSON object we made, as a string
console.log(JSON.stringify(json));
// Print the first item inside the 'student' array
console.log(json.student[0]);
If you instead have your JSON as a string, you can parse it to JSON object with:
var json = JSON.parse(jsonString);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
[EDIT] I solved the problem using D3, nevermind thanks!
So I have a csv file that looks something like this, and I need to import a local csv file into my client side javascript:
"L.Name", "F.Name", "Gender", "School Type", "Subjects"
"Doe", "John", "M", "University", "Chem I, statistics, English, Anatomy"
"Tan", "Betty", "F", "High School", "Algebra I, chem I, English 101"
"Han", "Anna", "F", "University", "PHY 3, Calc 2, anatomy I, spanish 101"
"Hawk", "Alan", "M", "University", "English 101, chem I"
I eventually need do parse it and output something like:
Chem I: 3 (number of people taking each subject)
Spanish 101: 1
Philosophy 204: 0
But for now, I am stuck on just importing it into javascript.
My current code looks like this:
<!DOCTYPE html>
<html>
<body>
<h1>Title!</h1>
<p>Please enter the subject(s) that you wish to search for:</p>
<input id="numb" type="text"/>
<button onclick="myFunction()">Click me to see! :) </button>
<script>
function myFunction() {
var splitResearchArea = [];
var textInput = document.getElementById('numb').value;
var splitTextInput = textInput.split(",");
for(var i =0; i<splitTextInput.length; i++) {
var spltResearchArea = splitTextInput[i];
splitResearchArea.push(spltResearchArea);
}
}
I've researched and found some helpful links on Stackoverflow like this, this, and this but I'm new to javascript and I don't completely understand it. Should I use Ajax? FileReader? jQuery? What are the benefits of using one over the other? And how would you implement this in code?
But yeah, I'm just confused since I'm very new to javascript, so any help in the right direction would be great. Thank you!!
Here is how to use the readAsBinaryString() from the FileReader API to load a local file.
Basically, just need to listen to change event in <input type="file"> and call the readFile function.
const fileInput = document.getElementById('csv')
const readFile = () => {
const reader = new FileReader()
reader.onload = () => {
document.getElementById('out').innerHTML = reader.result
}
// start reading the file. When it is done, calls the onload event defined above.
reader.readAsBinaryString(fileInput.files[0])
}
fileInput.addEventListener('change', readFile)
<div>
<p>Select local CSV File:</p>
<input id="csv" type="file" accept=".csv">
</div>
<pre id="out"><p>File contents will appear here</p></pre>
jsFiddle
There are as many ways of accomplishing what you want as you could possibly imagine.
If I were doing this, I might start by splitting the input text into lines like so:
var lines = inputText.split('\n');
Then, I would extract the names of the headers from the first line.
You need a function to read the values from each line.
// This assumes no commas in the values names.
function getCsvValuesFromLine(line) {
var values = line[0].split(',');
value = values.map(function(value){
return value.replace(/\"/g, '');
});
return values;
}
var headers = getCsvValuesFromLine(lines[0]);
Next, I would loop over the remaining lines and create an array of objects representing the values in the lines.
lines.shift(); // remove header line from array
var people = lines.map(function(line) {
var person = {};
var lineValues = getCsvValuesFromLine(line);
for (var i = 0; i < lines.length; i += 1) {
person[headers[i]] = lineValues[i];
}
return person;
});
If this all works, you should end up with an array of objects representing the values in each line in your CSV.
The above is a rough outline of what the code might look like. I have not tested it and it certainly is not production ready, but I hope it gives you an idea of how to go about doing what you want.
I've used several built-in Javascript functions. I suggest looking them up on MDN if you're not familiar with them; they are good to know.
Finally, there is an odd quirk in Javascript with its automatic semi-colon insertion (a bad feature of the language, IMO). In order to avoid problems, do not put a new-line before an opening brace.
Always write
XXXX {
....
}
and don't write
XXXX
{
....
}
i use this library from google: https://github.com/evanplaice/jquery-csv/
First - u have to
$.get(ur_csv_file_path);
and then use guide from page
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
I obfuscated my javascript code using this one http://www.javascriptobfuscator.com/Default.aspx but it seems I can' find way to back it to original code.. is there any way?
You can get back some of your code, but almost all function names will be lost and local variables tend to get replaced.
Take for example the default code at the link you provided:
ORIGINAL
function NewObject(prefix)
{
var count=0;
this.SayHello=function(msg)
{
count++;
alert(prefix+msg);
}
this.GetCount=function()
{
return count;
}
}
var obj=new NewObject("Message : ");
obj.SayHello("You are welcome.");
OBFUSCATED
var _0x5601=["\x53\x61\x79\x48\x65\x6C\x6C\x6F","\x47\x65\x74\x43\x6F\x75\x6E\x74","\x4D\x65\x73\x73\x61\x67\x65\x20\x3A\x20","\x59\x6F\x75\x20\x61\x72\x65\x20\x77\x65\x6C\x63\x6F\x6D\x65\x2E"];function NewObject(_0xa158x2){var _0xa158x3=0;this[_0x5601[0]]=function (_0xa158x4){_0xa158x3++;alert(_0xa158x2+_0xa158x4);} ;this[_0x5601[1]]=function (){return _0xa158x3;} ;} ;var obj= new NewObject(_0x5601[2]);obj.SayHello(_0x5601[3]);
STEP 1 - Decode variable array
Firstly we need to decode the variable array (the part that starts var _0x5601= and ends just before the first function). I find the easiest way to do this is to copy and paste the array into Chromes developer console. Just paste the whole line and hit enter, then in the console type the variable name and you'll get something like this:
["SayHello", "GetCount", "Message : ", "You are welcome."]
STEP 2 - String Replace code for variable array item
Next we employ the help of whichever programming language you'd like to parse this new array back into the js. In essence, take your newly decoded array, and perform a string replace the rest of the code. I had PHP handy, so i did this:
<?php
// decoded array
$_0x5601 = array("SayHello", "GetCount", "Message : ", "You are welcome.");
// rest of the obfuscated code
$code = "function NewObject(_0xa158x2){var _0xa158x3=0;this[_0x5601[0]]=function (_0xa158x4){_0xa158x3++;alert(_0xa158x2+_0xa158x4);} ;this[_0x5601[1]]=function (){return _0xa158x3;} ;} ;var obj= new NewObject(_0x5601[2]);obj.SayHello(_0x5601[3]);";
// loop over array
for($x = 0; $x < count($_0x5601); $x++){
// string replace on the code
$code = str_replace('_0x5601['.$x.']', '"'.$_0x5601[$x].'"', $code);
}
// output result
echo $code;
?>
STEP 3 - BEAUTIFY
Now, lets "beautify" the code using something like: http://jsbeautifier.org/
function NewObject(_0xa158x2) {
var _0xa158x3 = 0;
this["SayHello"] = function(_0xa158x4) {
_0xa158x3++;
alert(_0xa158x2 + _0xa158x4);
};
this["GetCount"] = function() {
return _0xa158x3;
};
};
var obj = new NewObject("Message : ");
obj.SayHello("You are welcome.");
STEP 4 - Regex replace array items with object notation
The last step is to perform one last replace, but this time we need to employ the help of regex. I use an IDE called Sublime Text 2 that has the ability to do find and replace regex (im sure most IDE's have this too).
The regex pattern i used looks like this \[\"([a-zA-Z0-9\-\_]+)\"\] to explain:
\[\" // code must start with ["
( // open capturing group
[a-zA-Z0-9]+ // match all characters a-zA-Z0-9 you may need to adjust this to include -, _ etc as needed
) // capture everything in this group
\"\] // code must end with "]
You want to replace anything that matches this pattern with .$1. Resulting in:
function NewObject(_0xa158x2) {
var _0xa158x3 = 0;
this.SayHello = function(_0xa158x4) {
_0xa158x3++;
alert(_0xa158x2 + _0xa158x4);
};
this.GetCount = function() {
return _0xa158x3;
};
};
var obj = new NewObject("Message : ");
obj.SayHello("You are welcome.");
It's not quite as pretty, and as i mentioned local variables have been replaced. But if you know your code it shouldnt be too difficult to understand what they are doing.