How can I tell which language was detected with HighlightJS? - angularjs

For what it's worth, I'm using angularjs and https://github.com/pc035860/angular-highlightjs. I want to know which language was detected and if there's any way to do this.
If this library doesn't do it, are there any that do?

You could search for the hljs class with JavaScript and then find the language class associated with it (assuming the language class is the last class). Example with jQuery:
function findLanguageOfHLJSWithID(id) {
var foundClasses = jQuery('#' + id + '.hljs').attr('class').split(' ');
return foundClasses[foundClasses.length - 1];
}
If you want all the languages highlighted on the page, use this function:
function findAllHLJSLanguages() {
var tempClasses = jQuery('.hljs'), foundClasses = [];
for (var iter = 0; iter < tempClasses.length; iter++) {
var tempClassesSplit = $(tempClasses[iter]).attr('class').split(' ');
foundClasses.push(tempClassesSplit[tempClassesSplit.length - 1]);
}
return foundClasses;
}

Related

How do you dynamically create unpacked variable names using destructuring syntax in JS ES6? [duplicate]

How can I use a for loop to dynamically create variables, and be returned.
function createVariables()
{
for ( i=0; i<=20; i++ )
{
var account = i;
return var account + i;
}
}
The goal is to have the result below:
var account1;
var account2;
var account3; and etc.....
You should use an array:
function createVariables(){
var accounts = [];
for (var i = 0; i <= 20; ++i) {
accounts[i] = "whatever";
}
return accounts;
}
You then have access to accounts[0] through accounts[20].
The only way I know how to do this would be to use the JavaScript eval function.
Something like eval("account" + 1 + "='some value'");
http://www.w3schools.com/jsref/jsref_eval.asp
However, I think #Domenic has a better answer.
I was unsure about answering an old question however I stumbled across this while seeking an answer myself.
for (var i = 1; i < 11; i++) { // Creating 10 objects
window["Object"+i] = new Object();
}
console.log(Object7); // is not undefined
The above code loops to 10 while creating dynamic objects, as described on https://www.codecademy.com/en/forum_questions/51068e93f73ad4947a005629
I find this a simplest solution
for (var i = 0; i < 10; i++) {
this["RONAK"+i] = "MY VAL";
}
Output
RONAK0 = "MY VAL"
RONAK1 = "MY VAL"
RONAK2 = "MY VAL"
...
RONAK9 = "MY VAL"
You can use the eval() method to declare dynamic variables as it executes JavaScript statements passed to it.
function createVariables()
{
for ( i=0; i<=20; i++ )
{
var str ="account"+ i+" = undefined";
//Declaring and Setting dynamic variable to undefined using eval
eval(str);
}
}
createVariables();
let etc = { name: 'foobar', city: 'xyz', company: 'companyName' };
Object.keys(etc).forEach(key=>{
window[`${key.toUpperCase()}`] = new Object(`${etc[`${key}`]}`)
});
console.log("-->"+NAME) //foobar
this is similar to what #whatevermike describes but it does not work in NodeJS because it uses window. :(
function createVariables() {
var accounts = [];
for (var i = 0; i <= 20; ++i) {
accounts[i] = "merhaba" + i;
}
return accounts;
}
The following code will actually create variables, instead of creating this sort of hash table proposed by #Domenic
function createVariables(){
var varName = "accounts";
for (var i = 0; i <= 20; ++i) {
eval('var ' + varName + i + ' = ' + '"whatever"' + ';');
}
return accounts;
}
I was pretty proud of the way I made iterating variables with my code, was going to share it but I think I'll just sort of show you modified version of it.
function variableBuilder() {
let i = 0;
while (i <= 20) {
let accountVariable = "account".concat(i);
`// variable can even be reassigned here`
console.log(accountVariable);
i++;
}
}
you can use the variable as an iterating variable identifier, in the spot that I suggested; I used this method to build DOM nodes, to create a dynamically built HTML table.
we can use map for it.
var map = {};
for (var i = 0; i < 10; ++i) {
map["nutrient" + i] = "some stuff" + i;
}
console.log(map)
result:
{
nutrient0: 'some stuff0',
nutrient1: 'some stuff1',
nutrient2: 'some stuff2',
nutrient3: 'some stuff3',
nutrient4: 'some stuff4',
nutrient5: 'some stuff5',
nutrient6: 'some stuff6',
nutrient7: 'some stuff7',
nutrient8: 'some stuff8',
nutrient9: 'some stuff9'
}
the easiest method is to use eval and write the variable declaration line inside a loop that follows your conditions
for (let i = 0; i <= 3; i++) {
eval(`var variable${i}=${i}`);
eval(`console.log(variable${i})`)
}
//Output:
0
1
2
3
You can also console log the values outside as they are declared global with the var keyword

AngularJS - Delete check box is not working correctly and only deleting one at a time

I've written out a block of code that allows the user to check or uncheck entities that will be added or removed via web services. My add function seems to be working correctly and provides the ability to add multiple entities. However, my delete function isn't working the same. It doesn't delete each time, and can only delete one at a time. I'm struggling since the code is effectively the same as the add, so I don't know if the issue is AngularJS related or perhaps my web service isn't working correctly.
Edit: I've actually noticed that the for loop goes through it all but doesn't select the correct id, it always starts from the first one.
var toDeleteService = [];
for (var i = 0; i < $scope.siteServices.length; i++) {
if ($scope.siteServices[i].chosen != $scope.siteServices[i].origChosen) {
if ($scope.siteServices[i].chosen == true) {
toAddService.push(i);
}
else {
toDeleteService.push(i);
}
}
}
if (toDeleteService.length > 0) {
var deleteRequest = {};
deleteRequest.services = [];
for (var i = 0; i < toDeleteService.length; i++) {
var parentServiceName = $scope.siteServices[i].parentServiceName;
var j = 0;
for (; j < deleteRequest.services.length; j++) {
if (deleteRequest.services[j].parentServiceName == parentServiceName) {
break;
}
}
if (j == deleteRequest.services.length) {
deleteRequest.services[j] = {};
deleteRequest.services[j].parentServiceName = parentServiceName;
deleteRequest.services[j].subservices = [];
}
var service = {};
service.serviceId = $scope.siteServices[i].serviceId;
deleteRequest.services[j].subservices.push(service);
}
var deleteUrl = "api/sites/" + $scope.targetEntity.siteId + "/services/" + service.serviceId;
$http.delete(deleteUrl)
.then(function (response) {
});
}
As I understood it you are trying to remove siteServices based by numbers stored in var toDeleteServices = [] so you need to access those numbers by its index. but in service.serviceId = $scope.siteServices[i].serviceId; you are using i instead.
service.serviceId = $scope.siteServices[toDeleteServices[i]].serviceId; as you need actual number of the service to delete.
If I understood your code correctly.

AS3 array indexOF

I am working on a game and have trouble with this array. There is all fruits on the stage which is generated from the array fruit. When the appel will hit the basket, we will count them. The melon is not to be counted. How do i find out if the current fruit is an appel or a melon?
var array_fruit:Array = new Array(appel1_mc, appel2_mc, melon_mc);
var appelsOnstage:Array = new Array();
var appelsCollected:Number = 0;
for (var i:int = 0; i<10; i++) {
var pickappels = array_fruit[int(Math.random()* array_fruit.length)];
var spel_appels:MovieClip = new pickappels();
addChild(spel_appels);
spel_appels.x = (Math.random() * 800) + 100;
spel_appels.y = Math.random() * -500;
spel_appels.speed = Math.random() * 10 + 2;
appelsOnstage.push(spel_appels);
}
stage.addEventListener(Event.ENTER_FRAME, catchappels);
function catchappels(e:Event):void {
for (var i:int = appelsOnstage.length-1; i > -1; i--) {
var currentfruit:MovieClip = appelsOnstage[i];
if (currentfruit.hitTestObject(basket_mc)) {
if(array_fruit.indexOf(currentfruit) == melon_mc ){
trace("melon");
} else {
trace("no melon");
appelsCollected++;
}
}
}
}
a_fruit.indexOf(currentfruit) = -1 all the time
The problem here is the confusion between classes and objects.
a_fruit holds classes, which are to be instantiated by this code
var pickappels = array_fruit[int(Math.random()* array_fruit.length)];
var spel_appels:MovieClip = new pickappels();
appelsOnstage holds objects of those classes and is filled here
appelsOnstage.push(spel_appels);
Classes and objects are - excuse the pun! - apples and oranges, very different things.
A class is like a blueprint for a building or a recipe for a meal. You cannot compare objects with classes and expect them to be the same.
Instead, you should find the class of an object, and then compare this class to another class. For this, you use the is operator. Something like
if(currentfruit is melon_mc)
should do the trick to tell you if you have a melon or not.
indexOf is going to return an int value. See my edit to your code below.
if (currentfruit.hitTestObject(basket_mc)) {
if(array_fruit.indexOf(currentfruit) == 2 ){
trace("melon");
} else {
trace("no melon");
appelsCollected++;
}
}
indexOf takes two arguments. The first is the exact element you are searching for. The second argument is the index position to start the search from. The default is position 0.
See the API documentation here. (Always good to give these a quick read first).
You should use is operator here, for better coding. What if you'd change the positions of classes in your arrays?
if ((currentfruit is appel1_mc) || (currentfruit is appel2_mc)) {
// apple
}
Just in pseudo code to figure a possible way to deal with this issue.
On the timeline :
import com.fruits.Fruit;
import com.fruits.Melon;
import com.fruits.Apple
var fruit_1:Melon = new Melon();
var fruit_2:Apple = new Apple();
if(fruit_1 is Melon){
trace("anyway my SuperclassName is : " + fruit_1.getType());
trace (fruit_1.getMyType());
trace("");
}
if(fruit_2 is Apple){
trace("anyway my SuperclassName is : " + fruit_2.getType());
trace (fruit_2.getMyType());
trace("");
}
in com.Fruit.as :
package com.fruits {
public class Fruit {
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flash.utils.getQualifiedSuperclassName;
public function Fruit() {
trace ("I'm a Fruit");
}
public function getType():String{
var type:String = getQualifiedSuperclassName(this)
var str:String = (type);
return str;
}
}
}
In com.Melon :
package com.fruits {
public class Melon extends Fruit {
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flash.utils.getQualifiedSuperclassName;
public function Melon() {
super();
trace ("Melon says : ");
trace (" because I'm Fruit and not happy to be a Melon");
trace("");
}
public function getMyType():String{
var type:String = getQualifiedClassName(this)
var str:String = ("Im a " + type);
trace("Class said : I worth nothing because I'm an Fruit and not proud to be an Melon");
str += "\n" + "but in fact I'm a " + getQualifiedSuperclassName(this)
return str;
}
}
}
In com.Apple :
package com.fruits {
public class Melon extends Fruit {
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flash.utils.getQualifiedSuperclassName;
public function Melon() {
super();
trace ("Melon says : ");
trace (" because I'm Fruit and not happy to be a Melon");
trace("");
}
public function getMyType():String{
var type:String = getQualifiedClassName(this)
var str:String = ("Im a " + type);
trace("Class said : I worth nothing because I'm an Fruit and not proud to be an Melon");
str += "\n" + "but in fact I'm a " + getQualifiedSuperclassName(this)
return str;
}
}
}
This is just an idea, tell me more about your target and if this may help You...
Best regards Nicolas.
PS : I'm sorry but my English is really bad. so I tried to figure me the issue...
You may perhaps forget about indexOf and use addChild anytime You want to set an object/instance over another one....
So You don't have to check about the indexes.
addChild(some old Child) will make the "old Child" be on the the last index (over the other instances).
Sorry I didn't wrote your code but the title said that you want to check if the fruit is a Melon or an Apple...
Sorry if I misunderstood. :(

how to search for a specific word in a huge array?

In AS3 :
I've got a long text in an array.
var myHugeArray:Array = ["I love Apple
I have an Iphone
I eat a Banana
I'm John
I sell a computer
I sell an Apple
I love rock
I sell a car"];
How can I do to search a specifics words ? (like : show me sentences with the word "apple") --> output : "I love Apple" and "I sell an Apple"
Thanks,
EDIT
Here's what I did so far :
loader5.load(urlReq);
loader5.addEventListener(Event.COMPLETE,completeHandler2);
function completeHandler2(event:Event):void{
loader5.removeEventListener(Event.COMPLETE,completeHandler2);
trace("Données envoyées");
feedbackText.text = "Données envoyées";
loader5.load(urlReq);
loader5.addEventListener(Event.COMPLETE, complete);
}
function complete(e:Event):void {
addChild(list);
products = JSON.parse(loader5.data) as Array;
feedbackText.text = "complete";
for(var i:int = 0; i < products.length; i++){
createListItem(i, products[i]);
}
showList();
}
function createListItem(index:int, item:Object):void {
var listItem:TextField = new TextField();
listItem.text = item.title;
listItem.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
showDetails(item);
});
list.addChild(listItem);
str = item.title;
bar();
}
function bar(){
var arr: Array ;
searchBar.type = TextFieldType.INPUT;
var suggested:Array = new Array();
var textfields:Array = new Array();
searchBar.addEventListener(Event.CHANGE, suggest);
arr = str.split(",");
trace(arr);
function suggest(e:Event):void
{
suggested = [];
for (var i:int = 0; i < textfields.length; i++)
{
removeChild(textfields[i]);
}
textfields = [];
for (var j:int = 0; j < arr.length; j++)
{
if (arr[j].indexOf(searchBar.text.toLowerCase()) != -1)
{
var term:TextField = new TextField();
term.width = 360;
term.height = 24;
term.x = 18;
term.y = (24 * suggested.length) + 135;
term.border = true;
term.borderColor = 0x353535;
term.background = true;
term.backgroundColor = 0xFF9900;
term.textColor = 0x4C311D;
term.defaultTextFormat = format;
addChild(term);
suggested.push(arr[j]);
term.text = arr[j];
}
}
function showList():void {
list.visible = true;
}
function showDetails(item:Object):void {
titleTxt.htmlText = item.title;
detailsTxt.htmlText = "<U>prix:</U> " + item.prix + " xpf"+ "\n\n<U>Description:</U> " + "\n"+item.theDescription + "\n"+"\n\n<U>Contact:</U> " + item.mail+ "\n"+item.phone;
}
So, my AS3 code go search for PHP variable with loader5.
All the items found by the php are put in an Array (products).
And a list of all the products is created. (createListItem).
If I click on an item, it show me some details (price, description..etc). It's the function showDetails();
Know I've created a searchBar (autocomplete).
An array is created (arr) that split the string (str).
Then it does what it does to search through the array.
Problems :
1/ Weirdly, not all the words are displayed in my searchBar. Some words are working, other not.
2/ How can I do to call the function showDetails() when the user click on the suggest term ? (term.addEventListener(MouseEvent.CLICK, showDetails)); doesn't work as the terms is not item.title. ShowDetails is showing details of item.title. (so how can I say that term = item.title ?)
3/ Do you see a way simpler than that ?
Your myHugeArray is just string, so split() it with \n', you got the
ret array for example, then find the one contains the word you search, like "apple", using indexof() in each string
You need to split the string into an array then search each item
check this out
https://stackoverflow.com/a/34842518/3623547

Use an array of values for a slider

I want to use an array of id, for my little slider-viewer I'm building. I just want to display multiple things using 2 buttons next and previous.
For now I use something like this, using only 2 url id, but I need at least 20 urlid in my viewer :
var urlid1 = 'd3885ca76ac54e958c2855a4fbd3dbf3';
var urlid2 = '3aa64527d1614998b4812bfefbbc896a';
function Next() {
client.init( urlid2 );
}
function Previous() {
client.init( urlid1 ); }
So I've never use an array before, and the things I tried didn't work. Do you know a proper way to do that ?
This seems straight forward enough
var index = 0;
var array = ["url1", "url2", "url3", ...]
function next() {
index++;
if(index > array.length) {
index = 0;
}
client.init(array[index]);
}
function previous() {
index--;
if(index < 0) {
index = array.length;
}
client.init(array[index]);
}
It may be better practice to actually refactor those changes to the index variable to other functions to enable reuse, but this should give you an idea of how it is done.
If client is something that you have wrote then you might want to look at the naming of your functions, init is normally reserved for instantiating the class as new, from your example you seem to be changing a resource so you may want a function name like client.show(); or client.update();
Thank's Varedis.
Final code is :
var index = 0;
var array = ["0e4b4e0789bf41c7b05129a76de0abb0","3aa64527d1614998b4812bfefbbc896a","d3885ca76ac54e958c2855a4fbd3dbf3","8f927023e10c40b9b22d3c13df7c08aa"];
client.init(array[index]);
function next() {
index++;
if(index >= array.length) {
index = 0;
}
client.init(array[index]);
}
function previous() {
index--;
if(index < 0 ) {
index = array.length-1;
}
client.init(array[index]);
}
I had to use " index = array.length-1; " but I can't explain it. You know why ? How index could be 5 if I only have 4 values ?

Resources