#StackBounty: #javascript #eslint Detecting nested undefined attributes using command line tools (eslint/standard)

Bounty: 50

I’d like to be able to use static code analysis tool (standard/eslint) to detect following situation:

  const obj = {a: {b: 'just a value'}}
  // should be obj.a.b
  const b = obj.a.c
  // so b will be undefined

Both Standard and ESLint will not find any issue here.
Is it possible to detect it using good code quality tools?

Just to give example, IDEA/Webstorm is reporting the problem correctly
enter image description here

so, just wondering, is it possible to detect the same issue using command line tools.


Get this bounty!!!

#StackBounty: #javascript #angularjs #routing #angular-ui-router #state-management How to pass $state variable into 2 other sibling $st…

Bounty: 200

Plnkr: https://plnkr.co/edit/Brmcxd2LjGVJ6DXwuJtF?p=preview

Architecture:

$login -> $container (contains $dashboard and $feed), dashboard contains: $tickers, $tags, $viewHeader and $socialMedia components.

Goal:

tags needs to communicate and send a tag object into the viewHeader and socialMedia states.

Expected:

After Login, selecting a button in the Tags list should send that tag into the ViewHeader and SocialMedia states/components.

Results:

After Login, selecting a button in the Tags and going to $state dashboard the $states for the ViewHeader and SocialMedia refresh but the view model variable {{ term }} does not update with the appropriate tag in either component.

enter image description here

Design explanation:

The reason I’m trying to use a mix of states, components, sibling components and views is that I’m trying to solve a problem I have where I do not want every single component re-init when something in the state changes.

IE: When I select a Ticker or a Tag I do NOT want the Feed component to refresh every single time. However the user should be able to take an action in the Feed component and it will update all the others.

This is why I created a container state to hold both the dashboard and feed states. Originally I had everything in the dashboard state, and anything $state.go('dashboard' happened the feed component would also refresh. If there is a better way to solve this issue lmk! 🙂

enter image description here


In this screenshot below I can clearly see that the correct tag is being passed into the correct $states, but yet {{ term }} does not update.

enter image description here

enter image description here

The click function in the Tags list:

$scope.clickTag = function(tag) {
  console.log(' Tag clicked', $state);
  $state.go('dashboard', { tag: tag });
}

socialMedia controller:

social.component('socialModule', {
  templateUrl: 'social-module-template.html',
  controller: function($scope, $state) {
    console.log('Social component', $state.params);
    $scope.term = $state.params.tag.term;
  }
});

viewHeader controller:

view.component('viewModule', {
  templateUrl: 'view-module-template.html',
  controller: function($scope, $state) {
    console.log('View component', $state.params);
    $scope.term = $state.params.tag.term;
  }
});

Strange doubling up of components

Just noticed this, after clicking on a tag and breaking inside of the social.component. It looks like the dashboard component is being re-rendering in place of the tags component for a split second:

enter image description here


Get this bounty!!!

#StackBounty: #javascript #neural-network #genetic-algorithm Avoid local optima training XOR

Bounty: 50

I’m using Gynaptic to train a neural network that solves an XOR with a genetic algorithm. The fitness is defined as follows:

// max score = 0
score -= Math.abs(0 - network.activate([0, 0])) * 5000;
score -= Math.abs(1 - network.activate([1, 0])) * 5000;
score -= Math.abs(1 - network.activate([0, 1])) * 5000;
score -= Math.abs(0 - network.activate([1, 1])) * 5000;

Sometimes it runs just fine. But i’m assuming it just lucked out then. But quite often, it won’t even reach -6000. It will hang around -8000 a lot.

These are my settings:

  GNN = new Evolution({
    size: 100,
    elitism: 10,
    mutationRate: 0.3,
    networkSize : [2,3,1],
    mutationMethod: [
      Methods.Mutate.MODIFY_RANDOM_BIAS,
      Methods.Mutate.MODIFY_RANDOM_WEIGHT,
      Methods.Mutate.SWAP_BIAS,
      Methods.Mutate.SWAP_WEIGHT,
      Methods.Mutate.MODIFY_SQUASH
    ],
    crossOverMethod: [
      Methods.Crossover.UNIFORM,
      Methods.Crossover.AVERAGE,
      Methods.Crossover.SINGLE_POINT,
      Methods.Crossover.TWO_POINT
    ],
    selectionMethod: [
      Methods.Selection.FITNESS_PROPORTIONATE
    ],
    generationMethod: [
      Methods.Generation.POINTS
    ],
    fitnessFunction: function(network){
      var score = 0;

      score -= Math.abs(0 - network.activate([0, 0])) * 5000;
      score -= Math.abs(1 - network.activate([1, 0])) * 5000;
      score -= Math.abs(1 - network.activate([0, 1])) * 5000;
      score -= Math.abs(0 - network.activate([1, 1])) * 5000;

      return Math.round(score);
    }
  });

(view the JSFiddle here, open console and press train)

What settings do you advise me to change?

P.S. I understand that training an XOR is much easier through backpropagation, but this is just for experimental purposes.


Get this bounty!!!

#StackBounty: #javascript #google-maps #angular2 #typescript How to remove drawn circle or polygon from google map using drawing manage…

Bounty: 50

How can I remove the drawn circle or polygon using drawing manager from the google map.

Component:

import {Ng2MapComponent, DrawingManager, Polygon} from 'ng2-map';

export class CreateAlertComponent implements OnInit {
   @ViewChild(Ng2MapComponent) mapObj: Ng2MapComponent;
   @ViewChild(DrawingManager) drawingManager: DrawingManager;

   polygonCompleteFunction(e) {
       console.log(this.mapObj);
   };

});

HTML:

<ng2-map [zoom]="mapOptions.zoom" [minZoom]="mapOptions.minZoom" [center]="mapOptions.center" clickable="false" (click)="mapClick($event)">
                    <drawing-manager *ngIf = "selectedJurisdictions.length > 0" 
                        [drawingMode]="'null'"
                        [drawingControl]="true"
                        [drawingControlOptions]="{
                        position: 2,
                        drawingModes: ['circle', 'polygon']
                        }"
                        [circleOptions]="{
                        fillColor: 'red',
                        fillOpacity: 0.3,
                        strokeColor: 'black',
                        strokeWeight: 2,
                        editable: true,
                        draggable: true,
                        zIndex: 1
                        }"
                        [polygonOptions]="{
                        fillColor: 'red',
                        fillOpacity: 0.3,
                        strokeColor: 'black',
                        strokeWeight: 2,
                        editable: true,
                        draggable: true,
                        zIndex: 1
                        }"
                        (polygoncomplete)="polygonCompleteFunction($event)"
                        (circlecomplete)="circleCompleteFunction($event)">
                    </drawing-manager>
</ng2-map>

But on polygon complete function or circle complete I am not getting the drawn polygons from the map object


Get this bounty!!!

#StackBounty: #javascript #angularjs #angular2 #webpack-2 AngularJS is not found in Hybrid app

Bounty: 50

I’m building a POC of Angular 1+2 Hybrid application. I have managed to run it and now I’m trying to introduce Webpack.

I get a Error: AngularJS v1.x is not loaded! error when bootstrapping the module. I’ve checked – the angular is loaded when initializing the module.

Any help would be appreciated.

Entry file:

import { downgradeInjectable, downgradeComponent } from '@angular/upgrade/static';
import { BrowserModule } from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {HelloAngular2} from './components/hello-angular2';
import {TimeZonesService} from './services/timezones';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { UpgradeModule } from '@angular/upgrade/static';
import * as angular from 'angular';

angular.module('scotchTodo', [/*'todoController', 'todoService'*/]);
angular.module('scotchTodo').directive('helloAngular2', downgradeComponent({ component: HelloAngular2}));
angular.module('scotchTodo').factory('timeZones', downgradeInjectable(TimeZonesService));   

@NgModule({
 declarations: [HelloAngular2],
 entryComponents: [HelloAngular2],
 imports: [BrowserModule, UpgradeModule],
 providers: [TimeZonesService]
})
class MyNg2Module {
    ngDoBootstrap() {};
}

platformBrowserDynamic().bootstrapModule(MyNg2Module).then(platformRef => {
  const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
  upgrade.bootstrap(document.documentElement, ['scotchTodo']);
});

Webpack config:

var webpack = require('webpack'),
    path = require('path'),
    ExtractTextPlugin = require('extract-text-webpack-plugin');

var config = {
  entry: {
    app: __dirname + '/public/js/boot.js'
  },
  output: {
    path: __dirname + '/public/dist',
    filename: 'app-loader.js'
  },
  resolve:{
      extensions: ['.js'],
      alias: {
          'controllers/main.js': 'controllers/main.js',
          'services/todos.js':'services/todos.js'
      }
  }
};

module.exports = config;

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "public/jslibs",
    "typings/main",
    "typings/main.d.ts"
  ]
}

Bootstrap generated part that has angular defined:

angular.module('scotchTodo', []);
angular.module('scotchTodo').directive('helloAngular2', static_1.downgradeComponent({ component: hello_angular2_1.HelloAngular2 }));
angular.module('scotchTodo').factory('timeZones', static_1.downgradeInjectable(timezones_1.TimeZonesService));
var MyNg2Module = (function () {
    function MyNg2Module() {
    }
    MyNg2Module.prototype.ngDoBootstrap = function () { };
    ;
    return MyNg2Module;
}());
MyNg2Module = __decorate([
    core_1.NgModule({
        declarations: [hello_angular2_1.HelloAngular2],
        entryComponents: [hello_angular2_1.HelloAngular2],
        imports: [platform_browser_1.BrowserModule, static_2.UpgradeModule],
        providers: [timezones_1.TimeZonesService]
    })
], MyNg2Module);
platform_browser_dynamic_1.platformBrowserDynamic().bootstrapModule(MyNg2Module).then(function (platformRef) {
    var upgrade = platformRef.injector.get(static_2.UpgradeModule);
    upgrade.bootstrap(document.documentElement, ['scotchTodo']);
});

–UPDATE–

After adding ProvidePlugin with this config:

new webpack.ProvidePlugin({
‘angular’: ‘angular’
})

the Error: AngularJS v1.x is not loaded! error which I presume came from Upgrade module has disappeared.
Now the angular is undefined in angular.module because angular is imported by __webpack_require__

–UPDATE 2–

It seems like the problem is that AngularJS doesn’t support CommonJS style module.exports. I’m trying to use exports-loader but it doesn’t work now. The config is:

loaders: [
      { test: /[/]angular.js$/, loader: "exports-loader?angular" }
    ]

–UPDATE 3–

After adding module.exports = windows.angular; to the bootstrap generated file there is no error. But application still doesn’t work because there is no resumeBootstrap function for angular available.

–UPDATE 4–

Here is the main page HTML:

<body ng-controller="mainController">

I'm a Todo-aholic {{ todos.length }}

<!-- TODO LIST -->
<p class="text-center" ng-show="loading"> <span class="fa fa-spinner fa-spin fa-3x"></span> </p> </div> </div> <!-- FORM TO CREATE TODOS -->
<!-- createToDo() WILL CREATE NEW TODOS --> <button type="submit" class="btn btn-primary btn-lg" ng-click="createTodo()">Add</button> </form> </div> </div>
A demo by Scotch. Read the tutorial.
</div>


Get this bounty!!!

#StackBounty: #javascript #google-maps #google-maps-api-3 Google map api directions service gives OVER_QUERY_LIMIT while displaying rou…

Bounty: 50

I’m working with project module which is using google map api direction services to draw path between multiple markers.

Here is my code:

var iconsetngs = {
    path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};

//Initialize the Path Array
var path = new google.maps.MVCArray();

//Initialize the Direction Service
var service = new google.maps.DirectionsService();

var polylineoptns = {
    strokeOpacity: 0.8,
    strokeWeight: 3,
    strokeColor: '#4986E7',
    map: map,
    icons: [{
              repeat: '600px', //CHANGE THIS VALUE TO CHANGE THE DISTANCE BETWEEN ARROWS
              icon: iconsetngs,
              offset: '100%'
            }]
  };


  var poly = new google.maps.Polyline(polylineoptns);

  //Loop and Draw Path Route between the Points on MAP
  for (var i = 0; i < lat_lng.length; i++) {
      if ((i + 1) < lat_lng.length) {
           var src = lat_lng[i];
           var des = lat_lng[i + 1];
           poly.setPath(path);
           service.route({
           origin: src,
           destination: des,
           travelMode: google.maps.DirectionsTravelMode.DRIVING                              

},function (result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
               for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) { 
                  path.push(result.routes[0].overview_path[i]);
                }
              }
           });
     }
   }
}

It’s displaying route, but after some points, it’s break.
Here is the result.

enter image description here

I’m not sure where I’m wrong or missing anything!

Edit:

It gives a status of OVER_QUERY_LIMIT


Get this bounty!!!

#StackBounty: #javascript #node.js #mongodb #passport.js #passport-local PassportJS not passing signup data to database, possible datab…

Bounty: 500

I’m using a scotch.io tutorial on setting up PassportJS local login for an app I’m working on. After setting up my signup/login pages, MongoDB, PassportJS, I tried making a test “account”, and…. nothing happens. No redirect, no flash message, nothing. It seems like nothing is getting picked up to post to the database. I’m including the pertinent scripts below. I tried to be as faithful as possible to the tutorial layout (source: https://scotch.io/tutorials/easy-node-authentication-setup-and-local).

index.js (entry point for server)

// load dependencies
var express = require('express');
var app = express();
var path = require('path');

var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var LocalStrategy = require('passport-local').Strategy;

var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var session = require('express-session');

var configDB = require('./config/database.js');

// setup views
var ejs = require('ejs');
var engine = require('ejs-locals');

//database configuration
mongoose.connect(configDB.url);

require('./config/passport')(passport);

app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

//view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/public', express.static(path.join(__dirname, 'public')));

// required for passport
app.use(session({ 
    secret: 'ilovescotchscotchyscotchscotch',
    resave: true,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // for flash messages stored in-session

// routes
require('./routes')(app, passport);

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
});

passport.js (passport settings)

var LocalStrategy = require('passport-local').Strategy;

var User = require('../user');

module.exports = function(passport) {
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    passport.use('local-signup', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true
    },
    function(req, email, password, done) {
        process.nextTick(function() {
            User.findOne({ 'local.email': email }, function(err, user) {
                if (err)
                    return done(err);
                if (user) {
                    return done(null, false, req.flash('signupMessage', 'That e-mail address is already taken.'));
                } else {
                    var newUser = new User;
                    newUser.local.email = email;
                    newUser.local.password = newUser.generateHash(password);
                    newUser.save(function(err) {
                        if (err)
                            throw err;
                        return done(null, newUser);
                    });
                }
            });
        });
    }));

    passport.use('local-login', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true
    },
    function(req, email, password, done) {
        User.findOne({ 'local.email': email }, function(err, user) {
            if (err)
                return done(err);
            if (!user)
                return done(null, false, req.flash('loginMessage', 'User not found.'));
            if(!user.validPassword(password))
                return done(null, false, req.flash('loginMessage', 'Invalid password, please try again.'));
            return done(null, user);
        });
    }));
};

/config/database.js

module.exports = {
    'url': 'mongodb://localhost:27017/users/'
}

routes.js

module.exports = function(app, passport) {
    app.get('/', function (req, res) {
        res.render('pages/index');
    });

    app.get('/login', function (req, res) {
        res.render('pages/login', { message: req.flash('loginMessage') });
    });

    app.get('/signup', function (req, res) {
        res.render('pages/signup', { message: req.flash('signupMessage') });
    });

    app.post('/signup', passport.authenticate('local-signup', {
        successRedirect: '/profile',
        failureRedirect: '/signup',
        failureFlash: true
    }));

    app.post('/login', passport.authenticate('local-login', {
        successRedirect: '/profile',
        failureRedirect: '/login',
        failureFlash: true
    }));

    app.get('/profile', isLoggedIn, function(req, res) {
        res.render('profile.ejs', {
            user: req.user
        });
    });

    app.get('/addroom', function (req, res) {
        res.render('pages/addroom.ejs', {
            message: req.flash('addroomMessage')
        });
    });

    app.get('/propconfig', function (req, res) {
        res.render('pages/propconfig.ejs', {
            message: req.flash('propconfigMessage')
        });
    });
    app.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });
};

// route middleware to ensure a user is logged in
function isLoggedIn(req, res, next) {
    if (req.isAuthenticated())
        return next();
    res.redirect('/');
}

user.js (user schema)

// load dependencies
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');

// define user schema
var userSchema = mongoose.Schema({
    local: {
        email: String,
        password: String
    }
});

// METHODS
// generating a hash

userSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

// checking if password is valid
userSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.local.password);
};

// creating model for user to expose to app
module.exports = mongoose.model('User', userSchema);

and finally, signup.ejs (template for signup UI)

<!doctype html>
<html>
<head>
    <title>Node Authentication</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
    <style>
        body        { padding-top:80px; }
    </style>
    https://code.jquery.com/jquery-3.1.1.min.js
    http://code.jquery.com/ui/1.12.1/jquery-ui.min.js
</head>
<body>

Signup

0) { %>
<% } %> <!-- LOGIN FORM --> <form action="/signup" method="post">
</div>
</div> <button type="submit" class="btn btn-warning btn-lg">Signup</button> </form> <hr> <p>Already have an account? <a href="/login">Login</a></p> <p>Or go <a href="/">home</a>.</p> </div> </div> http://../public/javascripts/validate.js </body> </html>

Update: I commented out the email validation script I was using, and now the POST action is happening (why it wasn’t before, I have no idea), but it’s still not getting to the database.

Update #2: I tried running the server in debug mode. The console returned this information:

GET /signup 304 34.791 ms - -
  express:router dispatching POST /signup +28s
  express:router query  : /signup +0ms
  express:router expressInit  : /signup +0ms
  express:router logger  : /signup +0ms
  express:router cookieParser  : /signup +1ms
  express:router jsonParser  : /signup +0ms
  express:router urlencodedParser  : /signup +3ms
  express:router session  : /signup +157ms
  express:router initialize  : /signup +2ms
  express:router authenticate  : /signup +0ms
  express:router <anonymous>  : /signup +1ms
POST /signup - - ms - -
  express:router dispatching POST /signup +2m
  express:router query  : /signup +0ms
  express:router expressInit  : /signup +0ms
  express:router logger  : /signup +1ms
  express:router cookieParser  : /signup +1ms
  express:router jsonParser  : /signup +2ms
  express:router urlencodedParser  : /signup +0ms
  express:router session  : /signup +4ms
  express:router initialize  : /signup +1ms
  express:router authenticate  : /signup +2ms
  express:router <anonymous>  : /signup +1ms
POST /signup - - ms - -

Meanwhile, the browser stayed on "Waiting for localhost..." for about 2 or 3 minutes (without crashing or timing out), before finally returning “The localhost page isn’t working

localhost didn’t send any data.
ERR_EMPTY_RESPONSE”

Update #3: This is another debug log, checking all modules (not just Express):

  express:router dispatching POST /signup +39s
  express:router query  : /signup +4ms
  express:router expressInit  : /signup +1ms
  express:router logger  : /signup +2ms
  express:router cookieParser  : /signup +5ms
  express:router jsonParser  : /signup +3ms
  body-parser:json content-type "application/x-www-form-urlencoded" +0ms
  body-parser:json skip parsing +4ms
  express:router urlencodedParser  : /signup +1ms
  body-parser:urlencoded content-type "application/x-www-form-urlencoded" +0ms
  body-parser:urlencoded content-encoding "identity" +3ms
  body-parser:urlencoded read body +0ms
  body-parser:urlencoded parse body +60ms
  body-parser:urlencoded parse extended urlencoding +5ms
  express:router session  : /signup +8ms
  express-session fetching 6M-W_9dEFDmsPBvNp2d0UmeBE9gDuXMn +14ms
  express-session no session found +3ms
  express:router initialize  : /signup +9ms
  express:router authenticate  : /signup +0ms
  express:router <anonymous>  : /signup +2ms
req.body: {"email":"matt@matt.matt","password":"pass1234"}
  mquery findOne +20ms users { 'local.email': 'matt@matt.matt' } { fields: {} }
  express-session saving EkaL4tXbUCZ9QXHDGt2XWxlgMjVGejAC +95ms
  express-session split response +1ms
  express-session set-cookie connect.sid=s%3AEkaL4tXbUCZ9QXHDGt2XWxlgMjVGejAC.cvTE1KsUvIzbnNqHP0ns9td75MUkR4mKRDvwuHk%2B4jE; Path=/; HttpOnly +4ms
  morgan log request +17ms
POST /signup 302 237.147 ms - 58
  express:router dispatching GET /signup +9ms
  express:router query  : /signup +2ms
  express:router expressInit  : /signup +0ms
  express:router logger  : /signup +1ms
  express:router cookieParser  : /signup +2ms
  express:router jsonParser  : /signup +0ms
  body-parser:json skip empty body +0ms
  express:router urlencodedParser  : /signup +13ms
  body-parser:urlencoded skip empty body +0ms
  express:router session  : /signup +1ms
  express-session fetching EkaL4tXbUCZ9QXHDGt2XWxlgMjVGejAC +1ms
  express-session session found +3ms
  express:router initialize  : /signup +1ms
  express:router authenticate  : /signup +1ms
  express:router <anonymous>  : /signup +1ms
  express:view lookup "pages/signup.ejs" +6ms
  express:view stat "/media/matt/PORTABLE/myapp/views/pages/signup.ejs" +1ms
  express:view render "/media/matt/PORTABLE/myapp/views/pages/signup.ejs" +1ms
  express-session saving EkaL4tXbUCZ9QXHDGt2XWxlgMjVGejAC +18ms
  express-session split response +0ms
  morgan log request +10ms
GET /signup 200 50.407 ms - 1736


Get this bounty!!!

#StackBounty: #javascript #angularjs #google-maps #google-maps-api-3 #ng-map AngularJS – Add walking distance to ngMaps with circle

Bounty: 50

I’ve been trying to achieve something like is done in this website.

So far I’ve managed to create a map with circles by using ngMaps.
Below is the snippet of what I have done till now…

Can anyone help me how to go ahead in getting the walking distance from the marker to each of the circle’s radius lines?

Thanks 🙂

var app = angular.module('mapApp', ['ngMap']);
app.controller('mapCntrl', function($scope) {
  $scope.geofences = [{
      "name": "circle",
      "lat": 30.45,
      "long": -91.15,
      radius: 200
    },
    {
      "name": "circle",
      "lat": 30.45,
      "long": -91.15,
      radius: 500
    },
    {
      "name": "circle",
      "lat": 30.45,
      "long": -91.15,
      radius: 800
    },
    {
      "name": "circle",
      "lat": 30.45,
      "long": -91.15,
      radius: 1000
    }
  ];
});
<!DOCTYPE html>
<html>

<head>
  <title>Simple Map with circles</title>
  <meta name="description" content="Simple Map">
  <meta name="keywords" content="ng-map,AngularJS,center">
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
  https://maps.google.com/maps/api/js?libraries=placeses,visualization,drawing,geometry,places
  https://code.angularjs.org/1.3.15/angular.js
  https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js
  http://app.js
</head>

<body ng-app="mapApp" ng-controller="mapCntrl">
  <ng-map class=map zoom="15" center="[30.45, -91.15]">
    <marker position="[30.45, -91.15]" />
    <shape ng-repeat="fence in geofences" name="circle" radius="{{fence.radius}}" center="[{{fence.lat}}, {{fence.long}}]" />
    <control name="overviewMap" opened="true" />
  </ng-map>
</body>

</html>


Get this bounty!!!

#StackBounty: #javascript #image #zoom #absolute How do you zoom into a specific point (no canvas)?

Bounty: 100

The goal is simple, using a mousewheel, zoom into a specific point (where the mouse is). This means after zooming the mouse will be in the same roughly the same spot of the picture.

Example of mouse mantaining position after zooming
(Purely illustrative, I don’t care if you use dolphins, ducks or madonna for the image)

I do not wish to use canvas, and so far I’ve tried something like this:

HTML

<img src="whatever">

JS

function zoom(e){
    var deltaScale = deltaScale || -e.deltaY / 1000;
    var newScale = scale + deltaScale;
    var newWidth = img.naturalWidth * newScale;
    var newHeight = img.naturalHeight * newScale;
    var x = e.pageX;
    var y = e.pageY;
    var newX = x * newWidth / img.width;
    var newY = y * newHeight / img.height;
    var deltaX = newX - x;
    var deltaY = newY - y;
    setScale(newScale);
    setPosDelta(-deltaX,-deltaY);
}

function setPosDelta(dX, dY) {
    var imgPos = getPosition();
    setPosition(imgPos.x + dX, imgPos.y + dY);
}

function getPosition() {
    var x = parseFloat(img.style.left);
    var y = parseFloat(img.style.top);
    return {
        x: x,
        y: y
    }
}

function setScale(n) {
    scale = n;
    img.width = img.naturalWidth * n;
    img.height = img.naturalHeight * n;
}

What this attempts to do is calculate the x,y coordinates of the dolphin’s eye before and after the zoom, and after calculating the distance between those two points, substracts it from the left,top position in order to correct the zoom displacement, with no particular success.

The zoom occurs naturally extending the image to the right and to the bottom, so the correction tries to pull back to the left and to the top in order to keep the mouse on that damn dolphin eye! But it definitely doesn’t.

Tell me, what’s wrong with the code/math? I feel this question is not too broad, considering I couldn’t find any solutions besides the canvas one.

Thanks!


Get this bounty!!!

#StackBounty: #javascript #selenium #selenium-webdriver #webdriver-io #firefox-profile How to use socks authentication in webdriverio

Bounty: 50

I would like to have SOCKSv5 authentication enabled in my webdriverio application. However it doesn’t seem to work at the moment.

So far i have tried the following configurations:

  1. Setting manually using firefox-profile as followed:
fp.setProxy({ 
    proxyType: 'manual', 
    socksProxy: `127.0.0.1:1080`,
    socksUsername: 'myuser',
    socksPassword: 'mypass'
});

this didn’t seem to work as pages simply don’t load.

  1. Using FoxyProxy

I have tried setting the url using its api:

proxy:host=${proxy}&port=1080&isSocks=true&enabled=true&username=myuser&password=mypass

Which gave me a warning that something is accessing its configuration and thus declining the request.

Creating a custom firefox profile and then loading that one doesn’t work as i will have to edit proxies during my applications runtime.

Has anybody came across a solution?


Get this bounty!!!