Search the Community
Showing results for tags 'javascript'.
-
How and why I made Syntatical (an NPM package that changes how you write JavaScript) Basics of Syntatical: Goal: The initial goal was to make an NPM package that changed how JavaScript is written. Not to make it "easier" or "weirder", just a different way to write it. How it works: Syntactical basically just puts JavaScript code into functions. Making multi-line functions one-line. It also makes console.log shorter, I did this because I hate using console.log() to log everything. To show it better I will use a snippit from the index file "arr_buff":function(num){ if(isNaN(num) == false){ var b = new ArrayBuffer(num); console.log(b.byteLength); } else if(Array.isArray(num)){ var x = num.length; console.log(x) } else { console.log("input invalid") } }, This basically takes if(isNaN(num) == false){ var b = new ArrayBuffer(num); console.log(b.byteLength); } else if(Array.isArray(num)){ var x = num.length; console.log(x) } else { console.log("input invalid") } and shrinks it down to s.arr_buff(633) // ------ OR ------ // You can use: s.arr_buff(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]) The one on top will print out: 633 The one bellow will print out: 26 s.arr_buff("a string, not an array") This one will print our "input invalid" Why Node.js and NPM? JavaScript's syntax is fine, but I thought I could make it simple. I would have done it in Python if I felt like Python needed this, which I feel it really does not. JavaScript's syntax is easy, but I wanted to make it easier. How to install and use: Install script and view the Syntatical NPM repo What does the future hold for Syntatical? A lot actually. I am going to gather a few friends to continue development on the main Syntatical package. Plans for syntatical-electron, syntatical-discord, syntatical-express and syntatical-passport do exist and are being considered. Having a Syntatical.py module is also in thought, same with a Syntatical.lua package. However these are plans in consideration, not yet confirmed!
-
Hi I'm using a .html file languages: html, css, javascript level: beginner problem: myFunction2() does not toggle the h2 class ("city") <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Use of The class Attribute in JavaScript </title> </head> <body> <h2> Use of the class Attribute in JavaScript </h2> <p> Click the button to hide/show all elements with the class name "city": </p> <button onclick="myFunction()"> Hide elements </button> <button onclick="myFunction2()"> Hide/Show Elements </button> <h2 class="city"> London </h2> <p> London is the capital of England </p> <h2 class="city"> Paris </h2> <p> Paris is the capital of France </p> <h2 class="city"> Tokyo </h2> <p> Tokyo is the capital of Japan </p> <p> <b> Note: </b> The element will not take up any space when the display property set to "none". </p> <script> function myFunction() { var x = document.getElementsByClassName ("city"); for (var i = 0; i < x.length; i++) { x[i].style.display = "none"; } } function myFunction2() { var x = document.getElementsByClassName ("city"); t.classList.toggle ("city"); for (var i = 0; i < x.length; i++) { x[i].style.display = "none"; } for (var i = 0; i > x.length; i--) { x[i].style.display = "block"; } /* if (x.style.display == "none") { x.style.display = "block"; } else { x.style.display = "none"; } */ } </script> </body> </html>
- 10 replies
-
- beginner programmer
- html5 css
-
(and 3 more)
Tagged with:
-
I have an index.js file that I want to load in the Node REPL to try some stuff, but when I use .load index.js in the REPL, it goes in an infinite loop and keeps repeating the first line in the file. const mongoose = require('mongoose'); I found an alternative solution which works in Ubuntu 20.04.5 in WSL2, which is to use the command node -i -e "$(< index.js)" in the terminal which loads the file perfectly fine and I can interact with its contents. But when I try the same command in PowerShell it gives me this error: < : The term '<' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:15 + node -i -e "$(< index.js)" + ~ + CategoryInfo : ObjectNotFound: (<:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException C:\Program Files\nodejs\node.exe: -e requires an argument The reason I'm asking about PowerShell "even though I use Ubuntu and things work there", is that I'm taking a web development course, and I provided the solution of using node -i -e "$(< index.js)" to people who were having the same issue, but other people can't get this to work in PowerShell, so I'm just trying to help. and I couldn't find any solution online to this .load issue, or to using an alternative to the node -i -e "$(< index.js)" command in PowerShell. index.js contents: const mongoose = require('mongoose'); mongoose.set('strictQuery', false); mongoose.connect('mongodb://localhost:27017/movieApp', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log("CONNECTION OPEN!!!") }) .catch(err => { console.log("OH NO ERROR!!!!") console.log(err) }) const movieSchema = new mongoose.Schema({ title: String, year: Number, score: Number, rating: String }); const Movie = mongoose.model('Movie', movieSchema); const amadeus = new Movie({ title: 'Amadeus', year: 1986, score: 9.2, rating: 'R' });
-
- javascript
- powershell
-
(and 2 more)
Tagged with:
-
my goal: for every "comment" load the childen (and run another function) and do the same for their childern etc etc etc. my test data = [ { "auth": "true", "children_comments": [ { "auth": "true", "children_comments": [ "can go on forever":true ], "comment": "<i>deleted</i>", "date": "5 months ago", "id": 784, "isOP": "false", "name": "<i>deleted</i>", "parent_id": 783, "user_icon": "{{URL}}" } ], "comment": "<i>deleted</i>", "date": "5 months ago", "id": 783, "isOP": "false", "name": "<i>deleted</i>", "parent_id": 777, "user_icon": "{{URL}}" } ] my python code that makes this array= comments_by_parent = defaultdict(list) for comment in data: comments_by_parent[comment['parent_id']].append(comment) for comment in data: comment['children_comments'] = comments_by_parent[comment['id']] ive tried simple For loops, For IN loops and nothing seems to work update: tried this, getting closer but not the same result function gothru(array) { if (Object.keys(array.children_comments).length >= 1) { console.log(array.children_comments) gothru(array.children_comments) //breaks here typeError: Cannot convert undefined or null to object return if (Object.keys(array.children_comments).length >=1) { console.log("e") gothru(array.children_comments) } } } JSON.parse(a).forEach(element => { gothru(element) });
-
so I'm trying to create an error event handler in javascript. I'm purposely adding the website wrong so that I get a specific error message but thats not what I'm getting. When I run my code I get the following: undefined:1 SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at IncomingMessage.<anonymous> (/Users/elmaschingon/Desktop/app.js:24:30) at IncomingMessage.emit (events.js:327:22) at endReadableNT (_stream_readable.js:1201:12) at processTicksAndRejections (internal/process/task_queues.js:84:21) Here is my code below // Problem: We need a simple way to look at a user's badge count and JavaScript points // Solution: Use Node.js to connect to Treehouse's API to get profile information to print out const https = require('https'); // Function: to pring message to console function printMessage (username, badgeCount, points) { const message = `${username} has ${badgeCount} total badge(s) and ${points} points in Javascript.` console.log(message); } function getProfile(username) { // Connect to the API url const request = https.get(`https://wwwteamtreehouse.com/${username}.json`, response => { let body = ""; // Read the data response.on('data', data => { body += data.toString(); }); // Parse the data response.on('end', () => { const profile = JSON.parse(body); printMessage(username, profile.badges.length, profile.points.JavaScript ); }); }); request.on('error', error => console.error(`Problem with request: ${error.message}`)); } const users = process.argv.slice(2) users.forEach(getProfile); The really weird thing is that when I make the site "https://wwwwteamtreehouse.com" (adding an additional w and still missing the '.') I get the right error code that I'm looking for which is: Problem with request: getaddrinfo ENOTFOUND wwwwteamtreehouse.com Any help would be GREATLY appreciated guys
- 2 replies
-
- javascript
- js
-
(and 2 more)
Tagged with:
-
If I add a new tree in Firebase, how do I detect that a new tree has been added in Java and Swift? I only want to detect when an item directly below the root has been added, not if any sub-fields have been added/updated.
- 2 replies
-
- firebase
- javascript
-
(and 1 more)
Tagged with:
-
Hey guys so I'm just learning to code in Javascript and APIs and how it all works. I want to practice but idk where to start? Does anyone have any recommendations or can point me towards a free API that would be "fun" to work with as my first project?
- 2 replies
-
- api
- javascript
-
(and 1 more)
Tagged with:
-
How to stop website from loading in Andriod webView?
Guest posted a topic in Programs, Apps and Websites
Codes that i have access too: Javascript, Mysql, PHP, Html, css, and Xml. How do i stop my site (apache2) from loading within Android webView? (and Open within a Real Web browser) User ---> Webview --> Google chrome/Firefox/etc help? (reason for wanting no webView, I use a PHP redirect to Desktop or Mobile.)-
- php
- javascript
-
(and 1 more)
Tagged with:
-
Howdy fellas, i need a little help, let me explain my problem. I have a website where user can fill out some stuff and then send it to database. Problem is the connection to the database can be done in Node.js, but i don't really know how to connect it with the javascript or the html button, or simply how to do it, because i'm myself just learning in Node.js. It is my school project and i only have 26days left to complete it (still got lot of work to do). I appreciate anyone who can help, or even be with me in touch if i would need some help. If you need more information feel free to ask for it. Thanks everyone for any help.
-
My code does not work and I have no idea where the missing comma is. Please help! (Sorry for it being sloppy. Im just learning coding) My Code is Below: const Discord = require('discord.js'); const bot = new Discord.Client(); //Deleted const so no one can see it const token = '' ; const PREFIX = '!'; const ytdl = require("ytdl-core"); var version = '0.7'; var servers = {}; bot.on('ready',() =>{ console.log('This bot is online!'); bot.user.setActivity ('Minecraft') }) bot.on('message', msg=>{ let args = msg.content.substring(PREFIX.length).split(" "); switch(args[0]){ case 'ping': msg.channel.sendMessage('pong!'); break; case 'ip': msg.channel.sendMessage('The server Ip is Nuclearwars.serv.gs'); break; case 'info': if(args[1] === 'version'){ msg.channel.sendMessage('Version ' + version); }else{ msg.channel.sendMessage('Invalid Args') } break; case 'commands': msg.channel.sendMessage('The following commands are: info version, ip, and ping. There will be more commands coming soon!'); break; case 'help': msg.channel.sendMessage('The following commands are: info version, ip, and ping. There will be more commands coming soon!'); break; case 'play': function play(connection, message){ var server = servers[message.guild.id]; server.dispatcher = connection.playStream(ytdl(server.queue[0], {filter: "audioonly"})); server.queue.shift(); server.dispatcher.on("end", funtion(), if(server.queue[0]){ play(connection, message); }else{ connection.disconnect(); } }; if(!args[1]){ MessageChannel.channel.send("you need to provide a link!") return; } if(!Message.member.voiceChannel){ message.channel.send("You must be in a channel to play the bot!") } if(!servers[message.guild.id]) servers[message.guild.id] = { queue: [] } var server = servers[message.guild.id]; server.queue.push(args[1]); if(!message.quild.voiceConnetion) message.member.voiceChannel.join().then(funchtion(connection),{ play(connection,message); }) break; } }); bot.login(token); Here are the pictures of it to.
-
Next semester is my senior year of high school. In one of my classes we will be leaving JavaScript. I thought I would spend my summer learning some basic JavaScript so that I have a good starting point. I am a relative novice when it comes to coding. I have some basic knowlage with html, php and css. What is the best way for me to start learning JavaScript?
- 6 replies
-
- learning
- javascript
-
(and 1 more)
Tagged with:
-
I want to keep it short here, but I am trying every place I know, to get help with this. This stackovervflow question is written by me. I have a map, that's presented by LeafletJS. I have some mapfeatures, that when in a cluster of mapfeatures is clicked da list pops up in a div. But when I scroll inside that div the div does f*ck all and the map zooms in and out. I have made some efforts to try and solve this. The closest I got is described in the StackOverflow post linked below. It was an attempt made with JS Event Bubbling, but it was only partially successful. Thanks for reading. https://stackoverflow.com/questions/62003454/disable-scroll-on-leafletjs-map-when-mouse-inside-infobox
-
Hey Everyone, I've been using an addon for my Google Sheets called AutoCrat and it basically takes Google Form submissions from Google Sheets and creates a PDF document which is then sent to the respective email address within the Google spreadsheet. The problem is that the addon doesn't work anymore. The time triggers are broken and I'm in need of something that works. I've tried looking into another addon called Yet Another Mail Merge just to try to see if it works but nope. I've also tried recreating my spreadsheet from scratch and have pasted in my formulas. That didn't seem to fix the issue. So it comes down to using Javascript. 1st problem: I have 1 column of data which is that if the condition is equal to the respective row, it would generate an automated invoice and be sent out. I know there's a lot of code with a simple Google search but none of these seem to have it. 2nd problem: I have 2 templates but the code I've added to the bottom of this post only allows for 1 template. This is Autocrat's script from a few years ago: https://github.com/NewVisionsForPublicSchools/autoCrat-SCRIPT but it's too complex so I looked for some other code I could possibly work with and I found this: http://www.andrewroberts.net/2016/01/google-apps-script-to-create-and-email-a-pdf/ /* PDF Create - with rename and email ================================== When you click "Create PDF>Create PDF" this script uses the data from the active row to construct a PDF in your GDrive. The value in the "File Name" column is used to name the file and - if there is a value - it is emailed to the recipient in the "Email" column. */ // Config // ------ // 1. Create a GDoc template and put the ID here var TEMPLATE_ID = '---- UPDATE ME -----' // var TEMPLATE_ID = '1wtGEp27HNEVwImeh2as7bRNw-tO4HkwPGcAsTrSNTPc' // Demo template // Demo script - http://bit.ly/createPDF // 2. You can specify a name for the new PDF file here, or leave empty to use the // name of the template or specify the file name in the sheet var PDF_FILE_NAME = '' // 3. If an email address is specified you can email the PDF var EMAIL_SUBJECT = 'The email subject ---- UPDATE ME -----' var EMAIL_BODY = 'The email body ------ UPDATE ME ---------' // Constants // --------- // You can pull out specific columns values var FILE_NAME_COLUMN_NAME = 'File Name' var EMAIL_COLUMN_NAME = 'Email' /** * Eventhandler for spreadsheet opening - add a menu. */ function onOpen() { SpreadsheetApp .getUi() .createMenu('Create PDF') .addItem('Create PDF', 'createPdf') .addToUi() } // onOpen() /** * Take the fields from the active row in the active sheet * and, using a Google Doc template, create a PDF doc with these * fields replacing the keys in the template. The keys are identified * by having a % either side, e.g. %Name%. * * @return {Object} the completed PDF file */ function createPdf() { var ui = SpreadsheetApp.getUi() if (TEMPLATE_ID === '') { ui.alert('TEMPLATE_ID needs to be defined in code.gs') return } // Set up the docs and the spreadsheet access var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy(), copyId = copyFile.getId(), copyDoc = DocumentApp.openById(copyId), copyBody = copyDoc.getActiveSection(), activeSheet = SpreadsheetApp.getActiveSheet(), numberOfColumns = activeSheet.getLastColumn(), activeRowIndex = activeSheet.getActiveRange().getRowIndex(), activeRow = activeSheet.getRange(activeRowIndex, 1, 1, numberOfColumns).getValues(), headerRow = activeSheet.getRange(1, 1, 1, numberOfColumns).getValues(), columnIndex = 0, headerValue, activeCell, ID = null, recipient = null // Replace the keys with the spreadsheet values and look for a couple // of specific values for (;columnIndex < headerRow[0].length; columnIndex++) { headerValue = headerRow[0][columnIndex] activeCell = activeRow[0][columnIndex] copyBody.replaceText('%' + headerValue + '%', activeCell) if (headerValue === FILE_NAME_COLUMN_NAME) { ID = activeCell } else if (headerValue === EMAIL_COLUMN_NAME) { recipient = activeCell } } // Create the PDF file, rename it if required, delete the doc copy // and email it copyDoc.saveAndClose() var newFile = DriveApp.createFile(copyFile.getAs('application/pdf')) if (PDF_FILE_NAME !== '') { newFile.setName(PDF_FILE_NAME) } else if (ID !== null){ newFile.setName(ID) } copyFile.setTrashed(true) if (recipient !== null) { MailApp.sendEmail( recipient, EMAIL_SUBJECT, EMAIL_BODY, {attachments: [newFile]}) } ui.alert('New PDF file created in the root of your Google Drive ' + 'and emailed to ' + recipient) } // createPdf()
- 1 reply
-
- javascript
- google api
-
(and 2 more)
Tagged with:
-
Hi guys, I’m a huge fan of the Linus Tech tips and i would really need the help of the wonderful community. Currently a computer engineer at Edinburgh i am currently working on a javascript project and i made a quick survey to understand some needs of web developers. Please fill up this survey (takes 2 minutes) : https://docs.google.com/forms/d/e/1FAIpQLScs9DWk2qmytXCROCwri5wVf4Dp9l9KZmxOQM5ol4Y0nzyCPg/viewform#responses Thanks
- 2 replies
-
- survey
- javascript
- (and 4 more)
-
I have an assignment to validate the form using JavaScript,Please help me out here,why is it not working? I am still trying to figure this out so its not complete yet. <!DOCTYPE html> <html> <head> <style type="text/css"> .container { width: 500px; clear: both; } .container input { width: 100%; clear: both; } body{ background-image:url('268641.jpg');} </style> <script type="text/javascript"> function c() { var mytext=document.getElementById('textarea').value; if(document.getElementById('name').value==0) { alert('Please Enter Your Name'); } var contact=document.getElementById("contact").value; var contactnum=/^\d{10}$/; if((contact.value.match(contactnum)) { return true; } else { alert("Invalid Contact Number"); return false; } } </script> </head> <body> <div class="container"> <form onsubmit="c()"> <label>Name:</label><input type="text" id="name" maxlength="50"><br/><br/> <label>Contact:</label><input type="text" id="contact" maxlength="10"><br/><br/> <label>E-mail:</label><input type="text" id="email"><br/><br/> Gender <br/> <input style="width: 22px;" type="radio" name="gender" value="male">Male<br/> <input style="width: 22px;" type="radio" name="gender" value="female">Female<br/> <input style="width: 22px;" type="radio" name="gender" value="other">Other<br/><br/> <br/> <br/> <label>Comment:</label><textarea id="textarea" rows="4" cols="50"> </textarea><br/> <input type="submit" value="Submit" > </form> </div> </body> </html>
-
Hi there, I am creating a flight simulation that focuses on the realistic delay due to varied factors. I'm not an experienced programmer or with unity. I have a simple UI element within my game that displays the plane's (UAV) altitude, speed, distance from a base point and the latency. My issue is that the script used for this was in JavaScript and im no expert, so I need help with converting this to c# to get the figures as they update within the game, displayed on screen! Here is my code: var plane : Transform; var b : Transform; public var item2 : GUIContent = GUIContent("Altitude"); public var item3 : GUIContent = GUIContent("Speed"); private var guiSkin : GUISkin; var Alt:int; var Spd:int; var Bloc:int; var latency: float; var Distance:int; var obritalSatellite:int; //var PosZ:int; function OnGUI(){ GUI.skin = guiSkin; GUI.Box(Rect(0, Screen.height-120, 200, 120),"Plane"); GUI.Label(Rect(20, Screen.height-80, 100, 50), "Altitude"); GUI.Label(Rect(15, Screen.height-60, 100, 50), "Speed"); GUI.Label(Rect(80, Screen.height-80, 100, 50), Alt.ToString()); GUI.Label(Rect(80, Screen.height-60, 100, 50), Spd + " m/s".ToString()); GUI.Label(Rect(10, Screen.height-40, 100, 50), "Base"); GUI.Label(Rect(80, Screen.height-40, 100, 50), Distance + " m".ToString()); GUI.Label(Rect(10, Screen.height-20, 100, 50), "latency"); GUI.Label(Rect(80, Screen.height-20, 100, 50), latency + " ms".ToString()); } function Update(){ Alt=plane.transform.position.y; Spd=plane.GetComponent.<Rigidbody>().velocity.magnitude; Bloc=b.transform.position.z; //distance measurement from base to plane var distance = Vector3.Distance(plane.transform.position, b.transform.position); obritalSatellite = 70000; Distance = distance; //delay calculation latency1 = (obritalSatellite + Distance) *0.000003 + 0.120; latency = latency1; } My main issue is converting the function Update to c#. Any help would be ideal, Thank You. Regards, Andre
-
I need to convert this code to JavaScript so that it can be embedded into a web browser. I am okay at python, but have never coded before. I would massively appreciate any help. from urllib.request import urlopen, Request import json import random greetings = ["Hello", "Hi", "Greetings"] response = ["I can do what ever you need", "I'm not as clever as your manager but ask me anyway", "I can't juggle. Anything else - just don't ask me to juggle"] def main(): print("Hello") print("As well as greetings I can also do other things. Type 'List' to see possible responses") while True: user = input("Enter your message: ") if user == "1": holidays() elif user == "2": shift() elif user == "3": swap() elif user in greetings: print("Hello. What can I help you with?") elif user == "Who are you?": print("I'm MyShiftPlanner, your shift working helper") elif user == "What can you do?": print(random.choice(response)) elif user == "List" or user == "list": print("1. Check how many days until your next holiday\n2. Check when your next shift is\n3. Swap your shift with someone else") elif user == "quit": return else: print("Sorry, I didn't understand that") def holidays(): choice = input("Do you want to know how many days are left until your holiday? (Y/N) ") if choice == "y" or choice == "Y": main = urlopen("https://myshiftplannercloud.azurewebsites.net/api/ChatBot/DaysOff?employeeID=joe512") string = json.loads(main.read()) print("Your next holiday is on", string["NextHoliday"]) print("You have", string["DaysUntil"], "days to go!") else: main() def shift(): choice = input("Do you want to know when your next shift is? (Y/N) ") if choice == "y" or choice == "Y": main = urlopen("https://myshiftplannercloud.azurewebsites.net/api/ChatBot/NextShift?employeeID=joe512") string = json.loads(main.read()) print("Your next shift is on", string["ShiftDate"], "and you are working", string["ShiftType"]) else: main() def swap(): choice = input("Do you want to change your shift? (Y/N) ") if choice == "Y" or choice == "y": datey = int(input("Please enter the year of the shift you want to swap(YYYY): ")) datem = int(input("Please enter the month of the shift you want to swap(MM): ")) dated = int(input("Please enter the day of the shift you want to swap (DD): ")) conditionsSetURL = "https://myshiftplannercloud.azurewebsites.net/api/ChatBot/SwapShift?employeeID=joe512&date={}-{}-{}&swapwith=frank".format(datey, datem, dated) newConditions = {"EmployeeID": "joe512", "ShiftDate": "{}-{}-{}".format(datey, datem, dated), "SwappedWith": "frank"} params = json.dumps(newConditions).encode('utf8') req = Request(conditionsSetURL, data=params, headers={'content-type': 'application/json'}) response = urlopen(req) print(response.read().decode('utf8')) print("Your shift on {}-{}-{} has been swapped with".format(datey, datem, dated), "Frank") else: main() main() Lewis
- 3 replies
-
- javascript
- python
- (and 4 more)
-
Hey there Just wanted to introduce our little community "Together Java" to you, we are a good amount of people trying to learn or help others learn Java. If you think about getting started or want help on your path feel free to check by and feel right at home ! Discord
-
- java
- javascript
-
(and 1 more)
Tagged with:
-
Hello, I am currently messing around with Snap, an implementation of Scratch that allows one to write their code in Javascript. I've run into a bit of an issue. So, I have this code that I've been writing, all it does is allow me to create circular objects and store them as images for later use. // Make sure we have no duplicates, just delete EVERYTHING. this.costumes = new List(); Wcx = []; Wcy = []; Wcs = []; Wcp = []; Wcc = []; // Used to convert degrees to radians, for ease of use. function toRads (degrees) { return degrees * 0.0174532925 }; // Circle class begin. circle = function (radius, x, y) { this.radius = 0.985 * radius; this.posX = x; this.posY = y; this.color = {} this.color.r = 0; this.color.g = 0; this.color.b = 255; this.Xmatrix = []; this.Ymatrix = []; this.offset = [x, y]; this.moved = false; // Generate the coordinate table needed to draw our object. it = 0; while (it < toRads(360)) { this.Xmatrix.push(Math.sin(it) * this.radius) - (Math.cos(it) * this.radius); this.Ymatrix.push(Math.cos(it) * this.radius) + (Math.sin(it) * this.radius); it = it + 0.0174532925; }; }; circle.prototype = {}; // We can now export our drawings as images, remove this. circle.prototype.position = function (offX, offY) { if (this.offset[0] == offX) { if (this.moved == true) { this.moved = false; }; } else if (this.moved == false) { this.moved = true; }; if (this.offset[1] == offY) { if (this.moved == true) { this.moved = false; }; } else if (this.moed == false) { this.moved = true; }; if (this.moved = true) { this.offset = [offX, offY]; }; }; // Inject our point array into the world buffer. circle.prototype.inject = function (mode = "OUTLINE") { a = 0; sic = 2 / 90 * this.radius; if (mode == "OUTLINE") { while (a < this.Xmatrix.length) { Wcx[Wcx.length] = (this.Xmatrix[a] + this.offset[0]); Wcy[Wcy.length] = (this.Ymatrix[a] + this.offset[1]); Wcs[Wcs.length] = false; Wcs[Wcs.length] = false; Wcp[Wcp.length] = this.radius; Wcp[Wcp.length] = this.radius; Wcc[Wcc.length] = [this.color.r, this.color.g, this.color.b]; Wcc[Wcc.length] = [this.color.r, this.color.g, this.color.b]; a = a + 1; }; } else if (mode == "FILLED") { while (a < this.Xmatrix.length / 2) { Wcx[Wcx.length] = -1 * (this.Xmatrix[a] + this.offset[0]); Wcx[Wcx.length] = (this.Xmatrix[a] + this.offset[0]); Wcy[Wcy.length] = (this.Ymatrix[a] + this.offset[1]); Wcy[Wcy.length] = (this.Ymatrix[a] + this.offset[1]); Wcs[Wcs.length] = false; Wcs[Wcs.length] = false; Wcp[Wcp.length] = sic; Wcp[Wcp.length] = sic; Wcc[Wcc.length] = [this.color.r, this.color.g, this.color.b]; Wcc[Wcc.length] = [this.color.r, this.color.g, this.color.b]; a = a + 1 }; } Wcx[Wcx.length] = this.offset[0]; Wcy[Wcy.length] = this.offset[1]; Wcs[Wcs.length] = true; Wcp[Wcp.length] = 1; Wcc[Wcc.length] = [this.color.r, this.color.g, this.color.b]; }; // Sets the color of our circle. circle.prototype.changeColor = function (ra, ga, ba) { this.color = {}; this.color.r = ra; this.color.g = ga; this.color.b = ba; }; // End circle class. // Begin light class, incomplete. particle = function (color, Xp, Yp, wid, hei) { this.color = {}; this.color.r = color[0]; this.color.g = color[1]; this.color.b = color[2]; this.posX = Xp; this.posY = Yp; this.width = wid; this.height = hei; this.matrix = {}; this.matrix.x = []; this.matrix.y = []; this.matrix.color = {}; this.matrix.color.r = color[0]; this.matrix.color.g = color[1]; this.matrix.color.b = color[2]; multiplier = 1; while (multiplier < 100) { Wc = multiplier / 100 * this.width; Hc = multiplier / 100 * this.height; Cc = {} Cc.r = multiplier / 100 * this.color.r; Cc.g = multiplier / 100 * this.color.g; Cc.b = multiplier / 100 * this.color.b; multiplier = multiplier + 1 }; }; // End light class. // Testing code, begin starBorder = new circle (300, 0,0); starBody = new circle (280, 0, 0); starBorder.changeColor(250, 230, 0); starBody.changeColor(250, 220, 0); starBorder.inject("FILLED"); starBody.inject("FILLED"); // Testing code, end. // Begin drawing our object. this.clear(); this.gotoXY(Wcx[0], Wcy[0]); this.down(0); wa = 0; while (wa < Wcx.length) { if (Wcs[wa] == true) { if (wa < Wcx.length) { this.up(); this.gotoXY(Wcx[wa], Wcy[wa]); this.down(); } } else { this.setColor(new Color(Wcc[wa][0], Wcc[wa][1], Wcc[wa][2])); this.setSize(Wcp[a]); this.gotoXY(Wcx[wa], Wcy[wa]); }; wa = wa + 1 }; //Take our drawing and turn it into a costume. var cst = new Costume( this.parentThatIsA(StageMorph).trailsCanvas ); cst.shrinkWrap(); cst.name = this.newCostumeName("tesT", null); this.addCostume(cst); this.wearCostume(cst); // Now that we've created our image, lets clear the screen so we can use it. this.clear(); this.up(); this.gotoXY(0, 0); the code actually runs within this block of code here, which contains all of my functions and variables. function anonymous (/**/) { // Code gets contatenated between the curly brackets. } this anonymous function contains all of the variables, objects, and functions I need in order to write working code. how can I create a function within this, and still access the parent objects and functions?
-
When I try to execute the code I want run, tampermonkey can't do it. Through the developer console I can. I tried an alert and it works, but anything else doesn't work. I tried using $('some element').length == 0 {} and it works on developer console but not through a user script.
- 9 replies
-
- javascript
- jquery
-
(and 1 more)
Tagged with:
-
Hey guys, I have been working on code for quite a while. I do web design here and there for money but I am only a high school student. Is there some way someone can explain to me what programming really is? I know the CSS, HTML, and not extensively but quite well Javascript. Is this programming on it's own is there more. Can someone explain this to me. (I'm sorry this is a dumb question, but I'm just curious)
-
https://arstechnica.com/security/2017/02/new-aslr-busting-javascript-is-about-to-make-drive-by-exploits-much-nastier/ ASLR, or Address Space Layout Randomization, is a technique used by operating systems to randomize the layout of where data are resident in RAM. For instance, one instance, all of the core components reside in address 0x1000, the next it resides in 0x2000. This is to prevent a class of attacks that read/write beyond a buffer into data that it shouldn't be accessing. Because the location of data in an ASLR system are not guaranteed, this makes those kinds of attacks infeasible. However, there is a flaw that's been proven that even JavaScript of all things can exploit: the cache in CPU still knows where everything is. The JavaScript code instead pokes at cache to figure out where data are and uses that to figure out where that data lives in RAM. Here's the problem though: caching is vital to the performance of a CPU. So you can't just simply disable cache and call it a day. And it's not like any of the processor manufacturers can apply a fix to any existing parts or come up with something overnight because it's a hardware issue.
-
Hello, I am currently beginning development on a game, however while writing the code for the GUI I wanted to implement the ability to "inject" code into frame objects as a method of rendering objects within said frames. Any and all methods of doing so that I have googled or though of thus far have failed. Not only do I need ot inject the code into the class but the injected code also has to be able to access variables within said class. If anyone could help me or teach me how to do this it would be appreciated. This is basically how the code for frames.js looks; just without all of the code that actually does stuff (I'm not on my home PC) function frame (parameters) { this.func = null; //Code goes here } frame.prototype = {} frame.prototype.render = function (parameters) { //Code goes here if (this.func != null) { this.func(); } } frame.prototype.move = function (parameters) { //Code goes here } frame.prototype.bind = function (func) { this.func = new func() } Currently frame.bind has been removed from the code and right now I'm just running the script within the main loop that performs all of my rendering. It produces the following result with some sample code.
-
Note: I welcome any questions and comments people have regarding anything in this thread. Note: I welcome any questions and comments people have regarding anything in this thread. Welp, while I already have a Trello page for this, I thought it would be nice to be able to write down my journey as work on this pet project goes along. At the time of writing this initial post, I currently have about 300 + lines of code, which to be honest is quite unimpressive. I should also mention that the majority of my coding time has currently centered around frames.js in order to clean it up, optimize it and debug weird parts of code. Not to mention adding comments where they are needed. So, where do I stand now? Well, the code currently is built for the Sphere v1.5 API which utilizes Javascript 1.5, however as of last night I have installed Minisphere 4.3.8 which uses the much more modern Sphere V2 API and Duktape for it's JavaScript interpreter. While Minisphere still allows me to use my Sphere V1.5 code I'm going to be adapting my code (while it's still in it's infancy) to the newer API so that I can leverage more performance and hopefully make use of any extra features that Minisphere provides me with. Also, full-screen finally works, I'm quite glad I went against reason and wrote my code to adapt to different resolutions, now if only I could implement features for changing resolutions on the fly. This probably wont have multi-player support, unless I decide I want pain and take the time to learn it. The Players window is just for show currently. Screenshot: