Monday, October 24, 2016

Regenerate WordPress thumbnails with media hosted on S3

Leave a Comment

I have a WordPress site that uses the WPRO (WordPress Read Only) plugin to host all media files on Amazon S3. I've changed the thumbnail and image sizes in my custom theme, and uploading new images to the media library uses the new sizes. However, when I try to regenerate all thumbnails using "Regenerate Thumbnails," it doesn't work, often complaining that the original cannot be found.

How can I force the regenerate thumbnails plugin to use the original image on S3 to recreate the thumbnails for existing images?

0 Answers

Read More

VS 2013 Designer - “An attempt was made to load a program with an incorrect format”

Leave a Comment

Amongst other items, my solution contains a project that defines a control and another project that uses this control on a form. When I try to open this form in the VS Designer, I get the following error:

 Could not load file or assembly 'libX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.  

where libX is neither the project with control, nor the project with the form. When I try to just build the solution, everything goes absolutely fine. When I run an application that shows the form, all is good. It's the Designer that seems to dislike something.

Things that I have tried so far:

  • Having googled the issue, I have gone through the common attempts to solve this. Namely, the config of my solution is correct in the Configuration Manager and the project does not use anything of IIS (hence the solution with enabling 32b does not apply)
  • I tried opening the form at work on a different version of VS 2013 (12.0.21005.1 REL) and that worked without any problems.
  • I am using VS 2013 Update 5. Since there were times when the Designed worked OK, I tried downgrading to Update 2 - without help.
  • I tried Repairing my VS - without help.

EDIT: A minimal project that demonstrates the problem is to be found here. The problematic form is to be found in the +lib.trading\lib.trading.obj.forms.strategyParametersForm project.

The error that I get when opening the form in VS Designer is tnhe following: enter image description here

Any help is much appreciated, Daniel

1 Answers

Answers 1

An attempt was made to load a program with an incorrect format. In case the application is run in Visual Studio installed on 64-bit OS with the TargetCPU = “Any CPU” the error message “An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000В)” can occur.

Read More

Website shows Forbidden message when using HTTPS

Leave a Comment

I have this in my htaccess file

Options +FollowSymLinks -MultiViews RewriteEngine On RewriteBase / Options -Indexes  RewriteRule ^login/?$ login.php [L] RewriteRule ^logout/?$ logout.php [L]  # This will process the /section/(.*) requests, ?section=1 will be appended to query string     RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^section\/(.*)?$ index.php?section=1&id=$1 [L,QSA]  # This will process all other requests RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-zA-Z0-9-/_]+)/?$ index.php?id=$1 [L,QSA] 

I have installed an SSL Certificate on my domain (wildcard SSL) to cover all subdomains.

When visiting my subdomain admin. using HTTPS, it returns a forbidden page.

I have tried adding %{HTTP_HOST} in front of all my RewriteCond's but i still see the same forbidden message

1 Answers

Answers 1

Make sure you have setup a seperate virtual host in Apache config for SSL

 <VirtualHost *:443>         SSLEngine On         SSLCertificateFile /etc/ssl/certs/example.com.crt         SSLCertificateKeyFile /etc/ssl/private/example.com.key         SSLCACertificateFile /etc/ssl/certs/ca-certificates.crt  #If using a self-signed certificate, omit this line          ServerAdmin info@example.com         ServerName www.example.com         DocumentRoot /var/www/example.com/public_html/         ErrorLog /var/www/example.com/log/error.log         CustomLog /var/www/example.com/log/access.log combined </VirtualHost> 

Also, please make sure you have place the certification files on the correct part and your server port 443 is open to listen.

Read More

angular tree control not highlighting the whole cell

Leave a Comment

I tried to implement angular tree control from http://wix.github.io/angular-tree-control, however, i cannot highlight the whole cell, it's only highlighting the label. I tried to change the css that the treecontrol comes with but still i can't make it highlight the whole cell.

the current and expected result is here:

enter image description here

treecontrol {     font-family: Verdana, Helvetica, Arial, sans-serif;     font-size:13px;     color: #555;     text-decoration: none; } treecontrol ul {     margin: 0;     padding: 0;     list-style: none;     border: none;     overflow: hidden; } treecontrol li {     position: relative;     padding: 0 0 0 20px;     line-height: 20px;     ul {       padding-left: 16px;     }     .tree-label {       cursor: pointer;       display: inline;       &:focus {         outline: none;       }       &:hover {         outline: none;         background-color: yellow;       }     }     .tree-selected {       background-color: yellow;     }     &.tree-expanded {       > div {         > .tree-icon-expand {           display: none;         }         > .tree-icon-collapse {           display: inline;         }       }     }  }  treecontrol li.tree-expanded i.tree-leaf-head, treecontrol li.tree-collapsed i.tree-leaf-head {display:none;} treecontrol li.tree-expanded i.tree-branch-head, treecontrol li.tree-collapsed i.tree-branch-head {display:inline;} treecontrol li.tree-leaf i.tree-branch-head {display:none;} treecontrol li.tree-leaf i.tree-leaf-head {display:inline;}  treecontrol li i.tree-branch-head {   cursor: pointer; }  treecontrol li.tree-expanded i.tree-branch-head {   padding: 1px 10px;   background: url("../images/node-opened-light.png") no-repeat; }  treecontrol li.tree-collapsed i.tree-branch-head {   padding: 1px 10px;   background: url("../images/node-closed-light.png") no-repeat; }  treecontrol li.tree-leaf i.tree-leaf-head {   padding: 1px 10px;   width: 16px; height: 16px;   background: none no-repeat; } 

1 Answers

Answers 1

You have an example in the same page that you linked

custom css classes

Your javascript would be

 function CustomCss($scope) {      $scope.treedata=createSubTree(3, 4, "");      $scope.opts = {          injectClasses: {              "liSelected": "c-liSelected",          }      };  } 

And your CSS

.c-liSelected {background-color: yellow} 
Read More

Sunday, October 23, 2016

Sending Email with Delayed_Job

Leave a Comment

I have what I think is a working setup to send emails via Delayed_Job. However, I haven't received my test email and it isn't practical to wait for more to happen with a delay of days. I need to figure out:

  1. What's wrong that's causing the email not to send.
  2. How to test it without waiting days at a time.

I'm new to Delayed_Job, so pardon the newbie mistakes.

Here's the model that includes the send_reminder_emails method. They were fully functional without the .delay(run_at: self.mail_date) bit, so at least I know that much works:

class Reminder < ActiveRecord::Base   belongs_to :user   before_save :create_mail_date   after_save :send_reminder_emails   extend FriendlyId   friendly_id :name, use: [:slugged, :finders]    def create_mail_date     @schedule = IceCube::Schedule.new(self.date)     case self.repeating     when "Weekly"         @schedule.add_recurrence_rule(             IceCube::Rule.weekly         )     when "Monthly"         @schedule.add_recurrence_rule(             IceCube::Rule.monthly.day_of_month(self.date.mon)         )     when "Yearly"         @schedule.add_recurrence_rule(             IceCube::Rule.yearly.day_of_year(self.date.yday)         )     end     if self.repeating         self.date = @schedule.next_occurrence(Time.now)     end     self.mail_date = self.date - 7.days   end    private    def send_reminder_emails       if self.reminder          ReminderMailer.delay(run_at: self.mail_date).reminder_send(self.user, self).deliver_now          self.create_mail_date      end   end   handle_asynchronously :send_reminder_emails  end 

The references to schedule are via the Ice_Cube gem and all of the date stuff has been tested via my console and is working. Here is my reminder_mailer.rb:

class ReminderMailer < ApplicationMailer   default from: "man@manlyartofbbq.com"    def reminder_send(user, reminder)     @user = user     @reminder = reminder      mail(to: user.email, subject: "Reminder! #{reminder.name} is fast approaching!")   end end 

I installed Delayed_Job step by step from their readme for Rails 4. Any help getting the delayed part of this mailer ironed out is appreciated!

2 Answers

Answers 1

When you send mails using delayed job, there is no need to add 'deliver' or 'deliver_now' when initializing the delayed_job for mailer. So

ReminderMailer.delay(run_at: self.mail_date).reminder_send(self.user, self) 

will itself work.

Convert your 'self.mail_date' to also include the time at which you want to send the mail. Passing only date will not work. Basically the run_at should specify both date and time.

Please check the 'delayed_job' github link under the heading "Rails 3 Mailers" https://github.com/collectiveidea/delayed_job

Answers 2

You can use Active Job for sending mails by scheduling the job at a particular time.

Active Job is a framework for declaring jobs and making them run on a variety of queuing backends. These jobs can be everything from regularly scheduled clean-ups, to billing charges, to mailings. Anything that can be chopped up into small units of work and run in parallel, really.

For enqueuing and executing jobs in production you need to set up a queuing backend, that is to say you need to decide for a 3rd-party queuing library that Rails should use. Rails itself only provides an in-process queuing system, which only keeps the jobs in RAM. If the process crashes or the machine is reset, then all outstanding jobs are lost with the default async back-end. This may be fine for smaller apps or non-critical jobs, but most production apps will need to pick a persistent backend.

Active Job has built-in adapters for multiple queuing backends (Sidekiq, Resque, Delayed Job and others). To get an up-to-date list of the adapters see the API Documentation for ActiveJob::QueueAdapters.

Once after configuring the queuing adapters, then create Job for sending mails

class RemainderMailerJob < ApplicationJob   queue_as :default    def perform(user, remainder)    ReminderMailer.reminder_send(user, reminder).deliver   end end 

For sending the mail on a specific time you need to enqueue the job and make it perform at a specific time. If you need to send mail 7 days from now then call this piece of code where ever you need.

RemainderMailerJob.set(wait: 1.week).perform_later(user, remainder) 

Now this Job will execute after 1 week, which in turn calls the mailer at that time, so your mails will be sent on the specific day.

IF you knew the specific Date Time then you can use

RemainderMailerJob.set(wait_untill: <Specific date>).perform_later(user, remainder) 

If you have any doubts regarding the active job kindly refer Active Job Basics

Read More

Friday, October 21, 2016

Transparent iframe over another iframe

Leave a Comment

What I'm trying to achieve is an iframe positioned over another iframe containing a PDF document - the first iframe should be transparent, and it should cover the iframe with PDF. I need this specifically for IE (9+).

The code I've tried so far:

<html> <head> <style> </style>  </head> <body>  <iframe src="iframeContent.html" frameborder="0" style="width: 1000px; height: 1000px; position: fixed; left:0px; top: 0px; background:transparent" allowTransparency="true"></iframe>  <iframe src='http://www.pdf995.com/samples/pdf.pdf' width="100%" height="300px" id="PDF" name="PDF"></iframe> </body> </html> 

iframeContent.html:

<html> <style type="text/css">  </style>  <body style="background: transparent"> </body> </html> 

However, the above doesn't work - the iframe is not transparent. Does anyone know how to solve this? As I said in the comments below, the solution posted below doesn't work with Adobe reader DC installed (if it works at all).

5 Answers

Answers 1

I created two html files as below and it worked for me. I adjusted the width and height to 100% and it worked as you expect. Don't try with any jsbin etc instance and its not working there for security reasons as you load external site in iframe. Try with actual html file and load them in the browser which worked for me.

Html 1: pdf.html

<html> <head>     <style type="text/css">         #outer {             position: fixed;             left: 150px;             top: 20px;             width: 100px;             z-index: 2;         }          #inner{             background-color: transparent;         }          .cover {             position: absolute;             border: none;             top: 0;             left: 0;             height: 100%;             width: 100%;             z-index: -1;         }          #pdf {             position: relative;             z-index: 1;         }     </style> </head> <body>       <div id="outer">         <div id="inner">             <iframe src="iframeContent.html" style="width:90px; height:70px; background-color: transparent;" frameborder="0" allowtransparency="true"></iframe>         </div>         <iframe class="cover" src="about:blank" allowtransparency="true"></iframe>     </div>     <iframe src='http://www.pdf995.com/samples/pdf.pdf' width="100%" height="600px" id="PDF" name="PDF" frameborder="0"></iframe>  </body>  </html> 

Html 2: iframecontent.html

    <html>  <body>     <h1 style="background-color:transparent;">Test</h1> </body> </html> 

Answers 2

May be this will helps you

 <html> <head> <style> </style>  </head> <body>  <iframe src="iframeContent.html" frameborder="0" style="width: 1000px; height: 1000px; position: fixed; left:0px; top: 0px; background:none transparent;" allowtransparency="true"></iframe>  <iframe src='http://www.pdf995.com/samples/pdf.pdf' width="100%" height="300px" id="PDF" name="PDF"></iframe> </body> </html> 

iframecontent.html

    <html> <style type="text/css">  </style>  <body style="background:none transparent;">  </body> </html> 

Answers 3

For the iframe which you want to display transparent:

body{   opacity: 0.0;   background: transparent;   color: transparent; } 

Answers 4

Try setting setting opacity: 0 on the outer iframe.

Using your modified code,

<iframe src="iframeContent.html" frameborder="0" style="opacity: 0; z-index: 2; width: 1000px; height: 1000px; position: fixed; left:0px; top: 0px; background:transparent" allowTransparency="true"></iframe>   <iframe src='http://www.pdf995.com/samples/pdf.pdf' width="100%" height="300px" id="PDF" name="PDF"></iframe> 

You can also use z-index to manage stacking of elements. All elements default z-indez is 1. THose with higher values will appear on top of elements with a lower z-index.

Answers 5

Try this code:

HTML 1

<!--Code for transparent iframe--> <html> <body style="background: none transparent"> <div> I am a crappy container on top of this boring PDF</div> </body> </html> 

HTML 2

<!--Code for both iframes. <html> <head> <style> </style>  </head> <body>  <iframe src="SO1.html" frameborder="0" style="width: 100%; height: 300px; position: fixed; left:0px; top: 0px;" allowtransparency="true"></iframe>  <iframe src='http://www.pdf995.com/samples/pdf.pdf' width="100%" height="300px" id="PDF" name="PDF"></iframe> </body> </html> 

This positions the transparent iframe correctly on top of the PDF. Also, you had a syntax error for the attribute allowTransparency, it shouldn't have a capital T.

Read More

How do I auto-submit an upload form when a file is selected?

Leave a Comment

I have a simple file upload form. How do I make it submit automatically when a file has been selected? I don't want the user to have to click the Submit button.

11 Answers

Answers 1

You can simply call your form's submit method in the onchange event of your file input.

document.getElementById("file").onchange = function() {     document.getElementById("form").submit(); }; 

http://jsfiddle.net/cwvc4/73/

Answers 2

Using jQuery:

<form id="target" action="destination.html">   <input type="file" id="file" value="Go" /> </form>   $('#file').change(function() {   $('#target').submit(); }); 

Answers 3

jquery .change() and .submit() will help you.

or in javascript with onchange event :

<form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="filename" onchange="javascript:this.form.submit();"> </form> 

Answers 4

The shortest solution is

<input type="file" name="file" onchange="javascript:document.getElementById('form').submit();" /> 

Answers 5

Just tell the file-input to automatically submit the form on any change:

<form action="http://example.com">     <input type="file" onchange="form.submit()" /> </form> 

http://jsfiddle.net/4ng96dkp/7/

This solution works like this:

  • onchange makes the input element execute the following script, whenever the value is modified
  • form references the form, that this input element is part of
  • submit() causes the form to send all data to the URL, as specified in action

Answers 6

<form id="thisForm" enctype='multipart/form-data'>       <input type="file" name="file" id="file"> </form>  <script> $(document).on('ready', function(){   $('#file').on('change', function(){     $('#thisForm').submit();   }); }); </script> 

Answers 7

For those who are using .NET WebForms a full page submit may not be desired. Instead, use the same onchange idea to have javascript click a hidden button (e.g. <asp:Button...) and the hidden button can take of the rest. Make sure you are doing a display: none; on the button and not Visible="false".

Answers 8

HTML

<form id="xtarget" action="upload.php"> <input type="file" id="xfilename"> </form> 

JAVASCRIPT PURE

<script type="text/javascript"> window.onload = function() {     document.getElementById("xfilename").onchange = function() {         document.getElementById("xtarget").submit();     } }; </script> 

Answers 9

Try bellow code with jquery :

<html> <head>     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </head>  <script> $(document).ready(function(){     $('#myForm').on('change', "input#MyFile", function (e) {         e.preventDefault();         $("#myForm").submit();     }); }); </script> <body>     <div id="content">         <form id="myForm" action="action.php" method="POST" enctype="multipart/form-data">             <input type="file" id="MyFile" value="Upload" />         </form>     </div> </body> </html> 

Answers 10

You can put this code to make your code work with just single line of code

<input type="file" onchange="javascript:this.form.submit()"> 

This will upload the file on server without clicking on submit button

Answers 11

<form action="http://example.com">     <input type="file" onchange="Submit()" /> </form>   <script>      // it will submit form 0 or you have to select particular form      document.getElementsByTagName("form")[0].submit();         </script> 
Read More

WebViewClient not calling shouldOverrideUrlLoading

Leave a Comment

The problem is rather simple. In the application we want to keep track of the current url being displayed. For that we use shouldOverrideUrlLoading callback from the WebViewClient by saving the url into a class field for every update. Here is the relevant code:

    mWebView.getSettings().setJavaScriptEnabled(true);     mWebView.getSettings().setDomStorageEnabled(true);      mWebView.setWebViewClient(new WebViewClient() {         @Override         public boolean shouldOverrideUrlLoading(WebView view, String url) {             mCurrentUrl = url;              // If we don't return false then any redirect (like redirecting to the mobile             // version of the page) or any link click will open the web browser (like an             // implicit intent).             return false;         }            @Override         public void onPageFinished(WebView view, String url) {             super.onPageFinished(view, url);             ...         }     });     mWebView.loadUrl(mInitialUrl); 

However, there is at least one scenario, where the callback never gets triggered and the mCurrentUrl field doesnt get updated.

The url: https://m.pandora.net/es-es/products/bracelets/556000

Last updated url (shouldOverrideUrlLoading never gets called when clicking the product): https://m.pandora.net/es-es/products/bracelets

I have tried with callbacks like onPageStarted(), but the url also gets filtered and there doesn't seem to be an accessible one upstream since its protected code.

Reading android documentation about WebView I found this:

https://developer.android.com/guide/webapps/migrating.html#URLs

The new WebView applies additional restrictions when requesting resources and resolving links that use a custom URL scheme. For example, if you implement callbacks such as shouldOverrideUrlLoading() or shouldInterceptRequest(), then WebView invokes them only for valid URLs.

But still doesnt make sense since the above url is generic and should meet the standard.

Any alternative or solution to this?

3 Answers

Answers 1

When you click a product on that web page, it loads the new content in with JavaScript and updates the visible URL in the address bar using the HTML5 History APIs.

From the above MDN article:

This will cause the URL bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.

These are sometimes called single-page applications. Since the actual loaded page doesn’t change, the WebView callback for page loads isn’t called.

In case you know precisely what kind of HTTP request you want to intercept, you could use the shouldInterceptRequest callback that gets called for each request. It’s likely that the web application loads some data from an API, for example when a product is shown, which you could then detect.

If detecting this isn’t possible, but you’re in control of the web application, you could use the Android JavaScript interface to invoke methods within the Android application directly from the web page.

If you’re not in control of the loaded page, you could still try to inject a local JavaScript file into the web page and observe when the history APIs are used, then call methods in your Android application over the JS interface. I tried observing these events in Chrome with the method described in the previous link and it seems to work fine.

Answers 2

please omit 'mWebView.getSettings().setDomStorageEnabled(true);' then again try, if a new url found then will invoke shouldOverrideUrl()

Answers 3

public class AndroidMobileAppSampleActivity extends Activity {  /** Called when the activity is first created. */ String mCurrentUrl=""; @Override public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.main);      WebView mWebView = (WebView) findViewById(R.id.mainWebView);      WebSettings webSettings = mWebView.getSettings();     webSettings.setJavaScriptEnabled(true);      mWebView.setWebViewClient(new MyCustomWebViewClient());     mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);      mWebView.loadUrl("https://m.pandora.net/es-es/products/bracelets/556000");  }  private class MyCustomWebViewClient extends WebViewClient {     @Override     public boolean shouldOverrideUrlLoading(WebView view, String url) {         mCurrentUrl = url;         Log.i("mCurrentUrl",""+mCurrentUrl);           view.loadUrl(url);          return true;     } } } 

try this one...

Read More

How to trigger tag creation in select2 single select (e.g. when adjacent button is pressed)?

Leave a Comment

I am using select2 4.0.3. I have a select2 box to enter email addresses, and I would like to make sure that all email addresses are included in .val(), also the one that the user was still typing in the search field.

Form element

The form field is referenced by $('.invite-emails-field'). When I press the Send button, in the event handler $('.invite-emails-field').val() just gives me the first two addresses test1@example.com and test2@example.com, but not the third address (test3@example.com).

This is how I initialize the select2 element:

$('.invite-emails-field').select2({   tags: true,   tokenSeparators: [',', ' '],   selectOnBlur: true }); 

The selectOnBlur has no effect, and I cannot find anything else that works on select2 v4. I tried firing several events at various elements, none of it worked.

I expect that when I press the Send button, that I can make some call to the select2 box to trigger creating a tag for the contents of whatever is then in the search field test3@example.com, and that subsequently .val() returns an array with all three addresses.

Update: I created a jsFiddle for you to play with. Enter input like this:

View of jsFiddle before pressing Send button

and then press the Send button, you will see:

View of jsFiddle after pressing Send

where test3@example.com is missing from the output.

Note that in my real application I have disabled the dropdown because I just want the tagging behaviour.

1 Answers

Answers 1

You need to add selectOnClose and set it to true so that it creates the tag for you when you close / click off of the search input.

$('select').select2({   selectOnClose: true }); 

See the official documentation here: https://select2.github.io/options.html#can-i-select-the-highlighted-result-when-the-dropdown-is-closed

Read More

Thursday, October 20, 2016

How to set the position of spinner with cordova

Leave a Comment

I have this in my config.xml

<preference name="show-splash-screen-spinner" value="true" />  

And the spinner works great, however i need to change the position from center to something like center + 10% vertically

There is any way of doing this?

1 Answers

Answers 1

You have to fork the original cordova-plugin-splashscreen on github

Then on your config.xml you change it to use your fork, remove the original plugin (something like <plugin name="cordova-plugin-splashscreen" source="npm" />) and add your fork <plugin spec="https://github.com/youruser/cordova-plugin-splashscreen.git" />

You have to change this lines to do what you want https://github.com/apache/cordova-plugin-splashscreen/blob/master/src/android/SplashScreen.java#L355-L370

Right now it centers the dialog, I'm not really sure how to accomplish what you want, you'll have to figure out how Android layouts work

You can try to use setY as progressBar is a View subclass, something like this:

DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int height = displaymetrics.heightPixels; float position = (float) (height*0.4); progressBar.setY(position); 
Read More

Open window and close immediately

Leave a Comment

There is a way in JS to open window and close it immediately, that it will not open in new tab , I just want want to open a window (like in background if possible ) do some check on it and immediately close it, without the effect that the new tab is open , is it possible?

Something like this but without the effect that the window is opened...

 var popup = window.open("http://www.google.com");  popup.close(); 

UPDATE: Here is solution which I found but it's flicking sometimes and I want to avoid it...

function goNewWin() {      var TheNewWin = window.open("http://www.yahoo.com", 'TheNewpop', 'toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1');      TheNewWin.blur();     TheNewWin.close();  } 

7 Answers

Answers 1

A solution to your problem is by using the window.postMessage() function. The child is used to notify the parent that the window has been loaded and it also works on cross domain.

Child

$(window).load(function(){     this.opener.postMessage({'loaded': true}, "*");     this.close(); }); 

Parent

$(window).on('message', function(event) {          alert(event.originalEvent.data.loaded); });  

There is also one more method as described in this thread of the stackoverflow.

Full attribution is given to the author of the stack overflow of this thread

Answers 2

Even if you call close immediately after window.open, and even if you try to locate the popup window outside of the screen or to make its size null, you will see it quickly flash on the screen:

var popup = window.open("", "Popup", "left=10000,top=10000,width=0,height=0"); popup.close(); 

For security reasons, window.open cannot position the popup window outside of the screen and cannot make it smaller than some minimal size. Here is an excerpt of the window.open topic in the MDN documentation:

Requested position and requested dimension values in the features list will not be honored and will be corrected if any of such requested value does not allow the entire browser window to be rendered within the work area for applications of the user's operating system. No part of the new window can be initially positioned offscreen. This is by default in all Mozilla-based browser releases.

Similar restrictions apply in Internet Explorer, as indicated in this document. The minimum size is 250 × 150 in Internet Explorer, and the minimum "inner" size is 100 × 100 in Firefox.

If you absolutely want to avoid the flashing popup window, you can use one of these methods:

  • Instead of testing with a call to window.open, display a warning on the page to inform the user that the popup blocker option should not be activated (as suggested here by UncaAlby)
  • Let the application run and warn the user, after the fact, if the real popup window could not be displayed
  • Use an alternative to window.open, for example the dialog widget from jQuery UI or the modals from Bootstrap

Answers 3

// Code for page from where you want to open the popup it will open small popup in right bottom corner.

var popup = window.open("popup.html", "Popup", "height=1, width=1, status=no, toolbar=no, menubar=no, location=no, top = 100000, left=100000 "); 

// In your popup.html add follwing code

this.close(); 

Answers 4

<html> <head> <script type= "text/javascript">     function closeWin() {     window.close();     return true; } </script>  </head> <body onload="return closeWin();">  </body> </html> 

Answers 5

How about dynamicaly create an iframe on the current window. Then you can open any page on it, later you could destroy iframe element at any time.

Answers 6

<button onclick="myFunction()">Try it</button>  <script> function myFunction() {     window.open("http://www.google.com"); } </script> 

here you go the answer that it will open the page new tab on button click

Answers 7

If you don't want user to know that you did some process on some url use AJAX call and process

or you do this

<script type="text/javascript"> var popup = window.open("http://www.exampleurl.com/popup.html", "Popup", "height=10, width=10, status=no, toolbar=no, menubar=no, location=no, top = 1, left=1"); </script> 

here in popup.html you can write code to close it.

Read More

Wednesday, October 19, 2016

How to let IDEA auto import pom.xml with Annotation Processors defined

Leave a Comment

I am using QueryDsl, so my source depends on generated code.

FIRST

Whenever IDEA (auto) imports pom.xml, the following setting is always empty:

Build, Execution, Deployment -> Compiler -> Annotation Processors -> Annotation Processors

I have to set it manually, which is very troublesome.

SECOND

I have multi-modules using QueryDsl, which I want to be grouped into one profile with the QueryDsl com.mysema.query.apt.jpa.JPAAnnotationProcessor applied.

Build, Execution, Deployment -> Compiler -> Annotation Processors -> profile

I currently have to group these modules into one profile manually.

I also have to write a README and inform all members to follow the guide to set IDEA manually.


How can I config pom.xml, so that IDEA can fill these two settings automatically?

1 Answers

Answers 1

I would recommend you add .idea/* under version control as well as the project .iml file.

Annotation Processors

Annotation Processors settings are stored in .idea/compiler.xml. Having all this under CVS will make it a lot easier for other developers to open the project as they will open a project file, not a pom file, already containing project settings, run configurations, etc.

Details onto what should go in CVS and what not could be found on the official IntelliJ guide on How to manage projects under Version Control Systems

Read More

Stratified sampling in Spark

Leave a Comment

I have data set which contains user and purchase data. Here is an example, where first element is userId, second is productId, and third indicate boolean.

(2147481832,23355149,1) (2147481832,973010692,1) (2147481832,2134870842,1) (2147481832,541023347,1) (2147481832,1682206630,1) (2147481832,1138211459,1) (2147481832,852202566,1) (2147481832,201375938,1) (2147481832,486538879,1) (2147481832,919187908,1) ...  

I want to make sure I only take 80% of each users data and build an RDD while take the rest of the 20% and build a another RDD. Lets call train and test. I would like to stay away from using groupBy to start with since it can create memory problem since data set is large. Whats the best way to do this?

I could do following but this will not give 80% of each user.

val percentData = data.map(x => ((math.random * 100).toInt, x._1. x._2, x._3) val train = percentData.filter(x => x._1 < 80).values.repartition(10).cache() 

2 Answers

Answers 1

One possibility is in Holden's answer, and this is another one :

You can use the sampleByKeyExact transformation, from the PairRDDFunctions class.

sampleByKeyExact(boolean withReplacement, scala.collection.Map fractions, long seed) Return a subset of this RDD sampled by key (via stratified sampling) containing exactly math.ceil(numItems * samplingRate) for each stratum (group of pairs with the same key).

And this is how I would do :

Considering the following list :

val list = List((2147481832,23355149,1),(2147481832,973010692,1),(2147481832,2134870842,1),(2147481832,541023347,1),(2147481832,1682206630,1),(2147481832,1138211459,1),(2147481832,852202566,1),(2147481832,201375938,1),(2147481832,486538879,1),(2147481832,919187908,1),(214748183,919187908,1),(214748183,91187908,1)) 

I would create an RDD Pair, mapping all the users as keys :

val data = sc.parallelize(list.toSeq).map(x => (x._1,(x._2,x._3))) 

Then I'll set up fractions for each key as following, since you've noticed that sampleByKeyExact takes a Map of fraction for each key :

val fractions = data.map(_._1).distinct.map(x => (x,0.8)).collectAsMap 

What I have done here is, actually, mapping on the keys to find distinct and then associate each key to a fraction equals to 0.8 then I collect the whole as a Map.

To sample now, all I have to do is :

import org.apache.spark.rdd.PairRDDFunctions val sampleData = data.sampleByKeyExact(false, fractions, 2L) 

or

val sampleData = data.sampleByKeyExact(withReplacement = false, fractions = fractions,seed = 2L) 

You can check the count on your keys or data or data sample :

scala > data.count // [...] // res10: Long = 12  scala > sampleData.count // [...] // res11: Long = 10 

Answers 2

Something like this is may be well suited to something like "Blink DB", but lets look at the question. There are two ways to interpret what you've asked one is:

1) You want 80% of your users, and you want all of the data for them. 2) You want 80% of each users data

For #1 you could do a map to get the user ids, call distinct, and then sample 80% of them (you may want to look at kFold in MLUtils or BernoulliCellSampler). You can then filter your input data to just the set of IDs you want.

For #2 you could look at BernoulliCellSampler and simply apply it directly.

Read More

Retrieve which replica instance was used for mongo query using node.js

Leave a Comment

I use the official node.js mongodb client for performing Mongo queries targeting a cluster via a connection string similar to: mongodb://euwest1-01,euwest1-02,uswest2-01/dbname?replicaSet=mycluster&readPreference=nearest. As you see, I include in my cluster some differently geo-located instances and "nearest" should guarantee the right replica to be picked.

Nevertheless, I would like to know which one was used to perform any query, so that I can include to each of my operations' log the mongo replica that was used to perform the query.

Hacking around the Cursor object, I can get what I want in an hacky way:

const find = (query, callback) => {      let cursor = coll.find(query);     cursor.toArray((err, items) => {       console.log(cursor.server.ismaster.me);       callback(err, items);     }); }; 

But I feel like this can break in any moment as not documented + it seems limited to the Cursor interactions (so I wouldn't know how to achieve the same for a findOne method).

Is anyone aware about a clean way to do this?

2 Answers

Answers 1

I suppose that it is not the best solution, but you can use the .eval() function to create a function which return server_info & result, like this:

db.getCollection('mycollection').eval(function construct(){     var res = db.getCollection('mycollection').find(query);     var explain = res.explain()['server'];     return {'server':explain,'result':res.toArray()}; })() 

which return something like :

{    "server" : "myservernode.mydomain:27017",    "result" : [         // your query results    ] } 

Answers 2

Here are some methods to determine which replica set was used for the query

This documentation might be able to help you.

It specifies how you can tail the oplog of the sharded clusters and can use find to specify which operation is used to modift the data in which cluster

To get the primary server IP you can use the following command line

rs.status().members.find() //add a query or any of your variables 

Documentation referred as here.

Read More

Tuesday, October 18, 2016

Setting an object on req. in the first of two middlwares seems to not be present at the time the second middlware is called

Leave a Comment

I have two express middlwares where one is setting an object to the req and the other that follows it uses that object to turn a switch statement.

Here's an illustration:

module.exports = (req, res, next) => {   if (!req.headers.authorization) {     return res.status(401).end()   }   const token = req.headers.authorization.split(' ')[1]   return jwt.verify(token, config.database.jwtSecret, (err, decoded) => {     if (err) { return res.status(401).end() }      const userId = decoded.sub     return User.findById(userId, (userErr, user) => {       if (userErr || !user) {         return res.status(401).end()       }       req.user = {         _id: user._id,         name: user.name       }       return next()     })   }) }      //My route         userpage.get('/', authCheck, (req, res) => {           return Event.findOne()           .populate('attending.user', 'name')            .exec((err, newEvent) => {             if (err) {               console.log(err)               res.status(400).end()             }             let uids = []             let imAttending = false             newDinner.attending.user.map(obj => {               uids.push(obj._id)               })             console.log(uids) // Shows the array with all uids             // Double checked that it is indeed an array             let isArr = Object.prototype.toString.call(uids) === '[object Array]'             console.log(isArr) // true             console.log(req.user._id) // Shows the id and it's indeed matching one of the ids in the uids array             imAttending = uids.indexOf(req.user._id) > -1             console.log(imAttending)  // false <--- Should be true             // Test             let id = '57ec2203ba3e994c7c9d5832' // I litraly copy pasted that from the console.log(req.user._id)             imAttendingII = uids.indexOf(id) > -1             console.log(imAttendingII) // true ???? what the heck?             // checking it's the same type as suggested in one of the comments             let check = ['57ec2203ba3e994c7c9d5832'].indexOf(req.user._id) === -1             console.log(check) //true           })         }) 

The comments below reassured me that it's not an async issue and following the results I'm getting I'm lost at what it could be.

Edit: The following works though, and shows true. But checking on the _id felds doesn't work even after doing uids.indexOf(req.user._id.toString()) > -1 on the _id element:

newEvent.attending.user.map(obj => {       names.push(obj.name)     })     imAttending = names.indexOf(req.user.name) > -1 // imAttending = true 

2 Answers

Answers 1

Decided to add another answer because of the additional information provided in the question.

It looks like you're using MongoDB and Mongoose (which should be in the tags if I'm right). Given that, a user document's _id property will not be equal to the string form of it, because the representation is actually ObjectID('blahblahblah'), it's not actually a string under the hood. If you console.log() it, it will look like a string because console.log calls toString() under its hood.

So the evaluation you might want to try is:

imAttending = uids.indexOf(req.user._id.toString()) > -1; console.log(imAttending); // should be true 

As a side note, this is also why it's a great reason to use something like node-inspector to set breakpoints and step through your code, rather than relying on console statements to debug. You'll see the actual representation of the various bits, rather than their stringified form.

Answers 2

It was an issue of toString() all along. The results you get back from querying the db are not necessarily the type you think it might be.

Read More

Monday, October 17, 2016

HttpUrlConnection setting Range in Android is ignored

Leave a Comment

I'm trying get a 206 response from my server using Android.

Here's the code.

@Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_splash);     new AsyncTask<Void, Void, Void>() {         @Override         protected Void doInBackground(Void... params) {             try {                 URL url = new URL("http://aviddapp.com/10mb.file");                 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();                 urlConnection.setRequestProperty("Range", "bytes=1-2");                 urlConnection.connect();                  System.out.println("Response Code: " + urlConnection.getResponseCode());                 System.out.println("Content-Length: " + urlConnection.getContentLength());                 Map<String, List<String>> map = urlConnection.getHeaderFields();                 for (Map.Entry<String, List<String>> entry : map.entrySet()) {                     System.out.println("Key : " + entry.getKey() +                             " ,Value : " + entry.getValue());                 }                 InputStream inputStream = urlConnection.getInputStream();                 long size = 0;                  while(inputStream.read() != -1 )                     size++;                  System.out.println("Downloaded Size: " + size);              }catch(MalformedURLException mue) {                 mue.printStackTrace();             }catch(IOException ioe) {                 ioe.printStackTrace();             }             return null;         }     }.execute(); } 

Here's the output:

I/System.out: Respnse Code: 200 I/System.out: Content-Length: -1 I/System.out: Key : null ,Value : [HTTP/1.1 200 OK] I/System.out: Key : Accept-Ranges ,Value : [bytes] I/System.out: Key : Cache-Control ,Value : [max-age=604800, public] I/System.out: Key : Connection ,Value : [Keep-Alive] I/System.out: Key : Date ,Value : [Tue, 04 Oct 2016 07:45:22 GMT] I/System.out: Key : ETag ,Value : ["a00000-53e051f279680-gzip"] I/System.out: Key : Expires ,Value : [Tue, 11 Oct 2016 07:45:22 GMT] I/System.out: Key : Keep-Alive ,Value : [timeout=5, max=100] I/System.out: Key : Last-Modified ,Value : [Tue, 04 Oct 2016 07:36:42 GMT] I/System.out: Key : Server ,Value : [Apache/2.4.12 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4] I/System.out: Key : Transfer-Encoding ,Value : [chunked] I/System.out: Key : Vary ,Value : [Accept-Encoding,User-Agent] I/System.out: Key : X-Android-Received-Millis ,Value : [1475567127403] I/System.out: Key : X-Android-Response-Source ,Value : [NETWORK 200] I/System.out: Key : X-Android-Sent-Millis ,Value : [1475567127183] I/System.out: Downloaded Size: 10485760 

Now I'm doing the same thing is pure java.

public static void main(String... args) {     try {         URL url = new URL("http://aviddapp.com/10mb.file");         HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();         urlConnection.setRequestProperty("Range", "bytes=1-2");         urlConnection.connect();          System.out.println("Respnse Code: " + urlConnection.getResponseCode());         System.out.println("Content-Length: " + urlConnection.getContentLength());         Map<String, List<String>> map = urlConnection.getHeaderFields();         for (Map.Entry<String, List<String>> entry : map.entrySet()) {             System.out.println("Key : " + entry.getKey() +                     " ,Value : " + entry.getValue());         }         InputStream inputStream = urlConnection.getInputStream();         long size = 0;          while(inputStream.read() != -1 )             size++;          System.out.println("Downloaded Size: " + size);      }catch(MalformedURLException mue) {         mue.printStackTrace();     }catch(IOException ioe) {         ioe.printStackTrace();     } } 

Here's the output

Respnse Code: 206 Content-Length: 2 Key : Keep-Alive ,Value : [timeout=5, max=100] Key : null ,Value : [HTTP/1.1 206 Partial Content] Key : Server ,Value : [Apache/2.4.12 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4] Key : Content-Range ,Value : [bytes 1-2/10485760] Key : Connection ,Value : [Keep-Alive] Key : Last-Modified ,Value : [Tue, 04 Oct 2016 07:36:42 GMT] Key : Date ,Value : [Tue, 04 Oct 2016 07:42:17 GMT] Key : Accept-Ranges ,Value : [bytes] Key : Cache-Control ,Value : [max-age=604800, public] Key : ETag ,Value : ["a00000-53e051f279680"] Key : Vary ,Value : [Accept-Encoding,User-Agent] Key : Expires ,Value : [Tue, 11 Oct 2016 07:42:17 GMT] Key : Content-Length ,Value : [2] Downloaded Size: 2 

As you can see I'm getting diffrent response codes in both cases. It seems like Android is not passing Range to the server maybe? What's happening here?

PS: I'm getting a 206 if the file size is 1mb.

4 Answers

Answers 1

I am relatively certain the error is not in the Android code.

It looks like the server might be delivering spurious results.

You can check with a third party tool (such as Postman) to determine the headers that web service is delivering.

My results using Postman. As you can see, it is delivering HTTP 200 (not 206). It is also not wending a capped Content-Length. If the server is yours, perhaps check that it is configured correctly. Also check your code with other servers.

Postman results

Answers 2

Hi Can u try this piece of code, it seems i am getting HTTP 206 here.

new Thread() {             @Override             public void run() {                 try {                     URL url = new URL("http://aviddapp.com/10mb.file");                     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //                    urlConnection.setRequestMethod("HEAD");                     urlConnection.setRequestProperty("Accept-Encoding", "");                      urlConnection.setRequestProperty("Range", "bytes=1-2");                     urlConnection.connect();                      System.out.println("Response Code: " + urlConnection.getResponseCode());                     System.out.println("Content-Length: " + urlConnection.getContentLength());                     Map<String, List<String>> map = urlConnection.getHeaderFields();                     for (Map.Entry<String, List<String>> entry : map.entrySet()) {                         System.out.println("Key : " + entry.getKey() +                                 " ,Value : " + entry.getValue());                     }                     InputStream inputStream = urlConnection.getInputStream();                     long size = 0;                      while (inputStream.read() != -1)                         size++;                      System.out.println("Downloaded Size: " + size);                  } catch (IOException ioe) {                     ioe.printStackTrace();                 }             }         }.start(); 

You just have to add this in async task.

Check this result commenting on/off this line.

urlConnection.setRequestProperty("Accept-Encoding", ""); 

Answers 3

I am not sure if this is related to Content-Length being cleared by android implementation by default. Look at the below snippet from the source code where it says it does gzip compression by default.

https://android.googlesource.com/platform/libcore/+/2e317a02b5a8f9b319488ab9311521e8b4f87a0a/luni/src/main/java/java/net/HttpURLConnection.java

By default, this implementation of HttpURLConnection requests that servers use gzip compression and it automatically decompresses the data for callers of getInputStream(). The Content-Encoding and Content-Length response headers are cleared in this case.

Can you try disabling the default caching using below code to check if that works?

urlConnection.setRequestProperty("Accept-Encoding", "identity");

PS: Sorry for bad formattings. Using the mobile version of SO.

Answers 4

Have you tried like that:

    urlConnection.setRequestProperty("Range", "bytes=1000-"); 
Read More

Docker - no such file or directory

Leave a Comment

I'm receiving an error from docker when I run my docker file. It's saying the /var/lib/docker/aufs/layers/xxxx: no such file or directory when I run Docker build .

I have tried numerous ways to remove containers and images so I'm pretty much stock on this one.

Any

The Docker file is:

FROM node:6  RUN git clone https://github.com/preboot/angular2-webpack.git  WORKDIR angular2-webpack  RUN sed -i.bak 's/--port 8080/--host 0.0.0.0 --port 8080/' package.json RUN npm i  CMD [ "npm", "run", "start" ] 

The complete console output is:

Sending build context to Docker daemon 9.728 kB Step 1 : FROM node:6 6: Pulling from library/node 6a5a5368e0c2: Already exists 7b9457ec39de: Already exists ff18e19c2db4: Already exists 6a3d69edbe90: Already exists 0ce4b037e17f: Already exists 82252a100d5a: Already exists Digest: sha256:db245bde5445eb122d8dc090ba98539a9ef7f56c0ea981ade643695af0d8eaf0 Status: Downloaded newer image for node:6 ---> 9873603dc506 Step 2 : RUN git clone https://github.com/preboot/angular2-webpack.git open /var/lib/docker/aufs/layers/9319fd93cb6d6718243ff2e65ce5d2aa6122a1bb9211aa9f8e88d85c298727e5: no such file or directory User:docker-test  

Edit

The issue was resolved thanks to @BMitchs' recommendation:

  1. rm -rf /var/lib/docker/*
  2. Uninstall Docker completely
  3. re install docker

2 Answers

Answers 1

With that sort of corruption, I'd give a full docker wipe a try, rm -rf /var/lib/docker/*. Before doing that, backup any data (volumes), then shutdown docker, and you'll need to pull or rebuild all your images again. If there are still problems with aufs, try changing the filesystem driver, e.g. changing to dockerd -s overlay2 in your service startup.

It doesn't hurt to check for common issues, like running out of disk space or old version of the application, first.

Answers 2

try building the image again on a clean machine or using the --no-cache flag, this seems like a caching issue.

Also - In my company, we clone the code into the machine building the image, and then copy the code into the container. In my opinion - it's a better solution, but I think it's a matter of taste.

Read More

How to read the json file of a dinamical way in relation to their size structure

Leave a Comment

I have the following JSON file named ProcessedMetrics.json which is necessary read for send their values to some template:

     {   "paciente": {     "id": 1234,     "nombre": "Pablo Andrés Agudelo Marenco",     "sesion": {       "id": 12345,       "juego": [         {           "nombre": "bonzo",           "nivel": [             {               "id": 1234,               "nombre": "caida libre",               "segmento": [                 {                   "id": 12345,                   "nombre": "Hombro",                   "movimiento": [                     {                       "id": 1234,                       "nombre": "flexion",                       "metricas": [                         {                           "min": 12,                           "max": 34,                           "media": 23,                           "moda": 20                         }                       ]                     }                   ]                 }               ],               "___léeme___": "El array 'iteraciones' contiene las vitorias o derrotas con el tiempo en segundos de cada iteración",               "iteraciones": [                 {                   "victoria": true,                   "tiempo": 120                 },                 {                   "victoria": false,                   "tiempo": 232                 }               ]             }           ]         }       ]     }   } } 

Through of the following class based view I am reading a JSON file.

class RehabilitationSessionDetail(LoginRequiredMixin,DetailView):     model = RehabilitationSession     template_name = 'rehabilitationsession_detail.html'      def get_context_data(self, **kwargs):         context=super(RehabilitationSessionDetail, self).get_context_data(**kwargs)         is_auth=False          user = self.request.user         if user.is_authenticated():             is_auth=True              with open('ProcessedMetrics.json') as data_file:                 session_data=json.loads(data_file.read())              #Sending a data to template                        context.update({'is_auth':is_auth,                                        'session_data':session_data                                      })        return context 

In my template rehabilitationsession_detail.html I put my tag of this way:

<td>{{session_data.paciente.sesion.juego}}</td>  

Then I get the document json in my template

enter image description here

In my template, I want get the dictionary(before json document) values of a separate way such as follow:

enter image description here

The idea is that without matter the nested levels of the json document I can get the values. Sometimes, the json document will have more identation levels in their structure and other times will be a json document more simple

I would that independently of the json document size (if this have more than one item in your arrays) will be possible read and get all the values.

I try accessing to the specific item from the RehabilitationSessionDetail view of this way:

segment = data["paciente"]["sesion"]["juego"][0]["nivel"][0]["segmento"][0]["nombre"] 

And this works, but not always I will get the same json document structure.

In summary, How to can I get the values (nested and parents) of my json document for send them to the template?

I hope can be clear in my question. Any orientation is highly graceful

1 Answers

Answers 1

If I understand correctly from your question, with different JSON sizes you mean different array sizes? You can loop in the django template to get all the information out. So you would do for a nested visualisation:

{% for nest1 in data["patiente"]["sesion"]["juego"] %} <li>{{ nest1["nombre"] }}</li> {% for nest2 in nest2["nivel"] %} etc... {% endfor %} {% endfor %} 

To get it as a table you would seperate the data and make a loop for each table column

<tr>     {% for nest1 in data["patiente"]["sesion"]["juego"] %}     <td>{{ nest1["nombre"] }}</td>     {% endfor %} </tr>  <tr>     {% for nest1 in data["patiente"]["sesion"]["juego"] %}     {% for nest2 in nest2["nivel"] %}     <td>{{ nest2["relevant_key"] }}</td>     {% endfor %}     {% endfor %} </tr> etc... 

because of the nested json data representation you template code will have to follow this nesting.

Hope I understood your question correctly and hope this helps.

Read More

Facebook API Error: “User does not have sufficient administrative permission for this action on this page.”

Leave a Comment

I'm using a Facebook app (in development mode) to generate a page access token so that my personal web app can schedule/edit/delete posts on a Facebook fan page.

I'm using the Graph Explorer to generate the token while logged in as the admin of the fan page.

When I use that token, I'm able to GET a list of the scheduled posts, but whenever I try to edit or delete a post, I get this error:

"User does not have sufficient administrative permission for this action on this page."

Here is the debug of the token:

enter image description here

Any ideas on how to fix this?

1 Answers

Answers 1

Here according to the documentation

DELETING YOUR POST

These are the permissions you need in the scope of your token.

  • To delete a user's post, a user access token with publish_actions permission is required.
  • To delete a Page's post a Page access token and publish_pages permission is required.
  • To delete a User's post on Page a Page access token is required.
  • To delete another User's post on a Page-owned event the user_managed_groups permission is required.

UPDATING YOUR POST

  • A user access token with publish_actions permission.

SO you need publish_actions permission within the scope of your token.

Read More

Sunday, October 16, 2016

How to display image in large size onmouseover inside a dynamic div

Leave a Comment

I am trying to make a simple photo gallery in angularJS. Below is the code

index.html

<!DOCTYPE html> <html > <head>      <title></title>       <script src="http://code.angularjs.org/1.2.0rc1/angular.js"></script>     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>     <script src="test.js"></script>  </head> <body ng-app="testModule" ng-controller="testCtrl">     <div style="width: 60%; margin: 0 auto;">                  <div id="dp"></div>     </div>  </body> </html> 

test.js (Controller)

function testMe(imgSrc) {     alert(imgSrc); }  angular     .module('testModule', [])     .controller('testCtrl', function($scope) {         var photoSource = [             ["images/ph1.jpg", "images/ph2.jpg"],             ["images/ph5.jpg", "images/ph6.jpg"]         ];         var body = "<table>";         var row = 2;         var col = 2;         for (var i = 0; i < row; i++) {             body += "<tr>";             for (var j = 0; j < col; j++) {                 body += "<td> <img id='" + i + j + "' src='" + photoSource[i][j] + "' onmouseover=testMe('" + photoSource[i][j] + "');></td>";             }             body += "</tr>";         }         body += "</table>";         console.log(body);         $("#dp").html(body);     }); 

The problem is that, when the mouse is over an image I want to display that image in the center on a div tag. But this portion I could not achieve.

Please help me

4 Answers

Answers 1

you don't need to manipulate the html inside your controller instead use bindings of angular so your javascript becomes

function testMe(imgSrc) {          alert(imgSrc);      }   angular .module('testModule', []) .controller('testCtrl', function ($scope) {      $scope.photoSource = [                     [ "images/ph1.jpg","images/ph2.jpg"],                     [ "images/ph5.jpg","images/ph6.jpg"]                                    ];       $scope.showFullImage = function(photoSrc) {       // this function will call when you mouseover so add logic here and photosrc will be current mouseover image src        } }); 

now in your html use this photoSource scope variable to generate table

<body ng-app="testModule" ng-controller="testCtrl">     <div style="width: 60%; margin: 0 auto;">                  <div id="dp"> <table>  <tr ng-repeat="photos in photoSource">   <td ng-repeat="photo in photos">     <img ng-src="{{photo}}" ng-mouseover="showFullImage(photo)" />   </td>  </tr> </table> </div>     </div>  </body> 

Answers 2

Two Way Data-Binding is a most useful feature of AngularJS, so u do not need write so many logic in js.

Try this:

angular.module('testModule', []).controller('testCtrl', function ($scope) {     $scope.photoSource = [         [ "images/ph1.jpg","images/ph2.jpg"],         [ "images/ph5.jpg","images/ph6.jpg"]      ];     $scope.fullImage = function (imgSrc) {         $scope.showImage = imgSrc;     } }); 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="testModule" ng-controller="testCtrl">     <div style="width: 60%; margin: 0 auto;">         <div id="ds">             <img ng-src="{{showImage}}"/>         </div>         <div id="dp" style="display: flex;">             <div ng-repeat="photos in photoSource">                 <img class="item" ng-src="{{photo}}" ng-mouseover="fullImage(photo)" ng-repeat="photo in photos" style="max-width: 100%"/>             </div>         </div>     </div> </body> 

Answers 3

This is the logic I would use to solve this problem. I am assuming you want the hovered item to be shown within a modal dialog box or a centered div on the page.

  1. Keep a div with required centering CSS (margin-left, margin-right: auto) hidden using a boolean say isVisible, set to false in your controller.

  2. Keep an empty image tag within this container. You can change the image src using ng-src based on a variable. Keep this variable source pointing to a placeholder image. We will later update this when the user hovers over an image.

  3. Using ng-mouseover call a function and pass the image source to the function as a parameter

  4. Within this function, use the image source to set the source of the placeholder image

  5. Show the hidden div by setting the flag, isVisible to true

  6. You will also need to handle mouse-out since the container will need to be hidden once the user hovers out of the image.

Some points to keep in mind when working with Angular JS:

  1. Do not use jQuery for DOM manipulation. You can show or hide content using ng-show/ng-hide or add/remove classes using ng-class directives. Also ng-if can actually render or remove content when needed.

  2. Do not dynamically insert HTML into the page. If you absolutely need to do this, use a custom directive.

Answers 4

I can't write all of the code but you can see this small video I hope it would be helpful

Read More

Make ServletContextListener spring aware

Leave a Comment

I am plugging in Spring to existing Java EE web Application. I have following lines in my web.xml:

<listener>     <listener-class>com.MyContextListener</listener-class> </listener>  

And Following MyContextListener class?

public class MyContextListener implements ServletContextListener {      public void contextInitialized(ServletContextEvent event) {        //...     } } 

What should I do to make MyContextListener be managed by Spring?


Edited:

My assumption is: Spring should create all servlets and all web app infrastructure so everything happened in contextInitialized method of MyContextListener should be somehow handled by Spring. How can I achieve, by implementing some interface I suppose. Correct me if I am wrong. Thanks!

4 Answers

Answers 1

What should I do to make MyContextListener be managed by Spring?

It depends on which configuration way you are using. Anyway, you should tell directly Spring to use the class you have declared. That could be done by the following way:

@WebListener public class MyContextListener implements ServletContextListener { ... } 

A class marked with this annotation (the Servlet 3.0 specification, 8.1.4) must implement one of these interfaces

HttpSessionAttributeListener HttpSessionListener ServletContextAttributeListener ServletContextListener (+) ServletRequestAttributeListener ServletRequestListener HttpSessionIdListener 

that it actually does.

Personally, I prefer a meta-annotation based approach which makes my configuration shorter and more concise.

Spring should create all servlets and all web app infrastructure so everything happened in contextInitialized method of MyContextListener should be somehow handled by Spring.

Yes, Spring will do it for you if you provide some information which could help it to register / configure / create / manage an instance.

The information may be either meta-information (a template that tells how to create an instance, like BeanDefinitions) or a completed instance itself (usually, it gets passed programmatically that, in turn, leads to writing a huge amount of code).

How can I achieve, by implementing some interface I suppose.

You are implementing an interface to make your listener a listener (a class that describes specific methods which will be called at some points of time). Spring, itself, is responsible for guaranteeing such calls at those points of time, placing an object in the existing web infrastructure before.

Answers 2

Annotate where you create a new instance of MyContextListener with @Bean if using Java Configs with Spring Boot.

Answers 3

Either annotate the class with @WebListener or the method with @Bean

Answers 4

Well,

We had a similar scenario of configuring an exiting Jersey web services app to use Spring for dependency injection. Our Jersey webapp had extended ContextLoaderListener as follow

public class XServletContextListener extends ContextLoaderListener {     ...      @Override     public void contextInitialized(ServletContextEvent arg0) {         super.contextInitialized(arg0);         ....     }      @Override     public void contextDestroyed(ServletContextEvent arg0) {         super.contextDestroyed(arg0);         ....     } }  

where ContextLoaderListener is

import org.springframework.web.context.ContextLoaderListener; 

We included the jersey-spring bridge with all spring dependencies including applicationContext.xml as follow

<beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:context="http://www.springframework.org/schema/context"     xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd     http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-4.0.xsd">      <context:component-scan base-package="com.xxx.*" />     ....     .... </beans> 

And obviously needed to make sure that XServletContextListener is included in the web.xml as follow

<context-param>     <param-name>contextConfigLocation</param-name>     <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener>     <listener-class>com.xxx.**.XServletContextListener</listener-class> </listener> 

Followed by servlet and its init-param values and servlet mapping. You can obviously adopt annotation config in place of xml confib in which case you would need to use WebListener annotation.

We use a variety of annotations such as

@Component for objects @Service for services  @Repository for DAOs @Controller for controllers/resources  @ContextConfiguration for tests 

Everything is loaded and autowired by Spring framework.

Read More

Friday, October 14, 2016

AWS MQTT on OSX

Leave a Comment

In the OSX app here, I can use AWS MQTT with iOS9, but when I try the same with OSX10.11, I get this error:

CFNetwork SSLHandshake failed (-9829)

Error -9828 is defined as

errSSLPeerCertUnknown = -9829, /* unknown certificate */

My OSX info.plist is

<key>NSAppTransportSecurity</key>     <dict>             <key>NSAllowsArbitraryLoads</key>             <true/>             <key>NSExceptionDomains</key>             <dict>                     <key>amazonaws.com</key>                     <dict>                             <key>NSExceptionRequiresForwardSecrecy</key>                             <false/>                             <key>NSExceptionAllowsInsecureHTTPLoads</key>                             <true/>                             <key>NSThirdPartyExceptionMinimumTLSVersion</key>                             <string>TLSv1.0</string>                             <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>                             <false/>                             <key>NSIncludesSubdomains</key>                             <true/>                     </dict>                     <key>amazonaws.com.cn</key>                     <dict>                             <key>NSExceptionRequiresForwardSecrecy</key>                             <false/>                             <key>NSExceptionAllowsInsecureHTTPLoads</key>                             <true/>                             <key>NSThirdPartyExceptionMinimumTLSVersion</key>                             <string>TLSv1.0</string>                             <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>                             <false/>                             <key>NSIncludesSubdomains</key>                             <true/>                     </dict>             </dict>     </dict> 

The p12 (from "openssl pkcs12 -info -in awsiot-identity.p12") is:

MAC Iteration 2048 MAC verified OK PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048 Certificate bag Bag Attributes     localKeyID: 5F 80 DC 6E AB F1 98 6A AA FC 0B 7B 04 F9 0E 66 99 E9 86 4F  subject=/CN=AWS IoT Certificate issuer=/OU=Amazon Web Services O=Amazon.com Inc. L=Seattle ST=Washington C=US -----BEGIN CERTIFICATE----- MIIDWTCCAkGgAwIBAgIUJQgfGjmoboOQ7eJo+NTRs5wr8KMwDQYJKoZIhvcNAQEL BQAwTTFLMEkGA1UECwxCQW1hem9uIFdlYiBTZXJ2aWNlcyBPPUFtYXpvbi5jb20g SW5jLiBMPVNlYXR0bGUgU1Q9V2FzaGluZ3RvbiBDPVVTMB4XDTE2MDcyNTA2NDU0 NloXDTQ5MTIzMTIzNTk1OVowHjEcMBoGA1UEAwwTQVdTIElvVCBDZXJ0aWZpY2F0 ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK57RCK3ppDk22TPA+97 2coZeo36lJpZ9M/0l6xHyeQiiVZMKGrkP3S+ej4Dgd+q4gviB2g5dc9T6jMwRSA8 qkdadxspSmEtCCwdFY3poVOpsD7Z0s3lVwBSgTiztfQo15yTyIjhkS0gS9tBg1sI xIJoYuxXEHkoJKHum8yaluL71jYLxdmp5YHGVHZ55ussZUrWuE4ut4EbHJ8+Ef+z caJtJB6YMEeKpKMvZ0vrb+jHytD6s7K20SnfTvEHsXNwWIfwXsxmqkG9KHT7q9Dd XlaeKiP0tWE/8ObOPk1W7xT9HTAvkrveJIEFYhMcfi0yTtxm9CyEG0p36yor2HAK T/UCAwEAAaNgMF4wHwYDVR0jBBgwFoAU8Kei7lBQZkzRV3if5sWxgF9WtM8wHQYD VR0OBBYEFM7oRgS5iXeFPcI4pzY/0BQCCE3mMAwGA1UdEwEB/wQCMAAwDgYDVR0P AQH/BAQDAgeAMA0GCSqGSIb3DQEBCwUAA4IBAQBDzKiP+Gldz4RUe0QyMcYDWS0V /3PeJTRjoD7IxUOO9czCZoCX46dxJkP1ijzuuqneaEPK7OUQxoHepqPdlbsycXv3 i/Ty649c/d2dizYqO2iM+6M+xdDLYPBmEAD4aQ9Qj8TpnC5OCSdqGq9XCFLTnz4j icx2lYS3COdfZbKs9KQG7dkPK7CWSjHHy21Ftz0zBx7wj5v+2lNbcHCFmYn9+lYg Jw1zUR/rGqTcQZHGUvgv3Mfp8xWtHDFhYAKnwGbhIxCanOM6An+yzEwLUEvkQ81Q Lzv/yReCVHO4M0+JTW4Fu6BWEaTThPzdN3kQbIzJsViIL9Q6dfAXlvepkHr4 -----END CERTIFICATE----- PKCS7 Data Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048 Bag Attributes     localKeyID: 5F 80 DC 6E AB F1 98 6A AA FC 0B 7B 04 F9 0E 66 99 E9 86 4F  Key Attributes: <No Attributes> 

Why does OSX fail but iOS succeed?

2 Answers

Answers 1

It is failing because of an SSL handshake issue. It is detecting an invalid certificate.

A similar issue was reported and resolved here, referencing the same error code. That issue was traced to an identity mismatch, due to multiple identities in the p12 file.

In that case, there were two certificates in the p12 files, but the code was only reading the first one.

I suggest dumping the contents of the .p12 file, and confirming the certificates(s). Post them here to review.

Answers 2

you missing signing CA on your OS X for the certificate, depends on how your created your certificate, you need to import the CA into your keychain. refer here

Read More

Thursday, October 13, 2016

Responsive pre tag

Leave a Comment

I simply want to show terminal output on a Webpage. Atm I'm using a pre tag to do that with pre { white-space: pre-wrap; } as you can see upon http://irc.dabase.com/.

My problem is that when I rotate my iPhone6 IOS device, it often doesn't reformat properly. Why is this? Can you offer some good CSS rules to make this use case of showing terminal output on a Webpage better?

Unresponsive pre tag

3 Answers

Answers 1

You can try this to achieve -

pre {     white-space: pre-line;     word-wrap: break-word; } 

Answers 2

pre {   white-space: pre-line;   word-wrap: break-word;   text-align: justify; } 

You Can Try It Once

Answers 3

pre {   white-space: pre-wrap;   word-wrap: break-word;   text-align: justify; } 

Here are the rules you need explained step by step:

Select all pre elements (set this to pre#yourID or pre.yourClass to select a specific pre)

pre { 

Allow pre to wrap at word breaks and line breaks. Unlike pre-line, pre-wrap will not modify your terminal output at all. pre-line will modify your terminal output by condensing whitespace into one whitespace which could make finding exact phrases difficult or mess with whitespace column formatting! See here

  white-space: pre-wrap; 

Make sure that words that go past the end of the element break off instead of being hidden (like links for examples)

  word-wrap: break-word; 

This part is optional Justify the text so that it fully fills the line. Spaces become wider but their number is not increased.

  text-align: justify;  } 

Optionally, this rule can be fit into a media-query so that it only applies in the mobile version. But I believe there is no harm in applying this rule to all screen sizes by simply omitting a media-query.

In the event that the wider version of your iphone makes your pre rule stop working, you should check to see if there isn't already a media-query in place that is applying a rule to the pre when the screen reaches a certain size.

You can also try intentionally creating a media-query for the wider version, which may re-initialize the styles if there is some kind of bug going on.

For example:

Include rule that applies to smallest possible version

pre {   white-space: pre-wrap;   word-wrap: break-word;   text-align: justify; } 

Then include another rule to re-initialize rule at landscape orientation

@media all and (orientation:landscape)     pre {         white-space: pre-wrap;         word-wrap: break-word;         text-align: justify;     } } 
Read More

Tuesday, October 11, 2016

Alamofire 4 and special characters in JSON

Leave a Comment

I've got a problem with special characters with Alamofire 4.
The JSON contains æ, ø and å and the browser shows them fine, also my previous solution using SwiftyJSON did.

Alamofire 4 shows something like this instead:

U00e6 

Using this call:

Alamofire.request(specificURL, method: .get, parameters: param, encoding: URLEncoding.default, headers: nil).responseJSON { (response: DataResponse<Any>) in     print(response) } 

What to do to solve this?

4 Answers

Answers 1

Edit:

Alamofire.request(url, method: .get, parameters: param, encoding: JSONEncoding.default)         .responseJSON { response in              switch response.result {             case .success(let value) :                  print(response.request)  // original URL request                 print(response.response) // HTTP URL response                 print(response.data)     // server data                 print(response.result)   // result of response serialization                  if let JSON = response.result.value as! [String:AnyObject]!{                     print("JSON: ",JSON)                     self.arrUser = Mapper<Users>().mapArray(JSONArray:JSON["user"] as! [[String : Any]])!                     self.tableView.reloadData()                 }             case .failure(let encodingError):                 //Print error             }     } 

I got the issue that I have added æ in json response and try to print.

Output:

JSON:  Optional(<__NSArrayI 0x600000050320>( {     "email_address" = "testwts06@gmail.com";      username = "testwts06 \U00e6"; }, {     "email_address" = "testwts01@gmail.com";     username = "testwts01 \U00eb"; }, {     "email_address" = "testwts100@gmail.com";     username = testwts100; }) 

While displaying it display in correct format.

image

Answers 2

Swift 3 update for Ekta's answer:

let encodedURL = specificURL.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) 

Answers 3

Seems the typical serialization error due to wrong JSON encoding, probably your response status code is 3840.

JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32.

You could try to convert the response data to correct UTF8 encoding:

let datastring = NSString(data: response.data!, encoding: String.Encoding.isoLatin1.rawValue) let data = datastring!.data(using: String.Encoding.utf8.rawValue) do {      let object = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)      let jsonDic = object as! NSDictionary      print("  ok, successfully converted..\(jsonDic)") } catch let aError as Error {      // print and handle aError  } 

Hope it helps you.

Answers 4

Here is a simple String extension that solves the issue:

extension String {     func fixUnicode() -> String {         var copy = self as NSString         let regex = try! NSRegularExpression(pattern: "\\\\U([A-Z0-9]{4})", options: .caseInsensitive)         let matches = regex.matches(in: self, options: [], range: NSMakeRange(0, characters.count)).reversed()         matches.forEach {             let char = copy.substring(with: $0.rangeAt(1))             copy = copy.replacingCharacters(in: $0.range, with: String(UnicodeScalar(Int(char, radix: 16)!)!)) as NSString         }         return copy as String     } } 
Read More

Swift / SKStoreProductViewController pushViewController results in (lldb)

Leave a Comment

To push the user to the iTunes store for desired items I'm using the following function:

func openStoreProductWithiTunesItemIdentifier(identifier: String) {      let storeViewController = SKStoreProductViewController()     storeViewController.delegate = self      let parameters = [ SKStoreProductParameterITunesItemIdentifier : identifier, SKStoreProductParameterAffiliateToken : ITUNES_AFFILIATE_ID]     storeViewController.loadProductWithParameters(parameters) { [weak self] (loaded, error) -> Void in         if loaded {              self!.navigationController?.pushViewControllerWithHandler(storeViewController, animated: true) {                  LilithProgressHUD.hide() // custom progress hud             }         }     } }  extension UINavigationController {      func pushViewControllerWithHandler(viewController: UIViewController, animated: Bool, completion: Void -> Void) {          CATransaction.begin()         CATransaction.setCompletionBlock(completion)         pushViewController(viewController, animated: animated)         CATransaction.commit()     } } 

Called by

let trackID = "thisIsMyTrackID" openStoreProductWithiTunesItemIdentifier(trackID) 

This results in

enter image description here enter image description here enter image description here

If I'm instead of:

self!.navigationController?.pushViewControllerWithHandler(storeViewController, animated: true) {              LilithProgressHUD.hide() // custom progress hud         } 

Using:

self?.presentViewController(storeViewController, animated: true, completion: {             LilithProgressHUD.hide() // custom progress hud         }) 

, it is working. But I need the controller to push within the navigationController to fit the rest of the views and animations. What am I missing? Help is very appreciated.

Backtrace as requested:

    (lldb) bt all * thread #1: tid = 0x9bb48, 0x000000018fcac524 libobjc.A.dylib`objc_exception_throw, queue = 'com.apple.main-thread', stop reason = breakpoint 1.2     frame #0: 0x000000018fcac524 libobjc.A.dylib`objc_exception_throw     frame #1: 0x0000000191274108 CoreFoundation`+[NSException raise:format:] + 116     frame #2: 0x000000019dca04d0 StoreKit`-[SKStoreProductViewController _throwUnsupportedPresentationException] + 76     frame #3: 0x000000019dc9ed24 StoreKit`-[SKStoreProductViewController willMoveToParentViewController:] + 108     frame #4: 0x0000000197159174 UIKit`-[UIViewController _addChildViewController:performHierarchyCheck:notifyWillMove:] + 568     frame #5: 0x000000019714f580 UIKit`-[UINavigationController pushViewController:transition:forceImmediate:] + 1220     frame #6: 0x000000019714f06c UIKit`-[UINavigationController pushViewController:animated:] + 652   * frame #7: 0x00000001000a32f4 cya`UINavigationController.pushViewControllerWithHandler(viewController=0x00000001028ae9c0, animated=true, completion=0x00000001000a35c4 cya`partial apply forwarder for reabstraction thunk helper from @callee_unowned @convention(block) () -> (@unowned ()) to @callee_owned () -> (@unowned ()) with unmangled suffix ".16" at UINavigationControllerExtensions.swift, self=0x0000000103844600) -> ()) -> () + 504 at UINavigationControllerExtensions.swift:24     frame #8: 0x00000001000a3578 cya`@objc UINavigationController.pushViewControllerWithHandler(UIViewController, animated : Bool, completion : () -> ()) -> () + 196 at UINavigationControllerExtensions.swift:0     frame #9: 0x00000001001b04f4 cya`DJProfileAsUserMusicTableVC.(loaded=true, error=nil, self=0x0000000102a358d0, storeViewController=0x00000001028ae9c0) -> ()).(closure #1) + 416 at DJProfileAsUserMusicTableVC.swift:697     frame #10: 0x00000001001b0654 cya`thunk + 56 at DJProfileAsUserMusicTableVC.swift:0     frame #11: 0x00000001001b0714 cya`thunk + 36 at DJProfileAsUserMusicTableVC.swift:0     frame #12: 0x00000001001b0804 cya`thunk + 80 at DJProfileAsUserMusicTableVC.swift:0     frame #13: 0x000000019dc9fb84 StoreKit`-[SKStoreProductViewController _loadDidFinishWithResult:error:] + 92     frame #14: 0x000000019127a160 CoreFoundation`__invoking___ + 144     frame #15: 0x000000019116dc3c CoreFoundation`-[NSInvocation invoke] + 284     frame #16: 0x0000000192e158bc FrontBoardServices`__FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 36     frame #17: 0x0000000192e15728 FrontBoardServices`-[FBSSerialQueue _performNext] + 176     frame #18: 0x0000000192e15ad0 FrontBoardServices`-[FBSSerialQueue _performNextFromRunLoopSource] + 56     frame #19: 0x0000000191222278 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24     frame #20: 0x0000000191221bc0 CoreFoundation`__CFRunLoopDoSources0 + 524     frame #21: 0x000000019121f7c0 CoreFoundation`__CFRunLoopRun + 804     frame #22: 0x000000019114e048 CoreFoundation`CFRunLoopRunSpecific + 444     frame #23: 0x0000000192bd1198 GraphicsServices`GSEventRunModal + 180     frame #24: 0x0000000197128628 UIKit`-[UIApplication _run] + 684     frame #25: 0x0000000197123360 UIKit`UIApplicationMain + 208     frame #26: 0x000000010020c08c cya`main + 144 at AppDelegate.swift:19     frame #27: 0x00000001901305b8 libdyld.dylib`start + 4    thread #3: tid = 0x9bbc9, 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #0: 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #1: 0x0000000190305188 libsystem_pthread.dylib`_pthread_wqthread + 968     frame #2: 0x0000000190304db4 libsystem_pthread.dylib`start_wqthread + 4    thread #4: tid = 0x9bbca, 0x0000000190304db0 libsystem_pthread.dylib`start_wqthread     frame #0: 0x0000000190304db0 libsystem_pthread.dylib`start_wqthread    thread #7: tid = 0x9bbdc, 0x0000000190242314 libsystem_kernel.dylib`__semwait_signal + 8, name = 'gputools.smt_poll.0x17403cde0'     frame #0: 0x0000000190242314 libsystem_kernel.dylib`__semwait_signal + 8     frame #1: 0x000000019016027c libsystem_c.dylib`nanosleep + 212     frame #2: 0x000000019016019c libsystem_c.dylib`usleep + 64     frame #3: 0x00000001025adeb0 GPUToolsCore`smt_poll_thread_entry(void*) + 136     frame #4: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #5: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #6: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #8: tid = 0x9bbef, 0x0000000190242314 libsystem_kernel.dylib`__semwait_signal + 8, name = 'gputools.smt_poll.0x170220020'     frame #0: 0x0000000190242314 libsystem_kernel.dylib`__semwait_signal + 8     frame #1: 0x000000019016027c libsystem_c.dylib`nanosleep + 212     frame #2: 0x000000019016019c libsystem_c.dylib`usleep + 64     frame #3: 0x00000001025adeb0 GPUToolsCore`smt_poll_thread_entry(void*) + 136     frame #4: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #5: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #6: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #9: tid = 0x9bbf4, 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8, name = 'com.apple.uikit.eventfetch-thread'     frame #0: 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8     frame #1: 0x0000000190223fdc libsystem_kernel.dylib`mach_msg + 72     frame #2: 0x0000000191221cec CoreFoundation`__CFRunLoopServiceMachPort + 192     frame #3: 0x000000019121f908 CoreFoundation`__CFRunLoopRun + 1132     frame #4: 0x000000019114e048 CoreFoundation`CFRunLoopRunSpecific + 444     frame #5: 0x0000000191c5cb1c Foundation`-[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 304     frame #6: 0x0000000191c7d60c Foundation`-[NSRunLoop(NSRunLoop) runUntilDate:] + 96     frame #7: 0x0000000197a9dc7c UIKit`-[UIEventFetcher threadMain] + 136     frame #8: 0x0000000191d5a50c Foundation`__NSThread__start__ + 1024     frame #9: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #10: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #11: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #12: tid = 0x9bbfb, 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8, name = 'com.apple.NSURLConnectionLoader'     frame #0: 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8     frame #1: 0x0000000190223fdc libsystem_kernel.dylib`mach_msg + 72     frame #2: 0x0000000191221cec CoreFoundation`__CFRunLoopServiceMachPort + 192     frame #3: 0x000000019121f908 CoreFoundation`__CFRunLoopRun + 1132     frame #4: 0x000000019114e048 CoreFoundation`CFRunLoopRunSpecific + 444     frame #5: 0x000000019193bcec CFNetwork`+[NSURLConnection(Loader) _resourceLoadLoop:] + 336     frame #6: 0x0000000191d5a50c Foundation`__NSThread__start__ + 1024     frame #7: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #8: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #9: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #14: tid = 0x9bbfd, 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8, name = 'AVAudioSession Notify Thread'     frame #0: 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8     frame #1: 0x0000000190223fdc libsystem_kernel.dylib`mach_msg + 72     frame #2: 0x0000000191221cec CoreFoundation`__CFRunLoopServiceMachPort + 192     frame #3: 0x000000019121f908 CoreFoundation`__CFRunLoopRun + 1132     frame #4: 0x000000019114e048 CoreFoundation`CFRunLoopRunSpecific + 444     frame #5: 0x00000001aa8f1fe8 AVFAudio`GenericRunLoopThread::Entry(void*) + 164     frame #6: 0x00000001aa917f14 AVFAudio`CAPThread::Entry(CAPThread*) + 84     frame #7: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #8: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #9: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #17: tid = 0x9bc0f, 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8, name = 'com.squareup.SocketRocket.NetworkThread'     frame #0: 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8     frame #1: 0x0000000190223fdc libsystem_kernel.dylib`mach_msg + 72     frame #2: 0x0000000191221cec CoreFoundation`__CFRunLoopServiceMachPort + 192     frame #3: 0x000000019121f908 CoreFoundation`__CFRunLoopRun + 1132     frame #4: 0x000000019114e048 CoreFoundation`CFRunLoopRunSpecific + 444     frame #5: 0x0000000191c5cb1c Foundation`-[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 304     frame #6: 0x00000001003f57ec cya`-[_FSRRunLoopThread main](self=0x00000001740918f0, _cmd=<unavailable>) + 252 at FSRWebSocket.m:1838     frame #7: 0x0000000191d5a50c Foundation`__NSThread__start__ + 1024     frame #8: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #9: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #10: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #18: tid = 0x9bc21, 0x000000019024223c libsystem_kernel.dylib`__select + 8, name = 'com.apple.CFSocket.private'     frame #0: 0x000000019024223c libsystem_kernel.dylib`__select + 8     frame #1: 0x0000000191228b84 CoreFoundation`__CFSocketManager + 640     frame #2: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #3: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #4: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #19: tid = 0x9bc70, 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #0: 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #1: 0x000000019030536c libsystem_pthread.dylib`_pthread_wqthread + 1452     frame #2: 0x0000000190304db4 libsystem_pthread.dylib`start_wqthread + 4    thread #20: tid = 0x9bc77, 0x0000000190304db0 libsystem_pthread.dylib`start_wqthread     frame #0: 0x0000000190304db0 libsystem_pthread.dylib`start_wqthread    thread #21: tid = 0x9bc78, 0x0000000000000000     frame #0: 0x0000000000000000 (lldb) 

Backtrace without exception breakpoint:

(lldb) bt all warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available. * thread #1: tid = 0x9c221, 0x0000000190242014 libsystem_kernel.dylib`__pthread_kill + 8, queue = 'com.apple.main-thread', stop reason = signal SIGABRT     frame #0: 0x0000000190242014 libsystem_kernel.dylib`__pthread_kill + 8     frame #1: 0x0000000190309460 libsystem_pthread.dylib`pthread_kill + 112     frame #2: 0x00000001901b63f4 libsystem_c.dylib`abort + 140     frame #3: 0x000000018fc812d4 libc++abi.dylib`abort_message + 132     frame #4: 0x000000018fc9ecc0 libc++abi.dylib`default_terminate_handler() + 304     frame #5: 0x000000018fcac844 libobjc.A.dylib`_objc_terminate() + 124     frame #6: 0x000000018fcac844 libobjc.A.dylib`_objc_terminate() + 124     frame #7: 0x000000018fc9b66c libc++abi.dylib`std::__terminate(void (*)()) + 16     frame #8: 0x000000018fc9b234 libc++abi.dylib`__cxa_rethrow + 144     frame #9: 0x000000018fcac71c libobjc.A.dylib`objc_exception_rethrow + 44     frame #10: 0x000000019114e0bc CoreFoundation`CFRunLoopRunSpecific + 560     frame #11: 0x0000000192bd1198 GraphicsServices`GSEventRunModal + 180     frame #12: 0x0000000197128628 UIKit`-[UIApplication _run] + 684     frame #13: 0x0000000197123360 UIKit`UIApplicationMain + 208   * frame #14: 0x00000001001e408c cya`main + 144 at AppDelegate.swift:19     frame #15: 0x00000001901305b8 libdyld.dylib`start + 4    thread #5: tid = 0x9c29d, 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #0: 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #1: 0x000000019030536c libsystem_pthread.dylib`_pthread_wqthread + 1452     frame #2: 0x0000000190304db4 libsystem_pthread.dylib`start_wqthread + 4    thread #7: tid = 0x9c2a7, 0x0000000190242314 libsystem_kernel.dylib`__semwait_signal + 8, name = 'gputools.smt_poll.0x174036a80'     frame #0: 0x0000000190242314 libsystem_kernel.dylib`__semwait_signal + 8     frame #1: 0x000000019016027c libsystem_c.dylib`nanosleep + 212     frame #2: 0x000000019016019c libsystem_c.dylib`usleep + 64     frame #3: 0x000000010257deb0 GPUToolsCore`smt_poll_thread_entry(void*) + 136     frame #4: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #5: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #6: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #8: tid = 0x9c2b2, 0x0000000190242314 libsystem_kernel.dylib`__semwait_signal + 8, name = 'gputools.smt_poll.0x1740366c0'     frame #0: 0x0000000190242314 libsystem_kernel.dylib`__semwait_signal + 8     frame #1: 0x000000019016027c libsystem_c.dylib`nanosleep + 212     frame #2: 0x000000019016019c libsystem_c.dylib`usleep + 64     frame #3: 0x000000010257deb0 GPUToolsCore`smt_poll_thread_entry(void*) + 136     frame #4: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #5: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #6: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #9: tid = 0x9c2b6, 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8, name = 'com.apple.uikit.eventfetch-thread'     frame #0: 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8     frame #1: 0x0000000190223fdc libsystem_kernel.dylib`mach_msg + 72     frame #2: 0x0000000191221cec CoreFoundation`__CFRunLoopServiceMachPort + 192     frame #3: 0x000000019121f908 CoreFoundation`__CFRunLoopRun + 1132     frame #4: 0x000000019114e048 CoreFoundation`CFRunLoopRunSpecific + 444     frame #5: 0x0000000191c5cb1c Foundation`-[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 304     frame #6: 0x0000000191c7d60c Foundation`-[NSRunLoop(NSRunLoop) runUntilDate:] + 96     frame #7: 0x0000000197a9dc7c UIKit`-[UIEventFetcher threadMain] + 136     frame #8: 0x0000000191d5a50c Foundation`__NSThread__start__ + 1024     frame #9: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #10: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #11: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #10: tid = 0x9c2b7, 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #0: 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #1: 0x000000019030536c libsystem_pthread.dylib`_pthread_wqthread + 1452     frame #2: 0x0000000190304db4 libsystem_pthread.dylib`start_wqthread + 4    thread #12: tid = 0x9c2bf, 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8, name = 'com.apple.NSURLConnectionLoader'     frame #0: 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8     frame #1: 0x0000000190223fdc libsystem_kernel.dylib`mach_msg + 72     frame #2: 0x0000000191221cec CoreFoundation`__CFRunLoopServiceMachPort + 192     frame #3: 0x000000019121f908 CoreFoundation`__CFRunLoopRun + 1132     frame #4: 0x000000019114e048 CoreFoundation`CFRunLoopRunSpecific + 444     frame #5: 0x000000019193bcec CFNetwork`+[NSURLConnection(Loader) _resourceLoadLoop:] + 336     frame #6: 0x0000000191d5a50c Foundation`__NSThread__start__ + 1024     frame #7: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #8: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #9: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #14: tid = 0x9c2c3, 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8, name = 'AVAudioSession Notify Thread'     frame #0: 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8     frame #1: 0x0000000190223fdc libsystem_kernel.dylib`mach_msg + 72     frame #2: 0x0000000191221cec CoreFoundation`__CFRunLoopServiceMachPort + 192     frame #3: 0x000000019121f908 CoreFoundation`__CFRunLoopRun + 1132     frame #4: 0x000000019114e048 CoreFoundation`CFRunLoopRunSpecific + 444     frame #5: 0x00000001aa8f1fe8 AVFAudio`GenericRunLoopThread::Entry(void*) + 164     frame #6: 0x00000001aa917f14 AVFAudio`CAPThread::Entry(CAPThread*) + 84     frame #7: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #8: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #9: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #15: tid = 0x9c2cc, 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8, name = 'com.squareup.SocketRocket.NetworkThread'     frame #0: 0x000000019022416c libsystem_kernel.dylib`mach_msg_trap + 8     frame #1: 0x0000000190223fdc libsystem_kernel.dylib`mach_msg + 72     frame #2: 0x0000000191221cec CoreFoundation`__CFRunLoopServiceMachPort + 192     frame #3: 0x000000019121f908 CoreFoundation`__CFRunLoopRun + 1132     frame #4: 0x000000019114e048 CoreFoundation`CFRunLoopRunSpecific + 444     frame #5: 0x0000000191c5cb1c Foundation`-[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 304     frame #6: 0x00000001003cd7ec cya`-[_FSRRunLoopThread main](self=0x0000000170097c00, _cmd=<unavailable>) + 252 at FSRWebSocket.m:1838     frame #7: 0x0000000191d5a50c Foundation`__NSThread__start__ + 1024     frame #8: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #9: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #10: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #16: tid = 0x9c2d8, 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #0: 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #1: 0x000000019030536c libsystem_pthread.dylib`_pthread_wqthread + 1452     frame #2: 0x0000000190304db4 libsystem_pthread.dylib`start_wqthread + 4    thread #18: tid = 0x9c2e8, 0x000000019024223c libsystem_kernel.dylib`__select + 8, name = 'com.apple.CFSocket.private'     frame #0: 0x000000019024223c libsystem_kernel.dylib`__select + 8     frame #1: 0x0000000191228b84 CoreFoundation`__CFSocketManager + 640     frame #2: 0x0000000190307860 libsystem_pthread.dylib`_pthread_body + 240     frame #3: 0x0000000190307770 libsystem_pthread.dylib`_pthread_start + 284     frame #4: 0x0000000190304dbc libsystem_pthread.dylib`thread_start + 4    thread #19: tid = 0x9c355, 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #0: 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #1: 0x0000000190305188 libsystem_pthread.dylib`_pthread_wqthread + 968     frame #2: 0x0000000190304db4 libsystem_pthread.dylib`start_wqthread + 4    thread #20: tid = 0x9c35f, 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #0: 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #1: 0x000000019030536c libsystem_pthread.dylib`_pthread_wqthread + 1452     frame #2: 0x0000000190304db4 libsystem_pthread.dylib`start_wqthread + 4    thread #21: tid = 0x9c360, 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #0: 0x0000000190242a88 libsystem_kernel.dylib`__workq_kernreturn + 8     frame #1: 0x0000000190305188 libsystem_pthread.dylib`_pthread_wqthread + 968     frame #2: 0x0000000190304db4 libsystem_pthread.dylib`start_wqthread + 4 (lldb)  

1 Answers

Answers 1

The exception and stack trace tell you that the store view controller isn't happy about being pushed into a nav stack. Your test shows it is happy being presented. From the documentation:

present the view controller modally from another view controller in your app

So, you should present it modally.

While it's possible that you could perhaps make it work in some other way it's likely to break in the future if you don't follow the (inconvenient) guidelines.

Read More