Tuesday, July 31, 2018

fsockopen(): unable to connect not work with PHP (Connection timed out)

Leave a Comment

I have this code:

$domain = 'massag.com';  $hosts = array(); $mxweights = array(); getmxrr($domain, $hosts, $mxweights);  var_dump($hosts); var_dump($mxweights);  $host = gethostbynamel($hosts[0])[0]; var_dump($host);  $f = @fsockopen($host, 25, $errno, $errstr, 10);  if(!$f) {     var_dump('NOT CONNECTED'); } 

It is not connected to smtp server but when I use command

smtp:217.196.209.9

on mxtoolbox.com it is connected.

Am I doing something wrong with PHP code? I already tried replace $host to smtp.massag.com but not helped.

2 Answers

Answers 1

Remove @ in your call to fsockopen(); so you can see any potential errors you have happening in your configuration.

This code seems to be working fine to me.

$domain = 'massag.com';  $hosts = array();  $mxweights = array();  getmxrr($domain, $hosts, $mxweights);  var_dump($hosts); var_dump($mxweights);  $host = gethostbynamel($hosts[0])[0];  var_dump($host);  $f = fsockopen($host, 25, $errno, $errstr, 10);  if(!$f) {     var_dump('NOT CONNECTED'); } 

example output

Something to consider is that the getmxrr() function was not available on Windows platforms before php version 5.3.0. If you're on Windows ensure you're at least on that version of php or later.

Answers 2

Using dig to query the IP provided or its reverse DNS it shows that there are no MX records so errors are expected.

dig -x 217.196.209.9 MX | grep 'IN.*MX' ;9.209.196.217.in-addr.arpa.    IN      MX  dig smtp.miramo.cz MX | grep 'IN.*MX' ;smtp.miramo.cz.                        IN      MX 

But returns results on massag.com

dig massag.com MX | grep 'IN.*MX' ;massag.com.                    IN      MX massag.com.             85375   IN      MX      20 miramo3.miramo.cz. massag.com.             85375   IN      MX      10 smtp.miramo.cz. 

Finally, adding some tests to avoid unnecessary errors and using working domains

<?php $domain = 'massag.com';  if(getmxrr($domain, $hosts, $mxweights)){     print_r($hosts);     print_r($mxweights);     if(count($hosts) > 0){         $host = gethostbynamel($hosts[0])[0];         print("Found host: " . $host . "\n");          $f = fsockopen($host, 25, $errno, $errstr, 10);          if(!$f){             var_dump('NOT CONNECTED');         }     }else{         print("no MX record found\n");     } } ?> 

Result using tutorialspoint.com as domain:

    Array (     [0] => ALT2.ASPMX.L.GOOGLE.com     [1] => ASPMX.L.GOOGLE.com     [2] => ALT1.ASPMX.L.GOOGLE.com     [3] => ALT4.ASPMX.L.GOOGLE.com     [4] => ALT3.ASPMX.L.GOOGLE.com ) Array (     [0] => 5     [1] => 1     [2] => 5     [3] => 10     [4] => 10 ) Found host: 74.125.128.26 

Using the domain provided by OP (massag.com)

    Array (     [0] => smtp.miramo.cz     [1] => miramo3.miramo.cz ) Array (     [0] => 10     [1] => 20 ) Found host: 217.196.209.9 
Read More

Monday, July 30, 2018

215 error while requesting Token from Twitter oAuth API

Leave a Comment

I'm trying to Implement Twitter login in my NodeJS app.

As per the documentation from Twitter, I need to pass the below parameters to this url via POST request. URL:

https://api.twitter.com/oauth/request_token

PARAMETERS:

 oauth_nonce=,   oauth_signature=,   oauth_callback="http%3A%2F%2Fmyapp.com%3A3005%2Ftwitter%2Fprocess_callback",   oauth_signature_method="HMAC-SHA1",         oauth_timestamp="currentTimestamp",   oauth_consumer_key=“myKEY”,   oauth_version="1.0" 

I'm passing a random string for oauth_nonce parameter. I'm not clear on how to create a oauth_signature?

I keep getting 215 error whenever I make the POST request beacuse of incorrect oauth_nonce and oauth_signature values I guess.

How do I generate oauth_nonce and oauth_signature values while making the request in NodeJS.

3 Answers

Answers 1

Those parameters need to be passed in your authorization header:

OAuth oauth_nonce="K7ny27JTpKVsTgdyLdDfmQQWVLERj2zAK5BslRsqyw",  oauth_callback="http%3A%2F%2Fmyapp.com%3A3005%2Ftwitter%2Fprocess_callback",  oauth_signature_method="HMAC-SHA1",  oauth_timestamp="1300228849",  oauth_consumer_key="OqEqJeafRSF11jBMStrZz",  oauth_signature="Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D",  oauth_version="1.0" 

But before that, you need to get a signature, which will then give you all of the parameters above. Check the documentation here.

A recommendation would be to use a 3rd party library like passport, which heavily simplifies this process if needed.

Answers 2

Twitter makes a whole lot of sense if used correctly. I have seen some tutorials that has been quite useful to those around me, that I feel maybe you might want to check Node Authentication: Twitter and Implementing Sign in with Twitter for Node.js

If you're using reactjs, this (npm i react-twitter-auth) might be useful to you too

Answers 3

can't comment, that's why answering here. the docu sais, oauth_nonce:

is a unique token your application should generate for each unique request

it is like the salt of the encryption. you can find oauth_signature under the same link. how to generate it is described here.

Read More

How to forecast using the Tensorflow model?

Leave a Comment

I have created tensorflow program in order to for the close prices of the forex. I have successfully created the predcitions but failed understand the way to forecast the values for the future. See the following is my prediction function:

test_pred_list = []  def testAndforecast(xTest1,yTest1): #     test_pred_list = 0     truncated_backprop_length = 3     with tf.Session() as sess:     #     train_writer = tf.summary.FileWriter('logs', sess.graph)         tf.global_variables_initializer().run()         counter = 0 #         saver.restore(sess, "models\\model2298.ckpt")         try:             with open ("Checkpointcounter.txt","r") as file:                 value = file.read()         except FileNotFoundError:             print("First Time Running Training!....")           if(tf.train.checkpoint_exists("models\\model"+value+".ckpt")):             saver.restore(sess, "models\\model"+value+".ckpt")             print("models\\model"+value+".ckpt Session Loaded for Testing")         for test_idx in range(len(xTest1) - truncated_backprop_length):              testBatchX = xTest1[test_idx:test_idx+truncated_backprop_length,:].reshape((1,truncated_backprop_length,num_features))                     testBatchY = yTest1[test_idx:test_idx+truncated_backprop_length].reshape((1,truncated_backprop_length,1))               #_current_state = np.zeros((batch_size,state_size))             feed = {batchX_placeholder : testBatchX,                 batchY_placeholder : testBatchY}              #Test_pred contains 'window_size' predictions, we want the last one             _last_state,_last_label,test_pred = sess.run([last_state,last_label,prediction],feed_dict=feed)             test_pred_list.append(test_pred[-1][-1]) #The last one 

Here is the complete jupyter and datasets for test and train:
My repository with code.

Kindly, help me how I can forecast the close values for the future. Please do not share something related to predictions as I have tried. Kindly, let me know something that will forecast without any support just on the basis of training what I have given.

I hope to hear soon.

1 Answers

Answers 1

If I understand your question correctly, by forecasting you mean predicting multiple closing prices in future (for example next 5 closing prices from current state). I went through your jupyter notebook. In short, you can not easily do that.

Right now your code takes the last three positions defined by multiple futures (open/low/high/close prices and some indicators values). Based on that you predict next closing price. If you would like to predict even further position, you would have to create an "artificial" position based on the predicted closing price. Here you can approximate that open price is same as previous closing, but you can only guess high and low prices. Then you would calculate other futures/values (from indicators) and use this position with previous two to predict next closing price. You can continue like this for future steps.

The issue is in the open/low/high prices because you can only approximate them. You could remove them from data, retrain the model, and make predictions without them, but they may be necessary for indicators calculations.


I somehow compressed your code here to show the approach of predicting all OHLC prices:

# Data xTrain = datasetTrain[     ["open", "high", "low", "close", "k",      "d", "atr", "macdmain", "macdsgnal",      "bbup", "bbmid", "bblow"]].as_matrix() yTrain = datasetTrain[["open", "high", "low", "close"]].as_matrix()  # Settings batch_size = 1 num_batches = 1000 truncated_backprop_length = 3 state_size = 12  num_features = 12 num_classes = 4  # Graph batchX_placeholder = tf.placeholder(     dtype=tf.float32,     shape=[None, truncated_backprop_length, num_features],     name='data_ph') batchY_placeholder = tf.placeholder(     dtype=tf.float32,     shape=[None, num_classes],     name='target_ph')   cell = tf.contrib.rnn.BasicRNNCell(num_units=state_size) states_series, current_state = tf.nn.dynamic_rnn(     cell=cell,     inputs=batchX_placeholder,     dtype=tf.float32)  states_series = tf.transpose(states_series, [1,0,2])  last_state = tf.gather(     params=states_series,     indices=states_series.get_shape()[0]-1)  weight = tf.Variable(tf.truncated_normal([state_size, num_classes])) bias = tf.Variable(tf.constant(0.1, shape=[num_classes]))  prediction = tf.matmul(last_state, weight) + bias   loss = tf.reduce_mean(tf.squared_difference(last_label, prediction)) train_step = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)  # Training for batch_idx in range(num_batches):     start_idx = batch_idx     end_idx = start_idx + truncated_backprop_length       batchX = xTrain[start_idx:end_idx,:].reshape(batch_size, truncated_backprop_length, num_features)     batchY = yTrain[end_idx].reshape(batch_size, truncated_backprop_length, num_classes)       feed = {batchX_placeholder: batchX, batchY_placeholder: batchY}      _loss, _train_step, _pred, _last_label,_prediction = sess.run(         fetches=[loss, train_step, prediction, last_label, prediction],         feed_dict=feed) 

I think it is not important to write the whole code plus I don't know how are the indicators calculated. Also you should change way of data feeding because right now it only works with batches os size 1.

Read More

How to quantize all nodes except a particular one?

Leave a Comment

I am using tensorflow Graph Transform Tool to quantize the graph using

input_names = ["prefix/input"] output_names = ["final_result"]   transforms1 = ["strip_unused_nodes","fold_constants(ignore_errors=true)",  "fold_batch_norms",  "fold_old_batch_norms","quantize_weights" ]  transformed_graph_def = TransformGraph(graph.as_graph_def(), input_names,output_names, transforms1) 

I use the option quantize_weights to quantize the weights in graph, I know that certain nodes can remain unquantized by changing threshold minimum_size in quantize_weights, so leaving some nodes unquantized is certainly possible.

I want to quantize the weights of all nodes except a particular node with name K or a set of nodes that have name in K(set). How can this be achieved ?

0 Answers

Read More

Android force compress sqlite with jpg extension

Leave a Comment

I have an old class in an Android app which copies a pre-generated sqlite database. Up to Android 2.3 we needed to change the sqlite extension to an extension which won't be compressed (like jpg as in this question). As we stop the support for Android prior to 4.1 this is no longer needed.

I want to reduce the apk size, but I want to avoid changing the database's filename. Is there a way to mark the file so it will be compressed when creating the apk although it has the jpg extension?

2 Answers

Answers 1

Which filetypes are not compressed is controlled by the noCompress property :

android {      aaptOptions {         noCompress "txt"     }      .... 

The corresponding aapt option is -0 :

-0 specifies an additional extension for which such files will not be stored compressed in the .apk. An empty string means to not compress any files at all.

Unfortunately it seems that you can either add new filetypes to the default list or completely disable compression, but not remove a filetype.

So the only solution I can think of would be to do it after the build. For example, with the Linux / Cygwin zip and unzip :

Extract the file :

$ unzip my_app.apk assets/*.jpg Archive:  my_app.apk  extracting: assets/some_file.jpg 

Replace it in the apk, (by default zip always compress) :

$ zip -r my_app.apk assets/* updating: assets/some_file.jpg (deflated 91%) 

Realign the apk (before signing, as we use the new apksigner) :

$ zipalign 4 my_app.apk my_app_aligned.apk 

Sign it :

$ apksigner sign --ks my_keystore.keystore -v -out my_app_aligned_signed.apk.apk my_app_aligned.apk Keystore password for signer #1: ********** Signed 

Answers 2

Instead of avoiding to properly change the filename suffix from jpg to db, it might be better to see if the file with the old one suffix still exists on the device and then rename it accordingly, before opening it - so that the databases of previous versions would seamlessly be migrated (and also, to be able to open it on a computer with the correct handler). just changing the filename will otherwise lead to amnesia due to an inaccessible database file.

aaptOptions {noCompress "db"} might be option, but most likely this is not required, unless the file's content would otherwise be corrupted (a smaller package size is ordinary to be preferred).

Read More

Spring - Construct new modelAndView from existing BindingResult and Model

Leave a Comment

I am trying to improve my Spring MVC application to use a global exception handler to catch various persistence exceptions across all my controllers. This is the controller code that runs when the user tries to save a new StrengthUnit object for example. All the validations work perfectly fine and the form is correctly returned with an error message underneath the name field when the PersistenceException is thrown. The resulting page also correctly contains the strengthUnit attribute and is able to bind the field (this entity just has a name field) back to the form :

@RequestMapping(value = {"/newStrengthUnit"}, method = RequestMethod.POST) public String saveStrengthUnit(@Valid StrengthUnit strengthUnit, BindingResult result, ModelMap model) throws Exception {     try     {         setPermissions(model);          if (result.hasErrors())         {             return "strengthUnitDataAccess";         }         strengthUnitService.save(strengthUnit);          session.setAttribute("successMessage", "Successfully added strength unit \"" + strengthUnit.getName() + "\"!");     }     catch (PersistenceException ex)     {         FieldError error = new FieldError("strengthUnit", "name", strengthUnit.getName(), false, null, null,                  "Strength unit \"" + strengthUnit.getName() + "\" already exists!");         result.addError(error);          return "strengthUnitDataAccess";     }      return "redirect:/strengthUnits/list"; } 

I am trying to use this as a starting point to incorporate the global exception handler that i built and I don't understand how that handler can be called and return the same page with the same model and binding result. I have tried something extremely ugly with a custom exception just to try and understand the mechanics and get the handler to return me the same page as before and I'm unable to get it to work.

Here is the custom exception I built :

public class EntityAlreadyPersistedException extends Exception {     private final Object entity;     private final FieldError error;     private final String returnView;     private final ModelMap model;     private final BindingResult result;      public EntityAlreadyPersistedException(String message, Object entity, FieldError error, String returnView, ModelMap model, BindingResult result)      {         super(message);          this.entity = entity;         this.error = error;         this.returnView = returnView;         this.model = model;         this.result = result;     }      public Object getEntity()      {         return entity;     }      public FieldError getError()      {         return error;     }      public String getReturnView()      {         return returnView;     }      public ModelMap getModel()     {         return model;     }      public BindingResult getResult()      {         return result;     } } 

Here is my modified catch block in my controller's saveStrengthUnit method :

catch (PersistenceException ex)     {         FieldError error = new FieldError("strengthUnit", "name", strengthUnit.getName(), false, null, null,                  "Strength unit \"" + strengthUnit.getName() + "\" already exists!");         result.addError(error);          throw new EntityAlreadyPersistedException("Strength unit \"" + strengthUnit.getName() + "\" already exists!", strengthUnit, error,                  "strengthUnitDataAccess", model, result);     } 

And finally the global exception handler's method to catch it :

@ExceptionHandler(EntityAlreadyPersistedException.class) public ModelAndView handleDataIntegrityViolationException(HttpServletRequest request, Exception ex) {     EntityAlreadyPersistedException actualException;      actualException = ((EntityAlreadyPersistedException)ex);      ModelAndView modelAndView = new ModelAndView();     modelAndView.setViewName(actualException.getReturnView());     modelAndView.addObject(BindingResult.MODEL_KEY_PREFIX + "strengthUnitForm", actualException.getResult());      if (actualException.getEntity() instanceof StrengthUnit)     {         modelAndView.addObject("strengthUnit", (StrengthUnit)actualException.getEntity());     }     return modelAndView; } 

This is extremely ugly and probably very foolish to an experienced Spring developer but I am not quite one (yet). This works BUT the binding result is lost and the validation errors do not appear. How can I modify this code to behave as it was before while still using the global exception handler to handle all errors?

Thanks!

2 Answers

Answers 1

If you are trying to catch the valid exception , which was throw when you are using the @Valid .And you want same handler handle that exception ,then add one more exception class in the @ExceptionHandler annotation

What the doc says

The @ExceptionHandler value can be set to an array of Exception types. If an exception is thrown matches one of the types in the list, then the method annotated with the matching @ExceptionHandler will be invoked. If the annotation value is not set then the exception types listed as method arguments are used.

The exception thrown by the @Valid annotation is MethodArgumentNotValidException , So you can add this exception on same handler method

I hope this may help you

Answers 2

1.you are setting the entity as strengthUnit.getName() not strengthUnit

    throw new EntityAlreadyPersistedException("Strength unit \"" + strengthUnit.getName() + "\" already exists!", strengthUnit, error,                      "strengthUnitDataAccess", model, result); 

2.but you are checking if (actualException.getEntity() instanceof StrengthUnit

Hope it helps, Try to set the entity as strengthUnit.

Read More

Assigning DIVs to php variables and looping on multiple hidden inputs

Leave a Comment

I have a CMS that I've built allowing users to create a 'Page' made up of different panels each with their own content. I've made this work so that a user can create a page with one panel and one textarea of content but I still can't figure out how to do this for multiple panels/content.

Currently, if the page load gets the value of '1' from the URL value, it loads html templates with a fullwidth div and halfwidth div. I'm trying to set the panel type of each with hidden input types and they each have their own tinymce text area.

<?php if($value == 1){?>     <form method="post">     <div class="col-lg-12 fullWidth" id="full">         <input type="hidden" name="fullWidth" value="">         <div class="fullContent" style="background-color: white; height: 100%;">             <form  id="form-data3" method="post">               <textarea class="original" id="mytextarea3" name="fullText">Some Text Here</textarea>               <input type="submit" value="Save Content">             </form>         </div>     </div>      <div class="col-lg-12 halfWidth" id="half">         <input type="hidden" name="halfWidth" value="">         <div class="halfContent" style="background-color: white; height: 100%;">             <form  id="form-data4" method="post">               <textarea class="original" id="mytextarea4" name="halfText">Some Text There</textarea>               <input type="submit" value="Save Content">             </form>         </div>     </div>     </form>  <?php } ?> 

Once this is done and they go to save page, there is another form that lets them set the title of the page and it also gets the page type ($value from above)

<form action="addPage.php" method="post"> <input type="hidden" name="pageType" value="<?php echo $value;?>">//This comes from the url value <input class="form-control" id="addTitle" name="addTitle"> <input type="submit" name="Save Page"> 

The problem is, when I now call my addPage.php script to insert the records, I don't know how to pass the values correctly so that I add one page record (the $value for page_type_id and the Title) but then insert 2 content and panel records for the text areas.

Here's my expected insert in the case of the above code:

pages  ID | Title    | page_type_id 1  | TitleNew | 1     /*this comes from $value*/  content  ID | Content 1  | Some Text Here 2  | Some Text There  panels  ID | panel_type_ID | page_id | content_id 1  |     1         |     1   |   1 2  |     2         |     1   |   2 

This works for one insert in all 3 tables but if I can set multiple panel types to each div, how can I modify this to still insert the one page record but successfully account for multiple panel and content?

Here's the add page script

//Insert Page $title = $_POST['addTitle']; $page_type = $_POST['pageType'];   $addpage = " INSERT INTO pages (title, page_type_id) VALUES ('$title','$page_type'); "; $mysqlConn->query($addpage)  $page_id = $mysqlConn->insert_id;  //Insert Content $content = $_POST['page_content'];  $addContent = " INSERT INTO content(content) VALUES('$content'); ";  $mysqlConn->query($addContent);  $cont_id = $mysqlConn->insert_id;  //Insert panel(s) $panelID = $_POST['panelType']; $addPanel = " INSERT INTO panels(panel_type_id, page_id, cont_id) VALUES ('$panelID', '$page_id', '$cont_id'); "; $mysqlConn->query($addPanel); 

2 Answers

Answers 1

I guess your problem is handling multiple data collection. use [] in your element names to collect more than one data of the same collection.

<textarea class="original" id="mytextarea3" name="fullText[]">Some Text Here</textarea> 

and while saving you get an array from fullText . Loop through that and save it.

if you have multiple documents in the same form. use the key in the first loop to access the respective data from the other elements array.

Hope it helps!!

Answers 2

You're manage it wrong, it should be:

pages  ID | Title    | page_type_id 1  | TitleNew | 1     /*this comes from $value*/  content  ID | Content 1  | Some Text Here 2  | Some Text There  panels  ID | panel_type_ID | page_id | content_id 1  |     1,2         |     1   |   1,2 

I can't find panelType in your form but, You should detect the panels Ids which user has chosen and then send it to php, Example:

if user choose the panel (1) and the panel (2) your script should wrote it here:

<input type="hidden" value="1,2"> 

We separate the panels Ids with a comma because we will need it when we get the data from the database.

How to get the panels IDs:

After we get the data from database it will be like 1,2 and this won't work for you so how to get them in array?

It's so simple just do this:

<?php      $string = "1,2";     $get = explode(',', $string ); // explode with ,  ?> 

Now, You have your array which will look like this:

Array ( [0] => 1 [1] => 2 ) 

how to use it?

You can use a loop:

<?php      $string = "1,2";     $get = explode(',', $string ); // explode with and      $count = count($get);      for ($i=0; $i < $count; $i++) {          $PaN = $get[$i];         /*Some code....*/     }  ?> 

I hope i understand you.

Read More

Laravel mail with g suites and XOAUTH2

Leave a Comment

I have a g suites account and applications associated with my e-mails. I was looking at the Laravel mail functions but I do not see any option to log in to gmail smtp with xoauth auth type.

I was using PHPMailer with codeigniter and I had to use clientId, clientSecret and refreshToken to send emails via smtp.gmail.com

Is there any chance I can authenticate using xoauth with native laravel swiftmailer?

1 Answers

Answers 1

Since Laravel doesn't have available configuration to set AuthMode then we need to tweak it a little bit.

  1. Register a new Mail service provider in config/app.php:

    // ... 'providers' => [     // ...      // Illuminate\Mail\MailServiceProvider::class,     App\MyMailer\MyMailServiceProvider::class,      // ... 
  2. app/MyMailer/MyMailServiceProvider.php should create your own TransportManager class:

```

namespace App\MyMailer;  class MyMailServiceProvider extends \Illuminate\Mail\MailServiceProvider {     public function registerSwiftTransport()     {         $this->app['swift.transport'] = $this->app->share(function ($app) {              return new MyTransportManager($app);         });     } } 

```

  1. In the app/MyMailer/MyTransportManager.php we can provide additional configuration to the SwiftMailer:

```

<?php  namespace App\MyMailer;   class MyTransportManager extends \Illuminate\Mail\TransportManager {     /**      * Create an instance of the SMTP Swift Transport driver.      *      * @return \Swift_SmtpTransport      */     protected function createSmtpDriver()     {         $transport = parent::createSmtpDriver();         $config = $this->app->make('config')->get('mail');           if (isset($config['authmode'])) {             $transport->setAuthMode($config['authmode']);         }          return $transport;     } } 

```

  1. Last thing to do is to provide mail configuration with authmode set to XOAUTH2 and password to your access token:

```

<?php  return array(  /* |-------------------------------------------------------------------------- | Mail Driver |-------------------------------------------------------------------------- | | Laravel supports both SMTP and PHP's "mail" function as drivers for the | sending of e-mail. You may specify which one you're using throughout | your application here. By default, Laravel is setup for SMTP mail. | | Supported: "smtp", "mail", "sendmail" | */  'driver' => 'smtp',  /* |-------------------------------------------------------------------------- | SMTP Host Address |-------------------------------------------------------------------------- | | Here you may provide the host address of the SMTP server used by your | applications. A default option is provided that is compatible with | the Postmark mail service, which will provide reliable delivery. | */  'host' => 'smtp.gmail.com',  /* |-------------------------------------------------------------------------- | SMTP Host Port |-------------------------------------------------------------------------- | | This is the SMTP port used by your application to delivery e-mails to | users of your application. Like the host we have set this value to | stay compatible with the Postmark e-mail application by default. | */  'port' => 587,  /* |-------------------------------------------------------------------------- | Global "From" Address |-------------------------------------------------------------------------- | | You may wish for all e-mails sent by your application to be sent from | the same address. Here, you may specify a name and address that is | used globally for all e-mails that are sent by your application. | */  'from' => array('address' => 'user@gmail.com', 'name' => 'user'),  /* |-------------------------------------------------------------------------- | E-Mail Encryption Protocol |-------------------------------------------------------------------------- | | Here you may specify the encryption protocol that should be used when | the application send e-mail messages. A sensible default using the | transport layer security protocol should provide great security. | */  'encryption' => 'tls',  /* |-------------------------------------------------------------------------- | SMTP Server Username |-------------------------------------------------------------------------- | | If your SMTP server requires a username for authentication, you should | set it here. This will get used to authenticate with your server on | connection. You may also set the "password" value below this one. | */  'username' => 'user@gmail.com',  /* |-------------------------------------------------------------------------- | SMTP Server Password |-------------------------------------------------------------------------- | | Here you may set the password required by your SMTP server to send out | messages from your application. This will be given to the server on | connection so that the application will be able to send messages. | */  'password' => 'YOUR ACCESS TOKEN',  /* |-------------------------------------------------------------------------- | Sendmail System Path |-------------------------------------------------------------------------- | | When using the "sendmail" driver to send e-mails, we will need to know | the path to where Sendmail lives on this server. A default path has | been provided here, which will work well on most of your systems. | */  'sendmail' => '/usr/sbin/sendmail -bs',  /* |-------------------------------------------------------------------------- | Mail "Pretend" |-------------------------------------------------------------------------- | | When this option is enabled, e-mail will not actually be sent over the | web and will instead be written to your application's logs files so | you may inspect the message. This is great for local development. | */  'pretend' => false,  'authmode' => 'XOAUTH2',  ); 

```

Read More

Is it possible pause & resume for Retrofit multipart request?

Leave a Comment

We are using Retrofit multi-part for file uploading process.

We want pause/resume when file uploading.

I want to know its possible or not?

Code for multi-part file upload

  RequestBody requestFile =             RequestBody.create(MediaType.parse("multipart/form-data"), file);    // MultipartBody.Part is used to send also the actual file name   MultipartBody.Part body =MultipartBody.Part.createFormData("image", file.getName(), requestFile);   Call<ResponseBody> call= api.uploadFile(body); 

2 Answers

Answers 1

As suggested by Jake Wharton from Square,

There is no built-in pause or resume for retrofit.

If you want to stick on to retrofit then you may need to make your backend to support range requests. This can help you to break the connection at any time during a streaming download. You can then use the range headers in every subsequent requests to support pause or resume download.

You may also check this answer using using okhttp

Answers 2

Yes its possible. You would have to create your own request body.

   public class PausableRequestBody extends RequestBody {     private static final int BUFFER_SIZE = 2048;     private File mFile;     private long uploadedData;      public PausableRequestBody(final File file) {         mFile = file;     }      @Override     public MediaType contentType() {         return MediaType.parse("image/*");     }      @Override     public long contentLength() throws IOException {         return mFile.length();     }      @Override     public void writeTo(BufferedSink bs) throws IOException {         long fileLength = mFile.length();         byte[] buffer = new byte[BUFFER_SIZE];         FileInputStream in = new FileInputStream(mFile);          try {             int read;             while ((read = in.read(buffer)) != -1) {                 this.uploadedData += read;                 bs.write(buffer, 0, read);             }         } finally {             in.close();         }     }      public long getUploadedData() {         return uploadedData;     } } 

use append instead of write..

Use following Retrofit call

PausableRequestBody fileBody = new PausableRequestBody(file, this);         MultipartBody.Part filePart = MultipartBody.Part.createFormData("image", file.getName(), fileBody);          Call<JsonObject> request = RetrofitClient.uploadImage(filepart);         request.enqueue(new Callback<JsonObject>{...}); 

to cancel the request request.cancel()

to restart use the same PausableRequestBody object with the same method mentioned above

Read More

How can I pass a command to a template and have it execute in my back end code and pass the parameter?

Leave a Comment

I have this template:

<?xml version="1.0" encoding="utf-8"?> <Grid Padding="20,0" xmlns="http://xamarin.com/schemas/2014/forms"        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"        xmlns:local="clr-namespace:Japanese;assembly=Japanese"        x:Class="Japanese.Templates.DataGridTemplate"        x:Name="this" HeightRequest="49" Margin="0">     <Grid.GestureRecognizers>          <TapGestureRecognizer               Command="{Binding TapCommand, Source={x:Reference this}}"              CommandParameter="1"              NumberOfTapsRequired="1" />     </Grid.GestureRecognizers>     <Label Grid.Column="0" Text="{Binding Test" /> </Grid> 

Behind this I have:

public partial class DataGridTemplate : Grid {      public DataGridTemplate()     {         InitializeComponent();     }      public static readonly BindableProperty TapCommandProperty =        BindableProperty.Create(            "Command",            typeof(ICommand),            typeof(DataGridTemplate),            null);      public ICommand TapCommand     {         get { return (ICommand)GetValue(TapCommandProperty); }         set { SetValue(TapCommandProperty, value); }     }  } 

and I am trying to call the template like this in file: Settings.xaml.cs

<template:DataGridTemplate TapCommand="openCFSPage" /> 

hoping that it will call my method here in file: Settings.cs

void openCFSPage(object sender, EventArgs e) {     Navigation.PushAsync(new CFSPage()); } 

The code compiles but when I click on the grid it doesn't call the openCFSPage method.

1) Does anyone have an idea what might be wrong?

2) Also is there a way that I can add a parameter to the template and then have that parameter passed to my method in the CS back end code?

Note that I would like to avoid adding a view model if possible. The application is small and I'd like to just have the code I need in the CS code of the page that calls the template.

4 Answers

Answers 1

You have 2 options depending on the the use case :

FYI, there's no way to call another method directly from the view (its a bad design pattern to do so)

  1. Using Event Aggregator :

Create interface

public interface IEventAggregator {     TEventType GetEvent<TEventType>() where TEventType : EventBase, new(); } 

All you have to do is call it from you TapCommand

_eventAggregator.GetEvent<ItemSelectedEvent>().Publish(_selectedItem); 

Then in your Settings.cs you can Create a method that can receive the data

 this.DataContext = new ListViewModel(ApplicationService.Instance.EventAggregator); 
  1. Inheritance and Polymorphism / Making openCFSPage a service :

Creating a interface / service that links both models

public interface IOpenCFSPage {      Task OpenPage(); } 

and a method :

public class OpenCFSPage : IOpenCFSPage { private INavigationService _navigationService; public OpenCFSPage(INavigationService navigationService){  _navigationService = navigationService; }         public async Task OpenPage()         {              await _navigationService.NavigateAsync(new CFSPage());         } } 

Answers 2

Please note that the simplest way to implement this would be through MVVM (i.e. a view-model), but if you want to side-step this option (as you mentioned in the question) then you can use one of the following options

Option1 : Wrap delegate into command object

If you look at it from the perspective of a XAML parser, you are technically trying to assign a delegate to a property of type ICommand. One way to avoid the type mismatch would be to wrap the delegate inside a command-property in the page's code-behind.

Code-behind [Settings.xaml.cs]

ICommand _openCFSPageCmd; public ICommand OpenCFSPageCommand {     get {         return _openCFSPageCmd ?? (_openCFSPageCmd = new Command(OpenCFSPage));     } }  void OpenCFSPage(object param) {     Console.WriteLine($"Control was tapped with parameter: {param}"); } 

XAML [Settings.xaml]

<!-- assuming that you have added x:Name="_parent" in root tag --> <local:DataGridView TapCommand="{Binding OpenCFSPageCommand, Source={x:Reference _parent}}" /> 

Option2 : Custom markup-extension

Another option (a bit less mainstream) is to create a markup-extension that wraps the delegate into a command object.

[ContentProperty("Handler")] public class ToCommandExtension : IMarkupExtension {     public string Handler { get; set; }     public object Source { get; set; }      public object ProvideValue(IServiceProvider serviceProvider)     {         if (serviceProvider == null)             throw new ArgumentNullException(nameof(serviceProvider));         var lineInfo = (serviceProvider?.GetService(typeof(IXmlLineInfoProvider)) as IXmlLineInfoProvider)?.XmlLineInfo ?? new XmlLineInfo();           object rootObj = Source;         if (rootObj == null)         {             var rootProvider = serviceProvider.GetService<IRootObjectProvider>();             if (rootProvider != null)                 rootObj = rootProvider.RootObject;         }          if(rootObj == null)         {             var valueProvider = serviceProvider.GetService<IProvideValueTarget>();             if (valueProvider == null)                 throw new ArgumentException("serviceProvider does not provide an IProvideValueTarget");              //we assume valueProvider also implements IProvideParentValues             var propInfo = valueProvider.GetType()                                         .GetProperty("Xamarin.Forms.Xaml.IProvideParentValues.ParentObjects",                                                       BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);             if(propInfo == null)                 throw new ArgumentException("valueProvider does not provide an ParentObjects");              var parentObjects = propInfo.GetValue(valueProvider) as IEnumerable<object>;             rootObj = parentObjects?.LastOrDefault();         }          if(rootObj != null)         {             var delegateInfo = rootObj.GetType().GetMethod(Handler,                                                            BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);             if(delegateInfo != null)             {                 var handler = Delegate.CreateDelegate(typeof(Action<object>), rootObj, delegateInfo) as Action<object>;                 return new Command((param) => handler(param));             }         }          throw new XamlParseException($"Can not find the delegate referenced by `{Handler}` on `{Source?.GetType()}`", lineInfo);             } } 

Sample usage

<local:DataGridView TapCommand="{local:ToCommand OpenCFSPage}" /> 

Answers 3

Settings.xaml:

<template:DataGridTemplate TapCommand="{Binding OpenCFSPage}" />  <!-- Uncomment below and corresponding parameter property code in DataGridTemplate.xaml.cs to pass parameter from Settings.xaml --> <!--<template:DataGridTemplate TapCommand="{Binding OpenCFSPage}" CommandParameter="A" />--> 

Settings.xaml.cs:

public Settings() {     InitializeComponent();      OpenCFSPage = new Command(p => OpenCFSPageExecute(p));      BindingContext = this; }  public ICommand OpenCFSPage { get; private set; }  void OpenCFSPageExecute(object p) {     var s = p as string;     Debug.WriteLine($"OpenCFSPage:{s}:"); } 

DataGridTemplate.xaml:

<?xml version="1.0" encoding="UTF-8"?>     <Grid xmlns="http://xamarin.com/schemas/2014/forms"           xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"          xmlns:local="clr-namespace:Japanese;assembly=Japanese"           Padding="0,20"           HeightRequest="49" Margin="0"          x:Class="Japanese.DataGridTemplate">     <Grid.GestureRecognizers>         <TapGestureRecognizer               Command="{Binding TapCommand}"              CommandParameter="1"              NumberOfTapsRequired="1" />     </Grid.GestureRecognizers>     <Label Grid.Column="0" Text="Test" /> </Grid> 

DataGridTemplate.xaml.cs:

public partial class DataGridTemplate : Grid {     public DataGridTemplate()     {         InitializeComponent();     }      public static readonly BindableProperty TapCommandProperty =          BindableProperty.Create(             nameof(TapCommand), typeof(ICommand), typeof(DataGridTemplate), null,             propertyChanged: OnCommandPropertyChanged);      public ICommand TapCommand     {         get { return (ICommand)GetValue(TapCommandProperty); }         set { SetValue(TapCommandProperty, value); }     }      //public static readonly BindableProperty CommandParameterProperty = BindableProperty.Create(     //    nameof(CommandParameter), typeof(string), typeof(DataGridTemplate), null);      //public string CommandParameter     //{     //    get { return (string)GetValue(CommandParameterProperty); }     //    set { SetValue(CommandParameterProperty, value); }     //}      static TapGestureRecognizer GetTapGestureRecognizer(DataGridTemplate view)     {         var enumerator = view.GestureRecognizers.GetEnumerator();         while (enumerator.MoveNext())         {             var item = enumerator.Current;             if (item is TapGestureRecognizer) return item as TapGestureRecognizer;         }         return null;     }      static void OnCommandPropertyChanged(BindableObject bindable, object oldValue, object newValue)     {         if (bindable is DataGridTemplate view)         {             var tapGestureRecognizer = GetTapGestureRecognizer(view);             if (tapGestureRecognizer != null)             {                 tapGestureRecognizer.Command = (ICommand)view.GetValue(TapCommandProperty);                 //tapGestureRecognizer.CommandParameter = (string)view.GetValue(CommandParameterProperty);             }         }     } } 

Answers 4

Check this code you help you. Here you have to pass a reference of list view and also you need to bind a command with BindingContext.

 <ListView ItemsSource="{Binding Sites}" x:Name="lstSale">             <ListView.ItemTemplate>                 <DataTemplate>                     <ViewCell>                         <StackLayout Orientation="Vertical">                             <Label Text="{Binding FriendlyName}" />                             <Button Text="{Binding Name}"                                     HorizontalOptions="Center"                                     VerticalOptions="Center"                                     Command="{Binding                                     Path=BindingContext.RoomClickCommand,                                     Source={x:Reference lstSale}}"                                     CommandParameter="{Binding .}" />                        </StackLayout>                     </ViewCell>                 </DataTemplate>             </ListView.ItemTemplate>         </ListView> 
Read More

asp.net while first request processing allow second request on click

Leave a Comment

In Asp.net Web Form app, I have Generate Report button and a Cancel button to cancel report generation process, if it takes a long time.

When I Click Generate Report it does the heavy task, after 3 seconds I try to cancel this heavy task by clicking the Cancel button.

But the server side code for Cancel button click is called after some time delay.

I even tried window.stop() in JavaScript to stop page loading and hit server code fast, but still, there is a delay.

Code:

protected void btnExportExcel_Click(object sender, EventArgs e) {  // Doing Heavy Task to Generate Report  }   protected void btnCancel_Click(object sender, EventArgs e) {     if (Response.IsClientConnected)     {         HttpContext.Current.ApplicationInstance.CompleteRequest();      } }         <asp:Button ID="btnCancel" runat="server" Text="Cancel Request"     OnClientClick="return StopPageLoading();" OnClick="btnCancel_Click" />    function StopPageLoading() {       try      {        window.stop();      } catch (exception)       {        document.execCommand('Stop'); // for IE and other browsers      }    } 

How can I allow to start another request on click fast, while current request is in processing?

How to allow UI to be responsive?

Update:

To reproduce the situation:

  1. I click Export To Excel , it takes 7 minutes to process.
  2. While still processing I click Cancel button , it takes another 5 minutes to cancel.

I read that Concurrent request is not possible in Asp.NET because of session state makes exclusive locks.

So How to cancel fast ?

Will making my methods async help to overcome session state exclusive locks issue ?

4 Answers

Answers 1

As in another question from you, you can do it this way

public partial class Contact : Page {      private static CancellationTokenSource tokenSource = new CancellationTokenSource();       protected void Page_Load(object sender, EventArgs e)     {      }      protected async void btnExportExcel_Click(object sender, EventArgs e)     {         CancellationToken cToken = tokenSource.Token;         cToken.Register(() => cancelNotification());          try         {              await Task.Run(() =>             {                 cToken.ThrowIfCancellationRequested();                  GenerateReport(sender, cToken);              }, cToken);         }         catch(OperationCanceledException)         {          }     }      private void GenerateReport(object sender, CancellationToken ct)     {         // Just to Simulate Export to excel          Thread.Sleep(70000);     }       protected void btnCancel_Click(object sender, EventArgs e)     {          tokenSource.Cancel();      }       private static void cancelNotification()     {         // Do your stuff when the user is canceld the report generation      } } 

And in your Page.aspx

Need something like this

<%@ Page Async="true" EnableSessionState="false" %> 

I hope this helps you!

Answers 2

Though, you can do it or not (I am not sure), it is generally not a good idea to create a long running task within ASP.NET, especially if they are background tasks. So there are some helper libraries that are for this purpose.

  1. HangFire http://docs.hangfire.io Hangfire allows you to kick off method calls outside of the request processing pipeline in a very easy, but reliable way. These method invocations are performed in a background thread and called background jobs. this support using cancellation tokens to cancel a background job
  2. Quarz.NET I have never tryed Quarz.NET
  3. Or you have to do it yourself. I know some projecs that take some dedicate servers just for run background and time consuming tasks. So the website is just a frontend layer that set some flags that control the task is cancel or not

Answers 3

The problem is in IIS (or any other Web Server) architecture. The server returns a response to a client (browser) and forget it. Your first request (btnExcelExport_Click) must be finished before it returns response to the browser. The click on btnCancel starts a new request which knows nothing about the first one.
The workaround is to send a long job to another thread. It is possible to communicate to that thread using state object sent to the new thread. Something like this.

<%@ Page Language="C#" %>  <!DOCTYPE html>  <script runat="server">      protected void btnRun_Click(object sender, EventArgs e)     {         var jobState = new StateInfo()         {             Id = 1,             Counter = 0,             Content = "Start the job",             Cancelled = false,             Completed = false         };         Session["job"] = jobState; //Save state between requests         System.Threading.ThreadPool.QueueUserWorkItem(             new System.Threading.WaitCallback(LongJob),             jobState             );//returns immediately         lblState.Text += "<br />" + jobState.Counter.ToString()              + " Completed: " + jobState.Completed.ToString()             + " Cancelled: " + jobState.Cancelled.ToString()             + "<br />" + jobState.Content;         btnCancel.Visible = true;         btnCheck.Visible = true;     }      protected void btnCancel_Click(object sender, EventArgs e)     {         var jobState = Session["job"] as StateInfo;         if (!jobState.Completed)             jobState.Cancelled = true;         System.Threading.Thread.Sleep(1000);//wait for the next loop to complete         lblState.Text += "<br />" + jobState.Counter.ToString()             + " Completed: " + jobState.Completed.ToString()             + " Cancelled: " + jobState.Cancelled.ToString()             + (jobState.Completed || jobState.Cancelled ? "<br />" + jobState.Content : "");     }      protected void btnCheck_Click(object sender, EventArgs e)     {         var jobState = Session["job"] as StateInfo;         lblState.Text += "<br />" + jobState.Counter.ToString()             + " Completed: " + jobState.Completed.ToString()             + " Cancelled: " + jobState.Cancelled.ToString()             + (jobState.Completed || jobState.Cancelled ? "<br />" + jobState.Content : "");     }      private void LongJob(object state)     {         var jobState = state as StateInfo;         do         {             System.Threading.Thread.Sleep(1000);             jobState.Counter++;             if (jobState.Counter >= 100)             {                 jobState.Completed = true;                 jobState.Content = "The job is completed";             }             else if (jobState.Cancelled)                 jobState.Content = "The job is cancelled";         }         while (!jobState.Cancelled && !jobState.Completed);     }     [Serializable]     class StateInfo     {         public int Id { get; set; }         public int Counter { get; set; }         public string Content { get; set; }         public bool Cancelled { get; set; }         public bool Completed { get; set; }     }  </script>  <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">     <title>Long Job</title> </head> <body>     <form id="form1" runat="server">         <div>             <asp:Label ID="lblState" runat="server"></asp:Label><br />             <asp:Button runat="server" ID="btnRun" OnClick="btnRun_Click" Text="Run" />             <asp:Button runat="server" ID="btnCheck" OnClick="btnCheck_Click" Text="Check State" Visible="false" />             <asp:Button runat="server" ID="btnCancel" OnClick="btnCancel_Click" Text="Cancel" Visible="false" />         </div>     </form> </body> </html> 

Answers 4

Did you try using the async/await operation in the code instead of synchronous

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/

when the report generation call is asynchronous then redirect to UI once the report generation process is kicked off. Now the cancel button can be clicked when needed.

Does this help?

Read More

Executing a js file returned inside an ajax response

Leave a Comment

I have a HTML5 application which is using jquery 3.2.1.

In part of the application - a search feature - I make an ajax request. The response from the ajax request is HTML, and this includes a <script> tag which links to a js file which is hosted on the same server as the application.

So the ajax code looks like this - for making the ajax request and writing the response to a div with the ID #ajaxContent:

$.ajax({     url: $('#searchRegulations').attr('action'),     type: 'post',     cache: false,     data: $('#searchRegulations').serialize()  }).done(function (response, status, xhr) {         if (response) {             $('main .content').hide();             $('#ajaxContent').html(response).show();             return false;         }     } }); 

If I inspect #ajaxContent I can see that the <script> tag is included in the ajax response:

enter image description here

I have also checked my Network tab to make sure /js/search_regulations.js is being loaded correctly, and it's giving a 200 response:

Inside search_regulations.js there is some jquery which toggles some filters that are present in #ajaxContent.

The problem is that this code only seems to be working about 50% of the time. When it works it will toggle the state of some filter buttons by adding/removing a class .active to elements inside .browse-ctp__filters-data and then writing them to a hidden form with the ID #tmpFilters.

To ensure the script was "firing" I put in the line console.log('search_regulations.js firing'); and sure enough this is shown in the Console every time irrespective of whether the script functions or not.

What's stranger is that if I cut/paste the code into my Console after the ajax response has been written to the page, it always works as expected.

Is this some issue with the way the script is being brought into the page?

I've pasted the script below, but I don't think it's an issue with the code in it, rather the way the browser/ajax response is being handled:

$(function() {    console.log('search_regulations.js firing');  /* toggle the active (applied) state on browse by filters */ /* @link https://stackoverflow.com/questions/48662677/switch-active-class-between-groups-of-include-exclude-buttons */ $(document).on('click', '.browse-ctp__filters-data .include, .exclude', function(){      var $this = $(this);      // Split name into array (e.g. "find_355" == ["find", "355"])      var arr = $this.attr('name').split('_');       // Toggle active class     $this.toggleClass("active");     if ($this.siblings().hasClass("active")) {       $this.siblings().removeClass("active")     }      // Remove any existing instances of the filter from hidden form     $('#tmpFilters input[value="exclude_'+arr[1]+'"]').remove();     $('#tmpFilters input[value="find_'+arr[1]+'"]').remove();      // If a filter has been applied then add it to hidden form     if ($this.hasClass('active')) {         $('#tmpFilters').append('<input type="hidden" name="tmpFilter[]" value="'+$this.attr('name')+'">');     } });     });  

Notes about the Bounty offered:

I've offered a bounty because it's not a trivial problem to solve - demonstrated by the fact nobody has given a workable answer. I expect the correct answer to:

  1. Be demonstrable with jsfiddle or equivalent.
  2. Explain how/why it works.
  3. Understand that the ajax response is HTML and js. The js acts on HTML elements in the response. Therefore both the HTML and js need to be included in the response - as opposed to saying "just add the js to a global file" (I don't want the js to be global, because it's specific to the HTML response given, and can vary in different parts of the application).
  4. Should not use a timeout (setTimeout or whatever). If the user interacts with the UI elements - such as buttons - returned in the HTML response before the timeout and therefore js is fired... that just leads to the same problem we have now. So that isn't a valid solution as far as I'm concerned.
  5. If this problem is impossible to solve in HTML5/jquery explain why and suggest any alternative ways to handle it.

jsfiddle showing the HTML and script tag returned via ajax:

Several people have asked for a fiddle or demo. No 2 people would get the same outcome - which is very much the point of the question - so I didn't make one originally. The HTML returned that gets written to #ajaxContent is shown here: http://jsfiddle.net/v4t9j32g/1/ - this is what dev tools in the browser shows following the ajax response. Please note that the length of the content returned can vary, since it's the response to a keyword search facility that brings back a load of filter buttons. Also note that this HTML response contains the line <script src="/js/search_regulations.js"></script>. That is where the problematic js is located and the full contents of that are shown above in this question - the bit that includes console.log('search_regulations.js firing')

8 Answers

Answers 1

One of the problems that I see is that you're binding the onclick to the same elements multiple times...

Since the js can be loaded multiply times via ajax requests, it is important to first detach, before attaching again events.

The other problem, is that you're running the code in $(document).ready event (that is when HTML-Document is loaded and DOM is ready), however you'd probably be better off to run the code in the $(window).load event (which executes a bit latter, when complete page is fully loaded, including all frames, objects and images)

Example:

$(window).load(function() {        console.log('search_regulations.js firing');      //off: detach the events     //on: attach the events     $('.browse-ctp__filters-data .include, .exclude').off('click').on('click', function(){         ...     } });  

Answers 2

In addition to what everybody were talking in the comments, I'll try to put it into an answer.

Event driven

JS is event driven, that doesn't mean you have to load scripts on the fly to make them execute functions when an event is fired. A better approach would be to load everything you need on the page load, and add event listeners, this will case much better user experience(less http requests) and much better code matinability.

TL;DR

In general I would do something like that in you html file:

<script src="/js/main.js">   <script src="/js/search_regulations.js" async>  <!-- bonus tip! google "async script tag" --> 

This will load all the js you need.

Keep in mind that search_regulations.js should add the event listener you want with jQuery on method, but since the html didn't exist when the script added the event listener, you might want to check this.

Why this is better?

  • Now you had pretty easy case where one file loads another. In the future you might want to add more features and more complex code. This will be painful to debug when you have chains of scripts that load each other.
  • The user has to wait until the request for the search_regulations.js file to be loaded, if they're on the a mobile network/the file will get bigger in size that might be a poor user experience.
  • You can still reuse your code over the application with search_regulations.js

Answers 3

You need to strip the < script > tag out of the HTML and create a script tag manually to add to the DOM. Essentially, you can convert the Html to JS via:

var $html = $(data.Html) 

Then, pull out all the script tags like this:

 var scripts = [];         $html.each(function(i, item) {             if (item instanceof HTMLScriptElement) {                 scripts.push(item);             }         }); 

Then you need to remove all the < script > tags from the html before appending it to the DOM.

$html.find("script").remove();  $("placeToAddHtml").append($html); 

Once the HTML, stripped of the tags is added, you can then manually add each script to the DOM at the end:

           for (var i = 0; i < scripts.length; i++) {                 var script = document.createElement('script');                  $(scripts[i]).each(function() {                     $.each(this.attributes, function(j, attrib) {                         var name = attrib.name;                         var value = attrib.value;                         script[name] = value;                     });                 });                  script.text = scripts[i].innerHTML;                 document.body.appendChild(script);             } 

Hope this works how you intend it!

Edit: You may need to build up the script tag here in a way that appends all of the pulled out scripts at the same time if they depend on each other. That way, you only add one giant script tag that has all the other tags internally at once.

Answers 4

To avoid the possibility of a race condition without implementing a flat timer, you will need to return an ajax response that separates the script from the html, such as a json object that returns two elements (the script or an array of scripts to support cases where you need multiple, and a second element that contains the stringified html markup).

Sample json response from ajax:

{     "script": "/yourscript.js",     "html": "<p>Your markup...</p>" } 

This (parsed) json will be referred to as xhrResponse below for brevity.

Before applying either to the dom, append a preload tag for your script(s) prior to loading the dom element, so they will start being resolved in the background without loading, which should minimize the overall loading timeline, and help alleviate much of the possibility of ongoing race conditions:

document.getElementsByTagName('head')[0].appendChild( '<link rel="preload" href="' + xhrResponse.script + '" as="script">' ); 

This will begin loading your script in the background without executing it, so it can be applied immediately when you apply the script tag to the dom later.

You will then want to append the dom elements next, and then apply the scripts after the new dom content has resolved. You may alternately pass the markup directly in the json response, or alternately return a link to a template file and serve that in conjunction with the above mentioned preload method for the template itself. If you are more concerned with the possibility of escaping issues on content, do the latter. If you are more concerned with bandwidth and latency, do the former. There are some minor caveats to both, depending on your use case.

document.getElementsByTagName('head')[0].appendChild( xhrResponse.html ); 

You will then want to check that the applied html content has resolved within the dom. An arbitrary wait timer is not a very good way to do this, as it has a high likelihood of making the user wait longer than is necessary, and occasional network bottlenecks may also cause your script to occasionally choke if the content does not resolve prior to your arbitrary timer length (more of an issue if you are serving a template from a link instead of stringified html markup), or if the end user has low memory currently available (old machines, bzillion tabs open, or very large html payloads even when served directly stringified).

Please see this answer for a pretty robust solution to check if dynamically added dom content has resolved correctly.

Once this has resolved, then apply the script elements afterward with something like this:

var script = document.createElement('script'); script.src = xhrResponse.script; script.async = true; // use false here if you want synchronous loading for some reason document.head.appendChild(script); 

The earlier mentioned preload tag should insure that your script has already been localized by the browser by this point, or is very nearly done doing so already. You can then check if it has completed with a ready state event listener if it is still giving you issues:

script.onreadystatechange = function() {     if (script.readyState === "complete") {         // debug stuff, or call an init method for your js if you really want to be sure it fired after everything else is done.     } } 

It should be noted that in the above ready state listener, if the preload resolves prior to this portion of your logic, the ready state will not change (because it is already done), and this portion of logic will not execute. Depending on the weight of your DOM content, this may or may not apply to you.


This approach will insure loading in the correct order, and also decouple your script and markup, so either can be recycled independently of each other elsewhere if applicable now or at any point in the future either.

Answers 5

The problems i think could be: 1. Include and exclude triggers the same function. Error in logic inside to handle both. (since you told it works 50% of the time). 2.Try updating the DOM after you have appended the HTML.

   componentHandler.upgradeDom(); 

just after

 $('#ajaxContent').html(response).show(); 

Hope it helps !!!

Answers 6

NOTE:

  • @bastos.sergios already answered your question — see his first point.
  • Credit should also be given to @yts for "strengthening" Bastos's answer.

So the following should fix the problem with your search_regulations.js script:

$(document)   // Detach the event handler to prevent multiple/repeat triggers on the target elements.   .off('click.toggleActive', '.browse-ctp__filters-data .include, .exclude')   // Attach/re-attach the handler.   .on('click.toggleActive', '.browse-ctp__filters-data .include, .exclude', function(){     ... put your code here ...   }); 

But my primary intention of writing this answer, is to let you see the problem with your script.

And if you're curious, here's script I used with that demo, which slightly modified:

https://codepen.io/anon/pen/RBjPjw.js

Answers 7

About the requirements

The solution to the problem is available using either HTML5/jQuery or a combination of a previous HTML version and native Javascript. The only reason to use a library like jQuery is to bring older browser to the same level of support or to fix bugs and to have a standard framework shared between groups of developers.

Also, in my opinion, it doesn't matter where you place the few lines of code needed to solve the problem, they can be put in the head section of the page, at the bottom of the page or as for the requirements of the bounty inside the Ajax response payload that is reloaded frequently.

About the issue

The real trick lies in the method you use to achieve the firing of click events, your choice of doing that inside the script present in the repeated Ajax responses is what makes your cade fail at some point.

Each time an Ajax request happens the script in the response adds new event listeners. These will continuously sum up until the browsers fails for some reason (not enough memory, exhausted event stack, or click events race conditions).

About the solution

So, the solution to your issue would be to avoid adding events each time the Ajax request/response happens. This is a task which can be easily solved by a simple "capturing phase event delegation" (not frequently used unfortunately).

An event listener is added only once on one of the top nodes which can be the "document" node itself or the "html" element or the "body" element, thus on one element that is always present in the DOM after the initial page load.

This element will be in charge of capturing all the click on the page, currently present or loaded at a later time (by your Ajax requests), and this element will act that way for the complete life span of the page, no need to setup/destroy events as I see some suggested. Well that will probably work as well but will generate more workload on the browser engine, consume more memory, require more code and overall be slower and unnecessarily tricky to say the least.

Code samples

I have setup two CodePen example for you:

Delegation1 has event handling code in the HEAD section, it is my preferred way to handle these kind of issues if no restrictions or other unknown quirks exists. The benefits with this version is shorter/faster and more maintainable code.

Delegation1

Delegation2 has event handling code in the Ajax response and should meet the requirements about HTML/JS being loaded continuously. There is a check to only install the listener once and avoid multiple events racing & overlapping.

Delegation2

The Javascript code in the examples contains relevant comments and should be enough to explain the implemented strategy to make this as simple as possible and reusable in other similar cases.

These examples were written with older browsers in mind, newer browser expose more powerful APIs like element.matches(selector) very useful with event delegation. I purposely avoided to use it for broader support.

Answers 8

Thinked that if you add this to your ajax params call all will be ok:

async: false

Read More

Compare keys of dictionary with values of another dictionary

Leave a Comment

I have two dictionaries, both of type Dictionary<string, List<List<string>>. I want to select the range of entries from dictionary 1 which match the values/entries from dictionary 2.

E.g. dictionary 1 has the keys 01, 01.1 and dictionary 2 has the matching values 01, 01.1. at key 1

First I get the entries from dictionary 2 at key 1 like this:

var dictList = (from entry in DbDict                 where entry.Key == id.ToString() // id = 1                 select entry).ToList(); 

I tried to select these via linq with something like this:

var matchingEntries = (from entry in ExcelDict                        where ExcelDict.Keys.Equals(dictList[0].Value)                        select entry).ToList(); 

and tried more along those lines, but it won't return any results.

How do I get the range of valuepairs from dictionary 1, whose keys match the values of dictionary 2?

Edit1:

Dictionary 1:  Key     Value 01      "these", "are"         ..., ... 01.1    "just", "some"         ..., ... 02      "sample", "values"         ..., ...  Dictionary 2: Key     Value 1       "01", "01.1"         "foo", "bar"         ..., ...                 2       "02", "02.21"         "value1" "value2" 

Edit2:

Expected output:

"01", "01.1" "foo", "bar" 

Edit3:

Compilable input as requested in the comments. This is exactly the structure I'm dealing with:

var dict1 = new Dictionary<string, List<List<string>>>();  dict1.Add("01", new List<List<string>> { new List<string> { "these" }, new List<string> { "are" } }); dict1.Add("01.1", new List<List<string>> { new List<string> { "just" }, new List<string> { "some" } }); dict1.Add("02", new List<List<string>> { new List<string> { "sample" }, new List<string> { "values" } });   var dict2 = new Dictionary<string, List<List<string>>>(); dict2.Add("1", new List<List<string>> { new List<string> { "01", "01.1" }, new List<string> { "foo", "bar" } }); dict2.Add("2", new List<List<string>> { new List<string> { "02", "value1" }, new List<string> { "02.21", "value2" } }); 

3 Answers

Answers 1

You wrote:

I want to select the range of entries from dictionary 1 which match the values/entries from dictionary 2.

From your output in Edit2, it seems that you want to take the values in Dictionary 2. You don't do anything with the Keys. Each value is a List>. In your example the all strings in the first list of the value with Key 1 have a corresponding key in dictionary 1. Therefore the complete value is in your output

The first list of the value with Key 2 has an element which is not a key in dictionary 1. Hence nothing of the value is in the output.

Unclear: what if the 2nd list would match instead of the 1st list?

Key     Value 3       "foo", "bar"         "01", "01.1" 

Should this also be in your final result?

Unclear Do you want as result a List>, or do you want one big list with all matching values? What abut duplicates?

Let's assume you only want to check the first List in your List of Lists:

We'll only look at the values from Dictionary 2, the keys are discarded. Then from every list in this value collection we take the first one (if there is one), and as a separate property remember the complete list.

Of course if the list is empty is should not be in the end result, hence we keep only those that have a first element:

IEnumerable<List<List<string>>> dict2Values = dictionary2     .Select(keyValuePair => keyValuePair.Value);  var separatedFirstList = dict2Values.Select(listOfLists=> new {      FirstList = listOfLists.FirstOrDefault(), // this is a List<string>      AllLists = listOfLists,                   // List<List<string>> where FirstList is the first }) .Where(stringListWithFirstElement => stringListWithFirstElement.FirstList != null); 

By now we have transformed your dictionary into:

{     FirstString = {"01", "01.1"},     FullList =    {"01", "01.1"}, {"foo", "bar"}, {...}, {...}, }, {     FirstString = {"02", "02.21"},     FullList =    {"02", "02.21"}, {"value1" "value2"}, ... }, {      FirstString = ...,      FullList = ..., }, ... 

From this sequence we only want to keep those WHERE ALL elements in the FirstString are keys of Dictionary 1:

IEnumerable<string> keysDictionary1 = dictionary1.Keys; var matchingItems = separatedFirstList     .Where(item => item.FirstList.All(txt => keysDictionary1.Contains(txt)); 

You see the Where and the All.

Result:

{     FirstString = {"01", "01.1"},     FullList =    {"01", "01.1"}, {"foo", "bar"}, {...}, {...}, }, ... 

The one with FirstString = {"02", "02.21"} is removed, because not all elements of firstString where a Key in dictionary 1,

Finally: get rid of the FirstString:

List<List<String>> finalResult = matchingItems.Select(matchingItem => matchingItem.FullList); 

Or if you want as a result one List<String>:

List<string> finalResult = matchingItems.SelectMany(matchingItem => matchingItem.FullList); 

Answers 2

It seems you are looking for join using linq:

var result = from d1 in dict1              join d2 in dict2              on double.Parse(d1.Key) equals double.Parse(d2.Key)              select d2.Value; 

In above query, we are joining two dictionaries by equality of key (by parsing the key as number) and for each match we select the Value from the second dictionary as result of the match.

Answers 3

This will give you what you want:

var result = dict2             .Select(kvp => kvp.Value)             .Where(list => list.Where(l => l.Join(dict1.Keys, s1 => s1, s2 => s2, (s1, s2) => s1).Count() == l.Count).Count() > 0)             .ToList(); 
Read More

Sunday, July 29, 2018

Password flag doesn't work to log into mongo

Leave a Comment

I created a mongo daemon. Then, I did:

$ mongo --port 27017  > use admin > db.createUser({            user: "AzureDiamond",             pwd: "hunter2",           roles: [{                role: "readWrite",                  db: "test_db1"           }]    }) >^D 

Then I tried to log into Mongo with the new account (exactly as in section 7 of Mongo's utorial):

$ mongo --port 27017 -u "AzureDiamond" -p "hunter2" --authenticationDatabase "admin" 

This is the weird part. It still prompted me for my password, and then appended that to the database path that I connected to:

Enter password: connecting to: 127.0.0.1:27017/hunter2 > 

What did I do wrong? How can I connect to Mongo while supplying the password in the command line, but not having my password displayed on the screen?

4 Answers

Answers 1

I think that it is just a typo that you've pointed out in your question, Can you please retry the command as shown below:

You just missed a d in your username!

$ mongo --port 27017 -u "AzureDiamond" -p "hunter2" --authenticationDatabase "admin" 

If this doesn't work, can you please try logging in to Mongo database as per the documentation provided here.

Hope this helps!

Answers 2

This will solve your problem:

mongo admin -u {username} -p '{password}' 

Ref: command line authentication of mongo fails

Answers 3

Did you try using the connection string URI?

e.g. mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

So in your case, mongo mongodb://AzureDiamond:hunter2@localhost:27017/test_db1?authSource=admin

Answers 4

Easiest and Most Secure way:


You don't need to specify the port, you can do it easily using:

mongo admin -u ""AzureDiamond"" -p 

Now it will prompt you for the password, enter your password and Voila!! You are logged in!

This is the most secure way, as your password is not visible to others as well.

Hope this works for you! Let me know if this doesn't work!

Read More

JS HTML5 Drag and Drop: Custom Dock Effect Jumping Around in Chrome

Leave a Comment

Situation: I'm using HTML5 drag-and-drop to place tiles in a game I'm writing. I'd like to add an effect where the two tiles that I'm about to drop a new tile between move slightly apart to indicate that this is where you're dropping (similar to the Mac OS dock).

My Approach: I have a flexbox into which I'm dropping these tiles. I wrote a function that essentially returns one period of a sine wave and I'm using it to update the dropped tiles' right: and top: CSS properties (the tiles are position: relative;) based on their original position relative to the mouse during drag.

  // Update occupant style for desired effect   occupants.forEach(function(occupant, index) {     $(occupant).css({'right' : -10 * nudgeSine(occupantsMouseOffset[index] * 10) + 'px',                      'top' : -10 * Math.abs(nudgeSine(occupantsMouseOffset[index] * 10)) + 'px',                      'opacity' : 1 - Math.abs(nudgeSine(occupantsMouseOffset[index])) });   });    // Function to return 1 period of a sine wave   function nudgeSine(x) {     if (x < -3.14159 || x > 3.14159) {       return 0;     } else {       return Math.sin(x);     }   } 

Problem: In Chrome (but not in Firefox), at some mouse positions, which I can't find a pattern in, the tile is jumping back-and-forth. See the .gif below:

In Chrome (left) and in Firefox (right):

demo in Chrome demo in Firefox

I even console.logged the element's calculated right: property, and while it is shown jumping around on screen, it outputs as a constant value.

What I've Tried/Thought About:

  • Even with the mouse stationary and console.log(event.clientX) outputting a constant value, the tile will jump around.
  • I thought event.clientX might be changing imperceptibly, so I'm basing my calculations on Math.trunc(event.clientX) to no avail.
  • I am using element.getBoundingClientRect() in my calculations, which I'm not very familiar with, and I think it may be the root cause of my problem.

I made this CodePen, but wasn't able to completely replicate the issue. Still, I think someone may be able to spot what's happening.

Edit: I've put this up on a github page to fully replicate. This link may not work for future readers of the question, but I'll keep it up for the foreseeable future. To demonstrate the issue, view in Chrome and Firefox.

Thank you.

1 Answers

Answers 1

Perhaps I can expand my answer later, but for now:

Related questions: How to keep child elements from interfering with HTML5 dragover and drop events? 'dragleave' of parent element fires when dragging over children elements

This is what happens: - you start dragging the operator - operator moves over the box, existing operators move along nicely - you move the operator over one of the existing operators - at this point the browser enters a kind of infinite loop thingy, because each time the elements move the position of the elements have to be updated again (because new events are triggered)

Since you need the click event on the existing operators you can't just set them to pointer-events: none; like in the related question, but you can add a class when you start dragging and apply this style to the operators while you're dragging.

Another solution would be to use a library, in the comments of an answer I found the library https://bensmithett.github.io/dragster/, I use draggable by shopify.

update

I wasn't able to find the exact term of this behavior, perhaps we could go with "cyclic case" or "undefined behaviour". See my examples:

:root {    /*colors by clrs.cc*/    --navy: #001f3f;    --blue: #0074D9;    --red: #FF4136;    font-family: sans-serif;  }    .animated {    transition: all .5s;  }    h2 {    color: var(--red);  }    div {    height: 160px;    width: 160px;    padding: 20px;    background: var(--blue);    margin-bottom: 20px;  }    .box1 {    border-right: 20px solid var(--navy);  }    .box1:hover {    border-right: 0px solid var(--navy);  }    .box2:hover {    border-radius: 100px;  }
<div class="box1 animated">hover your mouse over my border on the right →</div>  <div class="box2 animated">hover your mouse over an edge of this box</div>  <h2>Warning, the following boxes have no animations, flashes are expected:</h2>  <div class="box1">hover your mouse over my border on the right →</div>  <div class="box2">hover your mouse over an edge of this box</div>

When the user moves the mouse onto the border the following happens in a loop:

  1. box1 is being hovered
  2. hover styles apply, the border is removed
  3. box1 isn't being hovered
  4. hover styles stop applying, the border is readded

basically for the moment the CSS doesn't really evaluate, because as soon as it evaluates the evaluation is invalid. This is exactly what happens in your example. I don't know whether the CSS standard has rules that define how browsers should handle this. If the expected behavior is defined, either FF or Chrome is wrong and you can file a bug after you find out which browser's behavior is wrong. If no expected behavior is defined and the implementation is left open to browsers then both browsers are right.

Read More

How can I fix “[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction”?

Leave a Comment

When I rotate the device in the simulator, I receive the following message in the console: [App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction.

There is plenty of information about how to suppress the warning, such as in this question. However, it seems like that is just side stepping the problem without actually solving anything.

What exactly does the warning mean and how do I fix it?

1 Answers

Answers 1

"What exactly does the warning mean?"

Unfortunately, I don't know enough about the internals of CoreAnimation to fully explain the message's meaning. The second answer attempts to explain it by examining disassembled code.

"How do I fix it?"

This likely cannot be fixed by you because it is not a problem with your app, despite what the message might suggest with its use of "[App]". (The second answer to the referenced question says as much also.)

I believe this message began appearing in iOS 10, and it happens (typically) during device rotation. My evidence that it can't be fixed is that if you create a blank "Single View App" project, launch it (simulator or device) and rotate the screen the message will be emitted.

As of iOS 12 beta 4, this message is no longer being emitted when rotating the screen. That's not to say it won't happen at other times, as the reason UIKit is emitting it probably has some merit in other circumstances. If possible, try your app out in Xcode 10 beta 4 to see if it still prints the message.

It's worth mentioning here as well, that it's a bad idea to suppress the message with OS_ACTIVITY_MODE as that method suppresses far too much valuable debugging information, such as stack traces.

Read More

How to remove new Notifications from banner?

Leave a Comment

Is there any way to handle remote notification payloads before they’re delivered and display in notification centre?

1 Answers

Answers 1

With push notifications of default type there is no way to filter out notifications if the app is not in foreground.

The possible solution to this is to use VoIP push notifications in conjunction with PushKit.

VoIP pushes are always waking up the application, however they are not presented to the user and don't modify app badge value, so it's up to the developer to show a local notification upon the received VoIP push and to deal with app badge.

There is a technique with additional silent push that for example Facebook is using, to delete notification on iOS device when the message has been read on desktop web site. It's described here: https://www.pushwoosh.com/docs/deletable-ios-push

Read More