I wrote the code in Java, no problem. Here I am giving the Java code:
public class CarGallery {
static int carCounter=10;
static Gallery[] car = new Gallery[carCounter];
public static void main(String[] args) {
car[0].weight = (float) 1.25;
car[0].weight = (float) 0.87;
// ... and so on ... //
}
}
class Gallery {
public float weight;
public float height;
public int colorCode;
public int stockGallery;
};
The thing is, I want to write the same code in Javascript. Here is the code that does not work:
var cars = {weight:0 , height:0 , stock:0 , model:"..."};
var cars = new Array();
cars[0].weight=1.2;
cars[0].height=0.87;
cars[0].stock=2;
cars[0].model="320";
I read some documents and saw that there is no class definition in Javascript like Java classes.
I found class definition in JS with constructors, but I don't want to use constructors.
The member should be defined as array like:
static Gallery[] car = new Gallery[carCounter];
Thank you for your help!
The JavaScript equivalent to your Java would be.
function Gallery() {
this.weight = null;
this.height = null;
this.colorCode = null;
this.stockGallery = null;
};
var carCounter = 10;
var carGallery = new Array(carCounter);
carGallery[0] = new Gallery();
carGallery[0].weight = 1.2;
carGallery[0].height = 0.87;
carGallery[0].colorCode = 2
carGallery[0].stockGallery = 3;
carGallery[1] = new Gallery();
carGallery[1].weight = 2.2;
...
Related
Im trying to send an array that contains some objects via connection made in SignalR, the connection is not a problem, everything works fine. When the data arrives to the view it is no longer the array i need to use.
This is the class:
public class Empresa
{
public string nombre { get; set; }
public int vidID { get; set; }
public string img64 { get; set; }
public string color { get; set; }
}
At the end the object will be something like this:
The object is send to the view and this is the output:
I have already tried with JsonConvert.SerializeObjectas i found on other threads, yet it doesnt seems to work. I tried to convert the data send with this jQuery.parseJSON(data) (Left) and with this JSON.parse(data)(Right); it throws an error on both cases as seen in the picture below.
I'm not sure if it is that way because the object sended is made this way:
private readonly ConcurrentDictionary<int, Empresa> _ar1 = new ConcurrentDictionary<int, Empresa>();
var data = new List<Empresa>
{
new Empresa{nombre ="Globex Corp",color="red",vidId=1, img="data:image/jpeg;base64,blabla" },
new Empresa{nombre ="AM",color="blue",vidId=2, img="data:image/jpeg;base64,blabla" }
}
for(int i = 0; i<=6; i++)
{
_ar1.TryAdd(data[i].vidID, data[i]);
}
This is inside other function but it is the next one that involves the data send.
public IEnumerable<Empresa> GetArreglo()
{
return _ar1;
}
So far im not sure what could be wrong or if i need to aproach a different solution.
If any more info is needed ill post it. And even it is obvious im a newby still learning on this.
EDIT:
This is all the code involved:
// This is the JS
<script>
var ubi = '#ViewBag.ubicacion';
console.log("UbicaciĆ³n: " + ubi);
var conex = $.connection.channel;
var $marco = $('#marco');
var $imagen = $('#imagen');
var $empresa = $('#empresa');
function empezar() {
var min;
var max;
var pos;
var arreglo = new Array;
function init() {
conex.server.createGroup(ubi);
console.log("Entro al canal");
arreglo = conex.server.getArreglo(ubi);
//pos = arreglo.split('|');
//a.split is not a function
console.log(arreglo);
//console.log(pos);
setInterval(update, 6000);
}
function update() {
}
$.connection.hub.start().done(init);
}
window.onload = function() { empezar(); }
</script>
//It gets the conection to the HUB:
[HubName("channel")]
public class CanalHub : Hub
{
private readonly Canal _canal;
public CanalHub() : this(Canal.Instance) { }
public CanalHub(Canal canal)
{
_canal = canal;
}
public string[] GetArreglo(string ubi)
{
string[] array = _canal.GetArreglo(ubi);
return array;
//it is now a string[] because i wanted to
//try creating the obj with .split('|')
}
// And finally this is the last part involved:
public class Canal
{
private static Random random = new Random();
private volatile List<Canales> listaCan = new List<Canales>();
private readonly static Lazy<Canal> _instance = new Lazy<Canal>(() => new Canal(GlobalHost.ConnectionManager.GetHubContext<CanalHub>().Clients));
private readonly ConcurrentDictionary<int, Empresa> _datos = new ConcurrentDictionary<int, Empresa>();
private readonly ConcurrentDictionary<int, Empresa> _ar1 = new ConcurrentDictionary<int, Empresa>();
private Canal(IHubConnectionContext<dynamic> clients)
{
Clients = clients;
//Create the sample objects for the class
var datos = new List<Empresa>
{
new Empresa{nombre="Globex Corp", color="#A87F3D", vidID=1, img="balbal" },
new Empresa{nombre="AM", color="#535E89", vidID=2, img="balba" },
new Empresa{nombre="Frutijugos", color="#92191A", vidID=3, img="askldj" }
};
for (int i = 0; i <=6 ; i++)
{
_ar1.TryAdd(datos[i].vidID, datos[i]);
}
for (int i = 7; i <= 13; i++)
{
_ar2.TryAdd(datos[i].vidID, datos[i]);
}
for (int i = 14; i <= 20; i++)
{
_ar3.TryAdd(datos[i].vidID, datos[i]);
}
//sort them on 3 different arrays
}
private IHubConnectionContext<dynamic> Clients { get; set; }
public static Canal Instance
{
get { return _instance.Value; }
}
public string[] GetArreglo(string ubi)
{
string[] array = new string[7];
int i = 0;
if (ubi == "Campanario")
{
foreach (var item in _ar1)
{
array[i] += item.Value.nombre + "|";
array[i] += item.Value.color + "|";
array[i] += item.Value.img + "|";
array[i] += item.Value.vidID + "|";
i++;
}
return array;
}
//sort the array values and add them to the array
else return null;
}
It appears that your javascript promise is not set up correctly. The object in the view is the promise object and not the object returned. You are going to need to set up the promise correctly. deferred promise
I'm loading many pictures, and am using an array to do so.
loader[i].load(new URLRequest(picture[i]));
My Event Listener function is enabled like this:
loader[i].contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
My onComplete event handler shows this:
trace(e.target); //OUTPUT: [object LoaderInfo]
I've looked for properties in LoaderInfo that might identify which loader initiated the listener (the value of "i") so that I can putz around with each one specifically, like this:
bitmapDataArr[i] = e.target.content.bitmapData;
bmVisArr[i] = new Bitmap(bitmapDataArr[i]);
But cannot determine which "i" initiated the specific instance of the listener.
Any ideas? I tried giving a name to LoaderInfo to no avail. I still can't extract the pesky little identifying number.
EDIT showing loop for loaders and onComplete function:
for (i = 0; i < 10; i++) {
loader[i] = new Loader();
loader[i].contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
loader[i].load(new URLRequest(letter[i]));
}
private function onComplete(e:Event):void {
trace("e.target",e.target); //OUTPUT: e.target [object LoaderInfo]
var LI:LoaderInfo = e.target as LoaderInfo;
var eNum:int = (????);
bitmapDataArr[eNum] = e.target.content.bitmapData;
bmVisArr[eNum] = new Bitmap(bitmapDataArr[eNum]);
}
You'll somehow need to bring i value to onComplete function. For example, in the this context or thru an argument.
P.S.: It's easier to use weak ref. Dictionaries instead of deleting properties, though I don't know much about AS3.
Here's an example that also shows how to remove the event listeners (including their callback functions):
/* An object containing callback
* functions used along with event listeners.
*/
const callbacks: Object = {};
/* This function will re-declare and hoist i
* in itself. */
private function loop(i: uint): void {
loader[i] = new Loader;
const wrapped =
callbacks[i] = function wrapper(...args) {
// Pass all arguments (respectively event and i)
onComplete.apply(null, args);
// Function#apply(thisContext, arguments)
// Rest exp. isn't implemented yet, else we could just do:
// onComplete(...args);
};
loader[i].contentLoaderInfo
.addEventListener(Event.COMPLETE, wrapped, false,
0, true);
loader[i].load(new URLRequest(letter[i]));
};
for (var i: uint = 0; i < 10; ++i) loop(i);
private function onComplete(e: Event, i: uint): void {
const loaderInfo: LoaderInfo = e.target as LoaderInfo;
bitmapDataArr[i] = e.target
.content.bitmapData;
bmVisArr[i] = new Bitmap(bitmapDataArr[i]);
loader[i].contentLoaderInfo
.removeEventListener(
Event.COMPLETE, callbacks[i]
);
// Deletes the property that stores
// the function inside callbacks
delete callbacks[i];
}
Since posting this question, I've been utilizing the following class. It takes in an integer (number pictures to load) and gives public access to an array of Sprites in the Array "ShapeArr."
Each sprite's name property is derived from its URL name. (name:"pic1" from loaded url "assets/pic1.png")
I was having trouble with the whole concept/implementation of inline functions, and have been using this approach instead.
package {
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.display.Sprite;
import flash.events.Event;
public class MultipleImageLoader extends Sprite {
{private var pic:Array = [
"assets/pic1.png", "assets/pic2.png", "assets/pic3.png", "assets/pic4.png",
]}
private var loader:Array = [];
public var ShapeArr:Array = [];
public var bitmapDataArr:Array = [];
public var bmVisArr:Array = [];
private var shapeText:Array = [];
private var picArray:Array = [];
private var count:int = 0;
private var loaderCounter:int = 0;
private var numPicsToLoad:int;
private var a:String;
public var loaded:Boolean = false;
public function MultipleImageLoader(numPics:int):void {
numPicsToLoad = numPics;
loaded = false;
init();
}
private function init(e:Event = null):void {
if (hasEventListener(Event.ADDED_TO_STAGE)) {
removeEventListener(Event.ADDED_TO_STAGE, init);
}
picArray = new Array;
for (var i:int = 0; i < numPicsToLoad; i++) {
picArray.push(i);
}
initiateLoaders();
}
private function initiateLoaders():void{
loader[loaderCounter] = new Loader;
loader[loaderCounter].contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
a = pic[picArray[loaderCounter]];
//trace("shapecolor load:", a);
shapeText[loaderCounter] = (a.substr(16, a.length - 20));
loader[loaderCounter].load(new URLRequest(a ) );
}
private function onComplete(e:Event):void {
//trace("sssssssssssssssssssssssssshapecolor");
bitmapDataArr[loaderCounter] = e.target.content.bitmapData;
bmVisArr[loaderCounter] = new Bitmap(bitmapDataArr[loaderCounter]);
bmVisArr[loaderCounter].scaleX = .1;
bmVisArr[loaderCounter].scaleY = .1;
bmVisArr[loaderCounter].x =-bmVisArr[loaderCounter].width / 2;
bmVisArr[loaderCounter].y =-bmVisArr[loaderCounter].height / 2;
ShapeArr[loaderCounter] = new Sprite();
ShapeArr[loaderCounter].name = a.substr(7,4);
trace("Name",loaderCounter,ShapeArr[loaderCounter].name );
ShapeArr[loaderCounter].addChild(bmVisArr[loaderCounter]);
loader[loaderCounter].contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
if (loaderCounter <numPicsToLoad-1) {
loaderCounter += 1;
initiateLoaders();
}
//trace("gonna count",count);
counting();
count += 1;
}
private function counting():void {
trace("tile count", count,numPicsToLoad);
if (count < numPicsToLoad-1) {
return;
}
else{
removeEventListener(Event.ENTER_FRAME, counting);
loaded = true;
count = 0;
trace("All Images LOADED");
}
}
}//end Class
}//end Package
I'm currently developing an ANTLR4 javascript listener for this Grammar.
var _require = require;
var antlr = _require('./antlr4/index');
var javaLexer = _require('./generated/JavaLexer');
var javaParser = _require('./generated/JavaParser');
var javaListener = _require('./generated/JavaListener');
declare function require(name:string);
class CodeAnalysis {
input: String;
constructor(input:String) {
this.input = input;
this.antlrStack();
}
private antlrStack() {
console.log(this.input);
var chars = new antlr.InputStream(this.input);
var lexer = new javaLexer.JavaLexer(chars);
var tokens = new antlr.CommonTokenStream(lexer);
var parser = new javaParser.JavaParser(tokens);
var listener = new javaListener.JavaListener();
parser.buildParseTrees = true;
var tree = parser.compilationUnit();
antlr.tree.ParseTreeWalker.DEFAULT.walk(listener, tree);
}
public getInput() {
return this.input;
}
}
The problem is that the performance is very bad (takes over two min) with an input like this:
import codescape.Dogbot;
public class MyDogbot extends Dogbot{
public void run() {
turnLeft();
move();
}
}
The same grammar and the same listener in Java performs a lot faster (>2 sec).
Anybody an idea why? Or how to fix it?
Bruno
What I'm trying to do is spawn an enemy and create a marker/blip on the Minimap for the spawned enemy.
I get a NullReferenceException at line BlipCtrl:29.
The Blips on the Minimap have a Target GameObject which position reflects the position of the Blip on the Minimap. When an Enemy is instantiated I set it to have a unique name. I'm having trouble writing a function the sets the Target of the Blip to the GameObject with the Unique name that the Blip gets it's position and rotation from.
Spawner.js
public var enemy : Rigidbody ;
private var spawnValues : Vector3 = Vector3(50, 1, 50);
public var enemycount : int ;
public var enemyId : int;
static var enemiesarray = new Array();
public var blipcontroller : BlipCtrl;
var spawnPosition : Vector3;
var spawnRotation : Quaternion;
function Start () {
var blipcontroller = GetComponent("BlipCtrl");
SpawnWaves();
}
function SetName () {
enemy.name = "Enemy#" + enemyId++;
}
function SpawnWaves() {
for(var i = 0; i < enemycount; i++) {
var spawnPosition : Vector3 = new Vector3(Random.Range(-50, 50), spawnValues.y ,Random.Range (-50, 50));
var spawnRotation : Quaternion = Quaternion.identity;
SetName();
Instantiate(enemy, spawnPosition, spawnRotation);
enemiesarray.Push(this.enemy);
blipcontroller.CreateBlip(enemy, spawnPosition, spawnRotation);
}
}
BlipCtrl.js
public var EnemyBlipImage : Rigidbody;
public var bliparray = new Array();
public var blipID : int;
public var map : Minimap;
private var blipTarget : Blip;
private var gameobject : GameObject;
static var target : Transform;
var newBlip : GameObject;
function Awake () {
blipTarget = GetComponent(Blip);
map = GetComponent(Minimap);
}
function SetName() {
EnemyBlipImage.name = "EnemyBlip#" + blipID++;
}
function CreateBlip(object, objectName, position , rotation) {
SetName();
var newBlip = Instantiate(EnemyBlipImage, position, rotation);
newBlip.transform.SetParent(map.transform);
newBlip.gameObject.tag = "Enemy" ;
gameobject = GameObject.Find(objectName + "(Clone)");
blipTarget.target = gameobject.transform;
blipTarget.SetTarget(gameobject);
}
Blip.js
#pragma strict
public var target : Transform ;
public var keepInBounds = true;
public var LockScale = false;
public var LockRotation = false;
private var map : Minimap ;
private var myRectTransform : RectTransform ;
//set target to gameobject
function SetTarget(gameobject) {
target = gameobject;
}
function Start () {
map = GetComponentInParent(Minimap);
myRectTransform = GetComponent(RectTransform);
}
function Update () {
}
function LateUpdate() {
var newPosition : Vector3 = map.TransformPosition(target.position);
if(keepInBounds) {
newPosition = map.MoveInside(newPosition);
}
if(!LockScale) {
myRectTransform.localScale = new Vector3(map.zoomLevel, map.zoomLevel, 1);
}
if(!LockRotation) {
myRectTransform.localEulerAngles = map.TransformRotation(target.eulerAngles);
}
myRectTransform.localPosition = newPosition;
}
I have a function defined in my JavaScript with two properties: size and url:
function IconInfo() {
this.size = size;
this.url = url;
}
Inside another function I create a new instance of IconInfo and set the properties this way:
function SomeFunction() {
var icon = new IconInfo();
icon.size = 64;
icon.url = "http://somesite.com/image1.png";
}
Isn't there a way to create an instance like the following:
var icon = new IconInfo({
size : 64,
url : "http://somesite.com/image1.png"
});
I like that notation better, it seems more concise and easier to read.
===========================UPDATE================================
Based on Tim's answer of doing it the following way:
var icon = {
size : 64,
url : "http://somesite.com/image1.png"
};
I have the following question.
Let's say I have 2 functions both with the same exact properties and constructor arguments:
function Func1(x) {
this.x = x;
}
function Func2(x) {
this.x = x;
}
And I have a container that holds either type:
function Container() {
this.f = null;
}
If I add one of the functions using that method what type will it actually be?
...
var container = new Container();
container.x = new f { // is f Func1 or Func2?
x: 10;
}
There are a lot of options, but keeping it simple.. you could just do this:
var icon = {
size : 64,
url : "http://somesite.com/image1.png"
};
You don't have to declare a "type", but you could.. sort of like this:
function IconInfo(size, url)
this.size = size;
this.url = url;
);
var icon = new IconInfo(2, "www.google.com");
You can actually make it even more concise. First, you're forgetting to set the variables inside IconInfo; it should be this:
function IconInfo(size, url) {
this.size = size;
this.url = url;
}
To create a new IconInfo in your other function, you'll just need to call it like this:
function SomeFunction() {
var icon = new IconInfo(64, "http://somesite.com/image1.png");
}