apachesolr search form block that points to search page

Question: I have a custom search page configured in apachesolr_search module which displays only products as results (bundle:product_display). I want to create a simple block that contains an input field for a keyword and the submit button, and when the user submits the form it should direct to the specific search page.
I haven't found an easy way to do that. Other developers seem to modify the core block search form, but this does not help as I will have the same requirement in many pages over the same website (many apachesolr search blocks pointing to different apachesolr pages).
Answer: There is an issue queue asking for such feature:
https://drupal.org/node/326375
I also found a module (a sandbox) for Drupal7 to export for each search-page a search-block:
https://drupal.org/sandbox/incrn8/1315802


Update values using AJAX in field widget form

Question: Similar questions:
Ajax wrapper replacement on a field widget form
how to create an AJAX field widget
Problem:
Get FIELD_NAME and DELTA in AJAX callback function? (See below)
What is done:
Change value of a textfield  in a widget form (see here) upon value change (jQuery event .change()) of another textfield in widget form.
Code Sample:
in hook_widget_form:
// Changes of this field fire the AJAX event
$element['value'] = ...
$element['value']['#ajax'] = array(
                    'callback' => 'some_ajax_callback',
                    'wrapper' => 'location-div',
                    'method' => 'replace',
                    'effect' => 'fade'
            );
// This field is updated upon AJAX call
$element['location'] = ...
// Here is where the actual change occurs
if(!empty($form_state['values'][$field['field_name']]['und'][$delta]['value'])) {
            $element['location']['#value'] = ...;
        }

in some_ajax_callback:
function some_ajax_callback ($form, $form_state) {
  // Where do I get FIELD_NAME, and DELTA?
  return $field[FIELD_NAME]['und'][DELTA]['location'];
}

What happens?
As it is mentioned here #default_value is not populated using AJAX so according to this #value should be used instead.
The problem is how to get FIELD_NAME and DELTA in AJAX callback function? (See above)
UPDATE (NOT WORKING!)
I managed to figure out a workaround to make this work as following:

Item to be updated receives an ID composed of field_name and delta (e.g. location-div-myfield-0 (this is necessary if multiple instances of the same field are on the same page)
Save field name (here myfield) and delta (here 0) in $field_state (in hook_field_widget_form)
Read the saved values from $field_state in ajax callback (here some_ajax_callback) and return the desired form element.

This however works if there is only one instance of the field in the form, otherwise the values in $form_state are always those of last instance.

Possible solution
Using the triggering_element of $form_state in some_ajax_callback all necessary info can be derived:
function some_ajax_callback ($form, $form_state)
{
    // This contains info about triggering element
    // Index 0 = field name, 1 = language, 2 = delta, 3 = element name
    $element = $form_state['triggering_element']['#parents'];
    $delta = $element[2];
    $field_name = $element[0];
    ...
}

Answer: I generally do something like this:
function gft_enable_display_callback($form, $form_state) {
  // Get the array parents of the triggering element
  $parents = $form_state['triggering_element']['#array_parents'];
  // Pop off the triggering element as we usualy want the one above it
  array_pop($parents);
  // Get the element from the nested array
  $element = drupal_array_get_nested_value($form, $parents);

  return $element; // or we can return $element['someotherfield']
}

We can also use the drupal_array_get_nested_value to retrieve values from form_state['values'] as needed.
Answer: I had the same problem. I could solve this by just using

$element['#parents'][0] for the field name
$element['#delta'] for delta

This works with a multivalued field.
Answer: Since you can access the submit button form element in the AJAX callback, using $form_state['triggering_element'], you could add some identifier to the submit button. For example, in your hook_widget_form():
$element['value']['#ajax'] = array(
  'callback' => 'some_ajax_callback',
  'wrapper' => 'location-div',
  'method' => 'replace',
  'effect' => 'fade'
);
$element['value']['#name'] = 'submit_field_name_FIELD_NAME';

and then in your AJAX callback:
$submit_name = $form_state['triggering_element']['#name'];
$field_name = str_replace('submit_field_name_', '', $submit_name);

You could do something similar to get the field delta (i.e. use submit_field_name_FIELD_NAME_delta_DELTA, and use some regex or something to extract both). This links the field name and delta directly to the submit button, so even if you had multiple fields and deltas, it would be easy to figure out which one each particular submit button applies to.
Answer: Add another property to the form element that contains the delta it had when it was built. In your AJAX callback you can retrieve this delta via the triggering element value.
$element[$delta]['value']['#element_index'] = $delta;
$element[$delta]['value']['#ajax'] ...;

And in your AJAX callback
$delta = $form_state['triggering_element']['#element_index'];

This lets you explicitly set and get the delta without relying on pulling it from other data.
Answer: This should help for Drupal 8/9:
function some_ajax_callback ($form, $form_state) {
  $trigger = $form_state->getTriggeringElement();
  $parents = NestedArray::getValue($form, array_slice($trigger['#array_parents'], 0, -1));
  ...
}

Don't forget to include Drupal\Component\Utility\NestedArray


Heartbeat module comments collapsed by default

Question: I set my user's profiles with Heartbeat. At first moment they just look fine but when I open the web to the private beta I realized that when users started to comment nodes, the heartbeat logs of their profiles began to show too much information, they started to look overcrowded. So I have been asking to implement an option to the module core to show the log comments collapsed by default but none has replied.
There is another thread (Display a comment link instead of all the textareas.) on Drupal forums referring to something similar but I don't know how to use that information because I'm a rookie in Drupal hooking & custom modules writing.
Hint: maybe using this code (default option when clicking on Heartbeat comment count)
javascript:Drupal.heartbeat.comments.toggleComments(this, COMMENT_NUMBER); return false;

Answer: In this case you can use Collapsible Comment module. This module will help you to collapse the threads of the comments.
Now if you want to collapse entire comment region in collapsible form then you can do this using javascript.
Create a js file and add below javascript in a js file and add it to your theme or module.
(function($) {$(function() {
      var $comments = $('#comments');
      if (!$comments.size()) return;
      var count = $comments.find('.comment').size();
      // if (!count) return; // Do nothing when there is no comment.
      var label = Drupal.formatPlural(count, '1 comment', '@count comments');
      var $legend = $(document.createElement('legend')).html('' + label + '');
      var fsetclass = 'comments collapsible' + (location.href.search(/#(comment|new)/) == -1 ? ' collapsed' : '');
      var $fset = $(document.createElement('fieldset')).addClass(fsetclass);
      var $fsetwrap = $(document.createElement('div')).addClass('fieldset-wrapper');
      $fset.insertBefore($comments).append($legend).append($fsetwrap);
      $fsetwrap.append($comments);
      var attach = function() {Drupal.behaviors.collapse.attach($fset.parent(), Drupal.settings);};
      Drupal.behaviors.collapse ? attach() : $.getScript(Drupal.settings.basePath + 'misc/collapse.js', attach);
    });})(jQuery);

The above code will help you to collapse comments. Enjoy!!! :-)
Comment: Are you sure that module supports Heartbeat?
Comment: I am not sure about this but the code which is written in js will help you to collapse comments. I am using it
Comment: So you say this code will collapse all the comments of each logged activity? I will give it a try and let you know... thanks!
Comment: Sorry @mohit_rocks but that code only works for node comments.


Unable to add header in firefox os

Question: I am unable to add a header in my app for firefox os the code that i used is :
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Hindie</title>

    <link rel="stylesheet" type="text/css" href="/css/style.css">
    <link rel="stylesheet" type="text/css" href="css/base.css">
    <link rel="stylesheet" type="text/css" href="/css/headers.css">
    <link rel="stylesheet" type="text/css" href="/css/buttons.css">
    <link rel="stylesheet" type="text/css" href="/css/toolbars.css">

        <button>close</button>
        <menu type="toolbar"><button>done</button></menu>

Title

I ran the same in simulator but am only getting an small orange rectangle on top left corner of my app
Comment: It's hard to tell without the CSS as it's probably where the problem is. Can you publish it, so we can check where the problem is?
Comment: ok the main style sheet is [style.css](http://snipt.org/BwI7) and the main html [Index.html](http://snipt.org/BwI7)
Comment: The link for index.html isn't the good one (it's the CSS one, again).
Comment: Sorry for that this is the new one [Index.html](http://snipt.org/Bwic7)
Answer: please retire "/"
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/base.css">
<link rel="stylesheet" type="text/css" href="css/headers.css">
<link rel="stylesheet" type="text/css" href="css/buttons.css">
<link rel="stylesheet" type="text/css" href="css/toolbars.css">

Comment: Think that's not a problem
Answer: I didn't find any problem: you may not have put the right CSS file online as there is no orange in it. I added
header {
    background-color: #FFA500;
}

to your CSS file, and I'm seeing a large orange rectangle (with some margins) in the browser as in the Firefox OS simulator. If you don't want the margin, add
body {
    margin: 0px;
}

Unable to add header in firefox os


AQGridView: Making a Selection

Question: I am using AQGridView to build an iPad app that incorporates a flexible grid like that found in the Apple iBooks app or the Marvel and DC Comics apps. My question is has anyone used AQGridView and can help me with sheding some light on how to make a grid cell selection. It supposedly just makes a sub-class of UITableView but I can't seem to find the correct method for cell selection.
Any help would be greatly appreciated.
Thank you,
L.
Answer: Just make sure header file (whatever.h) implements: < AQGridViewDelegate >. Then in your implementation file (whatever.m), add the following:
<code>- (void) gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index {

    NSLog (@"Selected theArgument=%d\n", index);

}
</code>
Comment: Yeah... I eventually figured it out. Thank you!
Comment: For anyone else, to actually make a selection (not be notified of selection), which was the first part of the question, you can do this: [[self gridView] selectItemAtIndex:index animated:NO scrollPosition:AQGridViewScrollPositionNone];

AQGridView: Making a Selection


Como converter um projeto de VB6 (.vbp) para VB.NET (.vbproj)?

Question: Eu descompilei um aplicativo em VB, só que não era .NET, era VB6. Eu gostaria de saber como converter, pois já usei o VbTo Converter e ele crashou em um dos arquivos.
 Aguardo rapidamente respostas :/
Comment: A princípio só programando de novo.
Answer: Esse artigo mostra o que é possível fazer para migrar de VB6 para .NET:
Estudo de Caso: Migração de um grande aplicativo VB6 para .NET
O autor cita algumas ferramentas, portanto não vou repetir aqui.
Essa ferramenta da Microsoft gera um relatório do que deverá ser alterado na migração.
Mas dificilmente uma ferramenta vá migrar seu código sem nenhum erro, dependendo da quantidade de código é melhor fazer manualmente.


Partial Model Validation in MVC4

Question: I have a PartialView that is a form used to create or modify a user and implements the ViewModel DynamicActionUserModel.  The view that referrences this partialView shows a table of all MembershipUsers and gives the ability to create a new user Membership.CreateUser() or modify a user 'Membership.UpdateUser()`. The form in the partialView does an ajax post to my controller to submit data.
The issue I'm running into is that when a user is created their userName, email, password and role is serialized back to the controller as DynamicActionUserModel.RegisterModel and validated, but when a user is modified, password is not a property that is available (nor do I want to make it available to modify on the client side) so it isn't set in DynamicActionUserModel.RegisterModel and ModelState.IsValid is always false.
Perhaps the design of my model and view needs to change, or is there a way to validate the model but ignore password when a user is being modified? Not sure what the best practice is for this one.
I guess another option would be to create another ViewModel and another partialView specifically for modifying a user but that seems sloppy.
Model
public class DynamicActionUserModel {
    public string Action { get; set; }
    public RegisterModel RegisterModel { get; set; }
}

public class RegisterModel {
    [Required]
    [Display(Name = "User Name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    public string[] SelectedRoles { get; set; }
    public MultiSelectList Roles { get; set; }

}

Controller
[HttpGet]
public ActionResult CreateUser() {
    var model = new DynamicActionUserModel {
        Action = "CreateUser",
        RegisterModel = new RegisterModel {
            Roles = new MultiSelectList(System.Web.Security.Roles.GetAllRoles())
        }
    };

    return PartialView("_UserPartial", model);
}

[HttpGet]
public ActionResult ModifyUser() {
    var model = new DynamicActionUserModel {
        Action = "ModifyUser",
        RegisterModel = new RegisterModel {
            Roles = new MultiSelectList(System.Web.Security.Roles.GetAllRoles())
        }
    };

    return PartialView("_UserPartial", model);
}

[HttpPost]
public ActionResult ModifyUser(DynamicActionUserModel model) {
    bool isEqual = true;

    if(!ModelState.IsValid) { // this is always false because password is empty
        return PartialView("_UserPartial", model);
    }

    var user = Membership.GetUser(model.RegisterModel.UserName);
    // do stuff
    Membership.UpdateUser(user);

    return Json(new {success = false});
}

View
@using RobotDog.Models
@model IEnumerable<RobotDog.Models.UserModel>

    @Html.Action("ModifyUser")

    @Html.Action("CreateUser")

PartialView
@model RobotDog.Models.DynamicActionUserModel

@using(Html.BeginForm(Model.Action,"Admin", FormMethod.Post, new { @class = "ajax" })) {

    @Html.TextBoxFor(x => x.RegisterModel.Email, new { @class = inputSize, placeholder = "Email"})

    @if(Model.Action == "ModifyUser") {
        @Html.HiddenFor(x => x.RegisterModel.UserName)
        @Html.DisplayNameFor(x => x.RegisterModel.UserName)
    } else {
        @Html.TextBoxFor(x => x.RegisterModel.UserName, new { @class = inputSize, placeholder = "User Name" })
    }

    @if(Model.Action == "Createuser") {
        @Html.PasswordFor(x => x.RegisterModel.Password, new { @class = inputSize, placeholder = "Password"})
    }

    @Html.ListBoxFor(x => x.RegisterModel.SelectedRoles, Model.RegisterModel.Roles)

    <input type="submit" value="Submit" class="btn"/>
}

Answer: Try with ModelState.Remove("password") before calling ModelState.IsValid, but as suggested here if a property is not always required you should not mark it as required.
Answer: Have you looked at ModelState.IsValidField ?

Note: even as of MVC4 the documentation is backwards and should say :
Determines whether there are any ModelError objects that are associated with or prefixed with the specified key.

I've made a little extension method helper for this:
public static class ModelStateHelpers
    {
        public static bool IsValidFor<TModel, TProperty>(this TModel model,
                                                         System.Linq.Expressions.Expression<Func<TModel, TProperty>> expression,
                                                         ModelStateDictionary modelState)
        {
            string name = ExpressionHelper.GetExpressionText(expression);

            return modelState.IsValidField(name);
        }
    }

Usage is simple:
 bool billingValid = model.IsValidFor(x => x.CheckoutModel.BillingAddress, ModelState);

Partial Model Validation in MVC4


Setup an IIS self signed certificate on Oracle Application Server

Question: My main server is running IIS 7 and has an ASP.NET/C# website that needs communicate to another server that uses Oracle Application Server.
Currently, the website is communicating to the Oracle Applicatoin Server using HTTP. I would like to setup the SSL certificate so that I can access the Oracle Application Server via HTTPS from the website.
Do I just need to create the self signed certificate on IIS 7 then export it and set it up on the Oracle Application Server?
Comment: Do you also need external access to this application running on this application server. Or is it only for internal use?
Comment: Just need access between these two servers. They're at different data centers, and the oracle server can only be accessed via HTTP.
Comment: That's different than what you said before. You said before that it only can be accessed using HTTPS? Can you clarify that?
Comment: Sorry, I meant that I would like to setup the certificate so that I can access it using HTTPS. Currently, it's being accessed using HTTP by an ASP.NET website. I updated my question.
Answer: You have three options I think

Creating your own certificate server. That's quite a lot of work, but it maybe worth the work If you need to deploy more certificates in the future.
Generating a self signed certificate. See here for more information:Create a Self-Signed Server Certificate in IIS 7
Buying an certificate from a certificate provider.

In this scenario you can try first with a self signed certificate, It that doesn't work, or doesn't fulfill your need you can always go with option 1 or option 3.
What I personally don't know is what requirements Oracle has for a certificate of their application server. After some research I found out that you probably have to submit a request a to a certificate authority (CA), which excludes option 2 for you then. See here for you reference:
13 Overview of Secure Sockets Layer (SSL) in Oracle Application Server


Verificar se string possui apenas números

Question: Qual comando eu posso usar para saber se dentro de uma string só possui números..
Por exemplo, estou usando o prompt:
var quantidade=prompt('Quantidade de entrada de produtos(somente números)');

Gostaria de verificar se realmente na variável quantidade possui apenas números, afinal não podemos confiar nesses usuários não é rs.
Comment: [Questão relacionada](http://pt.stackoverflow.com/questions/4095/como-saber-se-uma-variavel-e-do-tipo-numero-em-javascript).
Comment: Por isso eu disse "relacionada" e não "duplicada". Ocorre que várias respostas daquela pergunta servem para esta, inclusive várias respostas desta são iguais as de lá.
Answer: Opção 1 (somente Javascript):
function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

isNumber('123'); // true
isNumber('asda123'); // false

Opção 2 (usando jQuery):
$.isNumeric('123'); // true
$.isNumeric('asdasd123'); // false

Como curiosidade, aqui vai a implementação do isNumeric no jQuery 1.11.0:
isNumeric: function( obj ) {
    // parseFloat NaNs numeric-cast false positives (null|true|false|"")
    // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
    // subtraction forces infinities to NaN
    return obj - parseFloat( obj ) >= 0;
}

Comment: Por que o downvote?
Answer: Utilize isNaN para saber se a string contém somente números, se for falso significa que é um número:
if(!isNaN(num)) alert("a variavel num é numérica");

isNaN(123)         // false, então é numerico
isNaN('123')       // false então só contém numeros
isNaN('teste')     // verdadeiro, não contém números
isNaN('999teste')  // vardadeiro, contém números e letras

Comment: Na verdade, o `inNaN` verifica se o valor é um número. No caso, se for colocado algo como **1.23** ou **3-2**, ele retornará *true*. O que não parece ser o caso, uma vez que ele quer uma quantidade.
Comment: @JúlioPradera a função não verifica se é numérico, se assim fosse, isNaN(123) retornaria true e não false. O que a função faz é verificar se existem qualquer carácter além de números, no caso isNaN(123) retorna "NaN", ou seja, não há caracteres além de números.
Comment: @Felipe Faça o teste. Coloque "1.23" dentro de um `inNaN` e você verá que ele retornará false. Pois "1.23" É um numero. Mas não contem apenas números.
Comment: @JúlioPradera não estou a dizer o contrário. O exemplo resolve o problema, uma vez que exige apenas números, segundo o autor.
Answer: Veja se isso lhe ajuda:
function isNumeric(str) {
  var er = /^[0-9]+$/;
  return (er.test(str));
}

Answer: Você pode testar o String com uma expressão regular:
/^\d+$/.test('0'); // Retorna true.

Sendo que '0' é o numero recebido no String.
Caso queira aceitar numeros quebrados ela pode ser assim:
/^\d+(?:\.\d+)?$/.test('0.1'); // Retorna true.

Você também pode criar uma função para reaproveitar assim:
var

    isNumeric = function(value) {

        return /^\d+(?:\.\d+)?$/.test(value);

    };

String.prototype.isNumeric = function() {

    return isNumeric(this);

};

Assim você pode usar ela dessas duas formas:
isNumeric('0'); // Retorna true.

E:
'0.1'.isNumeric(); // Retorna true.

Com jQuery já exiate uma função (jQuery.fn.isNumeric):
$.isNumeric('0');


Download bunch of files in Bg

Question: I need to download bunch of files (~600mb) from an ftp server.
The question is how would be best to implement that?
The simplest solution would be to pause\resume the download each time the app goes back to foreground.
The problem with that of course is that the users won't be able to initiate the download, lock the iPad, and come back when it's all done.
Does iOS allow downloading that amount of files totally in the background?
Answer: You are only allowed to run in background for downloading content if you are a newsstand app and downloading the issues of your magazine. See this document for reference. I assume your app is not a newsstand app.
However, you can also ask for extra time to finish your task when your app moves to the background. Checkout beginBackgroundTaskWithExpirationHandler: method of UIApplication to see how you can do that. It will give you about 10 minutes to finish your task. It probably won't be sufficient to download all of the files but it will allow your app to download some of them.
I guess you can also send a local push notification to the user when your background execution time is about to finish to let him open the app again and continue the download. However, I have not sent any local notifications before so I am not sure if it is possible to send them while executing a background task.

Download bunch of files in Bg


is there is any way to include files?

Question: I am writing PHP code in a rule, where I include another PHP file.
include_once 'google-api-php-client/src/Google/autoload.php';

Where do I need to include files?
Answer:
You can use module_load_include() to include a PHP file.
module_load_include('php', $type, 'includes/google-api-php-client/src/Google/autoload');

Where type can be either theme name or module name. I guess in this you are building some drupal module so it must be module type. In which case it will look for autoload.php file inside your name module directory. However internally it will do the require_once instead of include_once :)
You can use Libraries API module to include a php file. For this you will have to keep this google-api-php-client inside libraries folder. And you will perform these steps to implement it.
function hook_libraries_info() {
  $path = libraries_get_path('google-api-php-client');
  set_include_path($path."/src/" . PATH_SEPARATOR .  get_include_path());
  $libraries['google-api-php-client'] = array(
  'name' => 'Google OAuth2 Library',
  'vendor url' => 'http://code.google.com/p/google-api-php-client',
  'download url' => 'http://github.com/google/google-api-php-client/archive/master.zip',
  'version arguments' => array(
    'file' => 'src/Google/Client.php',
    'pattern' => '/LIBVER = "([0-9\.a-z]+)/',
    'lines' => 40,
  ),
  'versions' => array(
    '1.0.5-beta' => array(
      'files' => array(
        'php' => array(
          'src/Google/Client.php',
        )
      ),
    ),
    '1.1.5' => array(
      'files' => array(
        'php' => array(
          'src/Google/autoload.php',
        )
      )
    )
  ),
  'files' => array(
    'php' => array(
      'src/Google/Client.php',
    ),
   ),
  );
  return $libraries;
}

Note: The version is 1.0.5-beta, so you may need to change the version as per your API version.
Then to include this library in another module.
function hook_init() {
  $path = libraries_get_path('google-api-php-client');
  if ($path) {
    set_include_path($path."/src/" . PATH_SEPARATOR . get_include_path());
  }
}

Since it comes it composer.json/autoload.php you can use these modules to load it automatically from libraries folder.
X Autoload, Composer Autoload, Composer Vender Autoload, although you will still need to define the location inside your module.

Using the XAutoload module
   function mymodule_libraries_info() {
     return array(
       'google-api-php-client' => array(
         'name' => 'Google Client Library',
         'xautoload' => function($adapter) {
           /** @var \Drupal\xautoload\Adapter\LocalDirectoryAdapter $adapter */
           // Scan sites/all/libraries/google-api-php-client/composer.json to look for
           // autoload information.
           $adapter->composerJson('composer.json');
         }
       )
     );
   }

Comment: where i need to place google-api-php-client folder?
Comment: For 2 and 3. place it inside sites/all/libraries folder.
Comment: Can't be do in simple way?
Comment: Well the most simple way is to place it inside a module. Say **gapi** and place the google-api-php-client inside it somewhere say includes within gapi module. Now you can get the autoload.php function from any other module or php or inc or from gapi.module itself file by just saying `module_load_include('php', 'gapi', '/includes/google-api-php-client');` at the top of file or inside functions where you want to get those functions.
Comment: i  am not getting any error.under debug mode  i am able to see the condition php_eval evaluated to FALSE
Comment: What you are doing is cryptic for me and cannot be answered without having a glimpse at what you are doing. Well it end up being another question.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/40935/discussion-between-ankita-kashyap-and-sarathkm).
Answer: Try the standard PHP way:

require 'google-api-php-client/src/Google/autoload.php';
include_once  'includes/google-api-php-client/src/Google/autoload.php';
include ('includes/google-api-php-client/src/Google/autoload.php');

or Drupal way:
include_once DRUPAL_ROOT . '/includes/google-api-php-client/src/Google/autoload.php';

Comment: `module_load_include();` function - [Drupal API documentation][1] - to include any PHP files from within your or other modules where needed,

 [1]: https://api.drupal.org/api/drupal/includes%21module.inc/function/module_load_include/7
Comment: seems this is not working for me. even i didnt any kind of error
Comment: Also where i need to place google-api-php-client folder?
Comment: Wherever you want to @AnkitaKashyap; a custom module or in the libraries folder might make most sense, but it depends what you're doing
Comment: @Clive: i am new to drupal. i place external directory in sites/all/libraries folder ..  and in rules i am not getting any error
Comment: You shouldn't necessarily expect to see an error, `include` and `include_once` are designed to fail with a warning
Comment: `include_once` is a PHP way more then a Drupal way even you used `DRUPAL_ROOT`....

is there is any way to include files?


Type 'T' is not assignable to type 'T[]'.ts(2345) in data that would be resolved from Promise

Question: I have a problem with type of data in my function promiseRace written in typescript.
function isPromiseLike<T>(U: T | Promise<T>): U is Promise<T> {
  return (U as any).then
}

function promiseRace<T>(values: Array<T | Promise<T>>): Promise<Array<T>> {
  const isArrayEmpty: boolean = Array.isArray(values) && values.length === 0

  return new Promise((resolve, reject) => {
    if (isArrayEmpty) resolve([])

    const promises = values.map((v) => (isPromiseLike(v) ? v : Promise.resolve(v)))

    promises.forEach((promise) => {
      if (promise instanceof Promise) {
        promise.then((data) => resolve(data)).catch((error) => reject(error))
      }
    })
  })
}

In line
promise.then((data) => resolve(data)).catch((error) => reject(error))

second data is underlined and I have a problem: Argument of type 'T' is not assignable to parameter of type 'T[] | PromiseLike<T[]> | undefined'. Type 'T' is not assignable to type 'T[]'.ts(2345).
When I make
promise.then((data: any) => resolve(data)).catch((error) => reject(error))

everything looks fine, but it's not a good solution for me.
I wanted to do sth like this either
return new Promise<Promise<T>>((resolve, reject) => {

but i have all function underlined then :P
Please about any help!
Comment: If it's a promise race, it should resolve to type `T` not `T[]`
Answer: Assuming your code is trying to resolve the promise array when the first promise completes successfully you need to change your code to call the resolve method with an array of data. This is because your returned promise has a generic argument of an array of promises, taken from the return type of your PromiseRace function, so it's resolve method is expecting an array as its argument.
promise.then((data) => resolve([data])).catch((error) => reject(error))

Playground Link
If you take Dane's suggestion above, which seems like a good suggestion, and you change the return type to Promise<T> then you'll just have to change the empty return condition to not return an array
if (isArrayEmpty) resolve()

Answer: You actually dont need function isPromiseLike, your promiseRace function can take values: Array<T> and then you map over it by calling Promise.resolve. It ll behave exactly like you doing in your original post.
Checkout this post for detailed explaination:
https://stackoverflow.com/a/27746324/5644120


Can't create WVD Resource Pool

Question: I'm trying to get Windows Virtual Desktop set up, and when it's going through the steps of provisioning my resource pools i get this error:

{"code":"DeploymentFailed","message":"At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/DeployOperations for usage details.","details":[{"code":"VMExtensionProvisioningError","message":"VM has reported a failure when processing extension 'joindomain'. Error message: "Exception(s) occured while joining Domain 'swiftchipinc.com'"\r\n\r\nMore information on troubleshooting is available at https://aka.ms/vmextensionwindowstroubleshoot "},{"code":"VMExtensionProvisioningError","message":"VM has reported a failure when processing extension 'joindomain'. Error message: "Exception(s) occured while joining Domain 'swiftchipinc.com'"\r\n\r\nMore information on troubleshooting is available at https://aka.ms/vmextensionwindowstroubleshoot "}]}
Comment: Is your Active Directory domain **swiftchipinc.com**?
Answer:
VM has reported a failure when processing extension 'joindomain'.
Error message: "Exception(s) occured while joining Domain '***.com'"

Looks like the info you provided for domain joining are not correct.
You should review your domain joining info, including username, password and OU path (if used).
WVD hosts need to join your AD domain, and you need to provide proper info for doing that.
(Also, your VMs need to use the correct domain DNS and be able to contact a Domain Controller in order to join your AD domain.)
Comment: Totally agree with Massimo, in addition to this question, most likely your VNET has no custom DNS configured, usually a WVD environment has a custom DNS in VNET where it runs pointing to your AD private IP.
Comment: @Taguada I'm currently working on a WVD deployment for a customer who doesn't specify DNS servers in their VNet config, because they have multiple domains. This is a royal pain.
I'd totally want for Azure VNets to be able to specify DNS settings at the subnet level, not only for the whole VNet. There's a feature request for this, please vote it if you feel like so:  https://feedback.azure.com/forums/217313-networking/suggestions/9310917-allow-dns-servers-to-be-advertised-per-subnet-inst

Can't create WVD Resource Pool


Validating the CART model in R

Question: I have built the CART model, however I want to understand how we predict/validate the results with Validation data.
d=sort(sample(nrow(red_data),nrow(red_data)*.7))

#Selecting training sample
train_data=red_data[d,]
test_data=red_data[-d,]
nrow(train_data) #20133#
nrow(test_data)#8629#

rpart(formula = red_status ~ VALUE_CLASS + GAP_1 + cs_rr1_2,
    data = train_data, method = "class", control = rpart.control(minsplit = 6))

print(cfit)
summary(cfit)

prp(cfit,type=2, extra=106, nn=TRUE,fallen.leaves=TRUE)

This is what I have done.
Could some one help me on this
Comment: You should provide some data so that people can reproduce what you've done. Also, you could consider adding some other tags, as you've only got the R tag right now, and no statistical ones.
Answer: Since we don't have access to your data, I am guessing that pages 39- 40 of the manual will help you.  I'll use the iris data set since it's readily available (and in the documentation):
data(iris)
d <- sort(sample(nrow(iris),nrow(iris)*.7))
(iris.rpart <- rpart(Species ~ . , data = iris, subset = d, method = "class"))
# n= 105
#
# node), split, n, loss, yval, (yprob)
# * denotes terminal node
#
# 1) root 105 68 setosa (0.3523810 0.3333333 0.3142857)
# 2) Petal.Length< 2.45 37  0 setosa (1.0000000 0.0000000 0.0000000) *
#   3) Petal.Length>=2.45 68 33 versicolor (0.0000000 0.5147059 0.4852941)
# 6) Petal.Width< 1.75 40  5 versicolor (0.0000000 0.8750000 0.1250000) *
#   7) Petal.Width>=1.75 28  0 virginica (0.0000000 0.0000000 1.0000000) *

# this validation of your test data set (30% of records) shows that the
# model predicted 44 of 45 correct.  Not bad.
table(predict(iris.rpart, iris[-d,], type = "class"), iris[-d, "Species"])
# setosa versicolor virginica
# setosa         15          0         0
# versicolor      0         15         1
# virginica       0          0        14

?predict.rpart

This could be a comment but. . .
In all seriousness, probably the best help anyone can give you is "read the manual."  Also I could point you to the rattle package: this is a pretty simple point and click interface to the rpart package, along with several other modeling tools.
By the way: as noted on the 2nd page of the manual, CART is a trademarked name.  "Recursive Partitioning" is a generic name, so you should probably describe your model accordingly.
I hope this helps.

Validating the CART model in R


Trying to access JSON API from local .html in Chrome

Question: I have built an API and I m trying to access it from a test .html file in Chrome. I m accessing the file through file:///... and I get the local filesystem restrictions. I have enabled cross origin request access on my api but I get the following when I try to access it:

XMLHttpRequest cannot load http://. Method undefined
  is not allowed by Access-Control-Allow-Methods.

The request / response headers are as follows:

and the javascript code I m using is as follows:
var xmlhttp;
if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        if (params.success) params.success(xmlhttp.responseText);
    } else if (xmlhttp.readyState == 4) {
        if (params.error) params.error(xmlhttp, xmlhttp.status, xmlhttp.responseText);
    }
};

xmlhttp.open(params.method, params.url, true);
xmlhttp.setRequestHeader('Content-Type', 'application/json');
xmlhttp.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01');

if (params.data) xmlhttp.send(params.data);
else xmlhttp.send();

If I use $.getJSON from jquery the api call works fine but I dont want that. It needs to be pure javascript. Any ideas on what could be wrong?
Comment: jQuery is pure JavaScript. It doesn't ever fall back to Flash or include any CSS like YUI.
Comment: Ok - What I meant is without any external libraries. This is because I dont want to force people using the javascript library to consume my API to have to import jquery as well.
Answer: Sorry.. I never asked if you need it for testing aka debugging or to production
open your chrome with this security param:
C:\****\chrome.exe chromium-browser --disable-web-security
for chrome:
C:\****\chrome.exe google-chrome  --disable-web-security
I'm using chromium but it's should work with chrome too..
Comment: But i m facing the same problem with firefox. There must be some permanent solution I can apply to either the API or the javascript side of things.


Intervention Analysis - Pulse over several periods

Question: I have a couple weekly time series and an intervention occurred over several weeks and then for some, after a period of no intervention, began again. So, the pattern is off for a period of weeks, then on for a period of weeks, then off for a period of weeks and perhaps on again.
The image below tries to show the possible patterns:

When there is a single pulse, then as discussed here it is pretty simple to code the intervention as a pulse (1 or that period and zero elsewhere) and code the transfer function as one of several shapes - e.g. only effecting a single period (the pulse), a permanent level shift (a step) or perhaps with a lasting (but decaying) effect (a pulse but with decay transfer function).
In the situation described here though, is there the same flexibility or do we really only have the option to code the interventions as 10 separate interventions (for the top series) or 5 separate ones for the bottom series and only allow the intervention to effect the single period? I am not sure how to have any of the "pulses" have a decaying effect because where does one start and the other stop?
In my reading thus far for this type of analysis I have seen the pulse and step but nothing like this, where there is an "on" for a period of time, then "off" and then on again (maybe).
Comment: it is fairly simple temporary level shift. You can dummy code a single variable with 5 consecutive observation as 1 and the rest as 0.
Comment: yes you need two vectors. If you need decayed response, then you would need a transfer function $ \frac {\omega}{1-\delta B} P_t$
Comment: Yes you can have 1 portion of time.
Comment: @forecaster what do you think?
Comment: B_Miner, if you have an step intervention for some time and then a decaying effect, what you need is a compound intervention transfer function. you just sum up the step and decaying intervention transfer function, you should be good.
Comment: If you have an example of this in TSA, I would like to see it. Is it the following specification (using the top row of data I show above):   xtransf = data.frame(intvertion=c(rep(0,6),rep(1,5),rep(0,7),rep(1,5),rep(0,3))),
transfer = list(c(0,0), c(0,1)))
Comment: Oops I meant the following (just focusing on the first intervention from row 1 ):
xtransf = data.frame(intvertionA=c(rep(0,6),rep(1,5),rep(0,15)), intvertionB=c(rep(0,6),rep(1,5),rep(0,15))),
transfer = list(c(0,0), c(1,0)))
Comment: So, for the top series it would be two vectors coded each with 5 '1's in the appropriate positions?
Comment: This doesn't allow for delayed effects does it? Simply an effect just during the times the intervention is "on"?
Comment: That goes to my question though - for transfer functions shown in textbooks that are shown either as a step ("1" from the time T to the end of the series) or pulse, can you use a step transfer function operating only on a vector that is a "1" for a portion of the time?
Comment: I think I am hung up too much on using only a (full) step or only a pulse. Is it your understanding that you have more flexibility  than that then? I also may be thinking to literally about having the vector of 1s and 0s match exactly what occurred in the intervention, versus getting the matching effect. For example, if you have an intervention where something changed and that change is constant (a step with 1s from some point onward) but you need a decreasing decay function, than you can change it to a pulse, even though a continuous step is what actually occurred. Is this your understanding?
Comment: If one ran a statistical test, wouldn't it show something like a transient change has a higher statistical probability than a pulse at any of these locations? Are there statistical tests for a pattern of interventions, rather than just hypothesis testing one intervention at each location?
Answer: Lets say you have a time series data 42 observations. Observation 7 to 13 have step(level shift) intervention and observations 29 to 35 have step intervention of 5 units. The remainder observations are 0.  As an example, see below chart for simulated data with actual and actual + error.
If you would like to model this data as a intervention analysis using arima transfer function, you simply need to create a dummy coded variable with 1's for 7 to 13 and 1's for 29 to 35 and pass this is a step intervention in ARIMAX model. I don't know how to use R for transfer function modeling, so I used SAS. See below the actual and predicted data. The ARIMAX approximated the data very well. See below the SAS code that I used to create the data and as well as the ARIMAX.
If your second intervention has a first intervention has a decaying effect, all you need to do is create a second intervention variable at the end of first step function and code it appropriately.
Hopefully this helped.

data temp;
    input actual @@;
    error = rand("NORMAL");
    datalines;
0 0 0 0 0 0 5
5 5 5 5 5 5 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
5 5 5 5 5 5 5
0 0 0 0 0 0 0
;
run;

data temp;
    set temp;
      actual_error = actual+error; *add random error;

      if 7 <= _n_ <= 14 or 29 <= _n_ <= 35 then step = 1; * First Intervention step;
            else step = 0;

run;

ods graphics on;
proc arima data = temp plots = all;
    identify var=actual_error crosscorr = (step);
     estimate input = (step) method = ml outest = mm1; /*Estimate Model using Transfer Function*/
     forecast out = out1 lead = 0;
run;
ods graphics off;

EDIT: as b_miner would like to know how to model this with temporary level shift with a linear decay, I have modified the example. I have shown only the first level shift, the second level shift could be easily added. If you are looking for a decay other than a linear decay then it is fairly easy to do, just use a step+gradual permanent decay function using transfer function. Intervention modeling is more of an art than science. You assume a shape, test the hypothesis, if acceptable move on else change the shape. Intervention modeling is deterministic in nature. If you are interested in learning more about transfer function modeling/intervention detection, I would highly recommend Forecasting-Dynamic-Regression-Models-Pankratz. This text has all the different types of intervention models possible, in addition to transfer function modeling.
Hope this helps.
data temp;
    input actual @@;
    error = rand("NORMAL");
    datalines;
0 0 0 0 0 0 5
5 5 5 5 5 5 4.1
4 3.5 3 2.5 2 1.75 1.25
0.75 0.25 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
;
run;

data temp;
    set temp;
    retain ramp 0;
      actual_error = actual+error; *add random error;

      if 7 <= _n_ <= 13 then step = 1;
            else step = 0;

      if 14 <= _n_ <= 23  then do;
            step = (_n_ - 24)/(13-24);

      end;

run;

ods graphics on;
proc arima data = temp plots = all;
    identify var=actual_error crosscorr = (step);
     estimate input = (step) method = ml outest = mm1; /*Estimate Model using Transfer Function*/
     forecast out = out1 lead = 0;
run;
ods graphics off;

Comment: Lets say that there is a step intervention (mean level shifts upward) during the first set of 1s (#7 to #13) as you show, but that the effect then decays slowly back to the previous mean level. What would the other vector of 1's and 0's look like? Would it be a pulse at #13 or #14?
Comment: Done with an example.
Comment: I'm reading the relevant chapters of the book. Thanks for the reference!
Comment: @B_Miner Have you tried AUTOBOX as it is much more powerful than SAS or any other time series software to deal with this issue.
Comment: GREAT book, very helpful. There is another one by Yaffee (SAS and SPSS) that goes into good detail on intervention and transfer functions (crazy amount of errors though - luckily most are on the companion site). Also, I try to avoid SAS if possible since R seems like a more flexible option (wherever I am working) but in this case, the flexibility of proc arima is unmatched in any other open source product I can find.


Configuring IIS for cross-forest kerberos authentication

Question: In my environment I have two separate forests FA.COM and FB.COM and two child domains DA.FA.COM and DB.FB.com. There is no forest trust but two-way external trust between DA.FA.COM and DB.FB.com.
I have an IIS server (IIS8.5 on Windows 2012r2) in DB.FB.com and I followed the instructions here https://blogs.msdn.microsoft.com/chiranth/2014/04/17/setting-up-kerberos-authentication-for-a-website-in-iis/ to configure Kerberos SSO for a static website in the IIS server and got it working for clients accessing from DB.FB.COM.
However I need to extend the access to allow users from DA.FA.COM logging into their client machines (also in DA.FA.COM) to access the static website (in DB.FB.COM) via Kerberos. Currently users and clients from DA.FA.COM are able to SSO but via NTLM instead of kerberos. (Note: I verify whether the SSO is working via Kerberos or NTLM by using both Fiddler and Klist to check)
My question is, if I gotten kerberos sso to work within that domain DB.FB.COM, do I need any further configurations on the IIS server to support cross-forest kerberos or is it a matter of configurations between the domain controllers in DA.FA.COM and DB.FB.com to support cross-forest kerberos?
Comment: `I verify whether the SSO is working via Kerberos or NTLM by using both Fiddler`. Are you saying the *client* is sending an NTLM authorization header first? That isn't something you fix on IIS, unless it is falling back to NTLM.
Answer: This probably requires configuring the "Use forest search order" Group Policy under Computer Configuration > Adminitrive Templates > System > <Kerberos or KDC> on FA.COM with a value of FB.COM.
If I change the Kerberos one locally I am able to connect to a SQL Server instance in a different forest via Kerberos. Which I can easily test with SELECT CAST(CONNECTIONPROPERTY('auth_scheme') AS NVARCHAR(MAX)) AS auth_scheme.
https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/hh921473(v=ws.10) is where you can find more extensinve documentation.
Hopefully this is still useful to someone.


Why do we look at morphisms?

Question: I am reading some lecture notes and in one paragraph there is the following motivation: "The best way to study spaces with a structure is usually to look at the maps between them preserving structure (linear maps, continuous maps differentiable maps). An important special case is usually the functions to the ground field."
Why is it a good idea to study a space with structure by looking at  maps that preserve this structure? It seems to me as if one achieves not much by going from one "copy" of a structured space to another copy.
Comment: This is a deep question and I don't think it has a a simple answer. The very short version is that long experience shows this to be a very productive method of thinking.
Comment: You're taking *preserving structure* too literally: in an algebraic setting, for instance, the maps that preserve structure in the intended sense are homomorphisms, not just isomorphisms; in topology, they're continuous functions, not just homeomorphisms. Thus, you're not just going from an object to a copy.
Comment: There is probably no easy answer because the question is too broad. Tell us the kind of properties of spaces you want, and we can try to give examples and reasons for how these follow from properties of morphisms. Generally, it is fair to say that in a good enough category (a category with free objects, to be precise - and this is something many objects have), one can "encode" elements of an object as morphisms to this object, so morphisms can be seen as a generalization of elements, and it is well-known that it is often easier to work with generalizations than with their ...
Comment: ... particular cases. One can do a lot with morphisms (e. g., composing, occasionally inverting) that one can't do with elements. Even when morphisms don't encode elements (e. g., in the category of fields they don't), they still can encode a lot. And don't forget that whenever you have an "identity-type" theorem (a theorem claiming that two elements are equal), you can apply any morphism to it to get a new one. So morphisms duplicate theorems; in a certain sense, "applying a theorem to some value" is generalized by "applying a morphism to a theorem".
Comment: As for "the functions to the ground field", however (i. e., elements of the dual space), these are not particularly important nowadays. They can be used in vector spaces or free modules to "sample" a vector, but outside of the free-module context they are not enough for even that. To get real profit from considering morphisms, one has to consider *all* morphisms, not just ones to the ground field.
Comment: Another short answer (hence posted as a comment) is that in certain contexts you constantly have to deal with abstract spaces, and you know absolutely nothing about the elements. It can simplify a lot of arguments to only talk about maps, instead of having lots of symbols for arbitrary elements floating around, particularly as your argument can't really use anything about the elements anyway.
Comment: The answer really depends on what we put into "... spaces with a structure...". A standard example is to look at the dual of $L^p(0,1)$ for $0<p<1$ - it consists of the zero functional...
Answer: It is hard to answer this question because it is hard to say what mathematicians mean when they talk about structure. Various attempts to define structures and their ultimate failure are chronicled in the book Modern Algebra and the Rise of Mathematical Structures by Leo Corry.
Instead of trying to give an intrinsic definition of structure, we can look at what we understand by and what we do with structures in mathematics. Intuitively, structure is something deep that goes beyond mere surface properties of an object. Different mathematical objects are structurally the same, the differences are superficial.
An indirect way of delinating structure is to define what it means to change the superficial properties of an object without actually changing the structure. As a simple example, take the process of adding up "objects". You can add up three apples and two apples by getting a bowl containing three apples and a bowl containing two apples. You "add" them by pouring the content of one bowl into the other bowl. Now apples are very concrete objects, but there is structure behind the process. There are numbers. You see that by replacing each apple in each bowl by an orange. Apparently, you can "add" oranges the same way you can add apples. When you replace each apple by an orange, you keep their number the same. And this abstraction process is essetially what we do when we use numbers in the real world. The concept of (counting) numbers is basically that there is some deep structure that keeps the same when we replace objects. Changing apples to oranges to stones to sheep to... are all transformations that do not change the underlying struture.
An important step in geometry was the insight that one can define geometric structures by taking a class of transformations of a geometric object and declaring that structure is what is not changed by the transformations, it is what is invariant. This is essentially the gist of the Erlangen program in geometry, developed by Felix Klein and a huge step in the history of structural mathematics. This shows the use of replacing some object by an equivalent one. What we learn is that the process of replacing the objects doesn't change the structure and if we know all these admissible ways of replacing objects, we know the structure.
So far, we have considered only reversible changes or transformations. But there are good reasons to allow for one-way transformations. The reason that they are useful is essentially the reason maps are useful. If we consider a country to be a map of itself, at least as useful as an actual 1:1-map of the country, we can replace the country by a simpler map that is sufficient for, say, a taxi driver. We can use the same map to draw an even simpler map that is merely good for getting from the railwaystation to the grand hotel. None of these processes are reversible, we cannot use the simple map to draw the bigger map without getting the needed additional information- or structure- from somewhere. So we can see these one-way transformations as ways to preserve parts of structure.
Further Reading:
When is one thing equal to some other thing? by Barry Mazur gives a detailed motivation of the abstraction process underlying category theory and adds a lot of depth.
A Hundred Years of Numbers. An Historical Introduction to Measurement Theory 1887-1990 by José Diez (part 2 here) shows how the structural ideas matter when we want to formalize what it means to measure something in science.
Comment: +1 for the link to Barry Mazur's paper, which I'm about to happily devour. Would +1 again if I could, for the excellent answer.
Comment: "*A category is a B.Y.O.S.T. party, i.e., you bring your own set theory to it.*" Love it.
Comment: +1. Brilliant answer, thank you for these insights. If only I could upvote this more than once.
Comment: Thank you for this very helpful answer.
Comment: Very good answer.
Comment: I absolutely love this answer. Thanks so much! Also, I love the imagery of pouring a bowl of sheep into another bowl in the same way as pouring apples. :) That they are, inherently, equivalent is astounding.
Comment: Excellent answer!
Answer: There is no short and simple answer, as has already been mentioned in the comments. It is a general change of perspective that has happened during the 20th century. I think if you had asked a mathematician around 1900 what math is all about, he/she would have said: "There are equations that we have to solve" (linear or polynomial equations, differential and integral equations etc.).
Then around 1950 you would have met more and more people saying "there are spaces with a certain structure and maps betweeen them". And today more and more people would add "...which together are called categories".
It's essentially a shift towards a higher abstraction, towards studying Banach spaces instead of bunches of concrete spaces that happen to have an isomorphic Banach space structure, or studying an abstract group instead of a bunch of isomorphic representations etc.
I'm certain all of this will become clearer after a few years of study.
Answer: I'm going to give some reason I don't think I can find the whole sets of reasons.
From here I'm going to refer to maps that preserve structure as morphisms.

Studying morphisms from one strucure always carry out some information about the structure itself, for instance looking at the group of automorphisms of two structures can helps us in saying if two structures are not isomorphic, isomorphic structures must have the some automorphisms group. In some cases, almost all, morphisms contain all the information about the structure: for instance the space $\mathbf{Top}(\bullet,X)$, of continuous function from the point space to the space $X$, is homemorphic to the space $X$, similarly the group $\mathbf{Grp}(\mathbb Z,G)$ of the homomorphisms from the group $\mathbb Z$ to the group $G$ with the componentwise product, is isomorphic to the group G and so on.
Other more interesting examples coming from to topology are loop spaces, foundamental groups, homology and cohomology groups (for instance singular homology which deals essentially with continuous maps from simplices in the space we want to study), but we can go on.
Often to study a given structure it is useful having various presentation, i.e. various example structures isomorphic to the starting structure in which we can made some calculations, that's so important because in such structures it's easier prove some facts about the structure itself. This is what we do when dealing with linear representation of groups or algebras, or group actions, or topological actions, or representations of vector spaces in $\mathbb K^\alpha$ for some ordinal $\alpha$, through a choice of a basis in the vector space (here $\mathbb K$ is the field subsumed).
Many properties relating structures can be expressed in a really useful way via universal properties i.e. the categorical language, which is the language of morphisms. This is really usefull for lot of reason, first of all it allows to see deeper unity in construction build up in different families of structures (i.e. different categories), helps to see how translate result from one environment (category) to another one, allows to generalize some result known in a particular class of structures to other similar, suggests the right definition for new concept in new environment (personally I don't know how to define the product between quasi-projective algebraic varieties without the morphism(category)-theoretic language).

Right now I'm not seeing other reasons, but I reserve to myself the right to add some stuff later.
Answer: Studying the structure of an object is producing theorems about this object that gives you information about this object.
If you want to understand the structure of an object by studying how it maps to another objects, then you $\textbf{have}$ to retain your attention to the maps that preserve the structure ! You can't expect to obtain information about the structure if you are looking at maps that don't have anything to do with it. In this case, preserving the structure is the least you can ask to a map you are looking at.
The two important questions, are, I think : why do we study structures ? what can we expect from the study of the maps preserving these structures ?
Why do we study structures ?
The mathematicians work, I think, is to detect some structure $\textbf{hidden}$ in an object, then study the structure, and hope it will help to understand the object better.
Two examples : the observation that the set of the permutations of a set $X$ possesses a natural operation, the composition of maps, and that this operation has a certain number of well-known properties led the mathematicians to study the objects called groups. This observation has been one of the most important in the history of math. The second example is the field $\mathbb{C}$ constructed by adding some special element $i$ to $\mathbb{R}$. It is just an algebraic object, until you discover that its topology has very interesting topological properties, which turn out to be very useful when you want to prove that it is algebraically closed.
Why can we expect from the study of the maps preserving these structures ?
If you want to study the structure of an object that maps to another object about which you know a lot, then you can expect to $\textbf{transport}$ the information that you know, using these maps ! It happens all the time : if you have a one-to-one linear map between two vector spaces, you can deduce that the dimension of the first is smaller that the seconds. If you have a continuous surjective map from a connected space to a topological space, you can deduce that it is connected.

Why do we look at morphisms?


Safety comparison, downhill mountain bike vs. downhill ski

Question: My twelve-year-old recently tried downhill mountain biking when we were in Lake Placid.  He found it thrilling and would like to continue with this new sport now that we are back home.  I am hesitant for him to practice this sport on a regular basis because of safety concerns.  We allow
- basketball (with mouth guard)
- soccer (with shin guards -- by the way, should he use the mouth guard as well when he is playing goalie?)
- swimming
- tennis
- cross country skiing
- ice skating for fun
We do not allow games with a stick -- ice hockey, lacrosse.  And we do not allow American football or downhill skiing.
I'd like to be reasonably consistent with our existing policy!
Where does downhill mountain bike riding (on an established track at a reputable ski center) fit, on the scale of things?  He has asked for a full-face helmet and elbow and knee pads, because that's what he was given to use as part of the fee at Lake Placid.

Clarification: I'd like to avoid fractures, of course, but I'd mainly like to avoid really serious injuries and things that might leave him with longlasting health problems such as a knee or back that is never the same again.
I'm not worried about scratches or bruises.
Comment: In 17 years of playing and watching football on a nearly daily basis, I have not once seen a football goalkeeper use a mouth guard. Though I have seen pretty hard shots that hit their heads a few times now (I was responsible for one of them), this did not result in any serious injury to their teeth. I think that is mostly due to a football's ability to deform and spread the impact over a larger part of the body. Besides that I think that his fellow twelve-year-olds are not able to kick the ball hard enough to inflict serious damage with it.
Comment: @Braamstruik Thank you, the question in the parenthesis is taken care of ....  Any thoughts about the downhill mountain biking?
Comment: You might check [bicycle.se] and see if this would be on topic there - they have a larger community and so might get better answers.
Comment: @Joe Thank you, will do.  I didn't know about that site -- sounds perfect.
Comment: Here is a link to the corresponding question on Bicycles Stack Exchange: [Safety comparison, downhill mountain bike vs. downhill ski](https://bicycles.stackexchange.com/q/32362).
Answer: Downhill mountain biking is definitely a dangerous genre because of the speed, the obstacles and the elements you should pass through. On the second hand, it is the most exciting, fun and self improving sport. I have tried various extreme sports (Snowboarding, wakeboarding, surfing, kite surfing, skiing and some more..) and this one satisfied me the most.
Things to do before starting DH on a regular basis:

Buy all the protection accessories that you need: Full-Face Helmet, Goggles (are much better then glasses), Gloves, Knee Guards (you can buy it with shin guard), Cycling shoes (for better handling, very important!), Neck brace (recommended for higher speeds and jumps) and for the beginning I would recommend a kind of Pressure suit for the whole upper body.
Kids learn very fast but still it's important to go step by step and not diving into extreme trails before you know the basics. Start riding some Cross-country / All-mountain trails and after gaining some experience try to go and ride a downhill track.
I think that taking a few private lessons with a MTB guide will give your kid the basic skills and put him on the right way.
If you think that it can be too early for your son (and it can be), you can look for some group courses for children that ride together with a guide on a regular basis. If you have DH tracks in your area than you should have groups and guides also. And I didn't mention it because its obvious - never let him ride alone.

Kids get injured much less than adults do but still it is important to explain them that they shouldn't take unnecessary risks. They should progress at their own pace and be careful when comparing themselves with their friends.
In conclusion, this is the ultimate sport! You meet great people, learn how to overcome obstacles, you get fit, and all this is in the nature! And there are many more advantages. I would recommend you also read some articles about mountain biking, it's great and very interesting!
And how could I forget?! Buy a DH bike!!! :)
I hope that was helpful, sorry for my bad English (I am Israeli and I'm practicing it :)) and feel free to contact me privately for more questions :)
ILAN.
Comment: Thank you.  Extreme sports are definitely out.  When my son is paying his own medical and dental insurance and expenses, he can choose for himself.  Your post cemented the decision -- very helpful.
Answer: My downhill cycling is limited to short runs that were incidental to the mountain biking trails I was riding, but I have 37 years of downhill skiing experience with only one injury, albeit a serious one, in which I shattered the proximal end of a tibia. It is on that experience and road cycling training that I base my advice.
Practice in an escalating scale of risk is the way to train and part of an athlete's training is learning to assess risk. Every twelve-year-old is different, but at some point in your young athlete's development, if he or she is to be an athlete, the assessment and management of the risk must fall to him or her.
My own 8 and 11 year-old children engage in tennis, swimming, ice skating, sailing, soccer, and basketball. They've not been much interested in alpine skiing since my introduction of it starting 8 years ago. American football is off the list for them, and I have reservations about field hockey which have not yet come to a point of requiring a ruling. Just to say I understand your sports reservations.
Answer: No, I'm a Dutchman, we don't have hills ;)
On a more serious note: I only ride a race bike, so this answer is based on my general knowledge of cycling (and cyclocross). I think this really has to do with the difficulty level of the courses he wants to ride. If he is going to ride downhill on a regular basis, he should get the proper training (from a trainer at a club) in which he should learn to get good control over his bike and maybe even a training on how to crash with limited damage. This obviously involves starting on easier tracks and subsequently learning to ride more difficult ones.
Of course, when he will be doing this regularly, he will crash. That is part of the learning process. Most often, he will get some minor injuries such as scratches and bruises. Incidentally, this might even lead to a broken arm or collarbone or so, but I cannot properly estimate that risk. In the end, the crashes will be a lesson and toughen him up.
When he will be riding an established track that has the required safety precautions and he will get the proper training from an experienced rider, the injuries should in general be limited. However, when not accompanied with the proper training and instructions, unrestrained enthusiasm and elation might cause him to pay a high tuition fee in the form of an unnecessary hard crash. This might lead to him getting fear of downhill and losing his interest in the sport.
One final remark, you might want him to start with cyclocross first. I know this sport is not that popular in the US, but it will teach him great steering skills and would provide an excellent basis before starting to ride downhill. Injuries tend to be less severe, since one is generally riding slower and there are less height differences. Furthermore, he might love passing the obstacles and riding through the mud.
Comment: Does cyclocross require special equipment and a special track?
Comment: Yes, for more basic information on cyclocross, check Wikipedia.


Infinite loop LeetCode 153 Find Minimum in Rotated Sorted Array

Question: I solved the leetcode problem and had added a line if start == end return arr[start] as an optimization. I am unable to come with a dataset where if I remove the line, why will the code go into an infinite loop. I have seen the leetcode submission fail if I remove the line. Here is my code. What data set can cause it to to into infinite recursion if I remove the first line inside the function?
    public int findPivot(int[]arr, int start, int end) {
        if(start==end) return arr[start];
        if (arr[start]<arr[end]) return arr[start];
        if(end-start == 1) {
            return Math.min(arr[start],arr[end]);
        }

        int m = (start+end)/2;
        if( (m>0 && arr[start]<=arr[m-1]) && (arr[m]<=arr[arr.length-1]) ) {
            return arr[m];
        }
        if(m>0 && arr[start]<=arr[m-1]) {
            return findPivot(arr,m,end);
        } else {
            return findPivot(arr,start,m);
        }
    }
}

Comment: What if you get an array with one element and `start = end = 0`?
Comment: I had thought of it but did not even bother to dry run in my head. Feel really stupid, the condition speaks for itself. Thanks. That will cause an infinite loop. Although, I was also thinking can recursion eventually lead to one element array based on some data set that can cause it even if array was more than one element
Answer: When resolving binary search questions, always test with two edge cases to avoid infinite loop, start = end and start + 1 = end.
Comment: I already have a similar check but my Q is around the different check that is in the first line of the function. I already have what you state
`
        if(end-start == 1) {
            return Math.min(arr[start],arr[end]);
        }
`


stop static to fixed scrollbar behavior on mobile in bootstrap

Question: I am making a bootstrap static to fixed navbar. When you scroll down 150px it changes from static to fixed. The issue is I don't want it to do this on mobile devices. I want it to stay fixed to the top on mobile at all times.
Basically I want the script to only run when you scroll down 150px OR when the viewport is 768px max.
I did find a possible solution here, which duplicates the navbar and shows the appropriate one but it was a bit cumbersome and I would like to try achieve this conditionally with just java.
Have a fiddle
Here is the code in question-
header {
    height: 150px;
    font-size: 100px;
}

.extrapadding {
  padding-top: 50px;
}

#more {
    height: 1000px;
}

@media only screen and (max-width: 768px) {

    header {
        display: none;
    }

    }

and
$(window).scroll(function() {
    var nav = $('#navbro');
    var body = $('body');
    var top = 150;
    if ($(window).scrollTop() >= top) {

        nav.addClass('navbar-fixed-top');
        body.addClass('extrapadding');

    } else {
        nav.removeClass('navbar-fixed-top');
        body.removeClass('extrapadding');
    }
});

Thanks for your help
Answer: I think the best way you can achieve that is:
1) Make a new class navbar-fixed-top-desktop with media queries (min-width: 768px).
2) In JavaScript add this class (not navbar-fixed-top which applies to all screen sizes).
Fiddle
Answer: This may help or give you some ideas: you can use Bootstrap Affix to handle the scroll position of you navbar and use jQuerys .width() to watch for the viewport to change so you can add the fixed navbar class.
See working example in Full Page Snippet.

$(document).ready(function() {

  $('#navbro').affix({
    offset: {
      top: $('header').height()
    }
  });

  function checkWidth(init) {

    if ($(window).width() < 768) {
      $('.navbar').addClass('navbar-fixed-top');
    } else {
      if (!init) {
        $('.navbar').removeClass('navbar-fixed-top');
      }
    }
  }

  checkWidth(true);

  $(window).resize(function() {
    checkWidth(false);
  });
});
body header {
  height: 150px;
  font-size: 100px;
}
div#navbro.affix {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 10;
}
@media (max-width: 768px) {
  body {
    padding-top: 60px;
  }
  body header {
    display: none;
  }
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

  Chad Radwell

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> Toggle navigation

          </button> Project name

Home

About

Contact

 Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Default

Static top

Fixed top (current)

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up
    one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum
    et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section
    1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia,
    looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de
    Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from
    a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College
    in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33
    of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes
    from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney
    College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32
    and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit
    amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor
    at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from
    sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem
    ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a
    Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem
    Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem
    Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard
    McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable
    source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first
    line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years
    old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the
    undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance.
    The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over
    2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered
    the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance.
    The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over
    2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered
    the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance.
    The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over
    2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered
    the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance.
    The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

Comment: Thanks, I like what you've done, especially because it works! I was playing around with affix at first but had some offset issues with it chopping off the top of the content. I also noticed it's being dropped in bootstrap 4 (which isn't very relevant in this case). Thanks again i'll see where this question leads


Jquery $.POST url not recieving values in response

Question: I have task to submit 2 values to a php file using ajax for which I have done the below code in jquery $.POST
$.post(
    "http://localhost/gcm_server_files/sample.php",
     {regId: id,message:msg},
     function(data){
      alert(data);
    });

and the code in sample.php is:
echo $_POST['regId'].' AND '.$_POST['message'];

I can see the POST values in console, but cannot see the response..
The values I am posting are:
regID:APA91bGmks8s9ytasjkhdjkhsdjkahsdkjhakjlYkpWpPmjB_nUhbTmVtAho7M6o-W4rsVJorB-ozX9v50YkBMg
message: Testing

Can someone show me whats wrong with code?
Comment: Can you open sample.php in your browser? Try echoing something at the top of the page, just to test it.
Comment: @OMTheEternity What is the address of the page making this request? Is it also at `http://localhost/`?
Comment: any error in console?
Comment: I am looking into the Fire bug where I can see the the URL in red color but with status 200OK
Comment: And what's the response?
Comment: I had 0 errors in replication testing.
Comment: Nothing in response blank in HTML
Comment: @Shomz Yes I did that and I can get the echo'ed value..
Answer: I think the problem is with the url;
    You are using the absolute path ( http://localhost/gcm_server_files/sample.php) in URL.
     Try to use the relative path of file in the URL (/sample.php) .
See this for more detail on the same origin policy that applies to Ajax request.
http://en.wikipedia.org/wiki/Same_origin_policy
  Try this

    $.post(
    "relative_path_to/sample.php",
     {regId: id,message:msg},
     function(data){
      alert(data);
    });

Comment: sorry to say but would not affect the things.. if domain is same it should work.. its not the crossed domain example..
Comment: i can bet absolute url will work.. if you both pages are on same domain.
Comment: @DeepakSharma But the elative path concept worked for me, yes both files are on same server and on same root path.


Proving the universal property for the localization functor $L_E$

Question: I am trying to prove the following statement:
If the functor $L_E$ exists,
$(iii)$ for any map $g: X \to Y$ where $Y$ is $E_*$-local, there is a unique map $\tilde{g}: L_E X \to Y$ such that $\tilde{g} \eta_X = g.$
Here is what is given to me in the paper "Localization with Respect to Certain Periodic Homology Theories."

(Note there were a typo in $(iii)$ but I corrected it in my statement)
Still, I do not know how to prove this statement, could anyone help me please?
Answer: Let $F$ be the fiber of the map $\eta_X: X \to L_E X$, so that we have an exact sequence $$\cdots \rightarrow [\Sigma F, Y] \rightarrow [L_E X, Y] \xrightarrow{(\eta_X)^*} [X, Y] \rightarrow [F, Y] \rightarrow \cdots.$$ We want to show that the map $(\eta_X)^*$ is a bijection.  For this it suffices to show that $[F, Y] = [\Sigma F, Y] = 0$.
Since $\eta_X$ is an $E$-equivalence, $F$ and thus also $\Sigma F$ are $E_*$-acyclic using the long exact sequence in $E_*$-homology.  Then, since $Y$ is $E_*$-local, $[F, Y] = [\Sigma F, Y] = 0$ as desired.
We conclude that $(\eta_X)^*: [L_E X, Y] \to [X, Y]$ is a bijection; i.e., given any $g \in [X,Y]$, there exists a unique $\tilde{g} \in [L_E X, Y]$ such that $\tilde{g} \circ \eta_X = g$.
Comment: We want an exact sequence in which the map $[L_E X, Y] \to [X, Y]$ appears, and this happens to be the map induced by $\eta_X$ in $Y$-cohomology.
Comment: Why we are using an exact sequence in cohomology and not homology?
Comment: Where are we using an exact sequence in cohomology?
Comment: I mean you reversed the arrows in your exact sequence and our map is now upper indexed and not lower indexed ..... I just guessed this ..... I could be wrong though


Coming to conclusion of the big O notation for binary search

Question: While mathematically finding the complexity of the binary search algorithm, We actually assume that there are 2K elements in the list. During the process we come to this particular part and the statement in my book:
"Hence, at most 2K + 2 = 2logn + 2 comparisons are required to perform a binary search when the list being searched has 2K elements. (If n is not a power of 2, the original list is expanded to a list with 2K+1 terms, where k = ⌊logn⌋, and the search requires at most 2 $\lceil logn\rceil $ + 2 comparisons.) Consequently, a binary search requires at most ϴ(logn) comparisons. "
There is one thing I do not understand in this:
1)How is this algorithm a ϴ(logn)? From what I understand a big ϴ is only when it is both big O and big Ω, but where are the functions, f(x) and g(x) such that f(x) is both O(g(x))  as well as Ω(g(x))?
Answer: To get a $\Theta$ result for the worst case complexity, you basically want to furnish the worst case (which gives an $\Omega$ result, i.e. a lower bound on the worst case runtime) and prove it is the worst case (which gives an $O$ result, i.e. an upper bound on the worst case runtime). It may be easier to proceed in the other order: determine from the structure of the algorithm what the worst possible case could ever be, and then construct an input that leads to this behavior.
For binary search on $2^K$ elements, the worst case situation would be $K$ halvings of the array, because at that point there is only one element left (so you merely check whether it is the element you want and then you're done). That gives an $O$ result. To get an $\Omega$ result you can furnish an array of size $2^K$ and an element to search for so that binary search actually takes $K$ halvings, or perhaps just a little bit less. Hint: put the desired element in the second position and nowhere else.
Comment: @BeshalJaenal You are trying to bound the worst case runtime both above and below. The upper bound is the $O$, the lower bound is the $\Omega$. You can get a lower bound on the worst case by just producing an example, whereas an upper bound on the worst case requires a proof using the structure of the algorithm. So here, the upper bound is saying "it can't take more than $K$ halvings" while the lower bound is producing an array and search item that actually require $K$ halvings.
Comment: @BeshalJaenal It does have an upper bound. For a lower bound, you need to produce an example where the runtime is at least some amount, because the worst case is at least as bad as any example you produce. The upper bound is where the analysis really takes place.
Comment: @BeshalJaenal No, when I said "you are trying to ..." I was not saying "where your mistake is is in trying to ..." I was saying the actual correct goal of the analysis.
Comment: In the passage you quoted the author did not do this part of the analysis, but it is not hard to do. See my hint.
Comment: Don't bother to exactly compute the worst case time. It is not useful. Just note that at worst you need K halvings and that there is a case that uses K halvings. Then (since it is perhaps not obvious that a halving can be done in constant time), count comparisons in the case of K halvings. Then do whatever you need to adapt this to a length that isn't a power of 2.
Comment: Knowing how to determine the $\Theta$ asymptotic for the runtime? Yes, that's useful. Knowing how to compute the *exact* worst case runtime is hopeless in the case of most algorithms, and it's usually not useful anyway because the leading order term usually already dominates by the time you get to a case large enough to give it to a computer.
Comment: (Cont.) This approach also avoids sensitivity to implementation details; for instance I disagree that binary search's leading order term is $2\log(n)$ comparisons. I'd say it's $\log(n)$ comparisons, because in my implementation I would remember the result of a comparison that I already did. Thus if I have 16 elements, and I know that the search item is smaller than the 8th element and bigger than the first, I don't recompare the search item with the first element. I just go straight to the 4th element.
Comment: @BeshalJaenal To come to *exact* formulas for numbers of steps, that's right.
Comment: @BeshalJaenal Yes. You can also use benchmarking to check these kinds of theoretical results. For example, try running binary search on inputs of size $n=1000,2000,\dots,10000$, putting the target in the second position every time. Time the results and plot the time against the size. You should see a perfect logarithmic shape. (These examples need to be a little bit large because smaller examples will be done so fast that your timing will not be accurate.)
Comment: @BeshalJaenal In general both. I'm not in software engineering but I doubt that people use theoretical analysis to estimate the performance of an *entire program*. Instead they would use it to estimate the performance of some of the individual functions. Extending this to the whole program is difficult because you'd need to know how often the individual functions get called.
Comment: I don't really get it, how is Ω the worst case? If it is the lower bound, isn't it basically saying, "for a certain x > k, for the number of elements n, the minimum number of search is given by g(n)". (At least , i've understood it like this, {I just study from books, please note me where I'm wrong.")
Comment: I'm not getting it technically. Are you saying the worst case analysis doesn't have to have an upper bound? Because, you mention " You are trying to ........", I thought, am I doing wrong trying to bind it?
Comment: you must be meaning things in general. But, in this case, for the binary search algorithm, Why is the algorithm deduced to be  ϴ(logn)? I understand how procedurally the author step by step analyzes the algorithm, but there's nothing about the lower bound, and for that we do not even know that the lower bound is some constant multiple of logn.
Comment: would it be correct to say that, the upper bound is: 2 $\lceil logn\rceil $ + 2, and the lower bound function is: 2⌊logn⌋+2 and also, the function for our algorithm is actually: 2logn+2, which is obviously less than the first and more than the second function, and hence we could deduce that it is Theta logn.   Would it be correct?
Comment: would knowing how to calculate this help when we would develop our own algorithms? (Someday):-)
Comment: what I did above, was it correct?
Comment: What you wrote three comments back was basically correct, assuming that each halving requires $2$ comparisons. But again such fine details are not required. You should simply say that at most $\lceil \log(n) \rceil$ halvings are required and that a halving takes $\Theta(1)$ comparisons to calculate.
Comment: by hopeless, in the first of your latest 3 comments, do you mean , it's too hard to come to these results for most algorithms?
Comment: thanks a lot, that's most of what I wanted to understand. Thanks! :-)
Comment: one additional thought, if you'd like to answer. Are these used for benchmarking?
Comment: in a more commercial kind of software analysis part, are things done statistically as you've given above(plotting) or from theoritical conceptual proofs? Or both perhaps?


Probability of getting certain numbers at least once in four dice rolls

Question: Let us suppose we have normal dice and we   rolled it 4 times,there is two question which we  are asked

probability that at least one of number is less then $4$

we answered it  light this : probability that neither of them is  less then $4$ is $1/81$
so answer to this question will be   $1-1/81=80/81$
2.at least one of them is $6$,
this  should equal  probability that  one of them is $6$ +probability that two of them is equal $6$ +probability that three of them is $6$+probability that all of them is $6$  are we  right?
thanks in advance
Comment: In 2 you could proceed with 1-P(none are 6). This is similar to what you did in one.
Comment: Your English needs some improvement.
Answer: For (1), probability that none is less than $4$ is $\left(\frac12\right)^4=\frac{1}{16}$.  So probability at least one is less than $4$ is $\frac{15}{16}$.
(2) Is easier as $1-P(\mbox{no sixes)})=1-\left(\frac56\right)^4$
Comment: sorry i wrote  incorrectly
Comment: for first one i mixed  this situation with one  situation which i have not  posted and that why, definitely  you are right


MVC: Dynamically populate html select

Question: I have a field that is generated for each row in the view as follows:
@Html.DropDownListFor(m => m.MenuParentKey, ViewBag.MenuKeys as SelectList)

But I want the drop-down to be populated for each row individually, by calling an action in the controller, here is what I mean:
public ActionResult GetMenuKeys(string currentMenuKey)
{
  var dictionary = MenuKeys.Where(mk => mk.Key != currentMenuKey);

  return View(new SelectList(dictionary,
      "Key",
      "Value",
      Page.DefaultParentKey));
}

currentMenuKey should be provided according to current row, I want the value of the current row to be excluded from the drop-down (notice it's the parent-key property).
Answer: You could create a Helper that would return a SelectList instead.
That would allow you the call it directly from your view, you would also be able to pass the parameter as required.
I think that would be easier than calling an action on your controler.
From what I see here, the controler action does not fetch any other resources than the list.
You could go with something like this :
public static SelectList FilteredList( this HtmlHelper helper, MenuKeys keys, string CurrentMenuKey)
{
var dictionary = MenuKeys.Where(mk => mk.Key != currentMenuKey);

  return new SelectList(dictionary,
      "Key",
      "Value",
      Page.DefaultParentKey);
}

Then you could call it this way :
@Html.DropDownListFor(m => m.MenuParentKey, Html.FilteredList(ViewBag.MenuKeys as SelectList, m.currentKey))

MVC: Dynamically populate html select


Manipular objecto json

Question: Tenho o seguinte json:
{
   "home":[
      {
         "id":"1",
         "menu":"1",
         "title":"Titulo 1",
         "image":"image01.jpg",
         "url":"http:\/\/www.exemplo.pt\/images\/image01.jpg"
      },
      {
         "id":"2",
         "menu":"3",
         "title":"Titulo 2",
         "image":"image02.jpg",
         "url":"http:\/\/www.exemplo.pt\/images\/image02.jpg"
      },
      {
         "id":"3",
         "menu":"4",
         "title":"Titulo 3",
         "image":"image03.jpg",
         "url":"http:\/\/www.exemplo.pt\/images\/image03.jpg"
      }
   ]
}

Já experimentei os seguintes métodos mas ambos acabam por dar erro:
JSONArray
try {
    JSONArray JOBJECT = new JSONArray(jsonString);
    JSONArray home = JOBJECT.getJSONArray(0);
    JSONArray home_idx_1 = home.getJSONArray(0);
    String image = home_idx_1.getString(0);

    Log.v("view content", image);
} catch (JSONException e) {
    e.printStackTrace();
}

JSONObject
try {
    JSONObject JOBJECT = new JSONObject(jsonString);
    JSONObject home = JOBJECT.getJSONObject("home");
    JSONArray home_idx_1 = home.getJSONArray("0");
    String image = home_idx_1.getString("image");

    Log.v("view content", image);
} catch (JSONException e) {
    e.printStackTrace();
}

Como posso fazer para armazenar o valor de image do índice 2 do array home na variável image?
Comment: Já tentou utilizar a biblioteca `Gson` do Google?
Answer: O que acontece é que o seu home é um array de objetos, então experimente assim:
try {
    JSONObject JOBJECT = new JSONObject(jsonString);
    JSONArray array = JOBJECT.getJSONArray("home");
    JSONObject home_idx_1 = array.getJSONObject(0);
    String image = home_idx_1.getString("image");

    Log.v("view content", image);
} catch (JSONException e) {
    e.printStackTrace();
}

Isso para que o seu código funcione. Agora, para obter o índice 2 como você perguntou, acredito que vai ser preciso iteragir sobre o array até chegar no índice desejado.

Manipular objecto json