Sunday, July 31, 2016

How to change theme tabs to be more lighter in Visual Studio

Leave a Comment

I am using Visual Studio 2015 and the theme color extention (light color) and don't like the theme tab dark colors:

enter image description here

I would like to have something more lighter tabs like this:

enter image description here

How can I change it?

Thanks in advance.

2 Answers

Answers 1

Finally I found the cause of the colorized tags.

It happend because of a Productivity Power Tools extension. All I need to do is to go to: Tool -> Opthions -> Productivity Power Tools -> Custom Document Well -> uncheck the checkbox Color tabs by project.

Answers 2

You might want to check these out: https://visualstudiogallery.msdn.microsoft.com/366ad100-0003-4c9a-81a8-337d4e7ace05

Read More

How to add a class to the corresponding popup

Leave a Comment

I have got two div's

<div id="one"> and <div id="two"> 

Each div has got a button class named addonsBtn , when clicked on that it will open a popup and append data to the corresponding popup

If clicked on First Addon , is it possible to add class by name 'foroneclass' so that it looks this way

<div data-role="popup" id="addonsWrap789" class='foroneclass' data-theme="a"> </div> 

Similarly

If clicked on Second Addon , is it possible to add class by name 'fortwolass' so that it looks this way

<div data-role="popup" id="addonsWrap790" class='fortwolass' data-theme="a"> </div> 

This is my fiddle http://jsfiddle.net/cod7ceho/109/

7 Answers

Answers 1

Sure. There are a few ways to skin a cat



Basic solution

Based on your fiddle, you can extend the following two lines:

Line 8 is:

$("#addonsWrap789").popup({history: false}).popup('open').enhanceWithin();  

Becomes:

$("#addonsWrap789").popup({history: false}).popup('open').enhanceWithin().addClass("foroneclassfo"); 

And line 15:

$("#addonsWrap790").popup({history: false}).popup('open').enhanceWithin(); 

Becomes:

$("#addonsWrap790").popup({history: false}).popup('open').enhanceWithin().addClass("foretwoclassfo"); 



Cleaner solution

I've cleaned up your jsfiddle file a bit. We can approach it in a bit more of a reusable way by taking the toppname and appending your desired class suffix onto the end. This way, you could have 2 or 10 modals and it would continue to work as intended.

$(document).on('click', '.addonsBtn', function (e) {   var toppname = $(this).data('toppname');   var html = '<div class="popup_inner addonsContent"><div class="popup_content"><div class="popup_content_addonsWrap"><div class="addonsListWrap"><h3>Toppings</h3><ul><li><form><div class="ui-checkbox ui-mini"></div></form></li></ul></div></div></div></div>';    $("#addonsWrap789").html(html).trigger('create').trigger('pagecreate');   $("#addonsWrap789").trigger('create').trigger('pagecreate');   $("#addonsWrap789").popup({history: false}).popup('open').enhanceWithin().addClass(toppname + 'class'); }); 

Updated fiddle: http://jsfiddle.net/cod7ceho/110/

Answers 2

$(document).on('click', '.addonsBtn', function(e) {     var toppname = $(this).data('toppname');     var html = '<div class="popup_inner addonsContent"><div class="popup_content"><div class="popup_content_addonsWrap"><div class="addonsListWrap"><h3>Toppings</h3><ul><li><form><div class="ui-checkbox ui-mini"></div></form></li></ul></div></div></div></div>';     if (toppname === 'forone') {         $("#addonsWrap789").addClass($(this).attr('data-toppname')+'class');         $("#addonsWrap789").html(html).trigger('create').trigger('pagecreate');         $("#addonsWrap789").trigger('create').trigger('pagecreate');         $("#addonsWrap789").popup({             history: false         }).popup('open').enhanceWithin();     } else if (toppname === 'fortwo') {         $("#addonsWrap790").addClass($(this).attr('data-toppname')+'class');         $("#addonsWrap790").html(html).trigger('create').trigger('pagecreate');         $("#addonsWrap790").trigger('create').trigger('pagecreate');         $("#addonsWrap790").popup({             history: false         }).popup('open').enhanceWithin();     } }); 

Highlight this code:

$("#addonsWrap789").addClass($(this).attr('data-toppname')+'class'); 

and :

$("#addonsWrap790").addClass($(this).attr('data-toppname')+'class'); 

Answers 3

$(document).on('click', '.addonsBtn', function(e) {   var toppname = $(this).data('toppname');   var id = $(this).attr('id');   var html = '<div class="popup_inner addonsContent"><div class="popup_content"><div class="popup_content_addonsWrap"><div class="addonsListWrap"><h3>Toppings</h3><ul><li><form><div class="ui-checkbox ui-mini"></div></form></li></ul></div></div></div></div>';    $("#" + id ).html(html).trigger('create').trigger('pagecreate');   $("#" + id ).trigger('create').trigger('pagecreate');   $("#" + id ).popup({     history: false   }).popup('open').enhanceWithin().addClass(toppname);  }); 

Answers 4

Here is a Demo

$(document).on('click', '.addonsBtn', function(e) {  var $toppName = $(this).data('toppname'),      $topClass = $(this).data('topclass'),      $popup = $("#" + $(this).data("popup")),      $popupContent = '<div class="popup_inner addonsContent"><div class="popup_content"><div class="popup_content_addonsWrap"><div class="addonsListWrap"><h3>Toppings</h3><ul><li><form><div class="ui-checkbox ui-mini"></div></form></li></ul></div></div></div></div>';    $($popup).html($popupContent).trigger('create').trigger('pagecreate');   $($popup).trigger('create').trigger('pagecreate');   $($popup).popup({     history: false   }).popup('open').enhanceWithin().addClass($topClass);  // addClass method will keep the class even when the popup is hidden  }); 

and you can add the Popup Class and Id reference within the Button's data attributes - No need for If statements -

 <button class='btn-d addonsBtn' data-toppname="forone" data-topclass="foroneclassfo" data-popup="addonsWrap789" ui-btn ui-shadow ui-corner-all><a data-rel="popup" data-position-to="window" aria-haspopup="true" aria-expanded="false" class="ui-link">Addons First Item</a></button> 

Answers 5

Here i'd suggest a simpler way of doing this. Lets say that you put the desire class name in a attribute of both of your div's.

div id="one" key="foroneclass" and div id="two" key="fortwolass" 

Now when user will click what you can do is pick the value of attribute key.
var current_clasname = $(this).attr("key");

and then place it it the class name of your popup.

$(".pop_up").removeAttr("class"); // To make sure that previous class is removed!! $(".pop_up").adddClass(current_clasname);

Answers 6

Here is link of my code you can go through it might be it can help you -

JSFiddle

Add these lines in your code

JAVASCRIPT Code  $('#addonsWrap789').addClass('foroneclass'); $('#addonsWrap790').addClass('fortwoclass'); 

Answers 7

Thanks for sharing. It's very useful.

Read More

Scikit-learn SVM digit recognition

Leave a Comment

I want to make a program to recognize the digit in an image. I follow the tutorial in scikit learn .

I can train and fit the svm classifier like the following.

First, I import the libraries and dataset

from sklearn import datasets, svm, metrics  digits = datasets.load_digits() n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1)) 

Second, I create the SVM model and train it with the dataset.

classifier = svm.SVC(gamma = 0.001) classifier.fit(data[:n_samples], digits.target[:n_samples]) 

And then, I try to read my own image and use the function predict() to recognize the digit.

Here is my image: enter image description here

I reshape the image into (8, 8) and then convert it to a 1D array.

img = misc.imread("w1.jpg") img = misc.imresize(img, (8, 8)) img = img[:, :, 0] 

Finally, when I print out the prediction, it returns [1]

predicted = classifier.predict(img.reshape((1,img.shape[0]*img.shape[1] ))) print predicted 

Whatever I user others images, it still returns [1]

enter image description here enter image description here

When I print out the "default" dataset of number "9", it looks like:enter image description here

My image number "9" :

enter image description here

You can see the non-zero number is quite large for my image.

I dont know why. I am looking for help to solve my problem. Thanks

6 Answers

Answers 1

My best bet would be that there is a problem with your data types and array shapes.

It looks like you are training on numpy arrays that are of the type np.float64 (or possibly np.float32 on 32 bit systems, I don't remember) and where each image has the shape (64,).

Meanwhile your input image for prediction, after the resizing operation in your code, is of type uint8 and shape (1, 64).

I would first try changing the shape of your input image since dtype conversions often just work as you would expect. So change this line:

predicted = classifier.predict(img.reshape((1,img.shape[0]*img.shape[1] )))

to this:

predicted = classifier.predict(img.reshape(img.shape[0]*img.shape[1]))

If that doesn't fix it, you can always try recasting the data type as well with

img = img.astype(digits.images.dtype).

I hope that helps. Debugging by proxy is a lot harder than actually sitting in front of your computer :)

Edit: According to the SciPy documentation, the training data contains integer values from 0 to 16. The values in your input image should be scaled to fit the same interval. (http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits)

Answers 2

1) You need to create your own training set - based on data similar to what you will be making predictions. The call to datasets.load_digits() in scikit-learn is loading a preprocessed version of the MNIST Digits dataset, which, for all we know, could have very different images to the ones that you are trying to recognise.

2) You need to set the parameters of your classifier properly. The call to svm.SVC(gamma = 0.001) is just choosing an arbitrary value of the gamma parameter in SVC, which may not be the best option. In addition, you are not configuring the C parameter - which is pretty important for SVMs. I'd bet that this is one of the reasons why your output is 'always 1'.

3) Whatever final settings you choose for your model, you'll need to use a cross-validation scheme to ensure that the algorithm is effectively learning

There's a lot of Machine Learning theory behind this, but, as a good start, I would really recommend to have a look at SVM - scikit-learn for a more in-depth description of how the SVC implementation in sickit-learn works, and GridSearchCV for a simple technique for parameter setting.

Answers 3

It's just a guess but... The Training set from Sk-Learn are black numbers on a white background. And you are trying to predict numbers which are white on a black background...

I think you should either train on your training set, or train on the negative version of your pictures.

I hope this help !

Answers 4

If you look at: http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits

you can see that each point in the matrix as a value between 0-16.

You can try to transform the values of the image to between 0-16. I did it and now the prediction works well for the digit 9 but not for 8 and 6. It doesn't give 1 any more.

from sklearn import datasets, svm, metrics import cv2 import numpy as np  # Load digit database digits = datasets.load_digits() n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1))  # Train SVM classifier classifier = svm.SVC(gamma = 0.001) classifier.fit(data[:n_samples], digits.target[:n_samples])  # Read image "9" img = cv2.imread("w1.jpg") img = img[:,:,0]; img = cv2.resize(img, (8, 8))  # Normalize the values in the image to 0-16 minValueInImage = np.min(img) maxValueInImage = np.max(img) normaliizeImg = np.floor(np.divide((img - minValueInImage).astype(np.float),(maxValueInImage-minValueInImage).astype(np.float))*16)  # Predict predicted = classifier.predict(normaliizeImg.reshape((1,normaliizeImg.shape[0]*normaliizeImg.shape[1] ))) print predicted 

Answers 5

Hi in addition to @carrdelling respond, i will add that you may use the same training set, if you normalize your images to have the same range of value. For example you could binaries your data ( 1 if > 0, 0 else ) or you could divide by the maximum intensity in your image to have an arbitrary interval [0;1].

Answers 6

You probably want to extract features relevant to to your data set from the images and train your model on them. One example I copied from here.

surf = cv2.SURF(400) kp, des = surf.detectAndCompute(img,None)

But the SURF features may not be the most useful or relevant to your dataset and training task. You should try others too like HOG or others.

Remember this more high level the features you extract the more general/error-tolerant your model will be to unseen images. However, you may be sacrificing accuracy in your known samples and test cases.

Read More

How to secure REST API for SPA and Mobile App using Cordova

Leave a Comment

I've done a lot of research on "best practices" surrounding this and have read blog post after blog post, SO question after SO question, and OWASP article after OWASP article. I've arrived at a few clear answers but some unknowns.

First, the "Do's":

  1. Use JWT for authorizing users on my REST API [1] [2]
  2. Store the JWT in a HTTPOnly/Secure cookie and build in CSRF protection. Do NOT store in HTML5 local storage [3] [4] [5] (Actually, this point is debatable, is it easier to protect against XSS or CSRF? [6])
  3. Verify the signing method of the JWT [7]

Now I started with the assumption that having a SPA (built with Angular) and using HTML5 sessionStorage would be secure enough for short-lived tokens, but there is a point to be made that XSS attacks can happen from a "bad actor" originating in the one of many libraries loaded in from a CDN.

For my specific use case, I do not plan on having long-lived tokens - expiration after 10 minutes of non-use but I'm still figuring out if I want to track expiration by session or use refresh tokens - StormPath recommends the former (no longer stateless?) but I believe big players using JWTs use refresh tokens (Google uses them but states you need to store them in secure, long-term storage which means HTML5 localStorage is again, out of the question).

I would like to make it so my users don't have to log back in if they refresh the page (hence the need to store the token on the client side). I would also like to use my SPA as a "mobile app" with the help of Cordova. The obvious pitfall here is that if I use cookies, there is no baked-in cookie support/storage with Cordova and I'm urged to switch to HTML5 local storage instead. Since on mobile I don't really need to worry about refreshing pages, I can just let my token live in memory and expire with the strategy I settle on.

If I take this approach, cookie-based JWT on Desktop, "Bearer" headers on mobile, I now need an authentication end-point that will give tokens two different ways, and when I authorize on the REST API side, I need to support both cookie-based JWTs (with CSRF) and header based JWT verification. This complication has me worried as I don't know if I can accurately foresee security implications here.

To summarize the barrage of thoughts above:

  • Create an authentication handler that would hand out tokens via HttpOnly/Secure cookies to desktop, and by payload for mobile.
  • On my REST API, support both methods of verification - header based and cookie-based - including CSRF protection for the cookie-based approach.

Is there any reason why I wouldn't want to take this approach? I assume if I take XSS on my SPA as a serious risk, then I need a classic login-page for authentication to set the proper cookies because if I do authentication via the SPA, then any XSS attack could potentially intercept that as well (both on mobile and Desktop)! However, on mobile, I'd need to inject the JWT into SPA, maybe through some custom DOM element (meta tag?), but at that point I can just let the SPA perform the login and not consider XSS a threat on mobile devices. Cordova packages all assets into the install package so that's somewhat better but then why not take the same approach on the Desktop version?

My application takes very little user input, it is primarily a dashboard/reporting tool. There will be a "message center" but it's content should always be user-created (by only that user) and sanitized. In my use-case then, would it be ok to deviate from "best practices" and rely on localStorage not counting XSS as a serious risk for my SPA? This would simplify this entire thing (use HTML5 sessionStorage as originally planned) and reduce complexity, which would reduce attack surface for potential security blunders. I just want to make sure I understand the risks before moving forward.

Is there no secure way to make this secure other than by building a native app for mobile and not using Cordova to convert my SPA to a mobile app? I'd hate for this to be the case, but it might very well be.

I'd appreciate all thoughts on the matter!

0 Answers

Read More

Stream audio from PC to smartphones?

Leave a Comment

For Christmas 2016, me and my dad want to do a Lightshow for our neighborhood with lights and music.

enter image description here We have the lights set up, but the music is a problem. We don't want to put huge speakers in our garden because that would be very annoying for our densely populated neighborhood.

So, we came up with this concept:

enter image description here

The computer (Windows 7) handles the lights with a sequencer from Light-o-rama.

Now my question is:
How can I stream audio from the PC to the smartphones?
I can figure out the smartphone end myself, but the streaming audio from PC is the thing here.

The solution can be anything! But I can't seem to figure it out! Relevant languages I can do are:

  1. C++
  2. C#
  3. Java
  4. NodeJS
  5. ASP.NET

But it can also be a program that already can do this!

EDIT:
THIS IS A MUST: Lights and music have to stay in sync! The lights dance to the music

Anything helps! Thx in advance!

5 Answers

Answers 1

If you can get everyone to download this app: SoundWire you can stream audio from Windows to any Android phone (assuming your friends are cool)

Check it out looks pretty cool, you can even stream a youtube video and get the audio synced up with any android smartphone

Answers 2

It seems that the dev has already been done, there is an app "Speakerfy" that looks promising. It is available on most of the mobile platforms and seems to do exactly what you need. There is an article on this app at the following link that should give even more info. http://techland.time.com/2013/04/01/speakerfy-a-free-app-for-whole-home-audio-or-silent-discos/ I hope this helps.

Answers 3

Your diagram suggests that each device would be on your local WiFi, which means the guests would need to join your network. That means they would need to know the SSID, there would be no need for a passphrase as you would need to publicly post the SSID and passphrase. Then, unless you have created some DMZ for this musical network, anyone would have access to your network.

But the bigger issue is the act of streaming itself as there is device buffering with such things. It would be near impossible to have the music sync'ed on the devices to any light display.

The best solution would be to broadcast over radio wave on an open channel. Here are some starting points for that: http://www.jpole-antenna.com/2013/10/11/broadcast-high-quality-music-for-your-holiday-lights-display/

https://sourcefmtransmitter.com/shop/category/christmas-lights-to-music/

  • Good Luck!

Answers 4

I have a complete solution stack for you:

  • You should use an OpenWRT router to build a captive portal (all http could be redirected to your url -> your audio streaming pc)
  • A VLC is able to stream your content as you want. If you want you could start the stream from command line.

In my experience this kind of VLC stream is the most effective one, it has almost 0 delay compared to other solutions (I tried gstreamer). If you really would like to stick with Java you are able to use VLCJ which is a nice solution too.

Extra: also with VLC you could set up a camera in front of your house to show that in your stream too!

Answers 5

thinking about any device , i wold try get a Raspberry Pi (U$35) , install a Apache and Tomcat , Create a Web Application to play your musics , get a nice and easy domain or get a free domain and that's it . You will not need any one use your wifi (unless you want). if you get Hacked its just a U$35 Raspberry Pi , make sure to have a backup of you stuffs . Any device with web browser will do it .

Read More

Lifecycle events on ReactCSSTransitionGroup's component?

Leave a Comment

Is there a way to get notified of transition lifecycle events on a ReactCSSTransitionGroup's parent component? For example, if I have the following:

<ReactCSSTransitionGroup     transitionName={transitionNames}     transitionEnterTimeout={250}     transitionLeaveTimeout={250}     component={MyParent}>       ... </ReactCSSTransitionGroup> 

I'd like MyParent to accept either lifecycle events, or an isTransitioning-like prop, so that I can (for example) render a different className based on whether a transition is happening or not.. something along the lines of

const MyParent = (props) => {     if (props.isTransitioning) { // or something         return <div className="animating" { ... props } />     } else {         return <div { ... props } />     } } 

Is there a way to make this work? Can I know if a ReactCSSTransitionGroup is currently transitioning? All I can see is that the lifecycle events are fired on the child components entering or leaving the group, and not on the container component itself.

1 Answers

Answers 1

I'm not sure about passing Parent component to the ReactCSSTransitionGroup. I would recommend another approach: simply wrap <MyComponent /> with <ParentComponent /> and setup callback props in <MyComponent /> like so:

Link to the plunkr example -> https://plnkr.co/edit/hSRpiVIVQkZlYjyh2SuD?p=preview

Short explanation: Each item in the list has CSS-class .item

.item {   transition: opacity 250ms ease-in; } 

Once animation for the .item completed React (starting from v15) will fire the onTransitionEnd callback and will pass this information to the parent component.

And I've added callback onBeforeItemTransition to tell the <Parent /> component, that something gonna happen soon, the transition should start.

var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;    var ParentComponent = React.createClass({      render() {        return <MyComponent        onItemTransitionEnd={(item) => {          console.log('Transition end for item', item);        }} />      }  });    var MyComponent = React.createClass({        getInitialState() {      return {        items: ['Item #0']      }    },        getDefaultProps() {      return {        // We need to call this before we are starting animate items        onBeforeItemTransition: function() {          console.log('Transition started!');        },        // This should be called after ctra        onItemTransitionEnd: function() {        }      }    },        addItem() {      var newItems =        this.state.items.concat(['Item #' + (this.state.items.length)]);      this.setState({items: newItems});      this.props.onBeforeItemTransition();    },        render() {            var items = this.state.items.map((item, index) => {        return <div className="item" key={item} onTransitionEnd={this.props.onItemTransitionEnd.bind(this, item)}>          {item}        </div>      });            return <div>      <button onClick={this.addItem}>Add item</button>      <ReactCSSTransitionGroup       transitionName="example"        transitionEnterTimeout={250}        transitionLeaveTimeout={250}>        {items}      </ReactCSSTransitionGroup>        </div>    }      });      ReactDOM.render(    <div>      <h1>Rendered from script.jsx!</h1>      <ParentComponent />    </div>,    document.getElementById('example')  );

Read More

Saturday, July 30, 2016

Angular2 - Fire event on Leaflet-Event

Leave a Comment

I am trying to impement Leaflet with Angular 2 TS for my Ionic 2 app. I want to emit my pinClicked-event when a Leaflet-pin was clicked. How to do this? In Angular1 $scope.$apply was the solution...

private refreshMarkers() {     L.marker([40.731253, -73.996139])       .addTo(this.map)       .on('click', function() { alert('JA'); } );   }    private pinWasClicked() {     this.pinClicked.emit('');   } 

0 Answers

Read More

Android Expandable RecyclerView different Card height

Leave a Comment

I have a RecyclerView that contains a list of cards, each of which expand into child cards.
Each card has different text. I want that when the user clicks on a child card, it will expand to show the text inside. The expansion height is based on how much text the card contains.

I tried to measure the target height by using:

view.Measure(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); 

And then expanding the card to the Measured Height (see here). However, it gives the same Measured Height to all of the cards.

Here is my code, which is based on this (more specifically the Xamarin version):

This is the main Adapter, which creates and binds the parent and the child cards:

public class HalachaExpandableAdapter : ExpandableRecyclerAdapter<HalachaParentViewHolder, HalachaChildViewHolder>, View.IOnClickListener {     LayoutInflater _inflater;     bool expand;     int targetHeight;     bool wave = false;      public HalachaExpandableAdapter(Context context, List<IParentObject> itemList) : base(context, itemList)     {         _inflater = LayoutInflater.From(context);     }      public override void OnBindChildViewHolder(HalachaChildViewHolder childViewHolder, int position, object childObject)     {         var halachaChild = (HalachaChild)childObject;         childViewHolder.halachaChildTitle.Text = halachaChild.Title.ToString();          targetHeight = childViewHolder.halachaChildCard.Height;         childViewHolder.halachaChildCard.LayoutParameters.Height = 100;         childViewHolder.halachaChildCard.SetOnClickListener(this);         expand = childViewHolder.expand;      }      public override void OnBindParentViewHolder(HalachaParentViewHolder parentViewHolder, int position, object parentObject)     {         var halacha = (HalachaItem)parentObject;         parentViewHolder._halachaTitleTextView.Text = halacha.Title();         parentViewHolder._halachaContentTextView.Text = halacha.Content;         if (halacha.ChildObjectList.Count == 1)             wave = true;     }      public void OnClick(View v)     {         if (v.Height == 100)         {             AnimationCollapse anim = new AnimationCollapse(v, targetHeight, 100);             anim.Duration = 300;                             v.StartAnimation(anim);              expand = false;         }         else         {             AnimationCollapse anim = new AnimationCollapse(v, 100, v.Height);             anim.Duration = 300;                             v.StartAnimation(anim);              expand = true;         }     }      public override HalachaChildViewHolder OnCreateChildViewHolder(ViewGroup childViewGroup)     {         var view = _inflater.Inflate(Resource.Layout.halachotListItem, childViewGroup, false);         return new HalachaChildViewHolder(view);     }      public override HalachaParentViewHolder OnCreateParentViewHolder(ViewGroup parentViewGroup)     {         var view = _inflater.Inflate(Resource.Layout.halachotListHeader, parentViewGroup, false);         wave = false;         return new HalachaParentViewHolder(view);     } } 

I think this is where the code is needed to be done, but if you need some of the other code of the other classes, I will gladly post them. You can also look at the links above for reference to how this works.

Hope someone can help me.
Thanks!

2 Answers

Answers 1

I finally managed to solve the problem.
I needed to change the way I measured the view's wrap_content height to this:

v.Measure(MeasureSpec.MakeMeasureSpec(v.Width, MeasureSpecMode.Exactly), MeasureSpec.MakeMeasureSpec(ViewGroup.LayoutParams.WrapContent, MeasureSpecMode.AtMost)); 

The rest is the same.
Thanks to this post.

Answers 2

I dont know why do you want to find the height of the card , instead you can just wrap the child cards height to that of text and make child card invisible , as soon as user click a card , child card s visiblity will be turned to visible and card wih its text with the same height will appear !

Read More

Link to street view URL using address?

Leave a Comment

Is it possible to link directly to street view from an URL using only the address (and not lat/lng)?

For example, is there a way to do something like

http://maps.google.com/maps?q=&layer=c&address=Street,number,state&cbp=11,0,0,0,0 

Instead of

http://maps.google.com/maps?q=&layer=c&cbll=31.335198,-89.287204&cbp=11,0,0,0,0 

?

Lat/lng from geocoding tends to not be recognized by street view as being too far from a street, sometimes getting the wrong street altogether.

I have looked everywhere and even tried playing with google's URLs on my own, but I can't find anything on it. Most sources won't even mention address. I'm currently using the url sample from this question, but it still isn't really what I'm looking for.

If this is really not possible, could someone link to a source/documentation where it says so?

2 Answers

Answers 1

First reverse geocode to find the lat lng using another Google Service API.

Then feed the resulting lat lng into the streetview endpoint parameter.

Answers 2

Let's enhance your code, if you paste the code in browser then you will be redirect to google maps and will show result what you requested.

http://maps.google.com/maps?&q=Space+Needle,Seattle+WA

If you would like to pass the value (address) via php or any other code type then simply it will not work, you cannot use google maps without API to enhance your requirement. Lat & Lng is basic practice to show map and not require any api, but if you would like to pass additional properties then you will have to use google maps api to do so. Detailed documentation can be found here

https://developers.google.com/maps/documentation/embed/guide

but let's try an example try this code in browser

https://www.google.com/maps/embed/v1/place?q=Mumbai,+Maharashtra,+India

You will get an error that api key not found but if you try this one

https://www.google.com/maps/embed/v1/place?key=AIzaSyD4iE2xVSpkLLOXoyqT-RuPwURN3ddScAI&q=Space+Needle,Seattle+WA

Then you will get output. Hope it helps!

Read More

Friday, July 29, 2016

Path in PartialView method ( to share them between applications)

Leave a Comment

I want to share some Partial View between some applications. I tried different solutions which are suggested in internet, but none of them not work! But I hope by using absolute or relation path in PartialView method it works but I don't know is it possible or no.

So there are 2 questions here:

  1. If I create a common project in my solution as a sub domain, can I use a URL of it in other project's PartialView method?
  2. If I create common folder in my solution, I use a path something like "~/../Common/myView.cshtml". In this case Visual Studio not take error to me on editor by on runtime I got an error ("Cannot use a leading .. to exit above the top directory"). So is any solution to use a path of a common folder outside the root?

I know that it'was better that I separate these question into 2 ones, but as there was no solution to share partial views I gather them here.

As you can see there is a Common folder in my solution which contains _MainMenu.cshtml and also I have this file in Shared Folder in Website project too.

How should I write PartialView in Admin controller to path to each of them?

I want some code like these:

For Common folder:

return PartialView("~/../Common/_MainMenu.cshtml");

For shared folder:

return PartialView("http://localhost:16287/Module/Menu/_MainMenu");

enter image description here

2 Answers

Answers 1

You can try to read view from dll by using VirtualPathProvider.

1) You must register your VirtualPathProvider within the Global.asax Application_Start handler.

2) You must call the view in your DLL using the special path like so:

return View("~/Plugin/YOURDLL.dll/FULLNAME_YOUR_VIEW.aspx"); 

3) OR

I would suggest avoiding cshtml files and generating HTML manually in your HTML helpers. TagBuilder class does a great deal of help here.

Answers 2

  1. Can't be.
  2. Not a good idea.

Because that's not code which can be compiled to DLL and can be used by simply referencing it, it will be better you create Areas in you are application or replicate your views.

Edit : Razor Views CAN be compiled. But that doesn't change the fact that no View can be referenced by the Razor View Path resolver if it's located outside the Web Project. Virtual Paths could work. Thanks to @DaveAlperovich

Read More

Error messages when trying to use the Facebook API

Leave a Comment

I am getting an error message when attempting to use the Facebook API.

When I have Client OAuth Login enabled, Web OAuth Login enabled and a valid Oauth redirect URI set to http://localhost:8000/ the error I get is this when trying to log into Facebook with the correct App ID:

URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.

Is there a particular setting or thing I have to put in code to get this to work correctly?

This is the code I've got:

    $(window).load(function() {         if (window.cordova.platformId == "browser") {             facebookConnectPlugin.browserInit(MYAPPIDHERE);         }     }); 

And this:

            facebookConnectPlugin.login(["user_likes"],                     function(response) {                         likes();                     },                     function(response) {                         likes();                     });         } 

EDIT:

Added pictures of what is in the Facebook App, as well as the URL I am navigating from.

enter image description here

enter image description here

2 Answers

Answers 1

The Javascript API wont work on PhoneGap for the login. Use this cordova plugin instead.

https://github.com/Wizcorp/phonegap-facebook-plugin

Answers 2

It is impossible for Facebook to redirect to a local URL. What will happen is that you redirect a user to Facebook, they login, Facebook validates this and sends them back to you. Facebook sends them to the URL you provide. The URL http://localhost:8000 is a shorthand for: connect to port 8000 on your own machine. At the point where Facebook does the redirect, localhost refers back to Facebook, not you anymore. Apparently, Facebook has blacklisted that stuff - probably for security reasons.

What you need is a public URL that Facebook can redirect to. Maybe this helps?

Read More

How to fade in an image that gets set dynamically with Angular?

Leave a Comment

I am using Anuglar to set an image that will be used as a background image for my page. Currently, the image loads from top to bottom and it doesn't look great. I'd like to fade in the image (or even load the image from a blurry view to the actual image). Anything other than loading from top to bottom. Any advice on how to do this? I see other posts that show to use javascript/jquery, but I'm not sure how to integrate it into my Angular code.

Template

<body ng-controller="MainCtrl" ng-style="heroImage">      //rest of the html  </body> 

Javascript

$scope.heroImage = {     'background':  'linear-gradient( rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.5) ), url('+ $scope.place["imageLink"] +')',     'background-size': 'cover',   'height': '100vh',   'background-repeat': 'no-repeat' }; 

8 Answers

Answers 1

Did you try progressive jpeg ? It could be the simplest sollution.

Answers 2

If I understand correctly, what you're asking has been previously answer. Take a look at this: How can I use ng-animate with ui-view rather than ng-view?

Using the [ui-view].ng-enter & [ui-view].ng-leave, this will create a fade in animation once you enter and leave the page which works very well for every page in your web app

Answers 3

You can use another div element or just img itself wrapped by body and animate the opacity whenever you want

HTML

<body>     <div id='background'>         <img ng-src='yourimage' ng-class="{visible:imageVisible}"/>     </div> </body> 

CSS

body {    background: transparent; } #background > img {    opacity: 0;    display: fixed; //or absolute    left: 0;    top: 0;    right: 0;    bottom: 0;    height: 100%;    width: 100%;    z-index: -1;    transition: all 1s; } #backcgound > img.visible {   opacity: 1; } 

JS

$scope.imageVisible = true; 

this is good approach only for one image to show on page load but if You want multiple images to fadein then better approach will be canvas or multiple images

<body>     <div id="background">         <img ng-reapeat="image in images track by $index" ng-src="image.src" ng-class="{visible:image.visible}"/>     </div> </body> 

and then you can use $interval to change visible image by changing opacity JS

images=[{    src:'yoursrc',visible:false }, {    src:'yoursrc',visible:false }, {    src:'yoursrc',visible:false }, ... ] 

Answers 4

Provided that you are either hosting the image or that there are no CORS issues, you can wait until the image is loaded like this with Angular:

angular.module('app',[]) .controller('ctrl',function($scope){     $scope.style = {         background: 'red'     };     $scope.link = 'https://upload.wikimedia.org/wikipedia/en/f/f6/Not_A_Hero_Logo.png';     var image = new Image();     image.onload = function(){         $scope.$apply(function(){             $scope.style.background = 'url(' + $scope.link + ') center / contain no-repeat';         });     };     image.src = $scope.link; }) 

And in your HTML you would have:<div ng-style="style"></div>

Plunker: https://plnkr.co/edit/rC2IeU8bulOXB6HWlEK9?p=preview

EDIT: Directive-based approach Plunker: https://plnkr.co/edit/FRJla7MRu2JIaSYx7lTb?p=preview

Answers 5

I would highly recommend Animate.css which offers a wide variety of animations via @keyframes.

You can write super clean code and just add animation attributes inside your ng-style. Just choose the animation you like, and set the duration, and voila, you are good to go:

  $scope.heroImage = {     'background': 'linear-gradient( rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.5) ), url("https://hd.unsplash.com/photo-1452711932549-e7ea7f129399") center',     'background-size': 'cover',     'height': '100vh',     'background-repeat': 'no-repeat',      //set fadeIn as the animation, animate over duration of 1second.     'animation':'fadeIn 1s',   }; 

Here is the working plnkr

P.s. Of course, remember to include animate.css as your stylesheets. and it will have to load before your own stylesheets.

<!--load animate.css first--> <link rel="stylesheet" href="animate.css" /> <!--Your own stylesheet--> <link rel="stylesheet" href="Site.css" /> 

Answers 6

You can do this with an angular directive like so:

angular.module('app', [])   .directive('backgroundimg', function() {     return {       link: function(scope, element, attribs) {         let img = new Image(),           s = element[0].style;         s.transition = 'background-image 1s ease-in-out';         s.backgroundSize = attribs.backgroundsize || '800px 600px';         s.backgroundImage = 'url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)'; //1x1px transparent gif          img.onload = function() {           s.backgroundImage = 'url(' + attribs.backgroundimg + ')';         };         img.src = attribs.backgroundimg;       }     };   }); 

This lets you declare your background image, which then will fade in once loaded. To fade in properly, we need to have an image to fade from. You can set your own in the element style property, or else it will default to a 1px white image.

Example HTML:

<body ng-app="app" backgroundimg="mybackground.jpg" backgroundsize="600px 400px"> 

If you want to fade in from a blurry picture, just add it to the style:

<body ng-app="app" backgroundimg="mybackground.jpg" backgroundsize="600px 400px" style="background-image:url(mythumbnail.gif)" /> 

Or even better, encode it inline first with a tool like this. (Remember to resize it first)

Other styling you can do with CSS.

Full Plnkr Example

Answers 7

I had similar task some time ago and resolved it with compressing jpeg images or thing called progressive jpeg

read on wikipedia about compression of JPEG

NOTE

JPEG format is best for web.

SOLUTION WORKED FOR ME

I used this service for compressing my jpeg files

Now my site works really good

Answers 8

you can use jquery loading jquery before angular and then you can use it in your controller like this

angular.module('App', []).controller('MainCtrl', function ($scope) {  $(function () {        // wait till load event fires so all resources are available        //here you can use jquery fadeIn()    }); }) 

for watch that jquery is loading in you browser you can open console and write $ sing and you can see if jquery is loading or it's undefined

As mentioned in comment it's not a good practice to use Jquery with angular.

Read More

Thursday, July 28, 2016

Can I check devices location is open or close on React Native

Leave a Comment

Can I check devices location is open or close before using geolocation? I want to show alert message like App need to run your location, please open your devices location, when devices location is close.

Can I navigate to go native location setting both IOS and Android?

Like example -

componentDidMount() {   // Check condition device location is open or close.   if( DevicesLocation === 'close' ) {      alert('App need to run your location, please open your devices location');      // other process    } else {      navigator.geolocation.getCurrentPosition(         (position) => {            var initialPosition = JSON.stringify(position);            this.setState({ initialPosition});         },         (error) => console.log(error.message)      );   } } 

1 Answers

Answers 1

I think you can use

navigator.geolocation.getCurrentPosition(    (position) => {     //do stuff with location    },    (error) => {      this.setState({locationEnabled: false}),    },    {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}  );

For opening settings from your app, I think you will have to get your hands dirty with native code :D

Read More

Memory usage in LibGdx

Leave a Comment

I am in the middle of a huge application in a team of developers and the memory is something to consider early on. When I run the program as it is, it takes about 44 MB of memory (Found from the Task manager). I then create 10,000 bodies. The memory usage is now about 83 MB. I have a method to destroy the bodies when I click space, this is how it looks.

public static void disposeAllBodies(){     Array<Body> bodies = new Array<Body>();     world.getBodies(bodies);     int destroyCount = 0;     System.out.println("Attempting to destroy " + world.getBodyCount()+ " bodies");     for(Body b : bodies){         world.destroyBody(b);         destroyCount++;     }      System.out.println("Successfully destroyed " + destroyCount + " body(s), " + world.getBodyCount() + " remain");   } 

It disposes all the bodies with no problem, and these were the only things in the application. After they are disposed, the memory goes down to about 66MB for a few seconds then jumps up to 78 MB and stays there.

So I am wondering is there a better way to dispose these bodies? This application will be creating millions of bodies but most will be destroyed, however if the memory just keeps going up, it won't be able to handle this much disposing since the memory stays pretty much static.

Also, the CPU goes from 0.2% (before any bodies) to 23% (when 10,000 bodies present) then dwon to 2.3% (when disposed bodies). So even the CPU is doing more work after the disposing of bodies.

Thanks for any help!

Update: The code for creating the bodies is as follows:

BodyDef bodyDef = new BodyDef();     bodyDef.type = type;     bodyDef.position.set(new Vector2(position.x, position.y));      Body body = world.createBody(bodyDef);      FixtureDef fixtureDef = new FixtureDef();     Fixture fixture;     if(isCircle){         CircleShape circle = new CircleShape();         circle.setRadius(dimensions.x);         fixtureDef.shape = circle;         fixture = body.createFixture(fixtureDef);         circle.dispose();     }else{         PolygonShape rectangle = new PolygonShape();         rectangle.setAsBox(dimensions.x, dimensions.y);         fixtureDef.shape = rectangle;         fixture = body.createFixture(fixtureDef);         rectangle.dispose();     } 

These are all just Box2D bodies, no sprites attached or anything. Thanks!

1 Answers

Answers 1

Did you try a stripped down version of the "box2d only" code you posted to see if it still has the same problem? The reason I ask is that you also posted another question on "changing FixtureDef properties" at Changing FixtureDef properties Java Libgdx and you've given a lot more of your overall code. (The code from this question is a subset of the code from the other question). Looking at that code, there could be some issues.

In the other question you put bodies, bodyDefs, fixtures and fixtureDefs into a HashMap, you don't show how you retrieve/clear the map. That might/might not cause memory leaks. I'd say likely not, but you never know.

But I did see this bit, which I'm pretty sure will cause issues:

public void attachNewSprite(String internalPath){     entitySprite = new Sprite(new Texture(Gdx.files.internal(internalPath)));     ((Body)bodyObjects.get(BodyReferences.BODY)).setUserData(entitySprite); } 

In this question you said you used no sprites, but if you do the above somewhere in your code, each new Texture() will take up memory. You have to explicitly dispose each texture you create. You shouldn't really be creating a new Texture each time you create a new Sprite. Ideally, you create the texture once, then use the Sprite, which is a TextureRegion, to map to the texture. Then dispose the texture when you're all done (at the end of the level/game/etc). In order to dispose the texture, you'll have to keep a reference to it.

Edit/Update:

I had some time this morning so I took your posted code and added a bit to create a barebones simple app with your body creation and body deletion code. I setup a Timer to fire every X seconds just to see what happens when you create/destroy 10k bodies and the code you posted seemed fine. So I think your issue may be elsewhere with code you haven't posted. The memory on my machine would fluctuate a bit (you never really know when the GC will kick in, but it never really topped above 45 MB).

Unless you see something different below than what you're doing (or if you have more code to post, etc), I don't see an issue with what you've shared so far.

import java.util.concurrent.ThreadLocalRandom;  import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Timer; import com.badlogic.gdx.utils.Timer.Task;  public class Memory implements ApplicationListener {      private static World world;         private static void createNewBodies(boolean isCircle, Vector2 position, Vector2 dimensions) {             BodyDef bodyDef = new BodyDef();             //bodyDef.type = type; //all bodies here are dynamic             bodyDef.type =  BodyType.DynamicBody;             bodyDef.position.set(position);              Body body = world.createBody(bodyDef);              FixtureDef fixtureDef = new FixtureDef();             Fixture fixture;             if(isCircle){                 CircleShape circle = new CircleShape();                 circle.setRadius(dimensions.x);                 fixtureDef.shape = circle;                 fixture = body.createFixture(fixtureDef);                 circle.dispose();             }else{                 PolygonShape rectangle = new PolygonShape();                 rectangle.setAsBox(dimensions.x, dimensions.y);                 fixtureDef.shape = rectangle;                 fixture = body.createFixture(fixtureDef);                 rectangle.dispose();             }        }         public static void disposeAllBodies(){             Array<Body> bodies = new Array<Body>();             world.getBodies(bodies);             int destroyCount = 0;             System.out.println("Attempting to destroy " + world.getBodyCount()+ " bodies");             for(Body b : bodies){                 world.destroyBody(b);                 destroyCount++;             }              System.out.println("Successfully destroyed " + destroyCount + " body(s), " + world.getBodyCount() + " remain");          }         private static void buildAllBodies() {            int minPos = 10;            int maxPos = 400;            int minWidthHeight = 50;             Vector2 position = new Vector2();            Vector2 dimensions = new Vector2();             for (int i=0; i<10000; i=i+2) {                position.x = ThreadLocalRandom.current().nextInt(minPos, maxPos+1);                position.y = ThreadLocalRandom.current().nextInt(minPos*2, maxPos*2+1);                dimensions.x = ThreadLocalRandom.current().nextInt(minWidthHeight, minWidthHeight+1);                dimensions.y = dimensions.x;                createNewBodies(true, position, dimensions);                createNewBodies(false, position, dimensions);            }        }         @Override        public void create() {             world = new World ( new Vector2(0.0f, -9.8f), true);             Timer.schedule(new Task() {                    @Override                    public void run() {                        buildAllBodies();                        disposeAllBodies();                    }               }                , 1.0f                , 10.0f //how often to do the cycle (in seconds)               );        }         @Override        public void render() { }         @Override        public void dispose() {            world.dispose();        }         @Override        public void resize(int width, int height) { }         @Override        public void pause() { }         @Override        public void resume() { } } 
Read More

Intellij Scala class definition formatting

Leave a Comment

How can I get Intellij format my Scala class definition like this:

sealed class Traffic(     private[this] val javaTraffic: Traffic.JavaTraffic,     private[this] val sanitizer: Sanitizer)   extends Serializable with Logger { 

Basically 4 indents for member declaration on each line, and 2 indents for class inheritance.

0 Answers

Read More

Update Xcode build progress bar when using run script

Leave a Comment

In Xcode you can specify custom scripts to build your applications. I have a project which makes extensive use of these. For instance, one target builds the simulator versions (both 32bit and 64bit) and the ARM version as well as documentation and then bundles up the generated static library into a framework along with some other files

Running the above code can take a couple of minutes. Normally when you build, Xcode has a progress bar at the top of the screen. When you use these scripts it fills in a tiny amount and then stops there until your script completes.

It would be nice if there was a way to tell Xcode to update this progress bar? It doesn't have to be perfect, just a way of giving some feedback that something is happening and that the build process hasn't stalled.

Thanks!

1 Answers

Answers 1

It looks like you can use Bash in your custom build script. So why not do something like in the example linked, wherein for each build target you do

echo "building target name blare" 

In fact, if you really want a progress bar, why not just use Bash to make one? See an example here.

enter image description here

Read More

Wednesday, July 27, 2016

viewcontroller using a NULL baseURL argument with the loadHTMLString baseURL method : data theorem

Leave a Comment

I am facing the problem "MyViewcontroller using a NULL baseURL argument with the loadHTMLString baseURL method : data theorem"- i have successfully completed my task and all are working fine.

The Issue was in the OSWAP security scan for vulnerability it shows the above error.

My code snippet:-

  NSString *aHtmlString = kEmptyString;      // Getting the bool from configuration plist     NSString *thePlistPath = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"];     NSDictionary *theURLdata = [[NSDictionary alloc] initWithContentsOfFile:thePlistPath];     is  ServerFAQAvailable = [[theURLdata valueForKey:kIsServerFAQAvailableKey] boolValue];  if (one || two || three) {    aHtmlString = [self loadFAQFor]; } else {   aHtmlString = [self loadFAQForwithout]; } NSURL *baseURL = [NSURL fileURLWithPath:thePlistPath];  [self.faqWebView loadHTMLString:aHtmlString baseURL:baseURL];  

Update:

if (one || two || three) {        aHtmlString = [self loadFAQFor];     } else {       aHtmlString = [self loadFAQForwithout];     }     NSURL *baseURL = [NSURL fileURLWithPath:@"about:blank"];      [self.faqWebView loadHTMLString:aHtmlString baseURL:baseURL]; 

Still shows me scan issue

2 Answers

Answers 1

The issue is the baseURL: parameter. BaseURL isn't needed for an html string, it is usually used for relative links. If all you're trying to do is show some html, are you sure you need it?

The security issue flagged makes sense (my understanding, roughly): If a webview's baseURL is set to the local file system, then a page loaded (eventually) through that webview could access local resources.

Try passing nil for baseURL: should silence this warning.

Answers 2

baseURL should be [[NSBunld mainBunld] bunldPath], you can try like this..

NSString *path = [[NSBundle mainBundle]bundlePath]; NSString *htmlPath = [[NSBundle mainBundle] pathForResource:self.htmlName ofType:@"html"]; NSString *htmlContent = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil]; [self.webView loadHTMLString:htmlContent baseURL:[NSURL fileURLWithPath:path]]; 
Read More

How to use “Term of Use” in Popup

Leave a Comment

I want to customize the term of use in popup, when a user login for first time that page should appear in popup.

2 Answers

Answers 1

To set the terms of use you will need to do 2 things.

First you'll need to create a Web Content Article.

  1. Go to the Control Panel.
  2. Select "Web Content".
  3. Then Add > "Basic Content".
  4. Enter in your desired Terms of Use language.
  5. Write down the ID and the Group ID you've created the content.

Note: The ID is available when you're viewing the content's page but the group ID is less obvious. To find the group ID, look at the URL, and find the parameter doAsGroupId. Its value is the group ID you've created the article for.

Secondly, you'll need to configure your portal to load this Web Content article.

  1. From the file system, navigate to your Liferay Portal installation.
  2. From there find the portal.properties file. If you're using Tomcat, it will be located in webapps\ROOT\WEB-INF\classes.
  3. Here add a file named portlet-ext.properties, if it does not already exist.
  4. Add the following keys with the values you previously wrote down.

    terms.of.use.journal.article.group.id= terms.of.use.journal.article.id= 

Restart your server and the portal should now display the Terms of Use form the Web Content article.

Answers 2

You can make use of modal dialog in bootstrap through which u can achieve what you want.

$(window).load(function() { $('#newModal').modal('show'); }); 

Don't forget to add this style sheets import in your html file.

<link rel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">    </script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> 

Your html file should have the following code

<div class="container"> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog">    <!-- Modal content-->  <div class="modal-content">     <div class="modal-header">       <!Your Heading-->     </div>   <div class="modal-body">       <p>Your text in the modal.</p>   </div>   <div class="modal-footer">       <button type="button" class="btn btn-default" data-dismiss="modal">I Agree</button>    </div> 
Read More

Tuesday, July 26, 2016

Amazon and multi customer support in shared multi-tenant model

Leave a Comment

Are there any ready services (by amazon or partners) that help you manage multi-customer aspects of a "pool" [1][2] type service - where all the multi-tenancy is handled by internal context switching, databases are shared, etc.

AWS tools (marketplace, billing manager) seems to be geared toward "provision new service / host by customer" while what I'm looking for is the customer and license management, user association, authentication (including federated authentication integration with multiple customer portals) and perhaps even listing and catalog services - but when a new customer purchase (or change) a license / user / configuration - I expect to get an API call to my already existing solution - in which I'll decide what to do.

Seems like there should be many services like that - but either they are proprietary, or I'm using the wrong keywords to find the information.

[1] http://www.slideshare.net/AmazonWebServices/arc340-multitenant-application-deployment-models/9

[2] https://www.youtube.com/watch?v=DMP0leGZpo4

1 Answers

Answers 1

What you're asking is basically "what tools can I use to build a multi-tenant application".

And the answer will be "it depends". You don't have enough requirements to determine what would be useful or helpful.

However, AWS does have some technologies that may help. Start by looking at AWS Cognito. It can do authentication and data access, and use federated authentication providers. It also handles storing data for multiple users in DynamoDB.

If you're looking for anything more than that, however, you need to provide more information.

Can you shard MySQL across multiple RDS instances, and have one schema per client? Sure, but that's probably not going to work well if you have a million clients - there are limits on the number of schemas per instance.

Same thing with S3 - you can have a bucket per client, or a subdirectory under a shared bucket per client, but I can't tell you which approach is going to work best for your application.

AWS has enough tools to automate the creation of a complete stack per customer - between the API/CLI, CloudFormation, etc - but unless you're dealing with a very high-value product, that's probably not going to be cost effective.

Read More

OpenCV Matching Exposure across images

Leave a Comment

I was wondering if its possible to match the exposure across a set of images.

For example, lets say you have 5 images that were taken at different angles. Images 1-3,5 are taken with the same exposure whilst the 4th image have a slightly darker exposure. When I then try to combine these into a cylindrical panorama using (seamFinder with: gc_color, surf detection, MULTI_BAND blending,Wave correction, etc.) the result turns out with a big shadow in the middle due to the darkness from image 4.

I've also tried using exposureCompensator without luck.

Since I'm taking the pictures in iOS, I maybe could increase exposure manually when needed? But this doesn't seem optimal..

Have anyone else dealt with this problem?

2 Answers

Answers 1

This method is probably overkill (and not just a little) but the current state-of-the-art method for ensuring color consistency between different images is presented in this article from HaCohen et al.

Their algorithm can correct a wide range of errors in image sets. I have implemented and tested it on datasets with large errors and it performs very well.

But, once again, I suppose this is way overkill for panorama stitching.

Answers 2

Sunreef has provided a very good paper, but it does seem overkill because of the complexity of a possible implementation.

What you want to do is to equalize the exposure not on the entire images, but on the overlapping zones. If the histograms of the overlapped zones match, it is a good indicator that the images have similar brightness and exposure conditions. Since you are doing more than 1 stitch, you may require a global equalization in order to make all the images look similar, and then only equalize them using either a weighted equalization on the overlapped region or a quadratic optimiser (which is again overkill if you are not a professional photographer). OpenCV has a simple implmentation of a simple equalization compensation algorithm.

The detail::ExposureCompensator class of OpenCV (sample implementation of such a stitiching is here) would be ideal for you to use.

  1. Just create a compensator (try the 2 different types of compensation: GAIN and GAIN_BLOCKS)
  2. Feed the images into the compensator, based on where their top-left cornes lie (in the stitched image) along with a mask (which can be either completely white or white only in the overlapped region).
  3. Apply compensation on each individual image and iteratively check the results.

I don't know any way to do this in iOS, just OpenCV.

Read More

Monday, July 25, 2016

Async callback is called but not executed sometimes

Leave a Comment

Silverlight project.

In my View code behind, I call a method in the View Model to get value.

 public MyViewModel ViewModel     {         get         {             if (this.viewModel == null)                 this.viewModel = new MyViewModel();             return this.viewModel;         }         set         {             if (this.viewModel != value)             {                 this.viewModel = value;             }         }     } 

However the async callback is not called. Sometimes it is called by delay. Thus I get the value as 1900-01-01 00:00:00.000 instead of the correct date time.

DateTime value; public void GetDateTime()     {         var proxy = new WcfClient();         proxy.GetCurrentDateTimeCompleted -= ProxyGetCurrentDateTimeCompleted;         proxy.GetCurrentDateTimeCompleted += ProxyGetCurrentDateTimeCompleted;         proxy.GetCurrentDateTimeAsync();     }      private void ProxyGetCurrentDateTimeCompleted(object sender, GetCurrentDateTimeCompletedEventArgs args)     {         try         {             value = args.Result; 

To call it in code behind.

this.viewModel.GetDateTime(); 

Update 1

Upon the comment, I added some explanation. The View has a checkbox. If I click it or unclick it, a message box with Yes/No button will pop up. Whatever you select Yes or No, I will record the date and time in the MessageBoxYesNoSelection_Closed event. The event method is still in the code behind.

The checkbox part code is:

if (clickedCheckBox != null) {     var msgBoxControl = new MessageBoxControl();     msgBoxControl.Closed -= MessageBoxYesNoSelection_Closed;     msgBoxControl.Closed += MessageBoxYesNoSelection_Closed;      if (clickedCheckBox.IsChecked == true)     {         var curDateTime = this.ViewModel.value;// 1900-01-01 00:00:00.000 

Inside MessageBoxYesNoSelection_Closed, we get the value.

this.ViewModel.GetDateTime();// WCF async call this.ViewModel.UpdateValue(value); // another WCF async call, need value from GetDateTime() method's return result. this.ViewModel.UpdateAnotherValue(value, user); // third WCF async call 

What I found is sometimes the async callbacks are not executed although they are called.

1 Answers

Answers 1

I guess that you are experiencing a race condition, as you are not awaiting the this.ViewModel.GetDateTime() call and therefore in most cases the callback that sets the value (ProxyGetCurrentDateTimeCompleted) has not been called before you are using the value in the next statement (this.ViewModel.UpdateValue(value)).

The easiest solution would be to use async & await as described here and here.

If you can't do that another solution would be to move the code that depends on the value into the callback method.

Update 1

There is a possibility to use async & await with Silverlight 4 and .NET Framework 4.0. See Microsoft.Bcl.Async for more information. However, this method requires at least Visual Studio 2012, so in case you can't switch to a newer Visual Studio version this won't work for you.

In that case the idea would be to move the code dependent on the value into the callback method. So at first you would only call GetDateTime():

this.ViewModel.GetDateTime(); // WCF async call 

Then you'll call the other methods in the callback method:

private void ProxyGetCurrentDateTimeCompleted(object sender, GetCurrentDateTimeCompletedEventArgs args) {     value = args.Result;     UpdateValue(value); // another WCF async call, need value from GetDateTime()     UpdateAnotherValue(value, user); // third WCF async call } 

Update 2

Following your last comment, I would recommend you to restructure your application so that you can use an approach as shown in the first update. Storing data in the code behind and the view model seems a bit odd. However, if you want a quick solution you could also wait for the callback to set the value manually. See the following code as example to get you started:

DateTime value; bool wcfCallInProgress; public void GetDateTime() {     var proxy = new WcfClient();     proxy.GetCurrentDateTimeCompleted -= ProxyGetCurrentDateTimeCompleted;     proxy.GetCurrentDateTimeCompleted += ProxyGetCurrentDateTimeCompleted;     wcfCallInProgress = true;     proxy.GetCurrentDateTimeAsync(); }  private void ProxyGetCurrentDateTimeCompleted(object sender, GetCurrentDateTimeCompletedEventArgs args) {     value = args.Result;     wcfCallInProgress = false; } 

Now you can add a loop which waits until the value has been set:

this.ViewModel.GetDateTime();// WCF async call  while (this.ViewModel.wcfCallInProgress) {     Thread.Sleep(10); }  this.ViewModel.UpdateValue(value); // another WCF async call, need value from GetDateTime() method's return result. this.ViewModel.UpdateAnotherValue(value, user); // third WCF async call 

If you use this approach you'll have to make sure that timeouts and exceptions won't be a problem. Otherwise you may end up with an infinite loop.

Read More

Nginx location blocks factcgi php inheritance issue

Leave a Comment

I have a configuration file which reads a little like the below.

I have a mediawiki installation under the subfolder /wiki/ represented by its location block. I then have a default location / which serves the main part of the site. I have an embedded .php catch in the /wiki/ location block which seems to work. However, I have a legacy requirement in the default .php block to auto_prepend a file.

When making calls to /wiki/ this file is loaded. I presume because nginx is somehow falling into that block. Can someone explain whats wrong here?

I suppose I could ignore the /wiki/ with regex in the default .php block. But fishing for some other ideas.

Many thanks

  server {   listen *:80;    server_name           www.somesite.com   error_page 404 /404error.html;    index  index.php;    if ($http_x_forwarded_proto = "http") {         return 301 https://www.street-crime.com$request_uri;   }    location @extensionless-php {     internal;       rewrite ^(.*)$ $1.php last;   }    location ^~ /wiki {     index index.html index.htm index.php;     root  /var/www/html/somesite/current;     try_files $uri $uri /wiki/index.php?query_string;          location ~ /wiki/(.*\.php)$ {                 include /etc/nginx/fastcgi_params;                 fastcgi_pass  127.0.0.1:9000;                 fastcgi_connect_timeout 3m;                 fastcgi_read_timeout 3m;                 fastcgi_send_timeout 3m;         }   }    location @missing {      root          /var/www/html/somesite/current;     include       /etc/nginx/fastcgi_params;     try_files     /bootstrap/routes.php =404;      fastcgi_pass  127.0.0.1:9000;     fastcgi_param PHP_VALUE   auto_prepend_file="/var/www/html/somesite/current/includes/boot.php";     fastcgi_param SCRIPT_FILENAME $document_root/bootstrap/routes.php;     fastcgi_connect_timeout 3m;     fastcgi_read_timeout 3m;     fastcgi_send_timeout 3m;   }    location ~ \.php$ {      root          /var/www/html/somesite/current;     include       /etc/nginx/fastcgi_params;     try_files     $uri @missing;      fastcgi_pass  127.0.0.1:9000;     fastcgi_param PHP_VALUE auto_prepend_file="/var/www/html/somesite/current/includes/boot.php";     fastcgi_connect_timeout 3m;     fastcgi_read_timeout 3m;     fastcgi_send_timeout 3m;   } } 

0 Answers

Read More

Sunday, July 24, 2016

Share Authentication Across Secure and Nonsecure

Leave a Comment

I am in the situation where the site I am working on, the manager wants to allow the user to log in and not worry if they logged in through http or https. Based on another SO question (how can I share an asp.net session between http and https) I thought this would be possible if I set secure = false on the cookie. To add to this, we use a subdomain for the secure part of the site. So for http we use site.com, while https uses secure.site.com. So I tried setting the domain for the authentication in the web.config.

<authentication mode="Forms">      <forms loginUrl="/account/login"     protection="All" timeout="30" name=".ASPXAUTH" path="/"     requireSSL="false" slidingExpiration="true" defaultUrl="/"     cookieless="UseDeviceProfile" domain="site.com"     enableCrossAppRedirects="false" />  </authentication> 

Am I doing this all wrong? I understand there are some security concerns and I was going to address them when a request is made. I just want to allow the user to log in once and be remembered across http and https. Thanks.

1 Answers

Answers 1

I think you have wrong domain in your web.config. You should change it to

domain=".site.com" 

So you're allowing your forms auth cookie to live both on ssl.site.com and no-ssl.site.com domain for example.

All that being said any kind of security starts with https:// over all your solution - otherwise you're open into man-in-the-middle attacks (web proxy can inject inappropriate content into your solution, they can steal your authorization cookie & use it in flow on https://ssl.site.com etc.

Read More

Why async methods call sooner in Retrofit 2?

Leave a Comment

As you can see in the code below, I've call the getPostByPageId() method to get data from server and then check if the data was returned back, I do other jobs.

 private void recyclerViewJobs() {     getPostByPageId();     if (pageDtoList.size() > 0) {         emptyText.setVisibility(View.GONE);         recyclerView.setVisibility(View.VISIBLE);         PagesAdapter adapter = new PagesAdapter(pageDtoList, context);         recyclerView.setAdapter(adapter);         recyclerView.setLayoutManager(new LinearLayoutManager(context));     } else {         emptyText.setVisibility(View.VISIBLE);         recyclerView.setVisibility(View.GONE);     }   } 

.....

private void getPostByPageId() {      IPageEndPoint pageEndPoint = ServiceGenerator.createService(IPageEndPoint.class);     Call<List<PageDto>> call = pageEndPoint.getPostByPageId(profileId);     call.enqueue(new retrofit2.Callback<List<PageDto>>() {         @Override         public void onResponse(Call<List<PageDto>> call, Response<List<PageDto>> response) {             if (response.isSuccessful()) {                 pageDtoList = response.body();             } else {                 log.toast("response is not successful for getPostByPageId");             }         }          @Override         public void onFailure(Call<List<PageDto>> call, Throwable t) {             log.toast("getPostByPageId onFailure");         }     }); } 

I don't know why in the recyclerViewJobs() method, the if condition work first?

maybe I could not explain my issue very well but my big problem is to know when I want to get some data from REST and then use this data to another REST service, how can I do this job because enqueue in retrofit works asynchronous and do not wait for first method, because of that it is beginning the second method in another thread and because my data was not gotten from first method yet, my program was crashed and I didn't get the answer. That is my problem.....

Cheers

3 Answers

Answers 1

That's because retrofit's enqueue method is not a blocking method. which means the Thread calling it won't wait for it to finish its job. Like @Amir said, If you have other things to do after calling getPostByPageId(), you should put them after retrofit's callback:

    private void recyclerViewJobs() {         getPostByPageId();     }     private void getPostByPageId() {          IPageEndPoint pageEndPoint = ServiceGenerator.createService(IPageEndPoint.class);         Call<List<PageDto>> call = pageEndPoint.getPostByPageId(profileId);         call.enqueue(new retrofit2.Callback<List<PageDto>>() {             @Override             public void onResponse(Call<List<PageDto>> call, Response<List<PageDto>> response) {                 if (response.isSuccessful()) {                     pageDtoList = response.body();                     if (pageDtoList.size() > 0) {                         emptyText.setVisibility(View.GONE);                         recyclerView.setVisibility(View.VISIBLE);                         PagesAdapter adapter = new PagesAdapter(pageDtoList, context);                         recyclerView.setAdapter(adapter);                         recyclerView.setLayoutManager(new LinearLayoutManager(context));                     } else {                         emptyText.setVisibility(View.VISIBLE);                         recyclerView.setVisibility(View.GONE);                     }                 } else {                     log.toast("response is not successful for getPostByPageId");                 }             }              @Override             public void onFailure(Call<List<PageDto>> call, Throwable t) {                 log.toast("getPostByPageId onFailure");             }         });     } 

Answers 2

Your async call run first But your if-condition always goes false because if-condition not behave as you expected! As soon as your async request sent it goes to check if-condition and because your list is empty (your response from server is not fetch yet) it always return false.

If you want to call next operation just after your WebService response was successful you can do it with following code:

public void onResponse(Call<List<PageDto>> call, Response<List<PageDto>> response) {      if (response.body().YOUR_LIST.size() > 0) {         emptyText.setVisibility(View.GONE);         recyclerView.setVisibility(View.VISIBLE);         PagesAdapter adapter = new PagesAdapter(pageDtoList, context);         recyclerView.setAdapter(adapter);         recyclerView.setLayoutManager(new LinearLayoutManager(context));          //CALL_YOUR_NEXT webservice here     } else {         emptyText.setVisibility(View.VISIBLE);         recyclerView.setVisibility(View.GONE);     } } 

In your processResponse do your job. But one thing you should consider is that response.isSuccessful() return true most of time and it doesn't mean your responseBody contains data. according to document:

isSuccessful() Returns true if code() is in the range [200..300).

So the better way is to check that your response list contains data or not.

But as a better way (a bit difficult if you are beginner) is using RxJava/RxAndroid. you can process your call just one after other with flatMap.

Answers 3

What is an asynchronous task? Not only for retrofit but the answer is same for all, when you use asynchronous task to write some code, it seems you allow that code to run asynchronously, that is, any time it wants to run and that too in background without disturbing any other tasks and not giving any kind of effect on main UI thread. So asynchronous task clearly defines itself as a task running in background and the code written above or below is never affected by it. So in your case it asynchronous task might not have completed or may be it is possible that it might not had started also but it does not disturb your if condition. https://developer.android.com/reference/android/os/AsyncTask.html

Read More

Saturday, July 23, 2016

Nice Drag and drop on a canvas HTML5

Leave a Comment

I try to implement a nice drag and drop on a canvas representing 3 disks.

I would like to change with mouse the position of each mass. My main problem is that I am constrained by the length of axe for each of these 3 spheres.

For the moment, I have implemented the following function when mouse is moving inside the canvas ( value of indexMass indicates which mass is moved : 1, 2 or 3 and t1, t2, t3 represents respectively the angle of mass 1, 2, 3 ) :

// Happens when the mouse is moving inside the canvas function myMove(event) {     if (isDrag) {      var x = event.offsetX;      var y = event.offsetY;       if (indexMass == 1)        { // Update theta1 value          t1 = t1 + 0.1*Math.atan(y/x);        }      else if (indexMass == 2)        { // Update theta2 value          t2 = t2 + 0.1*Math.atan(y/x);        }      else if (indexMass == 3)        { // Update theta3 value          t3 = t3 + 0.1*Math.atan(y/x);        }       // Update drawing      DrawPend(canvas);      }      } 

As you can see, I did for each angle :

t = t + 0.1*Math.atan(y/x); 

with :

 var x = event.offsetX;  var y = event.offsetY; 

But this effect is not very nice. Once the sphere is selected with mouse (on mouse click), I would like the cursor to be stucked with this sphere or the sphere to follow the "delta" of the mouse coordinates when I am not on sphere anymore.

To summarize, I don't know how to create a fine and user friendly drag and drop, if someone could help me or give me some advices, this would be great.

Thanks

UPDATE 1

@Blindman67 : thanks for your help, your code snippet is pretty complex for me, I didn't understand it all. But I am on the right way.

I am starting by the first issue : make rotate the selected disk with mouse staying very closed to it or over it, when dragging.

For the moment, I have modified my function myMove (which is called when I have clicked down and move the mouse for dragging) like :

// Happens when the mouse is moving inside the canvas function myMove(event) {     // If dragging     if (isDrag) {       // Compute dx and dy before calling DrawPend      var lastX = parseInt(event.offsetX - mx);      var lastY = parseInt(event.offsetY - my);       var dx = lastX - window['x'+indexMass];      var dy = lastY - window['y'+indexMass];       // Change angle when dragging      window['t'+indexMass] = Math.atan2(dy, dx);       // Update drawing      DrawPend(canvas);       // Highlight dragging disk      fillDisk(indexMass, 'pink');      }                      } 

where indexMass is the index of dragged disk and window['x'+indexMass] , window['y'+indexMass] are the current coordinates of the selected disk center.

After, I compute the dx, dy respectively from coordinates mouse clicked when starting drag (mx, my returned by getMousePos function) and mouse coordinates with moving.

Finally, I change the angle of disk by set, for global variable (theta of selected disk), i.e window['t'+indexMass] :

// Change angle when dragging window['t'+indexMass] = Math.atan2(dy, dx); 

I have took your part of code with Math.atan2.

But the result of this function doesn't make a good animation with mouse dragging, I would like to know where this could come from.

Right now, I would like to implement only the dragging without modifying the length of axis, I will see more later for this functionality.

UPDATE 2

I keep going on to find a solution about the dragging of a selected mass with mouse.

For trying a synthesis of what I have done previously, I believe the following method is good but this dragging method is not working very well : the selected disk doesn't follow correctly the mouse and I don't know why.

In myMove function (function called when I start dragging), I decided to :

  1. Compute the dx, dy between the mouse coordinates and the selected disk coordinates, i.e :

var dx = parseInt(event.offsetX - window['x'+indexMass]);

var dy = parseInt(event.offsetY - window['y'+indexMass]);

indexMass represents the index of the selected disk.

  1. Increment the position of selected disk (stored in temporary variables tmpX, tmpY) by dx, dy.

  2. Compute the new angle theta (identified in code by global variable window['t'+indexMass]

  3. Compute the new positions of selected disk with this new value of theta, i.e for example with disk1 (indexMass=1 and theta = t1) :

    x1= x0 +l1 * sin(t1) y1= y0 +l1 * sin(t1) 

I have to make you notice that I want dragging with mouse not to modify the lengths of axes with mouse, this is a constraint.

Here's the entire myMove function (called when drag is starting) :

// Happens when the mouse is moving inside the canvas function myMove(event) {     // If dragging     if (isDrag) {       console.log('offsetX', event.offsetX);      console.log('offsetY', event.offsetY);      var dx = parseInt(event.offsetX - window['x'+indexMass]);      var dy = parseInt(event.offsetY - window['y'+indexMass]);      console.log('dx', dx);      console.log('dy', dy);        // Temp variables       var tmpX = window['x'+indexMass];         var tmpY = window['y'+indexMass];          // Increment temp positions       tmpX += dx;       tmpY += dy;       // Compute new angle for indexMass       window['t'+indexMass] = Math.atan2(tmpX, tmpY);          console.log('printf', window['t'+indexMass]);        // Compute new positions of disks       dragComputePositions();        // Update drawing       DrawPend(canvas);        // Highlight dragging disk       fillDisk(indexMass, 'pink');     } } 

UPDATE 4 - Bounty :

Problem solved ! I forgot to take into account the position of "indexMass-1" disk to compute the new angle with Math.atan2 function.

1 Answers

Answers 1

You can not move the OS mouse position. You can hide the mouse canvas.style.cursor = "none"; and then draw a mouse on the canvas your self but it will lag behind by one frame because when you get the mouse coordinates the OS has already placed the mouse at that position, and if you use requestAnimationFrame (RAF) the next presentation of the canvas will be at the next display refresh interval. If you don't use RAF you may or may not present the canvas on the current display refresh, but you will get occasional flicker and shearing.

To solve the problem (which is subjective) draw a line from the rotation point through the ball to the mouse position this will at least give the user some feedback as to what is happening.

I would also add some handles to the balls so you could change the mass (volume of sphere * density) and the length of axis.. The resize cursors are a problem as the will not match the direction of required movement when the angles have changes. You would need to find one closest to the correct angle or render a cursor to a canvas and use that.

Example code shows what I mean. (does not include sim) Move mouse over balls to move, when over you will also see two circles appear to change distance and radius (mass)

/*-------------------------------------------------------------------------------------   answer code  ---------------------------------------------------------------------------------------*/              var balls = [];  var startX,startY;  var mouseOverBallIndex = -1;  var mouseOverDist = false;  var mouseOverMass = false;  const DRAG_CURSOR = "move";  const MASS_CURSOR = "ew-resize";  const DIST_CURSOR = "ns-resize";  var dragging = false;  var dragStartX = 0;  var dragStartY = 0;  function addBall(dist,radius){      balls.push({          dist : dist,          radius : Math.max(10,radius),          angle : -Math.PI / 2,          x : 0,          y : 0,          mass : (4/3) * radius * radius * radius * Math.PI,      });  }  function drawBalls(){      var i = 0;      var len = balls.length;      var x,y,dist,b,minDist,index,cursor;      ctx.lineWidth = 2;      ctx.strokeStyle = "black";      ctx.fillStyle = "blue"      ctx.beginPath();      x = startX;      y = startY;      ctx.moveTo(x, y)      for(; i < len; i += 1){          b = balls[i];          x += Math.cos(b.angle) * b.dist;          y += Math.sin(b.angle) * b.dist;          ctx.lineTo(x, y);          b.x = x;          b.y = y;      }      ctx.stroke();      minDist = Infinity;      index = -1;      for(i = 0; i < len; i += 1){          b = balls[i];          ctx.beginPath();          ctx.arc(b.x, b.y, b.radius, 0, Math.PI * 2);          ctx.fill();          if(!dragging){              x = b.x - mouse.x;              y = b.y - mouse.y;              dist = Math.sqrt(x * x + y * y);              if(dist < b.radius + 5 && dist < minDist){                  minDist = dist;                  index = i;              }          }      }      if(!dragging){          mouseOverBallIndex = index;          if(index !== -1){              cursor = DRAG_CURSOR;              b = balls[index];              ctx.fillStyle = "Red"              ctx.beginPath();              ctx.arc(b.x, b.y, b.radius, 0, Math.PI * 2);              ctx.fill();              dx = b.x - Math.cos(b.angle) * b.radius;              dy = b.y - Math.sin(b.angle) * b.radius;              x = dx - mouse.x;              y = dy - mouse.y;              dist = Math.sqrt(x * x + y * y);              ctx.beginPath();              if(dist < 6){                  ctx.strokeStyle = "Yellow"                  mouseOverDist = true;                  ctx.arc(dx, dy, 12, 0, Math.PI * 2);                  cursor = DIST_CURSOR;              }else{                  ctx.strokeStyle = "black"                  mouseOverDist = false;                  ctx.arc(dx, dy, 5, 0, Math.PI * 2);                }              ctx.stroke();MASS_CURSOR              dx = b.x - Math.cos(b.angle + Math.PI/2) * b.radius;              dy = b.y - Math.sin(b.angle + Math.PI/2) * b.radius;              x = dx - mouse.x;              y = dy - mouse.y;              dist = Math.sqrt(x * x + y * y);              ctx.beginPath();              if(dist < 6){                  ctx.strokeStyle = "Yellow"                  mouseOverMass = true;                  ctx.arc(dx, dy, 12, 0, Math.PI * 2);                  cursor = MASS_CURSOR;              }else{                  ctx.strokeStyle = "black"                  mouseOverMass = false;                  ctx.arc(dx, dy, 5, 0, Math.PI * 2);                }              ctx.stroke();              canvas.style.cursor = cursor;          }else{              canvas.style.cursor = "default";          }      }else{          b = balls[mouseOverBallIndex];          ctx.fillStyle = "Yellow"          ctx.beginPath();          ctx.arc(b.x, b.y, b.radius, 0, Math.PI * 2);          ctx.fill();                        }    }  function display(){  // put code in here      var x,y,b          if(balls.length === 0){          startX = canvas.width/2;          startY = canvas.height/2;          addBall((startY * 0.8) * (1/4), startY * 0.04);          addBall((startY * 0.8) * (1/3), startY * 0.04);          addBall((startY * 0.8) * (1/2), startY * 0.04);                }      ctx.setTransform(1,0,0,1,0,0); // reset transform      ctx.globalAlpha = 1;           // reset alpha      ctx.clearRect(0,0,w,h);      if((mouse.buttonRaw & 1) && mouseOverBallIndex > -1){          b = balls[mouseOverBallIndex];          if(dragging === false){              dragging = true;              dragStartX = balls[mouseOverBallIndex].x;              dragStartY = balls[mouseOverBallIndex].y;          }else{              b = balls[mouseOverBallIndex];              if(mouseOverBallIndex === 0){                  x = startX;                  y = startY;              }else{                  x = balls[mouseOverBallIndex-1].x                  y = balls[mouseOverBallIndex-1].y              }              if(mouseOverDist){                  var dist = Math.sqrt(Math.pow(x-mouse.x,2)+Math.pow(y-mouse.y,2));                  b.dist = dist + b.radius;                                }else                  if(mouseOverMass){                  var dist = Math.sqrt(Math.pow(dragStartX-mouse.x,2)+Math.pow(dragStartY-mouse.y,2));                  b.radius = Math.max(10,dist);                  b.mass = dist * dist * dist * (4/3) * Math.PI;              }else{                  b.angle = Math.atan2(mouse.y - y, mouse.x - x);                  ctx.beginPath();                  ctx.lineWidth = 1;                  ctx.strokeStyle = "grey";                  ctx.moveTo(x,y);                  ctx.lineTo(mouse.x, mouse.y);                  ctx.stroke();              }          }                }else if(dragging){          dragging = false;      }        drawBalls();  }    /*-------------------------------------------------------------------------------------   answer code END  ---------------------------------------------------------------------------------------*/                                                                            /** SimpleFullCanvasMouse.js begin **/  const CANVAS_ELEMENT_ID = "canv";  const U = undefined;  var w, h, cw, ch; // short cut vars   var canvas, ctx, mouse;  var globalTime = 0;   var createCanvas, resizeCanvas, setGlobals;  var L = typeof log === "function" ? log : function(d){ console.log(d); }  createCanvas = function () {      var c,cs;      cs = (c = document.createElement("canvas")).style;       c.id = CANVAS_ELEMENT_ID;          cs.position = "absolute";      cs.top = cs.left = "0px";      cs.zIndex = 1000;      document.body.appendChild(c);       return c;  }  resizeCanvas = function () {      if (canvas === U) { canvas = createCanvas(); }      canvas.width = window.innerWidth;      canvas.height = window.innerHeight;       ctx = canvas.getContext("2d");       if (typeof setGlobals === "function") { setGlobals(); }  }  setGlobals = function(){ cw = (w = canvas.width) / 2; ch = (h = canvas.height) / 2; balls.length = 0; }  mouse = (function(){      function preventDefault(e) { e.preventDefault(); }      var mouse = {          x : 0, y : 0, w : 0, alt : false, shift : false, ctrl : false, buttonRaw : 0,          over : false,  // mouse is over the element          bm : [1, 2, 4, 6, 5, 3], // masks for setting and clearing button raw bits;          mouseEvents : "mousemove,mousedown,mouseup,mouseout,mouseover,mousewheel,DOMMouseScroll".split(",")      };      var m = mouse;      function mouseMove(e) {          var t = e.type;          m.x = e.offsetX; m.y = e.offsetY;          if (m.x === U) { m.x = e.clientX; m.y = e.clientY; }          m.alt = e.altKey; m.shift = e.shiftKey; m.ctrl = e.ctrlKey;          if (t === "mousedown") { m.buttonRaw |= m.bm[e.which-1]; }            else if (t === "mouseup") { m.buttonRaw &= m.bm[e.which + 2]; }          else if (t === "mouseout") { m.buttonRaw = 0; m.over = false; }          else if (t === "mouseover") { m.over = true; }          else if (t === "mousewheel") { m.w = e.wheelDelta; }          else if (t === "DOMMouseScroll") { m.w = -e.detail; }          if (m.callbacks) { m.callbacks.forEach(c => c(e)); }          e.preventDefault();      }      m.addCallback = function (callback) {          if (typeof callback === "function") {              if (m.callbacks === U) { m.callbacks = [callback]; }              else { m.callbacks.push(callback); }          } else { throw new TypeError("mouse.addCallback argument must be a function"); }      }      m.start = function (element, blockContextMenu) {          if (m.element !== U) { m.removeMouse(); }                  m.element = element === U ? document : element;          m.blockContextMenu = blockContextMenu === U ? false : blockContextMenu;          m.mouseEvents.forEach( n => { m.element.addEventListener(n, mouseMove); } );          if (m.blockContextMenu === true) { m.element.addEventListener("contextmenu", preventDefault, false); }      }      m.remove = function () {          if (m.element !== U) {              m.mouseEvents.forEach(n => { m.element.removeEventListener(n, mouseMove); } );              if (m.contextMenuBlocked === true) { m.element.removeEventListener("contextmenu", preventDefault);}              m.element = m.callbacks = m.contextMenuBlocked = U;          }      }      return mouse;  })();  var done = function(){      window.removeEventListener("resize",resizeCanvas)      mouse.remove();      document.body.removeChild(canvas);          canvas = ctx = mouse = U;      L("All done!")  }    resizeCanvas(); // create and size canvas  mouse.start(canvas,true); // start mouse on canvas and block context menu  window.addEventListener("resize",resizeCanvas); // add resize event    function update(timer){ // Main update loop      globalTime = timer;      display();  // call demo code      // continue until mouse right down      if (!(mouse.buttonRaw & 2)) { requestAnimationFrame(update); } else { done(); }  }  requestAnimationFrame(update);    /** SimpleFullCanvasMouse.js end **/

Read More