text:
Q: Windows - Long freezing busy process after restart following sudden turn off I've accidentally snapped my Windows because of power issue while playing a video from a locally remote computer. After booted again it first prompted me whether I want to fix or restart. I chose to restart because it's happened multiple times before without any serious injury to the Windows.
But this time it's different. It was rebooted successfully. Suddenly after half an hour everything is freezing. At first I can still do clicking on taskbar buttons with nothing happens afterward, selecting files, and toggling windows, but not for long. When I clicked on opened window close button, the button was disabled but the "(not responding)" text didn't show up. Afterall the taskbar also frozen and busy cursor showing. The fan was spinning quite fast for a long period which means CPU is doing a hard task.
But the strange is the video was still able to continue playing. Keyboard's and mouse's buttons are not working before and after replugging them, but I can still moving the mouse around. When I CTRL+ALT+DEL for the first time, the mouse cursor was reset to the center of screen but no task manager opened, before everything was frozen completely.
After a while, the freezing ended. I was allowed to interact with Windows for a number of seconds before it was frozen again. After twice of freezing, an alert popped up with title "Microsoft Windows is not responding". I chose "End process", closing all windows and recreating the taskbar and desktop icons. Everything is fine so far but sometines the freezing happened again but not as long as the first one.
I think that sudden shutdown triggered a background service which was consuming my CPU completely and froze everything. When I checked it's also consuming the GPU since the graph was also peaking. I guess it's just a disk checking process. I've also checked the resource monitor but yet I can't tell which process had done it. How may I know it and at least trying to stop it?


text:
Q: In Cucumber on Ruby w/rspec, how do I expect/assert a webmocked call in a Then clause? I'm writing a gem that acts as a client for a remote API, so I'm using webmock to mock out the remote API, testing with Cucumber with rspec-mock present too.
As part of my Cucumber tests I intend to stub my API in a Given clause but then I would like to specify that the remote API is called in a Then clause.
A really basic example would be:
Feature file
Scenario: Doing something that triggers a call
  Given I have mocked Google
  When I call my library
  Then it calls my Google stub
  And I get a response back from my library

Step definition
Given /I have mocked my API/ do
  stub_request(:get, 'www.google.com')
end

When /I call my library/ do
  MyLibrary.call_google_for_some_reason
end

Then /it calls my Google stub/ do
  # Somehow test it here
end

The question:
How can I verify that my google stub has been called?
Side note: I'm aware I could use the expect(a_request(...)) or expect(WebMock).to ... syntax but my feeling is I'll be repeating what's defined in my Given clause.

A: I answer this myself, though it would be good for someone to verify this is correct and/or has no major pitfalls:
Given /I have mocked my API/ do
  @request = stub_request(:get, 'www.google.com')
end

Then /it calls my Google stub/ do
  expect(@request).to have_been_made.once
end

The bits to note are the assignment of @request and the expectation placed upon it in the Then clause.
In a limited test of two separate scenarios this approach seems to work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating an event subscription for Azure storage account in Terraform I am trying to create the following resources in Azure using Terraform and Terraform provider for Azure.

*

*Create a storage account for blob storage.

*Create an event subscription that will raise events on blob activity.

When running the terraform scripts i get the following error

Error: Error creating/updating EventGrid Event Subscription
  "evtFileReceived" (Scope
  "/subscriptions/c17cf5ee-d3d7-4f64-b863-f2a4d6948594/resourceGroups/dominos-doodle"):
  eventgrid.EventSubscriptionsClient#CreateOrUpdate: Failure sending
  request: StatusCode=400 -- Original Error: Code="InvalidRequest"
  Message="The specified topic property does not match the expected
  topic from the event subscription scope."

How shoud i fix it ?. Google search didn't gave any results.
The script that generated the error is as follows. The step that throwed the error is terraform apply
Obviously one way is to use the ARM templates to achieve this, but i am trying to see if it can be created using native Terraform scripts. I referred to Terraform Docs and created the following.
variable "inp_resource_group_name" { }
variable "inp_geo_location" { }
variable "inp_account_name" { }
variable "inp_az_subscription_id" { }
variable "inp_resource_group_id" { }

resource "azurerm_storage_account" "cave" {
  name                     = var.inp_account_name
  resource_group_name      = var.inp_resource_group_name
  location                 = var.inp_geo_location
  account_tier             = "Standard"
  account_replication_type = "LRS"
  account_kind             = "StorageV2"
}

resource "azurerm_storage_container" "validName" {
  name                  = validName"
  resource_group_name   = var.inp_resource_group_name
  storage_account_name  = var.inp_account_name
  container_access_type = "blob"
}

resource "azurerm_eventgrid_event_subscription" "evtFileReceived" {
  name  = "evtFileReceived"
  scope = var.inp_resource_group_id
  topic_name="/subscriptions/${var.inp_az_subscription_id}/resourceGroups/${var.inp_resource_group_name}/providers/Microsoft.Storage/storageAccounts/{var.inp_account_name}"
  webhook_endpoint {
    url = "https://myendpoint.that.works.well.across.all.osi.layers"
  }
}

A: I had a similar issue and solved it by setting both the scope and topic_name to the storage account id. So in your example, I think this should work;
resource "azurerm_eventgrid_event_subscription" "evtFileReceived" {
  name  = "evtFileReceived"
  scope = azurerm_storage_account.cave.id
  topic_name = azurerm_storage_account.cave.id
  webhook_endpoint {
    url = "https://myendpoint.that.works.well.across.all.osi.layers"
  }
}

A: According to the error message, it indicates that the topic_name property in resource azurerm_eventgrid_event_subscription does not match the expected topic from the event subscription scope.
In this case, the scope should be created at the storage account level as the topic is associated with a storage account resource. It will like this:
resource "azurerm_eventgrid_event_subscription" "evtFileReceived" {
  name  = "evtFileReceived"
  scope = ${azurerm_storage_account.cave.id}
  topic_name="/subscriptions/${var.inp_az_subscription_id}/resourceGroups/${var.inp_resource_group_name}/providers/Microsoft.Storage/storageAccounts/{azurerm_storage_account.cave.name}"
  webhook_endpoint {
    url = "https://myendpoint.that.works.well.across.all.osi.layers"
  }
}

Or, refer to this GitHub issue, you could use the scope with the id of the
eventgrid topic.

Realized that the resource group in this case is an art from a topic
  type to subscribe and not a reference where to create the subscription
  resource. It seems that "topic_name" and "resource_group_name" are
  deprecated parameters. Use "scope" instead with the id of the
  eventgrid topic.

It will like this:
resource "azurerm_eventgrid_topic" "example" {
  name                = "my-eventgrid-topic"
  location            = "${azurerm_resource_group.default.location}"
  resource_group_name = "${azurerm_resource_group.default.name}"

}

resource "azurerm_eventgrid_event_subscription" "evtFileReceived" {
  name  = "evtFileReceived"
  scope = "${azurerm_eventgrid_topic.example.id}"

 webhook_endpoint {
        url = "https://myendpoint.that.works.well.across.all.osi.layers"
      }

}

Please let me know if this works or need further help.


text:
Q: Email address used by website but I do not know where I build a website for a client. This client then filled the website with content. I created 20 contact forms, using the contactform 7 and WP Mail SMTP Pro plugin.
The website has now more than 100 pages.
First my email address was used for the sites admin. I changed this later to my clients email address. I also used the client his email address for all of the contact forms.
But now I still get a emails from the site, every now and again. When a visitor from the site used the site to email my client, either by contactform, or otherwise (I do not know exactly how). Instead of sending the email to my client, the email was send to my email address.
I want to change this, but do not know from what part of the website the emails are coming from. They are not coming from the contact forms, I changed the email addresses there.
Is there a way I can see what page the emails are coming from? The people who send the emails do not remember which part of the website they used when sending the emails.
Maybe there is a way to download all of the source code of the website?

A: Email settings are usually somewhere in the database. You'll likely find it in a table that gives you a good clue about where the setting can be changed. It may be wise not to just search-and-replace it directly since data can be serialized, meaning that if you replace the address with a different one that has a different number of characters, that breaks the setting. However, there are plugins that can do safe search-and-replace because they unserialize and re-serialize data.
If you don't find the email address anywhere in the database, the other option would be in the files. Yes, you can download the site's files, typically using an FTP client, sometimes using a host's file manager tool. Then you would want to run a "find in files" type command to search for the email address, and again, carefully replace it. If you do find the email address in files, it would be better to take the time to convert that to a setting that can be changed in wp-admin, rather than having to edit any of the theme or plugin files directly.


text:
Q: I am new to flask tryin to run first application .. here is my code and what turns back in terminal .. any suggestions?
code

from flask import Flask, render_template, session, request

from flask_session import Session

app = Flask(__name__)

app.config["SESSION_PERMANENT"] = False

app.config["SESSION_TYPE"]= "filesystem"

Session(app)

@app.route("/", methods=["GET", "POST"])
def index():
    if session.get("comments") is None:
        session["comments"] = []

if request.method == "POST":
    comment = request.form.get("comment")
    session["comments"].append(comment)

CMD

(env) E:\COURSES\CS50W\lec2\exersice>set FLASK_APP=application.py
(env) E:\COURSES\CS50W\lec2\exersice>python -m flask run
E:\COURSES\CS50W\lec2\exersice\env\Scripts\python.exe: No module named flask

A: Check this out.
If you are not sure whether you have installed flask or not, try running only flask in the cmd or any terminal.If you get any commands about flask then you can be sure that it is installed or you can install by using
pip install flask

If you are concerned about the versions of the libraries you use for your application, then follow the above mentioned link!


text:
Q: Perfect matchings of a regular, uniform, partite hypergraph This is in relation to the question here. What, if any, are the known conditions for the existence of a perfect matching for a $r$-regular, $r$-uniform, $r$-partite hypergraph. I specifically interested in the $r=3$ case, but any general information is good. So far I have not been able to find a reference that discusses this particular case.
In the question link to above, he is not requiring that the $k$ (for $k$-regular) be the same as the $r$ (for $r$-uniform and $r$-partite), and the example given in the solution uses a case where $k\neq r$.
Any indication on where I might find references for this case or even just the theorems themselves (with the references) would be greatly appreciated.

A: Without the regularity assumption, Aharoni, Georgakopoulos and Sprüssel have a paper on this topic:
"Perfect matchings in r-partite r-graphs"
https://www.sciencedirect.com/science/article/pii/S0195669808000644
They give a pretty stringent, yet tight sufficient condition. In the discussion section, they speculate many other possible sufficient conditions, which might have been proved or disproved by this point. Perhaps digging through the many Google scholar citations might be helpful.

A: Here is a 3-regular 3-partite 3-uniform hypergraph with 3 vertices in each part having no perfect matching.  This example generalizes in a straightforward way to give a $d$-regular $k$-partite $k$-uniform hypergraph with $d$ vertices in each part having no perfect matching for all $d$ and $k$.
$x_1y_1z_1$
$x_1y_2z_2$
$x_1y_3z_3$
$x_2y_1z_1$
$x_2y_2z_2$
$x_2y_3z_3$
$x_3y_1z_2$
$x_3y_2z_3$
$x_3y_3z_1$
As for sufficient conditions, I think this is a very natural question as it attempts to generalize the specific fact that any regular bipartite graph has a perfect matching (and thus can be decomposed into perfect matchings).  I would look at "Hall's Theorem for Hypergraphs" by Aharoni and Haxell as a starting point, but I can't recall any results which specifically focus on the regular case.


text:
Q: Looking for a middle grade YA fantasy about girl who transitions into a fairy I've been trying to find this book for a while and I can't. From what I can remember:

*

*main character is a teenage girl, possibly named Alice

*She has an older brother away at college

*Single father, mother died

*When she reaches a certain age (16?) she starts a painful transition where she grows wings from her back.

*Her whole family (or i think just the mother's side) has the same thing because they are secretly fairies

*She gets feverishly sick during the process

*The wings she gets are blue?

*front cover of the book has blue fairy wings

*She may have a female best friend, name unknown

*most of the plot is very fuzzy and that's what I remember for sure


text:
Q: Grouped uitableview with shadow Any ideas how to show a shadow around the grouped uitableview's border?(around all border at top, bottom, sides as well as around rounded corners of sections).
I need exactly the same effect like here on the picture:

Pay attention to small shadow near the border(gray one, blue is the background)

A: Easiest one would be add drop-shadow styling to the layer to your cells in table. Remember you would have 3 types of styling - one for the top of the cell, one for the bottom cell and one for the other cells. Should not be very difficult if you start writing the code.

A: i came up with a rather "hackish" solution to this in my opinion, so i'm not totally happy with it but anyway! the basic functionality of drawing a drop shadow around a group of cells in a section is acomplished by that. therefore i subclassed UITableView and implemented the layoutSubviews method like this:
- (void) layoutSubviews {
    [super layoutSubviews];

    const CGFloat PageCellBackgroundRadius = 6.0;

    for(int i = 0; i < [self numberOfSections]; i++) {
        NSInteger viewTag = i + 123456;
        CGRect frameRect = [self shadowFrameForSection: i];

        UIView* shadowBackgroundView = [self viewWithTag: viewTag];
        if (shadowBackgroundView) {
            if (!CGRectEqualToRect(frameRect, shadowBackgroundView.frame)) {
                shadowBackgroundView.frame = frameRect;
                CGPathRef shadowPath = [UIBezierPath bezierPathWithRoundedRect: shadowBackgroundView.bounds
                                                             byRoundingCorners: UIRectCornerAllCorners
                                                                   cornerRadii: CGSizeMake(PageCellBackgroundRadius, PageCellBackgroundRadius)].CGPath;
                shadowBackgroundView.layer.shadowPath = shadowPath;
            }

            [self sendSubviewToBack: shadowBackgroundView];
        } else {
            shadowBackgroundView = [[[UIView alloc] initWithFrame: frameRect] autorelease];
            shadowBackgroundView.tag = viewTag;
            shadowBackgroundView.opaque = YES;
            shadowBackgroundView.backgroundColor = [UIColor clearColor];

            shadowBackgroundView.layer.shadowOpacity = 0.3;
            shadowBackgroundView.layer.shadowRadius = 2;
            shadowBackgroundView.layer.shadowColor = [[UIColor blackColor] CGColor];
            shadowBackgroundView.layer.shadowOffset = CGSizeMake(0.0, 1.0);
            CGPathRef shadowPath = [UIBezierPath bezierPathWithRoundedRect: shadowBackgroundView.bounds
                                                         byRoundingCorners: UIRectCornerAllCorners
                                                               cornerRadii: CGSizeMake(PageCellBackgroundRadius, PageCellBackgroundRadius)].CGPath;
            shadowBackgroundView.layer.shadowPath = shadowPath;
            shadowBackgroundView.layer.shouldRasterize = YES;

            [self addSubview: shadowBackgroundView];
        }
    }
}

and a little helper method:
- (CGRect) shadowFrameForSection: (NSInteger) section {
    CGRect sectionFrame = [self rectForSection: section];

    CGFloat sectionHeaderHeight = CGRectGetHeight([self rectForHeaderInSection: section]);
    CGFloat sectionFooterHeight = CGRectGetHeight([self rectForFooterInSection: section]);

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(sectionHeaderHeight + 1, 10, sectionFooterHeight + 1, 10);
    return UIEdgeInsetsInsetRect(sectionFrame, contentInsets);
}

the code is self-explanatory i think!
basically it revolves around adding UIViews to the UITableView as subviews, for a calculated frame of a section, and then drawing the drop shadow to the layer of the added UIView. UITableView provides
some methods for the frame calculations: "rectForSection" etc.
i'm not happy with it because it feels not right adding views in the layoutSubviews method! (this could be done somwhere else => table view delegate?)
i also would have liked more to work with CALayers, but you can't tag them! because my code works by
shrinking/expanding already added uiviews for performance reasons.
in this form, the solution won't work if sections disappear or if sections are reorderd etc.
it also behaves not well if you're adding rows in a animated fashion to the table view etc.
but it's quite useful for "static" grouped table views i think!
i also haven't tested for performance implications, so use at own risk!
so maybe this is a good starting point for a possibly better solution to this! :-)

A: In cellForRowAtIndexPath: function:
// drop shadow
cell.layer.shadowOpacity = 1.0;
cell.layer.shadowRadius = 1.7;
cell.layer.shadowColor = [UIColor blackColor].CGColor;
cell.layer.shadowOffset = CGSizeMake(0.0, 0.0);


text:
Q: Is there really a valid scenario for the new overload in C#?
The example shows my scenario. I have a BaseClass with some nice functionality which is used by the derived class SpecialClass. But the BaseClass has a Parent of type BaseClass. The SpecialClass needs a Parent of the type SpecialClass because I do not want to cast - better safe cast - the parent every time I use it. To solve this scenario I used the keyword new to create a overload of this property. The same applies for BaseConnection and some other properties.
Unfortunate I hate this keyword and in my opinion it represents always the lack of a good design. But in this case I have clearly no idea how to better solve this problem. Does anyone have an idea?
Regards, Yggdrasil

A: Why not use something like that (for example):
public class Base
{

    public virtual Base Parent { get {return ...}}

    public virtual BaseConnection Connection { get {return ... ;}}
}

public class Special : Base
{

    public override Base Parent { get {return MySpecialParent;}}

    public override BaseConnection Connection { get {return new SpecialConnection();}}
}

or even something like that (in case there is no relation between BaseConnection  and SpecialConnection):
public class Base
{

    public virtual dynamic Parent { get {return ...}}

    public virtual dynamic Connection { get {return ... ;}}
}

public class Special : Base
{

    public override dynamic Parent { get {return MySpecialParent;}}

    public override dynamic Connection { get {return new SpecialConnection();}}
}

But maybe you should give another thought about your class separations , maybe you should inject the specific relations to the Base class from it's creator or use some sort of container and work with interfaces instead . Just a thought ... :)


text:
Q: How to center external FitProportional Image on RDLC report? What is the easiest way to center an image (of unknown dimension) on an RDLC local view report in ASP.NET webform (Report Viewer 2012/Visual Studio 2013)?
The external image is set to FitProportional and its value is set to the URL of an image of unknown size and type. The image itself displays OK (most of the time) at the correct size but sits at top left of the image container. It seems to me that this control screams for two simple horizontal/vertical alignment properties. What kind of moron writes an image control that cannot at least be center aligned?
Is it possible to derive a custom Image control that overrides the drawing routine to manually center the image in the container? It would need to behave properly so the centering is also applied to the Word and PDF export (the only reason I'm using this awkward RDLC engine is for the "convenience" of Excel/Word/PDF export capabilities) (hence I cannot simply use CSS on the image to center it in the HTML output).
{rant} Sometimes the image is displayed with width=1 in HTML. Presumably this is something to do with delays in fetching the external image or some such lame excuse, so I probably have to further pollute my system with coding gymnastics to avoid that problem too. The main container layout is also easily messed up when changing zoom levels, and it really does not know how to size itself properly. I'm not sure if I'm missing something, if my CSS is messing it up or if it really is a just a badly implemented horror. {/rant}


text:
Q: Can I dynamically add a field to FormType form? I have a PostType form that extends AbstractType. In controller I'd like to add a field to it if certain condition is met. Can I do this somehow or is there another best practice on modifying FormTypes in controllers?
Thanks

A: Let say you have a Form of type FileType as follow:
<?php
namespace EventFlowAnalyser\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class FileType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', 'text', array('label' => 'Name'));
    }

    public function getName()
    {
        return 'file';
    }
}

You can use it in your controller like this:
$form = $this->createForm(new FileType(), $document);

Where $document is an object containing one field (name).
Now, if you need to add a field to the form object in another function, you can extend the FileType to add the field you need; for example if you want to edit the name field but want still to keep track of the previous state lets add an original_name field.
<?php
namespace EventFlowAnalyser\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

use EventFlowAnalyser\Form\EventListener\EditFileFieldSubscriber;

class FileEditType extends FileType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder->add('original_name', 'hidden', array('mapped' => false));
    }
}

Now, you can use the extended form like that:
$form = $this->createForm(new FileEditType(), $document);

And modify the value of the field like that:
$form->get('original_name')->setData($document->name);

I hope this will help somenone :o)

A: Sure You can add fields dynamically using Collection Type in form.
See the below link, this will helps you how to make fields dynamically.
Link1: Dynamic Field in Symfony2
Link2: Form Collection in symfony2 doc
Hope these two links helps you.
Happy coding..

A: You can do it by using Form Events.

A: I think you should add a boolean option to your form, and set it in your controller. This way you would have a clean M(V)C separation.


text:
Q: How to sort scraped items? I have working scraper here but im struggling with sorting the data.
Here is the scraper code:
var http = require('http');
var request = require('request');
var cheerio = require('cheerio');

http.createServer(function (req, res) {
request('http://www.xscores.com/soccer', function (error, response,
    html) {
    if (!error && response.statusCode == 200) {
        var $ = cheerio.load(html);
        var list_items = "";
        var arr = [];
        var arr2 = [];
        var j = 1;
        $('div.match_line.score_row.other_match.e_true').each(function (i, element) {
            var a = $(this).attr('data-home-team');
            arr.push(a + " Row Number " + j);
            j = j + 2;
            //list_items += "
" + a + "
";
            //console.log(arr.length);
        });
        var j = 2;
        $('div.match_line.score_row.other_match.o_true').each(function (i, element) {
            var b = $(this).attr('data-home-team');
            arr.push(b + " Row Number " + j);
            j = j + 2;
            //list_items += "
" + b + "
";
            //console.log(arr.length);
        });
        var arrayLength = arr.length;
        for (var i = 0; i < arrayLength; i++) {
            list_items += "
" + arr[i] + "
";
        }
        var html = "
" + list_items + "
"
        res.writeHead(200, {
            'Content-Type': 'text/html'
        });
        res.end(html);
        console.log(arr.length);
    }
});
}).listen(8080);
console.log('Server is running at http://178.62.253.206:8080/');

So to the problem, Sorting these elements.

*

*Element 'div.match_line.score_row.other_match.e_true' are in placed every nth
Odd Row Number in the source page.

*And element 'div.match_line.score_row.other_match.o_true' are in placed every nth Even Row Number in the source page.

The way It gets sorted now

*

*My array(arr) first pushes all rows of data into the array from the first
element (odd row number)

*Then array(arr) pushes all rows of data from the 2nd element into the same
array. (even row number)

So basically items in my array is sorted like this 1,3,5,7,9,2,4,6,8 (shortened)
How can I sort this so I can output this in correct order ?
Any suggestion for a solution would be much appreciated
Frederik

A: Check the arr.sort method below.

var http = require('http');
var request = require('request');
var cheerio = require('cheerio');

http.createServer(function(req, res) {
  request('http://www.xscores.com/soccer', function(error, response,
    html) {
    if (!error && response.statusCode == 200) {
      var $ = cheerio.load(html);
      var list_items = "";
      var arr = [];
      var arr2 = [];
      var j = 1;
      $('div.match_line.score_row.other_match.e_true').each(function(i, element) {
        var a = $(this).attr('data-home-team');
        arr.push({
          html: a,
          j: j
        });
        j = j + 2;
        //list_items += "
" + a + "
";
        //console.log(arr.length);
      });
      var j = 2;
      $('div.match_line.score_row.other_match.o_true').each(function(i, element) {
        var b = $(this).attr('data-home-team');
        arr.push({
          html: b,
          j: j
        });
        j = j + 2;
        //list_items += "
" + b + "
";
        //console.log(arr.length);
      });

      arr.sort(function(a, b) {
        return a.j - b.j
      })

      var arrayLength = arr.length;
      for (var i = 0; i < arrayLength; i++) {
        list_items += "
" + arr[i].html + "
";
      }
      var html = "
" + list_items + "
"
      res.writeHead(200, {
        'Content-Type': 'text/html'
      });
      res.end(html);
      console.log(arr.length);
    }
  });
}).listen(8080);
console.log('Server is running at http://178.62.253.206:8080/');


text:
Q: Detect latin1 characters in utf8 string I get data from the database that is utf8 encoded. But somehow some old data contains latin1 characters.
So this
$encod = mb_detect_encoding($string, 'UTF-8', true);

always is correct.
Is it safe to always use utf8_decode() to check for latin1 characters like 'äöüß'???
$string = utf8_decode($string);
$search = Array(" ", "ä", "ö", "ü", "ß", "."); //,"/Ä/","/Ö/","/Ü/");
$replace = Array("-", "ae", "oe", "ue", "ss", "-"); //,"Ae","Oe","Ue");
$string = str_replace($search, $replace, strtolower($string));

Regards

A: It seems to work without the utf8_encoding:
<?php
   $string = "äöüß";
   $search = Array(" ", "ä", "ö", "ü", "ß", "."); //,"/Ä/","/Ö/","/Ü/");
   $replace = Array("-", "ae", "oe", "ue", "ss", "-"); //,"Ae","Oe","Ue");
   $string = str_replace($search, $replace, strtolower($string));
   echo $string;
?>

DEMO: http://codepad.org/HGTyHkBU

A: Use htmlspecialchars(); it is more safer for work.
More info:
http://php.net/manual/en/function.htmlspecialchars.php


text:
Q: Writing small chunks of data to flash memory page I have an application where I must save chunks of data to flash memory. The flash memory used:
https://datasheet.datasheetarchive.com/originals/dk/DKDS-24/460477.pdf
In the datasheet, it is mentioned that I cannot write to the page that has already been written ( even if it is half empty). I would like some advice regarding what is the best way to manage the writes to the memory?

*

*I am writing chunks of 25 bytes.

*Total page size is 256 Bytes

*Total amount of pages 16,384

*Smallest erase sector : 4KB (16 Pages)
My questions:

*

*The only way I can think of to manage the memory, is to have a 4KB buffer and everytime I want to write some data, read the last 16 pages of data and save it in the buffer. Then I CAN erase the sector and rewrite the previous data as well as a new chunk. Is this the most common practise? Are there any other better methods available?

The only other way I can think of is to simply write 1 chunk of data per page which sounds like a complete waste of memory. But considering that I have 16384 pages available, saving 16384 chunks of data might be more than enough for my application.

*Is it normal practise to use some asci character to signal the end of the chunk?
For example using Decimal 13 (carriage return) as a seperator:

PAGE
[CHUNK1] 13 [CHUNK2] 13 [CHUNK3] ........
END OF PAGE
Appreciate all the help.

A: According to chapter 8.2.13 you can write to previously unwritten bytes. So you don't read the target page to be able to write few bytes. Just use the correct address and write the chunk.
If you have a fixed size of chunks, you don't need a separator, specifically if the contents of each chunk is binary. ASCII separators are solutions for stream-like data. This will give you 10 chunks per page.
Just in case that you want to use all space, you can write a function that knows how to split a chunk to write it in two adjacent pages. Think of some kind of HAL, hardware abstraction layer.


text:
Q: Getting error like [Utility] +[AFAggregator logDictationFailedWithError:] Error Domain=kAFAssistantErrorDomain Code=209 "(null)" I trying to develop an app which have both speech to text and text to speech one at a time that means , when I talking text to speech will be in off , when I playing a voice for text to speech then speech recognition will be in off state.
Steps:
1-Open a app-app should start recognize the voice
2-Start speaking the words like :hello
3-Then play -so if we say play app should play the text that present on the screen.
4-Again start speaking-After voice played again I want to start a speech recognition process.
The above step is the regular process that i would expecting.
The speech recognition should keep on running .For speech to text I used Apples Speech framework.For Text To speech I used AVFoundation and MediaPlayer library.
Here i am facing an issue ,i.e.,
1-I am saying hello it is printing Hello in screen
2-And I am saying play as a command app is playing a voice
3-After that i am getting an error [Utility] +[AFAggregator logDictationFailedWithError:] Error Domain=kAFAssistantErrorDomain Code=209 "(null)". i don't know why it is occurring.I have searched in google ,but i didn't get any fair solution for this , please help me to resolve this.
Here is my code
@interface ViewController ()

@end

@implementation ViewController
{
    SFSpeechAudioBufferRecognitionRequest *recognitionRequest;
    SFSpeechRecognitionTask *recognitionTask;
    AVAudioEngine *audioEngine;
    NSMutableArray *speechStringsArray;
    BOOL SpeechToText;
    NSString* resultString;
    NSString *str ;
    NSString *searchString;
    AVAudioInputNode *inputNode;
    BOOL didStartSpeaking;
    NSString *textToSpeak;
    NSMutableArray *speechCommandArray;

}

- (void)viewDidLoad {
    [super viewDidLoad];

    //Speech To Text ****
    speechStringsArray = [[NSMutableArray alloc]init];
    [self.textView resignFirstResponder];
    [self.textView setDelegate:self];

       ////             *****
    // Initialize background audio session
    NSError *error = NULL;
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:&error];
    if(error) {
        NSLog(@"@error: %@", error);
    }
    [session setActive:YES error:&error];
    if (error) {
        NSLog(@"@error: %@", error);
    }

    // Enabled remote controls
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    // Voice setup
    self.voicePicker.delegate = self;
    self.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-us"];
    self.voices = [NSMutableArray arrayWithObjects:
                   @{@"voice" : @"en-us", @"label" : @"American English (Female)"},
                   @{@"voice" : @"en-au", @"label" : @"Australian English (Female)"},
                   @{@"voice" : @"en-gb", @"label" : @"British English (Male)"},
                   @{@"voice" : @"en-ie", @"label" : @"Irish English (Female)"},
                   @{@"voice" : @"en-za", @"label" : @"South African English (Female)"},
                   nil];

    // Synthesizer setup
    self.synthesizer = [[AVSpeechSynthesizer alloc] init];
    self.synthesizer.delegate = self;

       // This notifcation is generated from the AppDelegate applicationDidBecomeActive method to make sure that if the play or pause button is updated in the background then the button will be updated in the toolbar
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateToolbar) name:@"updateToolbar" object:nil];

    if (self.textView.text.length >0) {

        [self.playPauseBarButtonItem setEnabled:YES];
     }
    else
    {
        [self.playPauseBarButtonItem setEnabled:NO];
        }}

-(void)viewDidAppear:(BOOL)animated
{

    self.speechRecognizer = [[SFSpeechRecognizer alloc]initWithLocale:[NSLocale localeWithLocaleIdentifier:@"en-US en-UK en-IN"]];

    self.speechRecognizer.delegate = self;

    audioEngine = [[AVAudioEngine alloc]init];

    self.textView.text = @"";

    [SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus authStatus) {
        switch (authStatus) {
            case SFSpeechRecognizerAuthorizationStatusAuthorized:
                //User gave access to speech recognition
                NSLog(@"Authorized");

                [self start_record];

                break;

            case SFSpeechRecognizerAuthorizationStatusDenied:
                //User denied access to speech recognition
                NSLog(@"AuthorizationStatusDenied");

                break;

            case SFSpeechRecognizerAuthorizationStatusRestricted:
                //Speech recognition restricted on this device
                NSLog(@"AuthorizationStatusRestricted");

                break;

            case SFSpeechRecognizerAuthorizationStatusNotDetermined:
                //Speech recognition not yet authorized

                break;

            default:
                NSLog(@"Default");
                break;
        }
    }];

    //MARK : Interface Builder Actions

}

 //methods for increase the speed
- (IBAction)handleSpeedStepper:(UIStepper *)sender
{
    double speedValue = self.speedStepper.value;
    [self.speedValueLabel setText:[NSString stringWithFormat:@"%.1f", speedValue]];
}
//methods for increase the pitch
- (IBAction)handlePitchStepper:(UIStepper *)sender
{
    double pitchValue = self.pitchStepper.value;
    [self.pitchValueLabel setText:[NSString stringWithFormat:@"%.1f", pitchValue]];
}
//methods for play and pause the voice
- (IBAction)handlePlayPauseButton:(UIBarButtonItem *)sender
{

    if (self.synthesizer.speaking && !self.synthesizer.paused) {

        if (self.pauseSettingSegmentedControl.selectedSegmentIndex == 0) {
            // Stop immediately
            [self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
        }

        else
        {
            // Stop at end of current word
            [self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryWord];

        }

        [self updateToolbarWithButton:@"play"];
    }

    else if (self.synthesizer.paused) {
        [self.synthesizer continueSpeaking];
        [self updateToolbarWithButton:@"pause"];
    }

    else {

        if(self.textView.text.length>0)
        {

        [self speakUtterance];

        [self updateToolbarWithButton:@"pause"];
        }
        else
        {
            [self updateToolbarWithButton:@"play"];

        }

    }
}

//methods for recognize the voice spoken by user -speech recognize
   -(void)start_record{

    NSError * outError;

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];

    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&outError];

    [audioSession setMode:AVAudioSessionModeMeasurement error:&outError];
    [audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation  error:&outError];

    recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc]init];

    inputNode = audioEngine.inputNode;

    if (recognitionRequest  == nil) {
        NSLog(@"Unable to created a SFSpeechAudioBufferRecognitionRequest object");
    }
    if (inputNode == nil) {
        NSLog(@"Audio engine has no input node ");

    }

    //configure request so that results are returned before audio recording is finished

    [recognitionRequest setShouldReportPartialResults:YES];

    // A recognition task represents a speech recognition session.
    //We keep a reference to the task so that it can be cancelled .

    recognitionTask = [self.speechRecognizer recognitionTaskWithRequest:recognitionRequest resultHandler:^(SFSpeechRecognitionResult * result, NSError *  error1) {

        BOOL isFinal = false;

        if ((result = result)) {

            NSString *speech = result.bestTranscription.formattedString;
            NSLog(@"the speech:%@",speech);

            //storing the results in array.
            for (int i = 0 ;i <speechStringsArray.count;i++)
            {

                str = [speechStringsArray objectAtIndex:i];

                NSRange range = [speech rangeOfString:str options:NSCaseInsensitiveSearch];
                NSLog(@"found: %@", (range.location != NSNotFound) ? @"Yes" : @"No");

                if (range.location != NSNotFound) {

                    NSLog(@"inside if");
                    resultString = [speech stringByReplacingCharactersInRange:range withString:@""];

                    speech = resultString;

                    NSLog(@" the result is : %@",resultString);

                }
                else
                {
                    NSLog(@"ifcondition fails");
                    //speech = resultString;
                    resultString = speech;

                }

            }

            //commands are used like play to play a voice
            if (resultString.length>0) {

                if ([resultString isEqualToString:@" play"]) {

                    [self play];

                }
                else if ([resultString isEqualToString:@" exit"])
                {
                    UIApplication *app = [UIApplication sharedApplication];
                    [self applicationWillTerminate:app];

                }

                else if ([speech isEqualToString:@" mute"])
                {
                    [[MPMusicPlayerController applicationMusicPlayer] setVolume:0];

                }
                else if ([speech isEqualToString:@" up"])
                {
                    float vol = [[AVAudioSession sharedInstance] outputVolume];
                    vol ++;
                    [[MPMusicPlayerController applicationMusicPlayer] setVolume:vol];

                }
                else if ([speech isEqualToString:@" down"])
                {
                    float vol = [[AVAudioSession sharedInstance] outputVolume];
                    vol --;
                    [[MPMusicPlayerController applicationMusicPlayer] setVolume:vol];
                }

                else if ([speech isEqualToString:@" speed"])
                {
                    double speedValue = self.speedStepper.value;
                    NSString *speedup = self.speedValueLabel.text;
                    double speed = [speedup doubleValue];

                    speed += 0.1;

                    [self.speedValueLabel setText:[NSString stringWithFormat:@"%.1f", speed]];
                }

                else
                {
                    NSLog(@"coming");
                    self.textView.text = [NSString stringWithFormat:@"%@%@",self.textView.text,resultString];

          if (![resultString isEqualToString:@" play"]) {

               [speechStringsArray addObject:resultString];

  }

                }

            }

            else
            {

                if ([speech isEqualToString:@"Play"]) {

                    [self play];

                }

               if ([speech isEqualToString:@"Speed"])

                {
                    double speedValue = self.speedStepper.value;
                    NSString *speedup = self.speedValueLabel.text;
                    double speed = [speedup doubleValue];

                    speed += 0.1;

                    [self.speedValueLabel setText:[NSString stringWithFormat:@"%.1f", speed]];
                }

                else if ([speech isEqualToString:@"Exit"])

                {
                   //[[NSThread mainThread] exit];
                    UIApplication *app = [UIApplication sharedApplication];
                    [self applicationWillTerminate:app];

                }

                else if ([speech isEqualToString:@"Mute"])
                {
                    [[MPMusicPlayerController applicationMusicPlayer] setVolume:0];

                }
                else if ([speech isEqualToString:@"Up"])
                {
                    float vol = [[AVAudioSession sharedInstance] outputVolume];
                  //  vol +=1.0;
                    vol ++;

                    [[MPMusicPlayerController applicationMusicPlayer] setVolume:vol];

                }
                else if ([speech isEqualToString:@"Down"])
                {
                    float vol = [[AVAudioSession sharedInstance] outputVolume];
                    //vol -= 1.0;
                    vol --;
                    [[MPMusicPlayerController applicationMusicPlayer] setVolume:vol];
                }
                else
                {

                    if (![speech isEqualToString:@"Play"]) {

                        [speechStringsArray addObject:speech];

                        if (self.textView.text.length > 0) {

                            self.textView.text = [NSString stringWithFormat:@"%@%@",self.textView.text,speech];

                        }
                        else

                        {
                            self.textView.text = speech;

                        }

                    }

                }

            }

            NSLog(@" array %@",speechStringsArray);

            isFinal = result.isFinal;

        }

        if (error1 != nil || isFinal) {

            recognitionRequest = nil;
            recognitionTask = nil;

            [audioEngine stop];
            [inputNode removeTapOnBus:0];
            [recognitionRequest endAudio];

            [self start_record];

        }

    }];

    AVAudioFormat *recordingFormat =  [inputNode outputFormatForBus:0];

    [inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when){

        [recognitionRequest appendAudioPCMBuffer:buffer];

    }

     ];
    NSError *error1;
    [audioEngine prepare];
    [audioEngine startAndReturnError:&error1];

}

-(void)play
{
    if (self.synthesizer.speaking && !self.synthesizer.paused) {

        if (self.pauseSettingSegmentedControl.selectedSegmentIndex == 0) {
            // Stop immediately
            [self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
        }

        else
        {
            // Stop at end of current word
            [self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryWord];

        }

        [self updateToolbarWithButton:@"play"];
    }

    else if (self.synthesizer.paused) {
        [self.synthesizer continueSpeaking];
        [self updateToolbarWithButton:@"pause"];
    }

    else {

        if(self.textView.text.length>0)
        {

            [self speakUtterance];

            [self updateToolbarWithButton:@"pause"];
        }
        else
        {
            [self updateToolbarWithButton:@"play"];

        }

    }

}
 - (void)applicationWillTerminate:(UIApplication *)application
{
    exit(0);

}

//text to speech method

- (void)speakUtterance
{

    if (audioEngine.isRunning) {

        NSLog(@"Running");
        recognitionRequest = nil;
        recognitionTask = nil;
        [speechStringsArray removeAllObjects];
        resultString = @"";

        [audioEngine stop];
        [inputNode removeTapOnBus:0];
        [recognitionRequest endAudio];

    }

    if (self.textView.text.length > 0) {
        NSLog(@"speakUtterance");
        didStartSpeaking = NO;
        textToSpeak = [NSString stringWithFormat:@"%@", self.textView.text];
        AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:textToSpeak];
        utterance.rate = self.speedStepper.value;
       utterance.pitchMultiplier = self.pitchStepper.value;
        utterance.voice = self.voice;
        [self.synthesizer speakUtterance:utterance];
        [self displayBackgroundMediaFields];

      //y  NSLog(@" after speaking:%@",self.textView.text);

    }

    else
    {
        [self updateToolbarWithButton:@"play"];

    }

}

- (void)displayBackgroundMediaFields
{
    MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"Play"]];

    NSDictionary *info = @{ MPMediaItemPropertyTitle: self.textView.text,
                            MPMediaItemPropertyAlbumTitle: @"TextToSpeech App",
                            MPMediaItemPropertyArtwork: artwork};

    [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = info;

}

- (void)updateToolbar
{
    if (self.synthesizer.speaking && !self.synthesizer.paused) {
        [self updateToolbarWithButton:@"pause"];
    }
    else {
        [self updateToolbarWithButton:@"play"];
    }

}

- (void)updateToolbarWithButton:(NSString *)buttonType
{

       NSLog(@"updateToolbarWithButton: %@", buttonType);
    UIBarButtonItem *audioControl;
    if ([buttonType isEqualToString:@"play"]) {
        // Play
        audioControl = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(handlePlayPauseButton:)];
    }
    else {
        // Pause
        audioControl = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:@selector(handlePlayPauseButton:)];

    }

    UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

    [self.toolbar setItems:@[flexibleItem, audioControl, flexibleItem]];
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent
{
    NSLog(@"receivedEvent: %@", receivedEvent);
    if (receivedEvent.type == UIEventTypeRemoteControl) {

        switch (receivedEvent.subtype) {

            case UIEventSubtypeRemoteControlPlay:
                NSLog(@"UIEventSubtypeRemoteControlPlay");
                if (self.synthesizer.speaking) {
                    [self.synthesizer continueSpeaking];
                }
                else {
                    [self speakUtterance];
                }
                break;

            case UIEventSubtypeRemoteControlPause:
                NSLog(@"pause - UIEventSubtypeRemoteControlPause");

                if (self.pauseSettingSegmentedControl.selectedSegmentIndex == 0) {
                    // Pause immediately
                    [self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
                }
                else {
                    // Pause at end of current word
                    [self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryWord];
                }
                break;

            case UIEventSubtypeRemoteControlTogglePlayPause:
                if (self.synthesizer.paused) {
                    NSLog(@"UIEventSubtypeRemoteControlTogglePlayPause");
                    [self.synthesizer continueSpeaking];
                }
                else {
                    NSLog(@"UIEventSubtypeRemoteControlTogglePlayPause");
                    if (self.pauseSettingSegmentedControl.selectedSegmentIndex == 0) {
                        // Pause immediately
                        [self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
                    }
                    else {
                        // Pause at end of current word
                        [self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryWord];
                    }
                }
                break;

            case UIEventSubtypeRemoteControlNextTrack:
                NSLog(@"UIEventSubtypeRemoteControlNextTrack - appropriate for playlists");
                break;

            case UIEventSubtypeRemoteControlPreviousTrack:
                NSLog(@"UIEventSubtypeRemoteControlPreviousTrack - appropriatefor playlists");
                break;

            default:
                break;
        }
    }
}

#pragma mark UIPickerViewDelegate Methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.voices.count;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *rowLabel = [[UILabel alloc] init];
    NSDictionary *voice = [self.voices objectAtIndex:row];
    rowLabel.text = [voice objectForKey:@"label"];
    return rowLabel;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component
{
    NSDictionary *voice = [self.voices objectAtIndex:row];
    NSLog(@"new picker voice selected with label: %@", [voice objectForKey:@"label"]);
    self.voice = [AVSpeechSynthesisVoice voiceWithLanguage:[voice objectForKey:@"voice"]];
}

#pragma mark SpeechSynthesizerDelegate methods

//in this method i called the method for speech recognition after voice is played.
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance
{
    // This is a workaround of a bug. When we change the voice the first time the speech utterence is set fails silently. We check that the method willSpeakRangeOfSpeechString is called and set didStartSpeaking to YES there. If this method is not called (silent fail) then we simply request to speak again.
    if (!didStartSpeaking) {
        [self speakUtterance];

    }
    else {
        [self updateToolbarWithButton:@"play"];

        //here i am checking weather speech recognition is running or not , if not i am starting the speech recognition after playing a voice i.e,text to speech.

            if (!audioEngine.isRunning) {

                double delayInSeconds = 1.5;
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

                  ///  NSLog(@"Not Running");

                    [self start_record];

                });

            }

    }

}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance
{
    didStartSpeaking = YES;

}

#pragma mark UITextViewDelegate Methods

#pragma mark Cleanup Methods

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"updateToolbar" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

In above code, in didFinishSpeechUtterance  methods ,after ending the voice i.e, text to speech i am calling the start record which will start the speech recognition again ,So playing a voice the control is going to start record method,in that
         recognitionTask = [self.speechRecognizer recognitionTaskWithRequest:recognitionRequest resultHandler:^(SFSpeechRecognitionResult * result, NSError *  error1) {

in these line it throwing an error like [Utility] +[AFAggregator logDictationFailedWithError:] Error Domain=kAFAssistantErrorDomain Code=209 "(null)" I don't know why....
Please help me to resolve this issue..
Thanks in advance!!!

A: I was getting this 209 error and occasionally 203.
I experimented a lot and finally was able to resolve it.
Here's what I did:

*

*Instead of doing [recogTask finish], I did [recogTask cancel].

*Then I waited in a while loop for the recogTask to cancel, before proceeding to set it to nil or any other step. e.g. I did:
while (recogTask && recogTask.cancelled == NO) {
[NSThread sleepForTimeInterval:0.1];
}
So I didn't get any 209 or 203 code errors, also I stopped recog for 2 seconds every 20 seconds. Yet to see if 2 seconds gap could be lowered.
Thanks.


text:
Q: Re-render a page using jquery In react, I could easily re-render a view by passing results from controller. I wish not to use React at this stage and was wondering if it's possible with JQuery?
I have few objects on page, and when clicked, I should see its content. Click the other object, I see its content etc. Sense? I was inspired by this dribbble.
I may not be doing this the right way but this is what I have:
Controller:
def index
  selected_contract = params[:selected_contract] || current_user.contracts.last.id
  @contracts = current_user.contracts.order(created_at: :desc).all
  @selected_contract = current_user.contracts.find_by(id: selected_contract)
end

View:
<% @contracts.each do |contract| %>
  <button class="ui button test" id="<%=contract.id%>"><%=contract.name%></button>
<% end %>

......................................
When clicked, show its content
....................................

<%= @selected_contract.name %>

JS:
$( ".ui.button.test" ).click(function(e) {
  let { id } = this
  console.log(id)
  $.ajax({
    url: `/url/${id}`,
    type: 'POST',
    success: function(result) {
      //$('#listview').redraw()
      console.log('success')
    }
  });
});

Routes are set properly so I get the params in the controller just fine. Is there a re-render a view, just like rerender a prop in React for jquery? Am I doing this the correct way?

A: If you are using jquery listview this should work.
$( "#listview" ).listview( "refresh" );

Reference
https://api.jquerymobile.com/listview/#method-refresh
or since its rails you can reload or render the partial view in your server side as well.


text:
Q: Laravel development: Implication when creating MySQL database manually I'm in the process of building a Laravel application and I started with the database design. I implemented this directly on the commandline (mysql).
Now, I have this lingering concern as for what this could lead to in the coming development cycles.
I do know that I miss out on the version control as well as the rollback of database structure changes that php artisan provides.

*

*Are there other Laravel/PHP specific aspects I should keep in mind?

*Would you (Laravel developer), recommend that I recreate the entire database structure using php artisan make:migration?

I could really use your input based on this situation of Laravel/PHP development in many cycles without database migration control?
Please advice.

A: Yes, In my opinion you should go for using migrations. Migrations provide a great interface to change database structure in version controlled manner.
For instance, If in future you have to move from mysql to some other database system. Following your current approach your would have to create all the db structures according to the new system.
While using migrations, you just have to update a config file for the db driver. And you are done.


text:
Q: What is the * used for in Ruby? What does the * do before 'test' in the below code and across the Ruby programming language?
  def sample (*test)
       puts "The number of parameters is #{test.length}"
       for i in 0...test.length
          puts "The parameters are #{test[i]}"
       end
    end
    sample "Zara", "6", "F"
    sample "Mac", "36", "M", "MCA"

A: The last parameter of a method may be preceded by an asterisk(*), which is sometimes called the 'splat' operator. This indicates that more parameters may be passed to the function. Those parameters are collected up and an array is created.
Example:
def sample (*test)
    puts test
end

And call it with:
sample(1,2,3)

Will return array: [1,2,3]
irb(main):001:0> def s(*t)
irb(main):002:1> puts t
irb(main):003:1> end
=> nil
irb(main):004:0> s(1,2,3)
1
2
3
=> nil

A: OxAX mentioned one good use of the * prefix operator - to collect arguments and this is what it does in your example.
def lots_of_args *args
  p args
end
lots_of_args 1,2,3 # => [1, 2, 3]

first, *rest = 1, 2, 3, 4
first # => 1
rest  # => [2, 3, 4]

We can even apply it outside of method definitions.

However, it's important to note that there's another good use for it:
def add_three_nums a, b, c
  a + b + c
end

add_three_nums *[1,2,3]  # => 6
# same as calling "add_three_nums 1,2,3"

Essentially, the * operator expands a method argument that's an array into a list of arguments.

There's even a third use case:
first, *rest = [1, 2, 3, 4]
first # => 1
rest  # => [2, 3, 4]

This third case is somewhat similar to the first. However, notice that we get the values of first and rest from an array, not from a list of values.


text:
Q: Padding and adding binary strings in C I have been tasked with writing a program in C that takes strings of binary digits and adds them. The two strings can be different lengths, so before they are added, they need to be padded to the same size.
    //Make copy of strings with proper padding
char *aCopy = (char *)calloc(size+1,sizeof(char));
char *bCopy = (char *)calloc(size+1,sizeof(char));

int i;
for(i = size; i >= 0; i--)
{
  aCopy[i] = '0';
  bCopy[i] = '0';
}

for (i = strlen(a); i >= 0; i--)
  if (i == 0 && a[i]=='1') //Two's complement
    aCopy[i] = '1';
  else
    aCopy[size - i] = a[strlen(a)-i];

for (i = strlen(b); i >= 0; i--)
  if (i == 0 && b[i]=='1') //Two's complement
    bCopy[i] == '1';
  else
    bCopy[size - i] = b[strlen(b)-i];

I am having an issue where, if the lines commented "Two's complement" are run (they serve to move the leading 1 digit to the front of the padded string), the length of the padded string becomes one more than it should be. I cannot figure out why this is happening, and it is screwing up my calculations.
Edit: To clarify, an extra '0' char is being added to the end of the two's complement string.


text:
Q: Nginx on my VPS is continuously trying to access the Wordpress API using 0.0.0.0 I'm running a docker container with Wordpress, MYSQL and PHP on my Centos 7 VPS.
I can access the frontend of my blog fine. I can also log into the admin panel and install plugins, but when I try to save pages, save posts, or make any kind of update to them, I get the following errors:

However, if I manually replace 0.0.0.0:8000 with my domain name, e.g. domain.com/wp-json/wp/v2/, then I don't get the error.
This is my Nginx setup:
server {

        server_name domain.com www.domain.com;

        location / {
           proxy_pass http://0.0.0.0:8000;
           proxy_set_header X-Forwarded-Host $host;
           proxy_set_header X-Forwarded-Proto $scheme;
        }

    if ( $http_host ~* "www\.(.*)") {
           return 301 https://$1$request_uri;
        }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

server {
    if ($host = www.domain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = domain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    server_name domain.com www.domain.com;
    listen 80;
    return 404; # managed by Certbot

}

I need to some how get Wordpress to use my domain at all times.

A: Modify wp-config.php and add WP_HOME and WP_SITEURL.
https://wordpress.org/support/article/changing-the-site-url/
Or just change it on your database (inside wp_options)


text:
Q: string quoting issues in doctests When I run doctests on different Python versions (2.5 vs 2.6) and different plattforms (FreeBSD vs Mac OS) strings get quoted differently:
Failed example:
    decode('{"created_by":"test","guid":123,"num":5.00}')
Expected:
    {'guid': 123, 'num': Decimal("5.00"), 'created_by': 'test'}
Got:
    {'guid': 123, 'num': Decimal('5.00'), 'created_by': 'test'}

So on one box repr(decimal.Decimal('5.00')) results in 'Decimal("5.00")' on the other in "Decimal('5.00')". Is there any way to get arround the issue withyout creating more compliated test logic?

A: This is actually because the decimal module's source code has changed: In python 2.4 and python2.5 the decimal.Decimal.__repr__ function contains:
return 'Decimal("%s")' % str(self)

whereas in python2.6 it contains:
return "Decimal('%s')" % str(self)

So in this case the best thing to do is just to print out str() of the result and check the type separately if necessary...

A: Following the hits by David Fraser i found this suggestion by Raymond Hettinger on the Python mailinglist.
I now use something like this:
import sys
if sys.version_info[:2] <= (2, 5):
    # ugly monkeypatch to make doctests work. For the reasons see
    # See http://mail.python.org/pipermail/python-dev/2008-July/081420.html
    # It can go away once all our boxes run python > 2.5
    decimal.Decimal.__repr__ = lambda s: "Decimal('%s')" % str(s)


text:
Q: Authorize one action in a controller but don't require a role I have a Product controller the required role of "product_editor" to access most of the methods.  there are a few actions that don't require authorization so [AllowAnonymous] works great.  However, I have one action i would like to require they are logged in but they may not be a product editor.
Is there a simple way to declare this for the one action?
you can see a couple of my attempts commented out
[Authorize(Roles = "product_editor")]
public class ProductController : Controller
{
    #region Public Actions
    [AllowAnonymous]
    public ActionResult Search(string keyword...

    [AllowAnonymous]
    public ActionResult Details(string id...
    #endregion

    //[Authorize]
    //[Authorize(Roles="")]
    public ActionResult AuthorizedDownload(long id, string step)
    {
        SecureDownloadLink link = SecureDownloadLink.Load(id);
        if(link.belongsTo(HttpContext.Current.User.Identity.Name))
        {
            //Allow download
        }
        else
        {
            //Return 404 Error
        }
    }
}

--Edit--
Found a working solution but would love an attribute based solution since the rest of my authentication is done in attributes and the [AllowAnonymous] is a bit misleading.
[AllowAnonymous]
public ActionResult AuthorizedDownload(long id, string step)
{
    if (!User.Identity.IsAuthenticated)
        return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.LocalPath });
....
}

A: I don't think there's a simple way to achieve that, other than explicitly specifying the Authorize attribute explicitly on each controller action:
public class ProductController : Controller
{
    #region Public Actions
    [AllowAnonymous]
    public ActionResult Search(string keyword...

    [AllowAnonymous]
    public ActionResult Details(string id...
    #endregion

    [Authorize]
    public ActionResult AuthorizedDownload(long id, string step)
    {
        SecureDownloadLink link = SecureDownloadLink.Load(id);
        if(link.belongsTo(HttpContext.Current.User.Identity.Name))
        {
            //Allow download
        }
        else
        {
            //Return 404 Error
        }
    }

    [Authorize(Roles = "product_editor")]
    public ActionResult SomeOtherAction()
    {
        ...
    }
}

or if you have many actions, another possibility is to move the action that differs in a separate controller.

A: Authorization uses cascading rules, so you somewhat streamline it this way.
[Authorize]
public class ProductController : Controller
{
    #region Public Actions
    [AllowAnonymous]
    public ActionResult Search(string keyword...

    [AllowAnonymous]
    public ActionResult Details(string id...
    #endregion

    public ActionResult AuthorizedDownload(long id, string step)
    {
        SecureDownloadLink link = SecureDownloadLink.Load(id);
        if(link.belongsTo(HttpContext.Current.User.Identity.Name))
        {
            //Allow download
        }
        else
        {
            //Return 404 Error
        }
    }

    [Authorize(Roles = "product_editor")]
    public ActionResult SomeOtherAction()
    {
        ...
    }
}


text:
Q: Error upgrading rails from 5.0.0.rc1 to 5.0.0.rc2 OS: Mac OS X El-Captain
current rails version: 5.0.0.rc1
ruby version: 2.3.1p112
I'm having following error. Googling and searching on Stack Overflow didn't give any results.
gem install rails -v 5.0.0.rc2
ERROR:  While executing gem ... (Gem::Resolver::Molinillo::CircularDependencyError)
    There is a circular dependency between camping and rack

A: I had to uninstall my version of Ruby (2.3.1) and re-install. Then running gem install rails --pre worked.
I use rbenv and ruby-build. The instructions for removing Ruby are found here, https://github.com/rbenv/rbenv#uninstalling-ruby-versions.

A: This appears to be related to out of date system gems. I encountered it installing bundler. I cleared it by entering :
gem update --system
I can install latest ruby, bundler, rails, and all works fine.
I'm running OS X 10.11.6.
Best,
John


text:
Q: Differential of the height function Consider the mapping $f:S^2\rightarrow \mathbb{R}$, with $f(x,y,z)=z$, giving the height of a point on the sphere. I am asked to find the points for which the differential $(df)_p$ is surjective and i have failed so far. It's an exercise on an introductory course on smooth manifolds, so please try to be clear about what theorems you use, i'm just a beginner!
Thanks a lot in advance!

A: Intuition
Draw a picture. At a tangent space, visualize tangent vectors and the result of projecting those tangent vectors to the $z$ axis. Do you see what are the (hint: only two) points such that the projection is not surjective?
Computation
We know that $f$ is actually the restriction of the projection map $F:\mathbb{R}^3\to \mathbb{R}$ taking $(x,y,z)\mapsto z$. Compute the differential of $F$, call it $dF$. Don't think too hard about this.
Now recall that the tangent space to $S^2$ at a point $p$ can be identified with the plane of vectors in $\mathbb{R}^3$ perpendicular to $p$. (Why?) Given a $p\in S^2$, compute a basis for $T_pS^2$.
Compute the matrix for $df_p$ by restricting $dF$ to the tangent space (which you know, as you have a basis).
What are the points where this map is not onto?

A: For $u=(x,y,z)\in R^3,v=(a,b,c)\in T_uR^3 df_u(v)=c$.Thus $df_u(v)=0$, i.e $c=0$, if $u\in S^2, T_uS^2\subset T_uS^3$ and $df_u(T_uS^2)$ i.e $T_uS^2=\{(a,b,0),a,b\in R\}$ i.e $u$ is the north pole or the south pole.


text:
Q: Getting error-'General Error Mounting Filesystems' while installing ubuntu 12.04 alongside Windows 7 starter edition I am trying to install Ubuntu 12.04 on my HP Mini 110 with 2 gb of ram and Windows 7 starter edition. However, when I try to boot from USB, the Ubuntu screen loads and then shows the message-'General Error Mounting Filesystem'. I have to press Ctrl+D to reboot, and the same process starts again until I remove my pen drive. I have tried making a Live USB from UNetBootin and the software Ubuntu suggests, downloaded from pendrivelinux.com. However, Ubuntu still won't load. I am new to the Ubuntu world and don't know what to do, please help.

A: Some things to try

*

*when the splash screen first comes up on boot (the screen has a keyboard and a guy in a circle at the bottom) hit enter. It will display a menu that will allow you to choose what you want to do. Hit f6 and enable all of the options except for "Free software only". Then try either "Try Ubuntu..." or "Install Ubuntu"

*Verify the state of the USB device by taking it to another computer and trying it there.
Hope that helps.

A: The problem is with your iso download. The download must have been broken. Always compare your md5 sum after downloading. Check these links:
HowToMD5SUM
and:
UbuntuHashes


text:
Q: Number of different lines in each file - Compare all files inside 2 directories I have 2 directories dir1 and dir2 with thousand of files. I have a perl script to compare these two and print the difference in a different file.
I am using the diff my $diff = diff -y --suppress-common-lines "$DirA/$file" "$DirB/$file"; to compare all files(with same name) in the two directories. With this, I also want to add
Filename:   # of different lines
File 1 – 1
File 2  - 30
and output the difference in a summary.txt file .
Can someone please help me with the same.

A: Try this:
echo $file - `diff -y --suppress-common-lines $DirA/$file $DirB/$file | wc -l` >> summary.txt


text:
Q: netbeans 8.1 cannot create new project of uninstall from windows 10 I have installed java 8.1 and netbeans 8.1 on my windows 10 pc and am having some problems:

*

*I cannot create a new project in netbeans.  When I attempt to
create a new project the netbeans application shuts down.

*I cannot uninstall the netbeans application; it starts with the
message that it is configuring the installer then shuts down.

I have been able to uninstall java on my pc and reinstall without error.  I don't know what steps to try from here.  Any help greatly appreciated.
ERROR LOG:
...
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x6f3321f4,
pid=7052, tid=0x0000141c
#
# JRE version: Java(TM) SE Runtime Environment (8.0_121-b13) (build
1.8.0_121-b13)
# Java VM: Java HotSpot(TM) Client VM (25.121-b13 mixed mode, sharing
windows-x86 )
# Problematic frame:
# C  [msvcr100.dll+0x121f4]
#
# Failed to write core dump. Minidumps are not enabled by default on
client versions of Windows
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
...


text:
Q: Why does Unix "strings" command remove XML comment close tags? I am not a Unix shell scripting expert, but I recently had a problem with a script removing the closing tag of an XML comment block, thus causing the entire file to be one huge unclosed comment, which immediately failed in the middleware system reading it. I narrowed the problem down to the strings command in the script.
As an example, a file, temp.xml, contains the following XML:
<?xml version="1.0" encoding="utf-8" ?>
<!--
This is a comment
-->
<object>Foo</object>

The following command is run against it: strings - temp.xml
The output is:
<?xml version="1.0" encoding="utf-8" ?>
<!--
This is a comment
<object>Foo</object>

Note that this behaviour is only observed when the closing comment tag is on a line of its own which contains nothing else. So This is a comment--> is left alone.
This seems completely nonsensical to me. Is there a reason for it?
It's happening on Linux 2.6.18. Distro is RHEL Server 5.10.

A: Because the strings command only print strings of length 4 characters or more. --> is a length of 3 so it ignores it. Any reason you process the files with strings?
The man page says:

For each file given, GNU strings prints the printable character sequences that are at least 4 characters long (or the
         number given with the options below) and are followed by an unprintable character.  By default, it only prints the
         strings from the initialized and loaded sections of object files; for other types of files, it prints the strings from
         the whole file.
strings is mainly useful for determining the contents of non-text files.


text:
Q: Have custom data with the Facebook Share dialog With Facebook Open Graph v2.0 the Feed Dialog became deprecated. I always used the feed dialog when dynamic meta data was needed to be shared.
For example, with a function like: "Share your score on Facebook" - before v2.0 this could be used:
var myScore = 20;

FB.ui({
    method: 'feed',
    name: 'My score was: ' + myScore + ' in AppName' ,
    link: 'https://appname.com',
}, function(response){});

Facebook says use the Share dialog instead as of v2.0.

On web, developers are encouraged to use the more modern Share Dialog, which can perform all of the same functions as these older dialogs, but can additionally publish custom Open Graph stories without requiring Facebook Login.

But does it really have the same functionality? It seems I cannot add custom parameters, this makes it harder to share dynamic meta data than before.
The share dialogs documentation:
https://developers.facebook.com/docs/sharing/reference/share-dialog
So I cannot add parameters to make the share dialog more dynamic, the share dialog seems a better fit to just share the app than sharing a users score.
Is there a solution to this? Or do I need to make the Facebook open graph meta tags more dynamic to achieve the same result?


text:
Q: В phpstorm не видит :pattern Случайным образом отключила какую-то функцию в phpstorm и после этого у меня во всем коде пропали шаблоны pattern:, path:, charlist: и т.д.
И раньше он их полсвечивал, а теперь подчеркивает красным двоеточие и считает ошибкой.


text:
Q: Does the number of rows really matter beyond a point? While working with any machine learning algorithm, does the number of rows really matter beyond a certain point?
I have kept some algorithms(decision tree in this instance) running for days, and the accuracy I get is similar to those I get immediately for 5000 rows. I'm kind of feeling that running it on the entire data set is more like a 'check' to verify the results you get with 5000 rows.
Is there any study on how many rows are actually needed and how much results vary when increasing the number of rows?

A: Answer here will probably be application-specific, data-set specific. In any given situation you can try yourself, select $m$ (say, 5000) rows at random, do the same again, again, ... and compare results.
You could also exploit your situation to draw some hold-out sample, to use for independent model verification.  If you are using some kind of automatic variable selection, that could be very valuable.
If you need confidence intervals for model parameters, those may be to long with this "use only a large random subsample" procedure, but, anyhow, the confidence intervals calculated with the full dataset are probably too short ... they depend on assumptions such as "the model is absolutely correct", "all variables measured without error", and so on, which might be fairly innocuous with small data sets, but not trustworthy with large data sets. Things like variables only measured with a finite (small) number of correct decimals will ultimately limit how short confidence intervals can be! You can yourself, with your data, investigate such questions by redoing the random subsampling many times, plotting the different coefficients obtained from each subsample, and compare the variation between them to the length of calculated confidence intervals.


text:
Q: Convex non-increasing, but not lower semicontinuous function? I am trying to think of an example of a function $f:\unicode{x211D}^n \rightarrow \unicode{x211D}$ that is convex and non-increasing, but not lower semicontinuous, without any luck. Is this actually possible?

A: A convex function from ${\mathbb R}^n$ to $\mathbb R$ is always continuous, not just lower semicontinuous.  To get examples that are not lower semicontinuous you must allow values of $+\infty$.  For example, with $n=1$, $f(x) = +\infty$ for $x \le 0$, $0$ for $x > 0$.


text:
Q: Tree traversal in Java I am studying for a job interview and was reviewing trees, I have no problem when traversing them but I got to a question I haven't been able to figure the right answer to:

Write a function that returns a node in a tree given two parameters:
  pointer to the root node and the inorder traversal number of the node
  we want to return. The only information stored in the tree is the
  number of children for each node.

So far, I haven't even been able to figure why I would care of the information stored in the tree (the number of children). Other than that if we assume there's a tree like such:
     5
  4     7
3  1  4

then the Inorder traversal would be 341547but I can't figure out the code to return the node I want (for sake of argument I'm assuming the inorder traversal number is 2 - meaning I want the node of value 1).
I tried doing a recursive traversal but I end up screwing the inner counter I had so I tried a different approach and just tried to put everything on a stack but I can't figure how to correctly do so. So far I have:
public int findNode(root, position){
   Stack<Integer> s = new Stack<Integer>();
   cNode = root; //cNode = current Node

   while(cNode.left != null)
      cNode = cNode.left;

     s.push(cNode);

   while(cNode.right != null)
     cNode = cNode.right;

   //stuck here.
}

The recursive approach was easier but I can't figure how to check if I have the # I'm looking for:
public int findNode(root, position){
    cNode = root;
    if(cNode != null){
       findNode(cNode.left, position);
       System.out.print(cNode.data);
       findNode(cNode.right, position);
   }
}

I know this traverses the tree but it still doesn't do exactly what I want. Any help would be appreciated.

A: The question is ambiguous.  "Inorder" is meaningful for binary trees, in which case "number of children" is always two, unless they mean "number of descendants", in which case you could use that to avoid doing a linear search through the inorder list (O*n) since at each node you can decide which branch to take (O*log n) based on the number of descendants.

A: You can do it as such:
public Node findNode(Node root, int position) {
    ArrayList<Node> a = new ArrayList<Node>();
    populateNodes(root, a);
    return a.get(position);
}

private void populateNodes(Node node, ArrayList<Node> a) {
    if (node == null) return;
    populateNodes(node.left, a);
    a.add(node);
    populateNodes(node.right, a);
}

Note: You don't need to use an extra data-structure if you don't want, but since you had a Stack i just went with it.
Note2: As Jim Garrison pointed out you can optimize the algorithm if you have the descendant count.

A: Instead of passing position, pass the inorder traversal number and append to it in each recursive method.

A: It is better to reduce the complexity of the algorithm by using the property of the tree that each node knows the total number of children it has. So you can calculate the order number of the current node if you know how many children it has on the left (for root it will be no. of children on left + 1) The following code should work:
Nodeptr nthInInorder(Nodeptr root, int x){
 Nodeptr curr = root;
 int countedIn = 0, leftchildren = 0, currIn=0;

 while(curr!=NULL){
  if(curr->left == NULL)
   leftchildren = 0;
  else
   leftchildren = (curr->left)->data + 1;

  currIn = countedIn + leftchildren + 1;

  if(currIn == x)
   return curr;
  else if(currIn > x)
   curr = curr->left;
  else if(currIn < x)
   { countedIn = currIn + 1;
     curr = curr->right;
   }
  }
  return NULL;
 }

Complexity of this algorithm is O(log n)


text:
Q: Difference between templates in JavaScript and design patterns What is the difference between templates and design patterns in JavaScript?
I read about the template method design pattern and now I wonder how it relates to JavaScript templates (if at all).

A: Templates (in the Javascript world) are a method to display Javascript (model) data in an HTML (or other) view.
Design patterns are known (and battle tested) methods of solving common problems.
Really, Javascript templates could be construed as a design pattern (depending on who you ask ;)).

A: Design patterns are used to solve commonly encountered problems related to software design.
Once you know how to solve a particular problem, when that problem presents again you can reuse the same approach you used before, the same pattern.
Patterns are not related to JavaScript only, but to every language.
The JavaScript Templates you are referring about may be a technique used to generate data in the document, originally called Micro-templating by the inventor, John Resig (jQuery).
Here's an article to better understand them.
And here's one for applying common design patterns in JS.


text:
Q: Clear form on `mfp-close` in magnific popup I am trying to clear all the errors and make input values blank on closing of magnific popup.
I inspected the class of 'close' button and tried to fire jquery event but it is not working.
$("button.mfp-close").on('click',function(){
  console.log("Closed");
});

When i click on mfp-close then there is no log in console.
HTML snippet is:

Upload Your Design

Congratulations! We have sent you the coupon code on your registered email id

<form novalidate="novalidate" class="form cmxform" id="customForm">
        <input name="leave" value="http://" type="hidden">
        <input name="isblank" value="" type="hidden">

        Name
        <input aria-required="true" class="form-control" name="nam_cst" id="nam_cst"
     placeholder="Enter Name.." required="" type="text">

    </form>

<button title="Close (Esc)" type="button" class="mfp- close">×</button>

How can we handle this operation??

A: First of all, if you are using bootstrap framework, use bootstrap modal instead magnific popup, no need for extra js librabry, you can achieve same with bootstrap modal
in your HTML, button you have class="mfp- close" it should be class="mfp-close" as you are binding it like this $("button.mfp-close")
To reset form on pop-up close, you can achieve it with $('form')[0].reset();
Script
$("button.mfp-close").on('click',function(){
    alert("Closed");
    $('form')[0].reset();
});

HTML
Open modal

Upload Your Design

            Congratulations! We have sent you the coupon code on your registered email id

        <form novalidate="novalidate" class="form cmxform" id="customForm">
        <input name="leave" value="http://" type="hidden">
        <input name="isblank" value="" type="hidden">

            Name
                <input aria-required="true" class="form-control" name="nam_cst" id="nam_cst" placeholder="Enter Name.." required="" type="text">

        </form>

<button title="Close (Esc)" type="button" class="mfp-close">×</button>

Working fiddle example


text:
Q: Android support library not working (Eclipse) I am unable to open certain activity when starting a new android poroject. I have tried fixing the problem by installing the correct "Android Support Library" in the SDK Manager but the problem remains unsolved! Even the "Install/Upgrade" and "check again" functions in the Install Dependencies Screen do not work! Btw I am using eclipse on a mac.
Any thoughts?

A: Use proxy:
windows-->preferences-->general-->network connections

Android SDK Manager:
Tools-->options-->enter your proxy

A: Android Studio now is official IDE for android development provided by Google. The Android plugin for Eclipse doesn't have support anymore. Eclipse is setting up Andmore project: https://projects.eclipse.org/projects/tools.andmore to try to continue work on allowing Eclipse to build Android apss. But you should use Android Studio instead.


text:
Q: Changing Variables in Multiple Java Instances Essentially I'm trying to do something that is stated here Changing variables in multiple Python instances
but in java.
I want to reset a variable in all instances of a certain class so something like:
public class NewClass{
int variable = 1;
}

then:
NewClass one = new NewClass();
NewClass two = new NewClass();
NewClass three = new NewClass();

Newclass.variable = 2;

System.out.println(one.variable);
System.out.println(two.variable);
System.out.println(three.variable);

output would be:
2
2
2

is there a way to do that?

A: Make that variable static so that it is now a property of the class and not an instance.
public class NewClass{
  static int variable = 1;
}

A: Mark the attribute static.
public class NewClass {
static int variable = 1;
}

A: Please use static variable
public class NewClass{
    static int variable = 1;
}

Important facts about static variable, please check

*

*If the value of a variable is not varied from object to object such
type of variables is not recommended to declare as instance variables.
We have to declare such type of variables at class level by using
static modifier.

*In the case of instance variables for every object a separate copy will
be created but in the case of static variables for entire class only
one copy will be created and shared by every object of that class.

*Static variables will be crated at the time of class loading and
destroyed at the time of class unloading hence the scope of the static
variable is exactly same as the scope of the .class file.

*Static variables will be stored in method area. Static variables should
be declared with in the class directly but outside of any method or
block or constructor.

*Static variables can be accessed from both instance and static areas
directly.

*We can access static variables either by class name or by object
reference but usage of class name is recommended.
But within the same class it is not required to use class name we can
access directly.

A: java does not support multiple instance...but you csn solve this problem using
interface. ex. public interface abc


text:
Q: How to find Queue type in assemblies? I need to deserialize classes created on different machines.
The programs are very similar but have differences in Program name, as well as .Net version etc.
This code below works quite well, except for when I have a Queue in my class. I am unable to search the exsting assemblies to find something suitable.
      public override Type BindToType(string assemblyName, string typeName)
        {
            string typeSearchString;// = typeName.Split('+')[1];

            try
            {
                typeSearchString = typeName.Split('+')[1];
            }
            catch
            {
                var parts = typeName.Split(new string[] { "[[" }, StringSplitOptions.RemoveEmptyEntries)[1].Split(',');
                typeSearchString = @"System.Collections.Generic.Queue"; //This does NOT find Queue<Double> but it does find something else which gives an error
            }

            Type tyType = null;
            string sShortAssemblyName = assemblyName.Split(',')[0];

            System.Reflection.Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();

            foreach (System.Reflection.Assembly ayAssembly in ayAssemblies)
            {
                foreach (Type type in ayAssembly.GetTypes())
                {
                    if (type.FullName.Contains(typeSearchString))
                    {
                        tyType = ayAssembly.GetType(type.FullName);
                        return tyType;
                    }
                }

            }
            return tyType;
        }

EDIT 1

This is what I have to create a search from:
typeName = "System.Collections.Generic.Queue`1[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"

A: My own classes appear to have a typeName that contains a "+", for example:
"MyNameSpace.MyDocName+MyClass"
I have been able to use this to determine where to look for the type:
      public override Type BindToType(string assemblyName, string typeName)
        {

            Type tyType = null;
            string sShortAssemblyName = assemblyName.Split(',')[0];

            System.Reflection.Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();
            string typeSearchString;

            try
            {
                typeSearchString = typeName.Split('+')[1];

                foreach (System.Reflection.Assembly ayAssembly in ayAssemblies)
                {
                    foreach (Type type in ayAssembly.GetTypes())
                    {
                        if (type.FullName.Contains(typeSearchString))
                        {
                            tyType = ayAssembly.GetType(type.FullName);
                            return tyType;
                        }
                    }

                }
            }
            catch
            {
                foreach (System.Reflection.Assembly ayAssembly in ayAssemblies)
                {
                    if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0])
                    {
                        tyType = ayAssembly.GetType(typeName);
                        return tyType;
                    }
                }
            }

            return tyType;
        }

I have posted this answer in case someone else is having similar problems.