How to Apply FiltersFeature to Grid in ExtJS MVC

Question: I found this post How to add filters in grid column headers in extjs? however, I don't know how to apply it in my code, which uses MVC pattern.  For example, this is my grid:
Ext.define('RateManagement.view.Grids.AirShipmentGrid', {
    extend: 'Ext.grid.Panel',
    xtype: 'AirShipmentGrid',
    plugins: [
        {
            clicksToMoveEditor: 1,
            autoCancel: false,
            ptype: 'rowediting',
            pluginId: 'rowediting'
        },
        'bufferedrenderer'
    ],
    loadMask: true,
    columns: [
        {text: 'Home Country', dataIndex: 'homeCountry', width: 175, sortable: true},
        {text: 'Home Location', dataIndex: 'homeLocation', width: 175},
        {text: 'Host Country', dataIndex: 'hostCountry', width: 175},
        {text: 'Host Location', dataIndex: 'hostLocation', width: 175},
        {text: 'Assignee Air Shipment & Insurance', dataIndex: 'assigneeAirShipmentPlusInsurance', width: 200, xtype: 'numbercolumn',
            editor: { xtype: 'numberfield', allowBlank: false, minValue: 0, blankText: 'Rate is required.', invalidText: 'Rate must be positive.' }},
        {text: 'Dependent Air Shipment & Insurance', dataIndex: 'dependentAirShipmentPlusInsurance', width: 200, xtype: 'numbercolumn',
            editor: { xtype: 'numberfield', allowBlank: false, minValue: 0, blankText: 'Rate is required.', invalidText: 'Rate must be positive.' }},
        {text: 'Small Container & Insurance', dataIndex: 'smallContainerPlusInsurance', width: 175, xtype: 'numbercolumn',
            editor: { xtype: 'numberfield', allowBlank: false, minValue: 0, blankText: 'Rate is required.', invalidText: 'Rate must be positive.' }},
        {text: 'Large Container & Insurance', dataIndex: 'largeContainerPlusInsurance', width: 175, xtype: 'numbercolumn',
            editor: { xtype: 'numberfield', allowBlank: false, minValue: 0, blankText: 'Rate is required.', invalidText: 'Rate must be positive.' }},
        {text: 'Rate Currency', dataIndex: 'currencyId', xtype: 'currency-column' }
    ]
});

Where do I put this part?
filters = {
        ftype: 'filters',
        encode: false,
        local: true
    };

I tried adding an initComponent: function() { but it gave me an error.
Note:  I am using ExtJS version 4.2.1.
Answer: You can declare the filter feature within your grid definition:
Ext.define('RateManagement.view.Grids.AirShipmentGrid', {
    extend: 'Ext.grid.Panel',
    xtype: 'AirShipmentGrid',
    requires:['Ext.ux.grid.FiltersFeature'],
    plugins: [
        {
            clicksToMoveEditor: 1,
            autoCancel: false,
            ptype: 'rowediting',
            pluginId: 'rowediting'
        },
        'bufferedrenderer'
    ],
    features: [{
        ftype: 'filters',
        encode: false,
        local: true,
        filters: [{
            type: 'filterType',
            dataIndex:'fieldToFilter'
        }]
    }],
    loadMask: true,
    columns: [
        {text: 'Home Country', dataIndex: 'homeCountry', width: 175, sortable: true},
        {text: 'Home Location', dataIndex: 'homeLocation', width: 175},
        {text: 'Host Country', dataIndex: 'hostCountry', width: 175},
        {text: 'Host Location', dataIndex: 'hostLocation', width: 175},
        {text: 'Assignee Air Shipment & Insurance', dataIndex: 'assigneeAirShipmentPlusInsurance', width: 200, xtype: 'numbercolumn',
            editor: { xtype: 'numberfield', allowBlank: false, minValue: 0, blankText: 'Rate is required.', invalidText: 'Rate must be positive.' }},
        {text: 'Dependent Air Shipment & Insurance', dataIndex: 'dependentAirShipmentPlusInsurance', width: 200, xtype: 'numbercolumn',
            editor: { xtype: 'numberfield', allowBlank: false, minValue: 0, blankText: 'Rate is required.', invalidText: 'Rate must be positive.' }},
        {text: 'Small Container & Insurance', dataIndex: 'smallContainerPlusInsurance', width: 175, xtype: 'numbercolumn',
            editor: { xtype: 'numberfield', allowBlank: false, minValue: 0, blankText: 'Rate is required.', invalidText: 'Rate must be positive.' }},
        {text: 'Large Container & Insurance', dataIndex: 'largeContainerPlusInsurance', width: 175, xtype: 'numbercolumn',
            editor: { xtype: 'numberfield', allowBlank: false, minValue: 0, blankText: 'Rate is required.', invalidText: 'Rate must be positive.' }},
        {text: 'Rate Currency', dataIndex: 'currencyId', xtype: 'currency-column' }
    ]
});

There is a decent non mvc example in the docs
Comment: @user1477388 They are listed in the **left hand tree** in [docs](http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.ux.grid.filter.BooleanFilter)
Comment: Thanks so much.  Do you know where the filters -> type options are listed?  I have some decimal types I would like to filter by, not just strings.


Error type - 2: preg_replace() [function.preg-replace]: Compilation failed: missing )

Question: I have following error:
Error type - 2: preg_replace() [function.preg-replace]: Compilation failed: missing ) at offset 25: in /var/www/hosting/com/galerielaboratorio/scripts/functions.php on line 766
Here is the function:
function getThumbName($photo, $name = 'thumb') {

$ext = preg_replace ("/.*\./", "", $photo);
$photo = preg_replace ("/\.". $ext ."$/", "" , $photo). "." . $name . "." .$ext; // this line causes the error

return $photo;

}
Thanks for help in advance.
Answer: Cannot read your expression, but you missed one ). ()-pairs define expression groups. One ( without its corresponding ) is just invalid (and thats what the error message tries to tell you). If you want to have a literal ( you must escape it \(
However, have a look at pathinfo(), explode() and str_replace(). This is not a scenario for regular expressions
$ext = pathinfo($photo, PATHINFO_EXTENSION);
$photo = basename($photo) . '.' . $name . '.' . $ext;

Answer: Not sure where it goes wrong; it's not clear from the code, as you're building a dynamic regular expression. Anyway, here's an alternative for you to enjoy, which contains slightly more error checking than your original function.
<?php
function getThumbName($photo, $name = 'thumb') {
    if( $ext = getExtension( $photo ) ) {
        return basename( $photo, $ext ) . 'thumb.' . $ext;
    }
    return false;
}

/**
 * Returns the file extension if it exists, false otherwise.
 * @param string $filename
 * @return string|bool
 */
function getExtension( $filename ) {
    return pathinfo( $filename, PATHINFO_EXTENSION );
}

echo getThumbName( 'foo.jpg' ) . PHP_EOL; // foo.thumb.jpg
echo getThumbName( 'slightly.more.complex.gif' ) . PHP_EOL; // slightly.more.complex.thumb.gif

echo getThumbname( 'This is where it gets interesting' ) . PHP_EOL; // false.


How to add a class to the image tag

Question: The input in file field.html.twig is normally like this:
{% for item in items %}

{{ item.content }}

{% endfor %}

And you get the output in HTML like this:

But I want to add a class to img-tag. How do I receive the following output:

I am looking for a solution like this (solution in another post), but it is not working. Can anybody help?
Comment: See also -- via theming docs on d.o: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates
Answer: I'd prefer to avoid editing templates for such simple things as adding just classes. I'd recommend to edit templates only if you really need to make changes to the markup.
For adding a simple class to your image all you need is the following snippet placed in your custom (sub-)theme's *.theme file. (Replace MYTHEME with the actual machine name of your theme). This one identifies the image by its image style (so ensure to have an unique image style applied to your image):
/**
 * Implements template_preprocess_image().
 */
function MYTHEME_preprocess_image(&$variables) {

  // Check the image style.
  if ($variables['style_name'] == 'img_fluid') {

    // Set class.
    $variables['attributes']['class'][] = 'img-fluid';
  }
}

If you are fine with adding the class not to the img tag directly, but to its wrapping container you could also use the following snippet. You can broaden the if-request as you like to only fire on certain content types (as you maybe use the same field in other content types as well), p.e. check for $variables['element']['#object']->bundle(). Replace field_MYIMAGE with your actual field name.
/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {

  // Check for your image field.
  if ($variables['element']['#field_name'] == 'field_MYIMAGE') {

    // Set class.
    $variables['attributes']['class'][] = 'img-fluid';
  }
}

Comment: Do I have a possibility to add a class to an image-tag in the body-field of a node? Authors can add an image inside the eck-editor. In this case I do not have an extra image field. The image is than e.g. inside the body-field. Can I add a class to the image using a preprocess function even in this case?
Comment: @lesleyn. – With a little bit of JS, sure. Or directly in the textarea when you switch to "Source" you can edit the `` directly. You see, your options are quite limited. Multi-purpose body fields are hell. I mean it. Switch to https://www.drupal.org/project/paragraphs and let editors build their content modularly. Then they'd have an extra paragraph type let's say "Image" with an image field, with all the features that come along with it: preprocessing, image styles, alt and title etc.
Comment: Thanks a lot for your infos! I am going to solve it with embed module.
Answer: You can first add theme suggestions for image elements based on the image style.
Add this in your mytheme.theme file:
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 *
 * Add theme suggestions for img elements.
 */
function mytheme_suggestions_image_alter(array &$suggestions, array $variables) {
  if (isset($variables['style_name']) && !is_null($variables['style_name'])) {
    $suggestion = 'image__' . $variables['style_name'];
    $suggestion = str_replace('-', '_', $suggestion);
    $suggestions[] = $suggestion;
  }
}

Then if you inspect your image you will see a theme suggestion based on the image style of that image. For example if you have an image style 'blog_item_teaser':

so now you can copy image.html.twig into your own theme and rename it to image--blog-item-teaser.html.twig and you can add your class there:

Of course, this will be applied to all images that use that image style.
Answer: You can first add attributes to your item and then add a class to it.
Like this:
{{ item.content, item.attributes.addClass('img-fluid') }}
Comment: I have put it in my template and after clearing the cache I got the info "The website encountered an unexpected error. Please try again later."
Answer: 2 is correct. However; it comes with drawbacks. Namely, there is nothing in the array passed via $variables to differentiate one img field from another.
In my case, I wanted to add classes to support Bootstrap functionality. BUT; I only want to do that in certain cases.
One line of jQuery did does the trick.
  $(".people-photo > img").addClass("card-img-top").removeAttr("width height");

And bonus: same line allowed me to easily get rid of height/width attributes that overrides Bootstrap.
Answer: In the view you created, select URL to image from Formatter.

Then, in the view template file, you can get the image URL using code similar to the following one.

field_cover_photo is the field machine name, in my case.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

How to add a class to the image tag


Cisco ASA 5505 Config -> Text File

Question: I'm just starting out learning to config Cisco ASA.  My office lent me their old ASA 5505 and I plan to do a factory-reset.  Before I do that, I'd like to backup the config to a text file on the machine I'm connecting to it from.
Right now, I ONLY have the console cable attached and am logged in using PuTTy.  The existing config is pretty big so I'm unable to do a "show run" and then copy/paste (the beginning of the config is cut off).  I also tried using logging in PuTTy but everything is all smushed together.
Is there a way to export the config directly to a text file on my desktop (using Win Server 2008)?
Comment: Problem solved but thought I would add this anyway, "everything is all smushed together" - try changing Session, Logging, Session Logging to "Printable Output" rather than "All Session Output"
Answer:
TFTP it off, if you can get IP connectivity to it
Configure PuTTY to allow more scrollback in the Window options:

ASDM also has an option to give you a copy of the config, with IP connectivity
Define "smushed" - perhaps it's giving you output with LF line endings?  Try opening it in a better text editor than notepad.
Answer: Log into your ASA 5505.
Type show run to display the running configuration.
Click the top/left screen icon (in Putty) and select COPY ALL TO CLIPBOARD
Open a text editor and paste the output.
The cleaner method is to use tftp, as it will preserve passwords. For basic backup, the above is okay.
If you're planning to use this firewall long-term, I'd recommend acquiring current copies of the ASA software and ASDM (graphical interface). There have been some major changes to the ASA software, and it makes sense to work with the newer versions.
Comment: `more system:running-config` will give you the passwords and keys that are redacted with a `*` in `show running-config`.
Comment: Thank you both!!!
I wound up doing a combo of both of your suggestions; I had to change the scrollback to 5000 to get it all!
Answer: The only way to get the full configuration off the ASA is either use more system:running-config (as opposed to show running-configuration) or to gain IP connectivity to it and copy the configuration to a tftp server. with copy running-config tftp://my.tftp.server/config.txt. Any other method will ommit 'sensitive' configuration information, such as pre-shared keys.
To make a local backup of the running configuration you can simply do copy running-config flash:/config.backup
Then you can do a write erase to clear the current startup  config and reload the ASA to start configuring again from scratch.
Comment: Your first statement is wrong. `more system:running-config` will show the config in all of its unsanitized glory.

Cisco ASA 5505 Config -> Text File


MvvmCross MvxTableView instead of MvxTableViewController

Question: I am using MvvmCross.
There is already implemented MvxTableViewController (also, respectively, DataSource and Cell). However, I need just UITableView (due to certain complicity of my parent view (ViewController (actually, it's already MvxViewController))), but I don't see any "MvxTableView" class exists.
Could you give me a clue, how to manage that situation. Generally, that sounds pretty trivial, as the table view already exists somehow inside of the MvxTableViewController, but instead, I currently use some "hand-made" approach.
Thank you!
Answer: There's nothing special about a databound UITableView - instead the data-binding is all placed in the MvxTableViewSource
So you can databind a standard UITableView by providing it with a databound source
There's an example using a UITableView N=6/N-7

video bookmark links via http://mvvmcross.wordpress.com/
source at https://github.com/slodge/NPlus1DaysOfMvvmCross/blob/master/N-07-BooksPlus/Books.Touch/Views/FirstView.cs

For choices on the available MvxTableViewSource classes, see What class to inherit from for bound table source
Comment: Thank you for the fast answer, and actually *public Func CellCreator* (if this is what you were mentioning in the last link above provided (under "GetOrCreateCellFor")) is exactly what I was looking for.
(That's sad that there is no way to use it as Generic, but I know that there is no such ability for creating Generic classes inherited from NSObject in Xamarin).


Prove that the set $\{x : \|Ax + b\|_2 \le c^Tx + d\}$ is convex

Question:
Prove that the following set is convex $$\{ x : \|Ax + b\|_2 \leq c^Tx + d\}$$

My initial thought is to choose two points $x_1,x_2$ in the set and then plug this back into the inequality to prove convexity, so:
$||Ax+b||_2 \Rightarrow ||A(\lambda x_1+(1-\lambda)x_2)+b||_2$
$\Rightarrow ||\lambda (Ax_1+b) +(1-\lambda)(Ax_2+b)||_2 \leq \lambda ||Ax_1+b||_2 +(1-\lambda)||Ax_2+b||_2$
This proves convexity of the LHS. I would then do the same for the RHS and because the LHS must be less than or equal to the RHS it must be a set contained within the RHS. Thus all x that satisfy the condition would be contained within the intersection of two convex sets and therefore the set is convex.
Is this the right way to think about it or am I totally off? Thanks in advance for the help!
Answer: You have to show that if $x_1,x_2$ satisfy the inequality, then so does $\lambda x_1+(1-\lambda)x_2$, for any $\lambda \in (0,1)$. So the goal is to show that $$\|A(\lambda x_1+(1-\lambda)x_2)+b\|\leq c^T(\lambda x_1+(1-\lambda)x_2)+d,$$assuming that $\|Ax_i+b\|\leq c^Tx_i+d$, for $i=1,2$, which is not quite what you have there. We do not think of "convexity on each side". One proceeds as follows: $$\begin{align} \|A(\lambda x_1+(1-\lambda)x_2)+b\| & = \|\lambda (Ax_1+b) + (1-\lambda )(Ax_2+b)\| \\ &\leq \lambda \|Ax_1+b\| + (1-\lambda)\|Ax_2+b\| \\ &\leq \lambda(c^Tx_1+d) + (1-\lambda)(c^Tx_2+d) \\ &= c^T(\lambda x_1+(1-\lambda)x_2) + d.\end{align}$$
Comment: Factor $c^T$ and use $\lambda+(1-\lambda)=1$ to get the single $d$.
Comment: Thanks for the response! One question, why can we say the last two equations are equal? By definition of convexity shouldn't it be $c^T(\lambda x_1 + (1-\lambda)x_2)+d \leq \lambda(c^Tx_1 + d) + (1-\lambda)(c^Tx_2+d)$? I believe either way it proves convexity but I was just curious if I had missed something.
Comment: Ahh got it thanks!
Answer: Call the left side $f(x)$ and the right side $g(x)$.
The set of points where a convex function $\le$ a constant is convex.
Here $f$ is convex and $g$ is affine, so $f-g$ is convex.


Get percentage progress of web services

Question: To initiliaze an intranet web site, it's necessary run a web service to obtain some info configuration. For this web service, I'd like show a progress bar.
In this simple way
$.ajax({
    url: "app.asmx/init",
    type: "GET",
    dataType: "json",
    xhrFields: {
    onprogress: function (e) {
        if (e.lengthComputable) {
            console.log(e.loaded, e.total);
        }
     }
});

I get the e.total and e.loaded when the call to the web service is ended.
In this article (not real percentage progress), is explaned a way to obtain a fake progress bar: not real percentage progress because is used a setInterval.
How can I get a real percentage progress? How can I get a server progress?
Answer: Use jQuery methods .ajaxStart() and .ajaxComplete().
Comment: I can't understand how .ajaxStart() and .ajaxComplete() can resolve my request: .ajaxStart() is 0%, .ajaxComplete() is 100%..but How I get the progress from 1% to 99%?
Comment: If you want to show the percentage from 1 to 100. Use **complete** method in jquery Ajax for each service request.
Comment: But the service request is unique: only app.asmx/init. Do you have a link for this approach?
Comment: So you want to call the request only once and still update the progress continuously?
Comment: The important is resolve my question. If I have to use more service request I will do it, but I can't figure out  how implement it. I'd like a link, if is possible, with more info about this solution

Get percentage progress of web services


Excel workday calculation

Question: I am using the following formula for a workday calculation where GB bank holidays are listed in sheet 'Bank Holidays' cell range B13:Z13.
=IF(F2<E2,IF(L2="GB",WORKDAY(E2,2,'Bank Holidays'!B13:Z13)),IF(L2="GB",WORKDAY(F2,2,'Bank Holidays'!B13:Z13)))

In the 'Bank Holidays' sheet I have 31 countries bank holidays listed across rows, column A has the list Country codes, columns B to Z have the holiday dates.
In my active worksheet ('ALL Data') I have rows of orders shipments including the country code (column L).
What I would like to do is when calculating the workday I want to exclude the holiday relevant to the country code.
In effect I need to do a vlookup using the country code on sheet 'ALL Data' Column L to the holiday days listed against the same country code on sheet 'Bank Holidays' column A.
But vlookup only returns the first value found. Is there a type of vlookup that will return all the dates against the relevant country code (range: column B:Z).
I believe an index match would work but, I'm not familiar with this and I cannot get this to work.
Comment: [INDEX](https://support.office.com/en-US/article/INDEX-function-a5dcf0dd-996d-40a4-a822-b56b061328bd) and [MATCH](https://support.office.com/en-US/article/MATCH-function-E8DFFD45-C762-47D6-BF89-533F4A37673A) will be what you are looking for
Comment: @DirkReichel  don't think INDEX/MATCH is all that easy/clean of a solution in this case...
Comment: Have you tried to google it? There are billions of examples showing how to use it (and also to avoid Lookup)... Even at this site are so many of them, you will have a hard time to ask a question wich is not a duplicate... but to simply throw the solution at him: `=WORKDAY(MAX(E2,F2),2,INDEX('Bank Holidays'!B:Z,MATCH(L2,'Bank Holidays'!A:A,0)))`
Answer: I actually OFFSET and MATCH would work easier for this particular case (but maybe it's just how I think about things in Excel):
=OFFSET('Bank Holidays'!A1,MATCH(L2,'Bank Holidays'!A:A,0)-1,1,1,24)
will get you the specific holidays for the country code in L2 in the Bank Holidays sheet.
So the entire formula becomes:
=IF(F2<E2,WORKDAY(E2,2,OFFSET('Bank Holidays'!A1,MATCH(L2,'Bank Holidays'!A:A,0)-1,1,1,24)),WORKDAY(F2,2,OFFSET('Bank Holidays'!A1,MATCH(L2,'Bank Holidays'!A:A,0)-1,1,1,24)))

The 24 column width argument assumes no holiday dates go beyond column Z for any given country.

Excel workday calculation


Will a lateral followed by a forward pass be ruled illegal in future?

Question: In the 2015 AFC divisional round game between the Patriots and the Raven, Tom Brady threw a lateral pass to receiver Julian Edelman; Edelman then threw a 51 yard touchdown pass to Danny Amendola. Will this kind of play be deemed illegal in the future?
Comment: Why do you believe this *might* be made illegal?
Comment: How could this be anything other than an opinion-based question - asking to predict the future?  More specifically asking if the NFL Rules Committee has taken it under consideration might be answerable, but not this as stands.
Answer: This is a perfectly legal play, and as far as I'm aware, there is no suggestion that this kind of play would be made illegal - what would you be making illegal anyway? A forward pass after a lateral? What about after a handoff?
Comment: One thing that may have been deemed illegal during that game was the [formation](http://www.businessinsider.com/nfl-banning-illegal-formation-patriots-used-in-playoffs-2015-3) the Patriots used on several plays, which is now considered illegal per the article. However, that is irrelevant to this play in question as said formation was not used.
Comment: @edmastermind29 interesting addition, thnx for the article
Comment: it's probably worth mentioning that a variation on this play has a name (flea flicker) and has been legal and used for a very long time.


How do I configure the mock server?

Question: According to the documentation, the test module included with the LDAP module  should  contain the mock LDAP server.
Where can I find it after enabling this module?
How should I configure it so that I can start testing logging in with a LDAP server?
Answer: The "Mock LDAP" server that is being used for the LDAP Test module is, in fact, a mock server object. It allows the tests to run, and doesn't exist outside the scope of the simpletests.
If you're looking to provide a way to "mock" an LDAP instance on your development site, it can't provide that functionality.
If you're trying to write your own simpletests for LDAP integration, check out the Examples for Developers project. The included module, simpletest_example, has excellent documentation for writing simple tests.

How do I configure the mock server?


get promise data through intermediate service angular 5

Question: I have an issue getting promise data through intermediate service.
There is a component, intermediate service and http service.
My component calls intermediate service and then call goes to http service through intermediate service.
Http service returns promise data, I think I am not able to process it in intermediate service hence nothing is returning to my component.
When I call Http service directly from component, it works well, I see the data coming on the UI.
Any help would be greatly appreciated.
component code.
Here is the method which calls method from intermediate service
public getDriversAndCars(){
    let promise = new Promise((resolve, reject) => {

        this.vehicleService.getVehicle()
        .then(
          res => {
           console.log("length"+this.listOfVehicles.length)
           this.getDriver();
         resolve();

        },
          msg => { // Error
          reject(msg);
          }
        );
    });
    return promise;
  }

Code from Intermediate Service
public getVehicle(): Promise<Vehicle[]> {

    this.associationservice.getVehicle(25, this.currentPageIndex, this.searchText)
      .then(
        res => {
          this.apimodel = res
          console.log("data" + this.listOfVehicles[0].assignedTo)
        },

    )
    return Promise.resolve(this.convertToVehicleModels(this.apimodel));

  }

code from Http Service
getVehicle(pageNumber: number,pageIndex: number, searchKeyword: string): Promise<VehicleResourceApiModel> {

    if (pageIndex !== 0 && searchKeyword.trim() !== '' && pageNumber !== 0) {
        // tslint:disable-next-line:max-line-length
        return  this.http.get<VehicleResourceApiModel>(api).toPromise()
        .then(response => {
            return response
        })
        .catch(err => err);

Answer: It looks like your intermediate service might be the problem. You are returning a resolved promise for this.convertToVehicleModels(this.apimodel) while this.apimodel is still undefined.  Your client gets back the result of this function immediately, while your associationservice is still retrieving and returning your actual data.
I suggest you modify your intermediate service something like this...
public getVehicle(): Promise<Vehicle[]> {
    return this.associationservice.getVehicle(25, this.currentPageIndex, this.searchText)
      .then(res => this.convertToVehicleModels(res))
}

This way the convertToVehicleModels method isn't called until your actual data are retrieved from your service, and your return value from getVehicle is the result of that promise chain.


XML processing using Apache Flink

Question: I am a newbie to Apache Flink and distributed processing as well. I have already went through Flink quick setup guide and understand the basics of MapFunctions.
But I couldnt find a concrete example for XML processing.
I have read about Hadoops XmlInputFormat, but unable to understand how to use it.
My need is,
I have huge(100MB) xml file of format as below,
<Class>
    <student>.....</student>
    <student>.....</student>
    .
    .
    .
    <student>.....</student>
</Class>

The flink processor would read the file from HDFS and start processing it(basically iterate through all the student element)
I want to know(in layman's terms), how can I process the xml and creata list of student object.
A simpler layman's explanation would be much appreciated
Answer: Apache Mahout's XmlInputFormat for Apache Hadoop extracts the text between two tags (in your case probably <student> and </student>). Flink provides wrappers to use Hadoop InputFormats, e.g., via the readHadoopFile() method of ExecutionEnvironment.
If you do not want to use the XmlInputFormat and if your XML file is nicely formatted, i.e., each student record is in a single line, you can use Flink's regular TextInputFormat which reads the file line by line. A subsequent FlatMap function can parse all student lines and filter out all others.

XML processing using Apache Flink


Is it possible to mock a function in all mounted components for every test file?

Question: Here is an example of a test file:
it('test case 1', () => {
       wrapper = shallowMount(Login, {
         store,
        localVue,
        mocks: {
           $router
           $GlobalVarForAllComponents // i want this variable to be assigned to every component i mock globally
         }
       })
       expect(true).to(true)
})

I want the $GlobalVarForAllComponents to be automatically assigned to every test case I write, without having to explicitly write this for every single test. Is it possible to use a global setting to do this?
Answer: You can use in the jest.init.js file
config.mocks['$store'] = {
state: {
id: 1
}
}
https://v1.test-utils.vuejs.org/api/config.html


Can anyone recommend a good Drupal module for managing/displaying videos

Question: I would like to put together a video gallery on my website and am wondering if there are any existing Drupal modules to manage that. I'm using Drupal 6 and most likely the videos will be hosted on YouTube.
Ideally, I would like to arrange them in topical albums in which each video could be annotated with a description of the videos.
Thanks.
Comment: That's a bit harsh. A search of drupal.org for 'video' returns 289 results, with neither emfield nor the media module in the top 10 results. The question does detail his use case, so it is feasible to come up with a recommendation.
Comment: When there is a canonical "best module" for a use-case, having that information as a resource is invaluable to a less experienced Drupal user.
Comment: Agreed, neither media nor emfield show up anywhere on the first page of results, even when only searching for modules. Also, this type of question is the one that has the most "on-topic" upvotes: http://area51.stackexchange.com/proposals/2978/drupal-answers/3001#3001
Answer: Drupal 6: Embedded Media Field. Now has a D7 version too.

This extensible module will create fields for content types that can be used to display video, image, and audio files from various third party providers. When entering the content, the user will simply paste the URL or embed code from the third party, and the module will automatically determine which content provider is being used. When displaying the content, the proper embedding format will be used.

Drupal 7: Media

The Media module provides an extensible framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site - it is commonly referred to as a 'file browser to the internet'.
Answer: The simplest modules to do this task are:

IMCE : IMCE is an image/file uploader and browser that supports personal directories and quota.
WYSIWYG : Allows to use client-side editors to edit content.
CKEditor - WYSIWYG HTML editor: loads faster (the number of files has been reduced, so the browser will perform less HTTP requests) and developers friendly.

Adding content(videos) using these modules will be simple and later css modifications can help in the positioning and look of the gallery.
Answer: Actually, a most modern approach to do this in drupal 7 is Module Asset. It has his its own entity Media asset to manage the medias.
It's very flexible since you can create your own types of Media Assets, which are fieldable entities, and has integration with CKEditor module.
Answer: Use the combination of CKEditor and Media module.
CKEditor:
It provides many HTML editing feature like:

Font formatting: type, size, color, style, bold, italic, etc
Text formatting: alignment, indentation, bullets list, etc
Cut and Paste, Undo and Redo
Link creation
Image insertion, with upload and server browsing support
Table creation and editing (add,delete rows, etc)
Right click context menus support
Complete toolbar customization
CSS support for a better integration in the web site
Lightweight and fast
For web developer it is easy to install and customize
For web users its simply easy to use!
Compatible with Internet Explorer 5+
Automatic browser detection and customization
Integration with ASP, ASP.NET and Javascript

Media: It provides an extensible framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site. It is a drop-in replacement for the Drupal core upload field with a unified User Interface where editors and administrators can upload, manage, and reuse files and multimedia assets.


Question on proof of when you add two rows on a matrix, why does $\det(B) = \det(A)$

Question:
Applying to a square matrix $A$ the row operation $R_i + \alpha R_j$ (that is, adding to Row $i$ a multiple of Row $j$), we obtain a new matrix $B$. Prove that $\det(B) = \det(A)$.

This is the proof:
$$\det(B) = \det \pmatrix{ a_{11} & \cdots & a_{1n} \\ \vdots & \vdots & \vdots \\ a_{i1} + \alpha a_{j1} & \cdots & a_{in} + \alpha a_{jn} \\ \vdots & \vdots & \vdots \\ a_{n1} & \cdots &a_{nn}}$$
$$ = \det \underbrace{ \pmatrix{ a_{11} & \cdots & a_{1n} \\ \vdots & \vdots & \vdots \\ a_{i1} & \cdots & a_{in}  \\ \vdots & \vdots & \vdots \\ a_{n1} & \cdots &a_{nn}} }_{\text{ A}} + \det \pmatrix{ a_{11} & \cdots & a_{1n} \\ \vdots & \vdots & \vdots \\ \alpha a_{j1} & \cdots & \alpha a_{jn} \\ \vdots & \vdots & \vdots \\ a_{n1} & \cdots &a_{nn}}$$
$$ = \det(A) + \alpha \det \underbrace{ \pmatrix{ a_{11} & \cdots & a_{1n} \\ \vdots & \vdots & \vdots \\ a_{j1} & \cdots &  a_{jn} \\ \vdots & \vdots & \vdots \\ a_{n1} & \cdots &a_{nn}}}_{\text{= 0 as two identical rows}}$$
$$= \det(A).$$
The bit I don't get is when you split $B$ up, how do you get that second matrix on the right? Shouldn't that have all zeros excepts for on row $i$ otherwise when you add it up, you will get double values on every entrance except for row $i$ wouldn't you?
Comment: The determinant is "column-wise" and "row-wise" linear, don't forget that.
Comment: Think about the matrix you need to multiply by to achieve the effect of adding one row to another, and look at the determinant of that. Not exactly what the question asks, but equivalent.
Comment: The matrix in the determinant on the first line is not being "split up" as a sum of two matrices on the second line.  There is no general rule for the determinant of a sum of two matrices, so another approach is being used.
Answer: The determinant is "column-wise" and "row-wise" linear, don't forget that. Thus, you have on one row that $$\begin{align}\det(R_1\mid \cdots \mid R_i+\alpha R_j\mid \cdots \mid R_b)= &\det(R_1\mid \cdots \mid R_i\mid \cdots \mid R_n)\\&+\;\alpha \det(R_1\mid \cdots \mid R_j\mid \cdots \mid R_n)\end{align}$$
That is, if we fix all the other $n-1$ rows, or $n-1$ columns, the determinant behaves exactly like a linear transformation on the "row vectors" or "column vectors". We also use that it is alternate, so equal rows yield a null image.
Comment: @amWhy Nope. I was about to tell you to look at $$\begin{pmatrix} 2&1\\0&1\end{pmatrix}=\begin{pmatrix} 1&0\\0&1\end{pmatrix}+\begin{pmatrix} 1&1\\0&0 \end{pmatrix}$$ though.
Comment: Because the statement you made about the determinant of a sum is not true in general.
Comment: I don't see why *I* was downvoted, since what I'm saying is true. The determinant is a multilinear alternating form.
Comment: @PeterTamaroff What do you mean by columnwise and rowwise linear?
Comment: @Kaish "That is, if we fix..." Did you read what I wrote?
Comment: @PeterTamaroff When you say fix, you just mean like leave it and don't alter it any way yeah?
Comment: @amWhy First off, I wasn't the downvoter.  I _was_ in the midst of posting my comment when your answer was deleted.
Comment: @Kaish Yes, when I say "fix" I mean "keep it constant".
Comment: @PeterTamaroff Thanks. Got it. Do you know about my other matrix questions?
Comment: @Kaish It might be worth noting that this is one of the defining properties of the determinant. You're notes should probably state it. Of course, we should first prove there exists a multilienar alternating form, (and that it is unique up to the value it takes on the identity) so maybe you wanna re-read your notes.
Comment: @Peter There are several standard definitions, and not all of them use this as a defining feature. For some, it's a consequence. Just sayin'.
Comment: @alex.jordan Yes. Duly noted. It seems the OP's notes define it this way, though.
Answer: I'll use Laplace's formula.
$$det(B) = \sum_{j=1}^n(-1)^{i+j} (a_{ij}+\alpha a_{kj})M_{ij} = \sum_{j=1}^n(-1)^{i+j} a_{ij}M_{ij} + \alpha  \sum_{j=1}^n(-1)^{i+j} a_{kj}M_{ij} = det(A) + \alpha  \sum_{j=1}^n(-1)^{i+j} a_{kj}M_{ij} $$
$$\alpha  \sum_{j=1}^n(-1)^{i+j} a_{kj}M_{ij} = \alpha \det  \pmatrix{ a_{11} & \cdots & a_{1n} \\ \vdots & \vdots & \vdots \\ a_{j1} & \cdots &  a_{jn} \\ \vdots & \vdots & \vdots \\ a_{n1} & \cdots &a_{nn}}=0$$


Why is RuntimeException not assignable from Throwable?

Question: I have a method that (unfortunately) accepts an Object instance as its sole parameter. I need to add logic that handles it differently if the Object is any type of Throwable (that means all Exceptions - checked or unchecked, as well as all Errors).
public void handle(Object toHandle) {
    if(toHandle.getClass().isAssignableFrom(Throwable.class))
        handleThrowable(toHandle);
}

When I invoke this method like so:
RuntimeException rte = new RuntimeExceptio("Panic!");
handle(rte);

The isAssignableFrom check returns false and handleThrowable never gets invoked. Why?
Instead, I have to use:
public void handle(Object toHandle) {
    if(toHanlde instanceof Throwable)
        handleThrowable(toHandle);
}

This works, as I expected it to. But still stumped as to why the isAssignableFrom isn't working...thanks in advance!
Comment: It is working. You can't assign the super type to the derived type. You really want to know if Throwable is assignable from your type, not the other way around.
Comment: Reverse the `isAssignableFrom`
Comment: That statement will always be false, since RuntimeExceptions (and all Exceptions) are not the same type, or a superclass of Throwable... It's inverted
Comment: Use [`instanceof`](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html).
Answer: Look at the documentation of isAssignableFrom:

Determines if the class or interface represented by this Class object
  is either the same as, or is a superclass or superinterface of, the
  class or interface represented by the specified Class parameter.

So you are actually checking if the class of toHandle is a superclass of Throwable. This is not what you want.
You should do it the other way around:
if (Throwable.class.isAssignableFrom(toHandle.getClass()))

or simply use instanceof.
Answer: Its other way around. here is the java doc of isAssignableFrom(...) method

Determines if the class or interface represented by this Class object is
  either the same as, or is a superclass or superinterface of, the class or
  interface represented by the specified Class parameter.
  It returns true if so; otherwise it returns false.

So when you do
if (toHandle.getClass().isAssignableFrom(Throwable.class))

Its actually checking whether RuntimeException class object  is either the same as, or is a superclass or superinterface of, the class or interface represented by Throwable.
Answer: isAssignableFrom checks if this class is the same as, or a parent of, the argument class.
In your code, you're asking if toHandle is the same as or a parent of Throwable, which is probably not what you want.


Issues with vif-nat and Xen after upgrading from Debian 8 to 10

Question: I'm getting this error when running xl create:
# xl create ../vm-www.rootspirit.com.cfg
Parsing config from ../vm-www.rootspirit.com.cfg
libxl: error: libxl_exec.c:118:libxl_report_child_exitstatus: /etc/xen/scripts/vif-nat online [12721] exited with error status 1
libxl: error: libxl_device.c:1286:device_hotplug_child_death_cb: script: /etc/xen/scripts/vif-nat failed; error detected.
libxl: error: libxl_create.c:1520:domcreate_attach_devices: Domain 32:unable to add vif devices

My VIF config looks like this:
vif = [ 'ip=172.16.1.51,mac=11:11:23:44:23:52,script=vif-nat', 'ip=2001:1AF8:3100:A00A:21::2000,mac=43:32:11:23:70:20,script=vif-bridge,bridge=xenbr0' ]

But anything that includes script=vif-nat or script=vif-route fails with the above error.
The package iproute2 and net-tools are installed. Logs don't show anything.
The xl -vvvv command is here.
What am I missing here?
Answer: Not sure why the vif-nat script crashes. I have resolved the problem by creating my own internal network.
Dom0:
allow-hotplug xenbr1
auto xenbr1
iface xenbr1 inet static
        address 10.13.37.1
        netmask 255.255.255.0

xen configs:

Public and LAN DomU: vif = [ 'ip=184.108.40.206,bridge=xenbr0', 'ip=10.13.37.123,bridge=xenbr1' ]
LAN only DomU: vif = [ 'ip=10.13.37.123,bridge=xenbr1' ]

iptables should be something along the lines of:
iptables -A FORWARD --in-interface xenbr1 -j ACCEPT
iptables --table nat -A POSTROUTING --out-interface xenbr0 -j MASQUERADE

And of course config the static IP in network settings of the DomU.


Expected value of a "logistic uniform" multivariate

Question: Let $\mathbf{a}_1,\ldots,\mathbf{a}_n \in \mathbb R^d$ and $b_1,\ldots,b_n \in \mathbb R$ be fixed.  For $\mathbf{x} \sim \mathcal U([0,1]^d)$ and $j \in \{1,\ldots,n\}$, consider the real variable defined by the softmax / "logistic" transformation
$$y_j(\mathbf{x}) = \frac{\exp(\mathbf{a}_j^T \mathbf{x} + b_j)}{\sum_{k=1}^n\exp(\mathbf{a_k}^T\mathbf{x} + b_k)}.
$$
I'm interesting in an efficient way to compute the expected value of $y_j$.
Poorman's solution:

Draw $\mathbf{x}_1,\ldots,\mathbf{x}_N \sim \mathcal U([0,1]^d)$
Compute the empirical mean $\hat{\mu}_N(y_j) := \frac{1}{N}\sum_i^N y_j(\mathbf{x}_i)$.

For sure, $\hat{\mu}_N(y_j) \overset{N \rightarrow \infty}{\longrightarrow} \mathbb E_{\mathbf{x} \sim \mathcal U([0,1]^d)} [y_j(\mathbf{x})]$ by law of large numbers.
Question:

How to make the above "poorman's solution" faster (i.e high accuracy with small $N$) ?
How can "importance sampling" be used to accomplish this ?

Details will be very much appreciated.
Comment: It's not just an artificial assumption, it's part of the problem data...
Comment: Why are you assuming $x_i$ are uniform? Wouldn't it make more sense to assume they are sampled from your data distribution?
Comment: not importance sampling, but for small $d$, quasi-Monte Carlo would give you a better convergence rate w.r.t $N$
Answer: A couple of thoughts on this problem which might be of interest: your predictor can be interpreted as the Bayes classifier for a Gaussian mixture model. For example, if you take $r \in \mathbf{R}^d, Q \succ  0$, then
\begin{align}
y_j(x) &= \frac{\omega_j \mathcal{N} \left( x | \mu_j, Q^{-1} \right)}{\sum_{k=1}^n \omega_k \mathcal{N} \left( x  | \mu_k, Q^{-1} \right)} \\
\text{where} \quad\omega_k &= \exp \left( b_k + \frac{1}{2} |a_k + r|_{Q^{-1}}^2 \right) \\
\mu_k &= Q^{-1} \left( a_k + r \right).
\end{align}
Your quantity of interest can be expressed as "given a uniform sample from the hypercube, what is the probability that it came from the $j^{\text{th}}$ component of this GMM?". This naturally suggests a simple importance sampling scheme which puts most of its mass near the $j^{\text{th}}$ mode, e.g.
\begin{align}
q_j (x) = \alpha_0 \cdot \mathbb{I} \left[ x \in [0,1]^d \right] + \alpha_1 \cdot \mathcal{N} \left( x  | \mu_j, \gamma \cdot Q^{-1} \right)
\end{align}
where $(\alpha_0, \alpha_1, \gamma)$ are tunable parameters. One could also consider importance distributions based on the full $n$-component mixture, e.g.
\begin{align}
q^n (x) = \alpha_0 \cdot \mathbb{I} \left[ x \in [0,1]^d \right] + \sum_{k = 1}^n \alpha_k \mathcal{N} \left( x  | \mu_k, \gamma \cdot Q^{-1} \right),
\end{align}
which induces additional tuning parameters, which has its costs and benefits. Of course, there is the complication of setting $(r, Q)$ as well. My guess is that if one can set $(r, Q)$ such that the support of the implied GMM overlaps well with the hypercube as a whole (by some measure), this will give well-behaved weights for a derived importance sampling scheme.
My suspicion here is that if one can find a good way of setting $(r, Q)$, then life is not too hard: one can use the above construction to parametrise a family of importance densities, and then apply standard adaptive importance sampling techniques, possibly also using some extra variance reduction tricks like QMC / stratification and control variates to sweeten the deal.
I hope this is at least somewhat useful. I am a little frustrated that I lack intuition for how to set $(r, Q)$ automatically, as once that is done, the problem is relatively friendly. One idea would be to try to tune $(r, Q)$ such that
\begin{align}
\sum_{k = 1}^K w_k \textbf{Var}_{\mathcal{N} \left( x  | \mu_k, Q^{-1} \right)} \left( y_j (x) \cdot \mathbb{I} \left[ x \in [0,1]^d \right] \right)
\end{align}
is minimal, though it should be emphasised that this is just a heuristic.


How to use vlookup if lookup value contains multiple values in single cell

Question: Suppose Sheet1 has the following table ( data range Cell A1 to B4)
Fruits  | Colors
======= | =======
 Apple  | Red
 Mango  | Green
 Banana | Yellow

Suppose in sheet2, Cell A1 has following values ( Apple Mango Banana) separated based on space.
How to use VLookup in Cell B2 based on A1 value which can give you the results in the same order ( Red Green Yellow)
Answer: This formula in Sheet2!B2 does it:
=INDEX(sheet1!B:B,MATCH(TRIM(LEFT(SUBSTITUTE(A1, " ", REPT(" ", 100)),25)),sheet1!A:A,0)) & " " &
INDEX(sheet1!B:B,MATCH(TRIM(MID(SUBSTITUTE(A1," ",REPT(" ",100)),100,25)),sheet1!A:A,0)) & " " &
INDEX(sheet1!B:B,MATCH(TRIM(RIGHT(SUBSTITUTE(A1, " ", REPT(" ", 100)),25)),sheet1!A:A,0))

This formula works fine when you have 3 values to match (in case there are 2 only, the second one will be repeated). It can be further complicated to treat any number of values.
Of course it can be simpler in VBA using the Split function, and it would take into account any number of keys, yielding the joined values. You can use this in a macro:
Sheet2.Range("B1").value = Join(Application.index(Sheet1.Columns("B"), _
    Application.match(Split(Sheet2.Range("A1")), Sheet1.Columns("A"), 0)), " ")

Of course you can adjust it to any cell in column B, using Range("B" & i) and Range("A" & i)...
Comment: Thanks a lot. that's what I was looking for. Both excel formula and VBA was important. However, VBA is more dynamic to use to suits all scenarios.
Comment: One quick question: - what if you don't have one value in the lookup table. suppose "Apple" does not exist in Sheet1? in another word, how we can use "if error" in VBA?
Comment: never mind, I fig. out the solution : Sheet2.Range("B2").Value = Trim(Join(WorksheetFunction.IfError(Application.Index(Sheet1.Columns("B"), _
    Application.Match(Split(Sheet2.Range("A2")), Sheet1.Columns("A"), 0)), " "), " "))
Comment: I was going to paste this (after some testing): check if it is exactly the same!! `Sheet2.Range("B1").value = Join(Application.IfError(Application.Index(Sheet1.Columns("B"), Application.Match(Split(Sheet2.Range("A1")), Sheet1.Columns("A"), 0)), ""), " ")`
Comment: once again here, I am getting an error when there is an extra space either at the beginning of the text or inside the text, for example, Cell A1 in sheet2 is (  Apple  Mango) with additional space at the beginning and in middle then VBA code doesn't work.
Comment: It works for me. However you can trim A1 before splitting: `Split(Application.Trim(Sheet2.Range("A1"))`. Important: use `Application.Trim` not the trim of VBA, because the former removes all extra spaces including interior ones.


cvs rtag: [07:34:59] waiting for cvsuser's lock in

Question: When I do rtag the process is rather slow with the message cvs rtag: [07:34:59] waiting for cvsuser's lock in ...; what causes this and how to resolve this? Thanks in advance.
Answer: Searching via Google for "cvs waiting for lock" returns plenty of results. This is the first result I see and it covers everything you need:

http://durak.org/sean/pubs/software/cvsbook/CVS-says-it-is-waiting-for-a-lock_003b-what-does-that-mean_003f.html

But in essence, someone else is in the middle of a CVS operation. Wait for it to complete.
If you know that this isn't the case (eg. you spoke to that user) then their cvs operation failed and left a lock file behind. Delete it. See the link for details.
Answer: The information in the link given by Burhan Ali is out of date. The latest incarnation of cvs seems to store locks in $CVSROOT/locks/project/directory... so if the message is "Waiting for foo's lock in /home/cvs/myproject/html" the lock file is in /home/cvs/locks/myproject/html with an owner of foo. The name of the lock file starts with #cvs but there only seem to be lock files there.


Javascript how to filter a list with category and subcategories

Question: UPDATE (Nov 2019): Like @Austin T French mentioned below, the key is to make sure to differentiate (ie. group) the countries by class for example. Updated code snippet added below!

In the code below is it possible to filter the list of "countries" (subcategories) so that the "continent" (parent category) filters as well?
For example if I search "China" I want to have "Asia" filter above it at the same time.
As a next step I'd also like to have the "subcategories" display when search for the "parent categories". For example, when searching for "Asia" I want to have "China", "Japan", and "South Korea" to filter.
Or would this be more practical to create a filtered table with two columns?

function filterCountries() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("search-country");
  filter = input.value.toUpperCase();
  ul = document.getElementById("country-list");
  li = ul.getElementsByTagName("li");
  for (i = 0; i
 -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

Countries

<input type="text" id="search-country" onkeyup="filterCountries()" placeholder="Search for countries.." title="Type in a country">

Asia

China

Japan

South Korea

Europe

France

Germany

United Kingdom

North America

Canada

Mexico

United States

South America

Argentina

Brazil

Chile

UPDATED CODE (Nov 2019)

function filterCountries() {
  const input = document.getElementById("search-country");
  const filter = input.value.toUpperCase();
  const li = document.querySelectorAll("li");
  for (let i = 0; i
 -1) {
      document.getElementsByClassName(li[i].className)[0].style.display = "";
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

Countries

<input type="text" id="search-country" onkeyup="filterCountries()" placeholder="Search
for countries.." title="Type in a country">

Asia

China

Japan

South Korea

Europe

France

Germany

United Kingdom

North America

Canada

Mexico

United States

South America

Argentina

Brazil

Chile

Answer: You don't currently have any actual method to differentiate regions. I'd add a property to the HTML and optionally select off of that:

function ShowAsia(){
  $(".asia").toggle();
}

function ShowEurope(){
  $(".europe").toggle();
}
li {list-style:none;}

China

Japan

South Korea

France

Germany

United Kingdom

<button type="button" onclick='ShowAsia()'>Show Asia</button>
<button type="button" onclick='ShowEurope()'>Show Europe</button>


What is the equivalent of theme_menu_item in Drupal 7?

Question: I know that in drupal 6 exist: theme_menu_item, but in drupal 7 there is not. Is there any replacements so that I modify the output for main system menu ?
Actually I want to do a kind of filter of the menu items depending some criteria, which I will set in the function.
Comment: Could you please rephrase your question to 'What is the equivalent of theme_menu_item in Drupal 7'?
Answer: Looking at the function that called the theme function theme_menu_item() (menu_tree_output()), and comparing it with the Drupal 7 version of the same function, I can say that the equivalent of theme_menu_item() is theme_menu_link().
Comment: Thanks, I have put `function mytheme_menu_link(array $variables)` in `template.php` file from my theme, but it has no effect to menu. I have checked with debugger and the function is not processed by drupal, just as he doesn't recognize this hook...
Comment: @Ek Kosmos: `theme_menu_link()` is not a hook, but a theme function. Theme implementation needs to be registered using `hook_theme()`, as reported in [Default theme implementations](http://api.drupal.org/api/drupal/modules--system--theme.api.php/group/themeable/7).
Comment: "Each module should provide a default implementation for theme_hooks that it registers. This implementation may be either a function or a template; if it is a function it must be specified via `hook_theme()`. By convention, default implementations of theme hooks are named `theme_HOOK`. Default template implementations are stored in the module directory."
Answer: The theme_menu_item() function has been replaced by theme_menu_link(). For details on this change, and all other changes made to the theme layer between Drupal 6 and 7, see the Converting 6.x themes to 7.x page. There is also a corresponding module conversion page.


How to get Pareto IV parameter estimates

Question: I have a serie with 850 observations, and I need to fit the Pareto IV distribution. How could I do this in R?
I read the guide VGAM, however, I'm not  able to run it.
If anyone knows, please provide me with a detailed (step by step) answer so that I can understand it...
Answer: First install package VGAM. After instalation, use library command to load it. Then fit and estimate like this:
> library(VGAM)
> #Generating a sample data
> pdata <- data.frame(y = rparetoIV(2000, scale = exp(1),ineq = exp(-0.3), shape = exp(1)))
> #Fitting paretoIV
> fit <- vglm(y ~ 1, paretoIV, data = pdata, trace = TRUE)
VGLM    linear loop  1 :  loglikelihood = -4458.70611
VGLM    linear loop  2 :  loglikelihood = -4016.73751
VGLM    linear loop  3 :  loglikelihood = -3649.98206
VGLM    linear loop  4 :  loglikelihood = -3638.00816
VGLM    linear loop  5 :  loglikelihood = -3295.17245
VGLM    linear loop  6 :  loglikelihood = -2950.35959
VGLM    linear loop  7 :  loglikelihood = -2899.05851
VGLM    linear loop  8 :  loglikelihood = -2888.96505
VGLM    linear loop  9 :  loglikelihood = -2888.71811
VGLM    linear loop  10 :  loglikelihood = -2888.71723
VGLM    linear loop  11 :  loglikelihood = -2888.71723
> coef(fit, matrix = TRUE)
            log(scale) log(inequality) log(shape)
(Intercept)   1.043666      -0.3020726   1.023722
> #Extracting coefficinets
> Coef(fit)
     scale inequality      shape
 2.8396070  0.7392844  2.7835358
> #summary of the fit
> summary(fit)

Call:
vglm(formula = y ~ 1, family = paretoIV, data = pdata, trace = TRUE)

Pearson residuals:
                      Min         1Q    Median      3Q    Max
log(scale)       -8.25407 -0.8617977 -0.328181 0.76683 4.4188
log(inequality)  -0.82645 -0.7260530 -0.378008 0.41872 7.1240
log(shape)      -17.23069  0.0058047  0.081766 0.15972 4.4172

Coefficients:
              Estimate Std. Error  z value
(Intercept):1  1.04367    0.14834   7.0358
(Intercept):2 -0.30207    0.03012 -10.0291
(Intercept):3  1.02372    0.14190   7.2145

Number of linear predictors:  3

Names of linear predictors: log(scale), log(inequality), log(shape)

Dispersion Parameter for paretoIV family:   1

Log-likelihood: -2888.717 on 5997 degrees of freedom

Number of iterations: 11
>

I took above codes form package VGAM, page 493. You need to replace your data with pdata.
Comment: I didn't have your data .... right? So I had to generate a sample from a Pareto IV distribution using rparetoIV. Therefore, the answer is no ... you don't have to generate with these parameters. You just need to create a data frame using your own observations like this : `pdata.new <- data.frame(y =c(obs.1,obs.2, ...., obs.850))`. Then use this new data frame to fit i.e. `fit.new <- vglm(y ~ 1, paretoIV, data = pdata.new, trace = TRUE)`
Comment: I had already read this guide on VGAM, the thing I do not understand is if I have to generate the data with these parameters of the example or not. if not, what should I use?


AngularJS $http ajax not working on asp.net web api call

Question: I have a simple AngularJS ajax call as follows.
    $scope.modelObject.sendRequest = function (requestType) {
        var dataTemp = { first: 7, second: 3 } ;
        alert($httpParamSerializer(dataTemp));
        $http({
            url: '/api/bindings/sumnumbers',
            data: $httpParamSerializer(dataTemp),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }
        ).success(function () {});
    }

And at the other end I have a web api BindingsController with sumnumbers action method as follows.
    [HttpGet]
    [HttpPost]
    public async Task<IHttpActionResult> SumNumbers() {
        if (Request.Content.IsFormData()) {
            NameValueCollection jqData = await Request.Content.ReadAsFormDataAsync();
            int firstValue, secondValue;
            if (TryGetValues(jqData, "first", "second", out firstValue,
                out secondValue)) {
                return Ok(firstValue + secondValue);
            } else if (TryGetValues(jqData, "value1", "value2", out firstValue,
                out secondValue)) {
                return Ok(firstValue - secondValue);
            }
        }
        return StatusCode(HttpStatusCode.BadRequest);
    }

The alert in the javascript code alert($httpParamSerializer(dataTemp)); is showing the data correctly.
And a break point I placed in the action method is hit showing that the call is successiful. But the problem is TryGetValues(jqData ... is not not able to get any values. Is see that AllKeys property of jqData(NameValueCollection), does not have any keys at all!!. Can someone please suggest what am I missing?
Answer: its a petty mistake from my side. Just need to add
method:'Post'

inside the call so the call becomes
        $http({
            method:'Post',
            url: '/api/bindings/sumnumbers',
            data: $httpParamSerializer(dataTemp),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }

I used the fiddler to find this out.


When learning scales, is it important to know which key is being pressed when?

Question: I'm relatively new to learning the piano, though this has been a point of confusion since day one.
So, I started out with C Major and everything was going fine. I got the finger motions down, I was good with the overall technique, then I began to wonder: "What's the purpose of this?"
I went to the Internet for answers, and found a truly horrifying answer - One I had wished wasn't true, a single answer I've yet to see repeated elsewhere, but uncertainty is always present. Apparently, alongside the facts that many classical pieces utilize scales and it's a good finger exercise, someone suggested that you have to memorize each key pressed in the correct order per sequence.

My conclusion:
There are twelve scales (7 major, 5 minor) (12 major AND 12 minor as I'm told, ignore the incorrect math following), each consisting of twelve keys - "96" keys in total. Then, you must also mentally overcome the same feat with your less dominant hand, essentially doubling the amount you must commit to memory. At one point you'll be expected to do this quickly, with both hands, sometimes with separate scales, and possibly backwards. It begins to sound like an entirely separate skill than actually playing the piano.
It sounds like a form of torture conceived by the devil himself - To punish the most wicked, corrupt soul for committing crimes our mortal minds cannot comprehend.
Now, I understand knowledge of scales aren't required to actually "play" the piano, but I wish to learn properly and everything seems to suggest that "scales" (Vague scales - We mustn't elaborate!) are the one of the most important things to pick up.
I'm thinking this may be like math and me - I'm really good at it as far as knowing the techniques and all, but I've always had I hard time seeing the raw math behind it (WHY does the distance formula work?).
So, in technique and practice, is it actually required that you "train" to the point where you become mentally aware that you're pressing "C D E F G A B C - C B A G F E D C", or is it just a finger/mental exercise?
I've always wanted to compose my own music - Understand the logic behind it. I'd be willing to go through this potentially traumatizing experience if I must. I want to fully grasp every aspect of it, it's something I love.
Comment: How do you conclude there are 12 scales, 7 major and 5 minor? Just possible you're mixed up with white and black keys on the piano? Each note on a piano will be the root note for both major and minor scales, thus 12 of each. There are 3 different minor scales, and possibly one includes pentatonics and blues, the there's the modes, etc.
Comment: I think the point of such repetition is for the memorization to happen automatically in your motor-control neurons.  You don't need to be concerned with being able to have perfect recall about what you played - in fact some of the most "talented" musicians can struggle in analytical areas like that much more than average.  The value is in associating your mental/emotional states associated with the scales with the technical methods required to reproduce them on the keyboard.  This is a constant ongoing process which is never fully mastered.
Comment: @Tim Aye, that's correct. Again, just started so I assumed white keys = major and black keys = minor. The instructor (DVD) began to teach the use of 'major scales' and skipped any that began with a black key.
Answer: It's always counter-productive to feel horrified while you're trying to learn something!  At your level, please don't feel you have to memorize your fingering or your black-white key patterns.  For now, make sure each scale you work on feels comfortable and smooth.  What you are mainly doing at this point is getting some fluency, practicing these figures out of the context of a piece.  It can be fun to play your scale at a couple of different speeds, and experiment with different groupings of notes, for example what happens when I play two notes to a group?  What happens when I play four notes to a group?  Etc.
I wouldn't spend more than five minutes per day working on scales at this point.
Preview for later: you will find yourself using muscle memory, and in practice you won't need to do nearly as much explicit memorization as you are imagining.  Also, with a scale, once you know what finger to start on, the scale sort of plays itself for the most part.
Now, if you're interested in composing, then you'll want to be able to analyze music, and that's where the study of music theory comes in.  For your first stage of this (which you may start now, or a year from now, or anything in between), you can get some elementary level music theory workbooks from a store that sells sheet music and instrument method books.
Comment: I completely agree. You'll find common repeating patterns across numerous scales. So in short whilst there may seem like a lot of scales in reality they draw from a much smaller set of frequently occurring patterns.
Answer: Just think about what you have to memorize in order to drive a car!  The accelerator opens the throttle to give more power to the engine.  If you want to accelerate at the rate of two miles per hour per second, you have to push it down by a precise amount, plus or minus a certain amount if you are going uphill or downhill.  At the same time you do this, you have to adjust the steering wheel, and if you're driving a standard-shift car, then at just the precise moment when the tachometer hits 2,000 you have to let off the gas, press in the clutch and take one hand off the wheel to move the stick!
In actuality, nobody memorizes all of that stuff.  You just practice doing it over and over until you can do it without thinking.  Same with scales and arpeggios.
Answer: When reciting poetry, you don't just need to learn the sounds of the 26 letters, but also the sounds of various combinations, partly even those of whole words.  I mean, compare "bough", "rough", "dough", "cough", "plough", "tough".  Then you need to learn where to stress each word, just compare "determinate" and "determination" where the word ending affects the stresses at the beginning.  And then words are pronounced different in combination, like "the" in "the beginning" vs "the ending".
So you spend years practising letter combinations and word stresses and word combinations.
Now what kind of nightmare is that?  Or is it?  Most people get by reasonably fine by not making a systematic exercise regime from it.  When you're obsessed enough that it becomes important to you, you will turn this into a regular exercise on your own anyway and annoy everybody in hearing range.  Don't worry about it yet.
Answer: In fact there are 12 major scales (one for each root note) and 12 minor scales -- and there are other scales too - chromatic scales, various pentatonic scales, blues scales... the list goes on and on.
However, don't be daunted.  Most people don't even learn all the major scales -- there is a smaller group that are most commonly used, because they are easier to play, or sound better, on certain instruments. If you follow a structured lesson plan, a good set of scales will be introduced to you in a sensible order.
It's good that you're asking what the point of learning scales is, because knowing the reasons will help motivate you to learn and practice.

Playing scales in general exercises your fingers and helps you get into the habit of a set of movements that often come up when playing real pieces.
Most of the time, real musical pieces use only the notes from a particular scale (the piece's key). So if, for example, you're playing a piece in G minor, and you've been practising the G minor scale, then you'll be in the habit of playing Bb and Eb instead of B and E. When there's a run in the piece, you'll already have muscle memory of how to play it. If you've also practised arpeggios in that key, you'll be able to play those too, when they appear in a piece.
If you have any ambition to improvise, knowing scales is important here too, for the same reason as when reading music. If you're improvising against a backing in A minor, you'll primarily be using notes from the A minor scale in your improvisation.

Different people's minds work in different ways. But many of us don't find that learning scales is a matter of learning by rote. The first scale, yes. But every scale of a given type has the same pattern of intervals -- so all major scales go up in steps of 2,2,1,2,2,2,1 semitones. Once you know that, you can (slowly) play any major scale without learning it, by just starting on the root note and counting semitones up. "Learning" a scale is just a matter of getting to the point where you can get to those notes without spending too much time thinking.
Notice that C major and A minor contain the same notes, and so do all the other pairs of major/minor scales a third apart. If you take an observant and analytical approach, you will see loads of these patterns and it will make learning easier.
Answer: While only skimming the other answers, let me answer it simply this way:
How difficult was it for you to learn how to read and write?  Think of all the different combinations of letters and spaces that are required in order for this sentence to "make sense" to you.  The same applies to music although much more simply.
As you learn your scales, you will begin to recognize relationships between the different scales, and you won't be memorizing every individual note progression, but rather you will naturally memorize the patterns.
For example: A major and D major both have a raised 3rd that results in the keyboard going from a white key (C for aM, F for dM) to a black key; overtime you will recognize this while you play and improvise, and it will become a sort of mental "anchor" for you.  As you play more and more, more and more "anchors" will become apparent.  You will ultimately get to the point where you are naturally mentally comfortable with all scales and how to play them, from any position, on demand.
I know this seems like a lot since you are a beginner, but understand the most important thing about music:  Music is all about relationships.  How a note relates to another note, chord to another chord, progression of chords to another phrase, etc etc.  As you expand your musical vocabulary more and more, these relationships (patterns) will emerge and it will help "glue" all of the various aspects of music together more and more.
Hope this helps.  I only practiced my scales and had lessons for 1 year out my 10 years playing (I did practice scales sporadically since that year, however not consistent).  If I had practiced my scales like I should have, I would have been a "virtuoso" (at least in terms of technical ability) years ago. <-- Keep practicing your scales and arpeggios; there is a reason why there is so much emphasis on them.
Answer:
So, in technique and practice, is it actually required that you "train" to >the point where you become mentally aware that you're pressing "C D E F G A >B C - C B A G F E D C", or is it just a finger/mental exercise?

You've already got lots of great answers, but just a quick note about the above.
A piano method will usually recommend not just notes, but a particular finger for each note in each scale.  Also the sequence will be different for the right & left hand.  If you stick to these recommended fingerings, you'll find the notes are automatically easier to play; for example the longer fingers tend to be in a good position to reach the black keys.
Of course not every piece will use the recommended fingerings, but in general learning these positions will allow you to read through most new pieces without your fingers getting tied into knots.
Answer:
someone suggested that you have to memorize each key pressed in the correct order per sequence.

What you read about rules and finger-setting might have been a good meant advice to a beginner and was not meant for all piano pieces but for just a difficult passage.

It sounds like a form of torture conceived by the devil himself - To punish the most wicked, corrupt soul for committing crimes our mortal minds cannot comprehend.

If you start with the  scale  of B-major there are just 2 white keys that you can play with the thumb as it makes sense to play the black keys with the longer finger. The more you come across the scales of the circle of fifths BEADGC... the more white keys can be played by the thumb and the more freedom you will have to use your fingers. Still reserve one black key to cross the thumb under the 4. finger. This is not a rule it's just more comfortable.

So, in technique and practice, is it actually required that you "train" to the point where you become mentally aware that you're pressing "C D E F G A B C - C B A G F E D C", or is it just a finger/mental exercise?

It will be benefit for composing when you are aware of what your finger are pressing. But even more helpful will be that you hear what you are playing. You can practice this mentally by thinking or singing those passages (together with the finger-settings). It will help you memorizing the music and understand what you're playing. One day this will function automatically.
Answer: Old post, but I'm adding an answer for new visitors.

There are twelve scales... (12 major AND 12 minor...), each consisting of twelve keys - "96" keys in total. Then, [you have to play it in both hands] essentially doubling the amount...

Let's not quibble about the math and simply admit there are a lot of keys on the piano and lots and lots of combinations to play in all the keys. Of course this will seem overwhelming!
But let's consider two things to make learning the keyboard more manageable.
Musical elements like chords and scales follow repeating patterns and have overlapping similarities. For example the D, A, and E major triads are all the same shape on the keyboard. Instead of three totally different things, they are one common shape. Similarly the C, G, and F major scales each have 7 tones, but instead of 21 separate tones for all three, the tones C, D, E, G, and A shared between the three keys, and the unique tones are F, F#, B and Bb. That's a total of 9 tones not 21. Learning the difference between the three keys can be though of as just learning how to handle the F's and B's. The real focus is on only those two letters.
Secondly, focus on learning a small set of keys and then learn how the patterns are transposed to different keys. The process is about re-applying patterns. Normally beginners start by playing short pieces in C, G, and F. That will provide the foundation for fundamental patterns. Probably the two next most important stages are learning minor keys and learning keys that start on black keys like Bb and Eb. Minor keys will introduce new harmonic ideas. Black keys introduces mostly a mechanical challenge about how to place your hands on the black keys.

...is it actually required that you "train" to the point where you become mentally aware that you're pressing "C D E...

Eventually your hands start moving automatically and you don't literally thing of each and every key pressed. You think of the key harmonic notes. Also, you tend to stop thinking about concrete letter names like F# and think for about _leading tone in G major.`

I've always wanted to compose my own music - Understand the logic behind it.

The logic behind it is music theory. That is where you study all the patterns. Instead of the concrete letters like chord C F Ab to C E G you think of the patterns cadential 6/4 chord and _borrowed subdominant in a major key`.

Learn the basic patterns in a few keys
Learn how to transpose the patterns into other keys
Learn about the mechanical fingering issues involving black keys

That's a managed approach instead of thinking you have a thousand different combinations to memorize.