Apache Solr Search proper syntax in url?

Question: Can anyone provide some info on how to properly execute a filtered apache sold search through the url?  So far I've figured out that
<code>?fq[]=bundle:type
</code>
will return a results filtered by that bundle type.  I've also noticed that
<code>?f[0]=machine_name:value
</code>
will return results if that particular facet has been configured.  What I want to figure out, though, is how to use the url to send any filter request.  For example, if I want to write a url that would return results based on a particular taxonomy term, how would I enter that?  Furthermore, can any field be used to filter a search?
Answer: You should integrate Updated Apachesolr module.
Write some custom menu hook to invoke your custom function.
<code> $query = apachesolr_current_query();
 $params_query = $query->getParams();
</code>
The above two statements will help us to check our solr queryString that we have triggered from our application.
<code>/**
 * Implementation of hook_search_execute().
 */
function Custom_Function($keys = NULL, $conditions = NULL) {

  $filters = isset($conditions['fq']) ? $conditions['fq'] : array();
  $solrsort = isset($_GET['solrsort']) ? $_GET['solrsort'] : '';

  $response = NULL;
    $filt = array();
  // add custom filters if you want to add few custom filters in certain conditions.
   if($_GET['some key'] == 'some condition') {
        $filt[] = array('name' => 'entity_type', 'value' => 'trend_tips');
      }else{
        $filt[] = array('name' => 'im_16_field_category', 'value' => $_GET['category']);
      }
  $filters = $filt;
  $results = apachesolr_search_run('apachesolr', array('q' => $keys, 'fq' => $filters), $solrsort, 'search/' . arg(1), pager_find_page());

    // Set name for search results
    $query = apachesolr_current_query();

    $params_query = $query->getParams();

    if (module_hook($module, 'search_page')) {
      return module_invoke($module, 'search_page', $results);
    }
 }
/**
 * Implementation of hook_apachesolr_query_prepare().
 */
function CustomeModule_apachesolr_query_prepare(&$current_query) {

  // add query filters for Style tips and trends
  $current_query->addParam('fl', 'tm_image,tm_url,content');
  $current_query->addParam('qf', 'tm_title');
  $current_query->addParam('qf', 'tm_short_content');
  $current_query->addParam('qf', 'tm_perex');
  $current_query->addParam('mm', '1<-90%'); // if you write more then 1 word to search, solr search as 'OR'
  $current_query->addParam('bf', 'recip(rord(created),4,5759,5759)^5.0'); // remove time dependency on search results

  // remove following content types (product and page) from search
    $current_query->addFilter('entity_type', 'product', true);
    $current_query->addFilter('bundle', 'page', true);
    $current_query->addFilter('tid', "63", true);
    $current_query->addFilter('tid', "64", true);

  $current_query->addParam('facet.field', 'bundle');
  // add a new facet type for filter trends and tips on search results

}
</code>
Please let me know if the above codebase helped to get some grip.
Thanks
Answer: It might help you using something like the Pretty Paths module
https://www.drupal.org/project/facetapi_pretty_paths
It will be much easier to construct the urls you want.


How do I click on a link in the same row as another string which I've made into a list?

Question: I want to click on a link in the same row as another link/text which I have copied into a list. What is the best way to go about this?
I want to click on the "Edit" Button in the same row as the Invoice. I copied all the Invoices into a list but I had to remove the "invoice #" part out of each invoice.
Thank you for your help!

Edit | View

ID

ID2

Customer

Stripe Code

Event Date

Invoice

Invoice Sales Order

Invoice Terms

Event Type

Balance

Edit | View
214433
245950
Salads & Wraps
funds
11/14/2019
Invoice #INV10
Order #0073
On Shipping
The account has insufficient funds
476.00

Edit | View
214502
3831
Bbq and Pizzeria
funds
11/14/2019
Invoice #INV20
Order #0068
ACH on Shipping
The account has insufficient funds
1,027.18

Edit | View

ID

ID2

Customer

Stripe Code

Event Date

Invoice

Sales Order

Invoice Terms

Event Type

Balance

Comment: i'm not sure if i understand the question correctly do you want to click it using selenium?if yes using selenium you could find the element i.e top row with xpath : //tr[@id='row0']//a[contains(@class, 'edititem')] then click it
Comment: Hi, yes I want to click it using selenium. I would try that method but it isn't always going to be in the top row. I need it to be in the same row as the Invoice ID. But,  Thank you for taking your time to help me!
Answer: I'd say if the you wanted to click based on the invoice id, you should know the invoice id right or at leas part of it e.g : INV10 . so you need to construct xpath around that like so
"//tr[ .//a[contains(text(),'INV10')]]//a[contains(@class, 'edititem')]"

the xpath //tr[ .//a[contains(text(),'INV10')]] means looks for tr that has descendant anchor that has text containing INV10
but if you wanted it to be dynamic let say it's always had INV + something, you could construct the string there and append as needed
String dummyVar = 10;
"//tr[ .//a[contains(text(),'INV"+dummyVar +"')]]//a[contains(@class, 'edititem')]"

Sorry i'm not familiar with phyton, but it should be understandable.
EDIT : i'm assuming the id is the INV10, but when i take a look you have id column. so if the id column is the invoice ID then you could do
"//tr[ .//td[contains(text(),'245950')]]//a[contains(@class, 'edititem')]"

just a warning, if you are able to put at least class in the id's td to make it more accurate for you to find it as well as more robust in case you have a coincident 2 elements found with the xpath
Answer: It seem like you want click Edit based on particular #INV number, try the following xpath:
//tr[contains(.,"#INV10")]//td//a[text()="Edit"]

Try change #INV10 to #INV20 and see the result.


How to add css classes to modal forms module

Question: My Problem
I'm trying add CSS classes to help me style the modal forms created using the Modal Forms module.
I have a User Login and a User Register form at the moment, but they have no form specific CSS classes.

Example 1
To style the height of the input boxes:
I either have to use "form-text" in <input> which will edit all form inputs across all forms or "edit-name" which will become "edit-name--1" if the user fails to login and the break the css.

    <input id="edit-name" class="form-text required"
    type="text" maxlength="60" size="25" value="" name="name">

Example 2
To alter the labels "username & password" the only tag I can work with is edit-pass

    ...

Which will change edit-pass--x every time they fail to complete the form correctly, resetting the css.
How would I insert CSS classes using hook form alter?
What I've tried
I printed out the array for the user login form (using print_r, can't use dpm because have to be logged in and user login won't work if you're logged in), here's the first chunk of it.
Array ( [name] => Array ( [#type] => textfield
                          [#title] => Username
                          [#size] => 25
                          [#maxlength] => 60
                          [#required] => 1
                          [#description] => Enter your drupaltest2 username. )

        [pass] => Array ( [#type] => password
                          [#title] => Password
                          [#description] => Enter the password that accompanies your username.
                          [#required] => 1 [#size] => 25 )

        [#validate] => Array ( [0] => user_login_name_validate
                               [1] => user_login_authenticate_validate
                               [2] => user_login_final_validate )

        [actions] => Array ( [#type] => actions
                             [submit] => Array ( [#type] => submit
                                                 [#value] => Log in ) )

I tried inserting
[#class] => 'TEST';

into [name] and other slight variations but none of them work.  I can give more examples if I've explained this badly.
EDIT -- RajeevK Solution -- Not enough granularity
I added the following lines into my alter form:
Name array:
$form['name'][#prefix] = '
';
$form['name'][#sufix] = '
';

Pass array:
$form['name'][#prefix] = '
';
$form['name'][#sufix] = '
';

And the end results looks like this:

This is what the page looks like (I'm using firebug to show what the div contains).

Or if I select CAPTAINTEST it looks like:

Hopefully this will help some though and cheers to RajeevK for the suggestion. I was hoping to control individual elements of the forms, does anyone know whether it would be possible to get more granularity without having to hack the module?
(Here's my form alter:
function mytheme_form_user_login_alter(&$form, &$form_state, $form_id) {
  //override to change text in user sign in box
  drupal_set_title('');
  $form['name']['#title'] = 'Username/Email';
  $form['name']['#description'] = '';
  $form['name']['#prefix'] = '
';
  $form['name']['#sufix'] = '
';
  $form['pass']['#description'] = '';
  $form['pass']['#prefix'] = '
';
  $form['pass']['#sufix'] = '
';
  $form['actions']['submit']['#value'] = 'Sign In.';

Comment: You can give permission to anonymous user to see developer message to access devel output.
Answer: You can use #attributes to add some classes to the elements:
$form['name']['#attributes'] = array('class' => array('your-class'));

Will output something like this (class added to input element):

  Username *
  <input type="text" maxlength="60" size="60" value="" name="name" id="edit-name" class="your-class form-text required">
  ...

Answer: You can use #prefix and #sufix for a form field to add class or ID of your wish. You can try something like this if you are altering user login form --
function MYMODULE_form_alter(&$form, &$form_state, $form_id){//replace MYMODULE with your module name
  if($form['#id'] == 'user-login'){
    $form['name'][#prefix] = '
';
    $form['name'][#sufix] = '
';
  }
}

Though I haven't tested this code but it should work. Inform me whether its working or not.
Comment: It sort of works. It gives a little more control but the granularity I was hoping for, the form doesn't build as I would expect it to and the divs surround large chunks of the form rather than individual elements. I posted an edit in the main question to show what happened.
Comment: @DominicWoodman You have passed both DIV for name field I think.. You need styling also as I see name field surrounded by the DIV class given by me and it ends after that, so now you have control over name field. Same you can do for pass, submit etc
Comment: Unfortunately the div ends up surrounding most of the form (I guess some quirk of how it is built) so if I pad usernamelogin, it ends up padding the whole box that's highlighted blue in the first image. I was hoping to just style itself. (thank you for the quick response!)
Answer: Maybe I am missing something here, considering all the preprocessing and all, but rarely drupal gives you not enough granularity for styling css as it creates so many elements to choose from. Consider this CSS without adding classes, pick some when going down the stairs of containing elements:
.popups-container #modal-content #user-login .form-item-name label {
  CSS
}
.popups-container #modal-content #user-login .form-item-name .form-text {
  CSS
}

I know this is not an answer to your specific question (adding classes), but I think it is a simpler solution for the problem you have here (styling individual elements).
Answer: You can use patch to add class containing the "modal style" to modal window.

With several modals, we have the need for different styling of each. Currently, the CTools Modal does not add any CSS classes to the modal container.
  We have added this to modal.js and it works for us.


Custom REST POST resource to accept JSON

Question: I am trying to build simple search autocomplete POST endpoint, that accepts JSON and outputs JSON, but I am having problems getting Drupal 8 to just accept plain JSON.
Currently I am getting a 404 error for that endpoint, even though it is enabled in REST UI and I have permission. If I add serialization_class with value Drupal\node\Entity\Node to the class comment, I get 415 error, because it expects a node. Okay, great. How do I actually make it accept JSON? Do I really need to make an Entity type just for my autocomplete search?
Here is the code I have in mymodule/src/Plugin/rest/resource/SearchAutocompleteResource.php.
namespace Drupal\MyModule\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\node\Entity\Node;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Provides a resource for search autocomplete.
 *
 * @RestResource(
 *   id = "mymodule:searchautocomplete",
 *   label = @Translation("MyModule: Search Autocomplete"),
 *   uri_paths = {
 *     "canonical" = "/api/v1/search-autocomplete",
 *     "https://www.drupal.org/link-relations/create" = "/api/v1/search-autocomplete"
 *   }
 * )
 */
class SearchAutocompleteResource extends ResourceBase {

  public function post($search = null) {

    return new ResourceResponse(array(
      'example' => 'return value'
    ));

  }

}

Answer: Up until Make serialization_class optional (#2419825) issue has been fixed for 8.2.x branch you couldn't get away without creating a custom serialization class which merely passes the provided data to satisfy the requirement for mandatory serialization.
If you need to make it work on Drupal <= 8.1, try the following:

Create a custom normalizer.
Expose it to the system as a service.
Use it as serialization_class for your Rest resource.

modules/mymodule/src/normalizer/JsonDenormalizer.php:
<?php

namespace Drupal\mymodule\normalizer;

use Drupal\serialization\Normalizer\NormalizerBase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

/**
 * Class JsonDenormalizer
 *
 * @todo Remove this class once https://www.drupal.org/node/2419825 is fixed.
 */
class JsonDenormalizer extends NormalizerBase implements DenormalizerInterface {

  /**
   * The interface or class that this Normalizer supports.
   *
   * @var array
   */
  protected $supportedInterfaceOrClass = array(__CLASS__);

  /**
   * {@inheritdoc}
   */
  public function normalize($object, $format = null, array $context = array()) {
    return parent::normalize($object, $format, $context);
  }

  /**
   * {@inheritdoc}
   */
  public function denormalize($data, $class, $format = NULL, array $context  = array()) {
    return $data;
  }
}

modules/mymodule/mymodule.services.yml:
services:
  # can be removed once https://www.drupal.org/node/2419825 is fixed.
  serializer.normalizer.mymodule.json:
    class: Drupal\mymodule\normalizer\JsonDenormalizer
    tags:
      - { name: normalizer }

mymodule/src/Plugin/rest/resource/SearchAutocompleteResource.php:
/**
 * Provides a resource for search autocomplete.
 *
 * @RestResource(
 *   id = "mymodule:searchautocomplete",
 *   label = @Translation("MyModule: Search Autocomplete"),
 *   serialization_class = "Drupal\mymodule\normalizer\JsonDenormalizer",
 *   uri_paths = {
 *     "canonical" = "/api/v1/search-autocomplete",
 *     "https://www.drupal.org/link-relations/create" = "/api/v1/search-autocomplete"
 *   }
 * )
 */

Comment: Another option for you is to just create a custom controller and return autocomplete values from there. Rest resource plugin is just one (and fancy) way of doing it.
Comment: Hmm, could there be a typo somewhere in your code, I get this error in the response: `
Fatal error:  Class 'Drupal\mymodule\normalizer\JsonDenormalizer' not found in /srv/www/drupal8/core/lib/Drupal/Component/DependencyInjection/Container.php on line 264` The file is mymodule/src/normalizer/JsonDenormalizer.php, should be correct
Comment: I added `<?php` for `JsonDenormalizer` class but other than that I believe the code is correct. I created a module `mymodule` with the provided code and REST client returned the correct JSON from your `SearchAutocompleteResource` class.
Comment: My bad, I renamed `mymodule` to my module name with uppercase letters and looks like that is not allowed. Now it works perfectly, thanks a lot!
Answer: The answer supplied by @maijs is correct for Drupal 8.1.x and lower, but for 8.2.x it's so much easier, because you don't even have to think about the normalizer.  Here's an example of my_module/src/Plugin/rest/resource/MyRestResource.php
<?php

namespace Drupal\my_module\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "my_rest_resource",
 *   label = @Translation("My rest resource"),
 *   serialization_class = "",
 *   uri_paths = {
 *     "canonical" = "/my_rest_resource"
 *   }
 * )
 */
class MyRestResource extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('my_module'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to GET requests.
   *
   * Returns a list of bundles for specified entity.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function get() {
    $response = 'hello world';
    return new ResourceResponse($response);
  }

  public function post(array $data = []) {
    $response = array(
      "hello_world" => $data,
    );
    return new ResourceResponse($response);
  }

  public function patch($arg) {
    return new ResourceResponse('hello patch');
  }

}

The key here is post(array $data = []) near the bottom of the file.  In 8.1.x that was impossible, but in 8.2.x that's all it takes to convert post data to an array.  Here's how it looks when you request that URL with postman:
Answer: This is what I did to receive a JSON object from a post.
use Symfony\Component\HttpFoundation\Request;

class AjaxController extends ControllerBase {
    public function save(Request $request) {
        $object = json_decode($request->getContent());

Comment: Could you provide an extended example, including routing settings and (possibly) example code?


What fingering do you think is better for "bass/chord" left-hand line?

Question: Here is one of million piano arrangements of Ed Sheeran's "Perfect" that I've chosen for learning. And now I'm stuck trying to choose between two fingerings for left-hand line in this part (marked with red on the picture).

5 for bass note and 531 for chord
or 5 for bass note and 421 for chord

Both of them comfortable and easy enought for me, but I consider this piece not just as piece, but also as exercise to master different left-hand lines (chords, arpeggio, bass/chord, and so on), so I'm trying to choose the fingering that is more common for such lines to master them for better skills development.
Seems like 5-421 is better for fast passages (because hand jump between bass and chord is shorter), but 5-531 seems a bit more comfortable for part marked with green on pictire (like 5-531-521-531), and I'm not sure that mixing theese fingering schemes is a good idea in learning-purposes terms.
So, what do you think will be better, looking from this prospective?
Context: I'm a 3-month-practice piano beginner, but with well-developeg fingers coordination (20 years of 10-fingers blind typing on computer keyboard, advanced-amateur guitar 15 years experience and so on). For now I've learned 6 piano pieces with about the same level of difficulty that this one is.
Answer: Use 531.
As you've observed, both 531 and 421 are fine, and pianists use both. However, since your purpose is to exercise standard hand positions, 531 is the canonical position for root position triads, which all of these chords are (except the one identified to be played 521).
You'll encounter plenty of opportunities to exercise the 421 version as you continue to play, but master 531 first.


Constant sheaf with value the empty set

Question: Let X be a topological space. Is there such a thing as the constant sheaf on X with value the empty set?  That is, a sheaf that assigns to each open set U the set of maps from U to the empty set and to each inclusion the empty map?
I ask because I am trying to show that the projection map from the etale space of a locally constant sheaf on X to X, defined to send a germ at a point x to the point x, is a covering map. It's not clear to me that this map is surjective. That is, why can't there be an x in X such that there are no sections over any neighborhood of x?
Comment: The sheaf that assigns to each open $U$ the set of maps $U\to\varnothing$ will send each *nonempty* U to the empty set, but it will send the empty open set $U$ to a $1$-element set (whose member is the empty function). A nice exercise is to show that *every* sheaf on any space must send the empty open set to a $1$-element set. (Hint: Consider the empty cover of $\varnothing$, not the cover $\{\varnothing\}$ but the cover $\varnothing$.)
Comment: I usually use "constant presheaf" to mean that the same value is assigned to all open sets, and I use "constant sheaf" to mean the associated sheaf of a constant presheaf.  With this terminology (which I think is fairly standard), your example is a constant sheaf but not a constant presheaf.
Comment: This is true. But does this mean this sheaf is not a constant sheaf?
Answer: The empty sheaf $E$ is exactly as you described it. Note that $E(\emptyset)$ has exactly one element (this is in fact true for all sheaves), and that if $U \neq \emptyset$, we have $E(U) = \emptyset$.
The corresponding etale map is the trivial map from the empty space to $X$. $\DeclareMathOperator{id}{id}$
In general, given a set $A$, the "constant presheaf of $A$" defined by $P(U) = A$ and $P(U \subseteq V) = \id_A$ for all $U, V$ open, and its associated locally constant sheaf $E$, the associated etale space over $X$ will be $p_2 : A \times X \to X$, where $A$ has the discrete topology.

Constant sheaf with value the empty set


Tela de Fragment para chamar outra tela Fragment

Question: Eu estou em um fragment, e nesse fragment eu quero chamar outra tela que também é um fragment. Estou usando recycleview. Se eu tentar chamar uma activity, eu consigo, mas não consigo chamar um fragment.
Veja o código abaixo:
@Override
public void onNoteClick(int position) {
    listaCursos.get(position);
   // aqui deve chamar outro fragment
}

Tentei alguns exemplos que achei, mas não abre uma outra tela que tem o fragment.
 Só lembrando que meu app só possui uma activity, todo o resto somente fragment.
Chamar a tela usando intent não é meu caso.
Tentei algo parecido com isso que achei e não foi:
Fragment fr = new Fragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, fr);
fragmentTransaction.commit();

Vou colocar aqui como ta meu xml:
<?xml version="1.0" encoding="utf-8"?>

tools:context=".fragmentos.consultarCursoUrl">

<LinearLayout
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_margin="10dp"
    >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="CONSULTAR CURSO"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:textSize="20sp"
        android:layout_marginBottom="20dp"
        android:textStyle="bold"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"

        >

    <EditText
        android:id="@+id/codigo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Código"
        android:layout_weight=".5"
        />

    <ImageButton
        android:id="@+id/btnConsultar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_menu_search"
        android:background="@color/colorPrimaryDark"
        android:layout_weight="3"

        />

    </LinearLayout>

    <EditText
        android:id="@+id/txt_nome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:layout_marginLeft="5dp"
        android:layout_marginBottom="10dp"

        />

    <EditText
        android:id="@+id/txt_professor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:layout_marginLeft="5dp"
        android:layout_marginBottom="10dp"

        />

    <EditText
        android:id="@+id/txt_categoria"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:layout_marginLeft="5dp"

        />

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/imagemId"
    >

    <Button
        android:id="@+id/btnAtualizar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Atualizar"
        android:layout_weight="2"
        android:layout_marginRight="1dp"
        android:layout_marginTop="122dp"
        android:background="@color/colorPrimaryDark"
        android:textColor="@color/colorWhite"
        />

    <Button
        android:id="@+id/btnDeletar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Deletar"
        android:layout_weight="2"
        android:layout_marginRight="1dp"
        android:layout_marginTop="122dp"
        android:background="@color/colorPrimaryDark"
        android:textColor="@color/colorWhite"
        />

</LinearLayout>

 <ImageView
     android:id="@+id/imagemId"
     android:layout_width="250dp"
     android:layout_height="250dp"
     android:layout_below="@+id/linearLayout"
     android:src="@drawable/sem_foto"
     android:layout_centerHorizontal="true"
     />

Answer: Você pode iniciar um outro fragment da seguinte:
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FrgmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer,new Fragment2()).commit();

Observe que R.id.fragmentContainer é o seu frameLayout contido no xml e o Fragment2() é o fragmento que você quer chamar;
Comment: Tentei do seu jeito, até que a tela aparece, mas os itens ficam sobrepostos com o da tela anterior. Vou por aqui como ta.
Comment: Agora que caiu a ficha em relação ao container. Consegui. Muito obrigado


Custom field type that has an array property won't save unless serialized, otherwise get "This value should be of the correct primitive type" error

Question: I have a custom field type with two properties I am storing on it. One stores a string. The other I want to store an array. The array should be serialized in the field value table of the database, but it should be an array when exported to YAML (default value setting of the field instance configuration).
I am having trouble getting this to work. In my head it would be similar to 'allowed formats' option on text long instances.
The field value schema:
field.value.myfieldtype:
  type: mapping
  label: Default value
  mapping:
    view_id:
      type: string
      label: View ID
    facets:
      type: sequence
      label: Facet list
      sequence:
        type: string
        label: 'Facet machine name'

The field properties are defined as:
  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {

    $properties['view_id'] = DataDefinition::create('string')
      ->setLabel(t('A Drupal View.'))
      ->setRequired(TRUE);

    $properties['facets'] = DataDefinition::create('string')
      ->setLabel(t('A list of facets selected by the user.'))
      ->setRequired(FALSE);

    return $properties;
  }

In the custom form widget I made, I have massageFormValues like this:
  /**
   * {@inheritdoc}
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    $facet_list = !empty($values[0]['facets']) ? array_filter($values[0]['facets']) : [];
    $values[0]['facets'] = serialize($facet_list);
    return parent::massageFormValues($values, $form, $form_state);
  }

If I call array_keys instead of serialize, or pass anything that is not a string, I get an error on save:
This value should be of the correct primitive type.

If I use serialize, it saves fine and I can see the serialized value in the tuple in the database. However, if I set a 'Default Value' on the field instance and run a configuration export, I get this:
default_value:
  -
    view_id: 'search:content_listing'
    facets: 'a:1:{s:16:"content_category";s:16:"content_category";}'

What I would expect is:
default_value:
  -
    view_id: 'search:content_listing'
    facets:
      - content_category
      - (other selected options)
      - (other selected options)

What am I missing?
Answer: Instead of serializing, I changed the schema of the property to store as JSON for sake of the storage and export since serialized strings are discouraged.


Dual stack linux router, can't forward IPv6 prefix

Question: I have a small offic here with a few workstations and I would like to implement a small server for stuff like a proxy server, samba etc.
This is the topology of said network:
+-----+   dynamic    +--------+        +-------------------+                 +--+workstation1
|     |  /56 prefix  |        |        |   Debian server   |        +--------+
| ISP +--------------+ Router +-+eth0+-+                   +-+eth1+-+ switch +--+workstation2
|     |   dynamic    |        |        | (squid,dhcp,etc.) |        +--------+
+-----+ IPv4 address +--------+        +-------------------+                 +--+workstationX

I would like to have the server assign global (maybe local as well) IPv6 addresses and private IPv4 addresses to all devices connected to eth1 via the switch. I have been able to get NAT masquerading working with dnsmasq and iptables but I can't get IPv6 traffic or even distributing IPv6 addresses to work. The router has three different settings in the IPv6 DHCP server tab:

assign DNS server only
assign DNS server and IPv6 prefix to downstream routers (what I assume should be enabled)
assign DNS server, IPv6 prefix to downstream routers and IPv6 address

I tried following this guide. It describes how to set up a DHCPv6 server with dnsmasq. I have a working eth0 which gets a global, unique local and a link local address. But my eth1 interface never gets a global IPv6 address, only a link-local one. The devices behind the server all have a working IPv4 address but I can't set the IP to a static one because the prefix is dynamic and changes every night. Currently I'm stuck at this point.
Here are my configuration files.
Thank you for your help.
Comment: Use an OpenWRT-based router, which is capable of doing this. Even a reflashed home router will do. Debian has absolutely no software included which can send IPv6 prefixes downstream. Nor, as far as I know, does _any_ other distribution.
Comment: You appear to have two layers of routers with dynamically assigned IPv6 addresses in your setup. In order for that to work `Router` has to act both as DHCPv6 client and server. `Router` must act as DHCPv6 client to request delegation of the /56 from the ISP. It must also act as DHCPv6 server to delegate a /60 out of that /56 to the Debian server. I have no idea whether the software you are running on your routers support such a configuration.
Answer: You will need to assign an IPv6 address to eth1 as it won't be able to autoconfigure.  Pick an /64 address from your /56 although you may be able to use your /56.  I've used the prefix 2001:0db8:a1b2:c2d3::/64 in the example below.
# This is an IPv6 interface
iface eth1 inet6 static
    address  2001:0db8:a1b2:c2d3::1
    netmask  64

Comment: @Leo Your provider should be providing a static IPv6 address with /64 or /56 range for your use.  Otherwise, consider using a tunnel broker for IPv6.   You should firewall your global IP addresses as you will not any protection from an NAT.
Comment: Unfortunately the prefix changes everytime the router reconnects (reboot or every 24 hours). But the bigger problem is that even after a reboot the static ip isn't shown with `ip addr`. It shows the global ip and so on on eth0 and only the link-local on eth1.
Answer: I have found the way. My interface eth0 got it's IP because of the enabled net.ipv6.conf.eth0.accept_ra=2 in /etc/sysctl.conf. The wide-dhcpv6-client tried setting eth0 address again, but it has already been set by the router advertisement. So if you want wide-dhcpv6-client to set the ip only to the internal interface (eth1 in my case) you have to omit the
id-assoc na 1 {
    # id-assoc for eth1
};

part from the posted tutorial. Otherwise dhcp6c will stop after seeing that the address is already in use.
This is what my dhcp6c.conf looks like now
interface eth0 {
        send ia-pd 1;
        request domain-name;
        request domain-name-servers;
        script "/etc/wide-dhcpv6/dhcp6c-script";
};

id-assoc pd 1 {
        prefix ::/64 infinity;
        prefix-interface eth1 {
                sla-len 0;
                sla-id 1;
                ifid 1;
        };
};

Now everything works like a charm.
I hope this information helps anyone with a similar problem.


Android Kotlin: How to get Context for a Toast?

Question: In my MainActivity I can use Toasts with application context "this".
I have two more activities, it does also work in the second, but not in the third.
The code Im trying to write it:
fun onButtonLogoutClicked(view: View){
        if (user != null){
            auth.signOut()
        } else {
            Toast.makeText(this, "there is no logged-in user", Toast.LENGTH_SHORT).show()
        }
    }

So AndroidStudio tells me "'this' is not defined in this context.
I also googled and tried stuff like "getApplicationContext()" but AndroidStudio does not know this methods and I cannot import them.
Can anyone help (and explain me why "this" does not work?)?
Thank you very much, have a nice day!
Comment: Just use the context inside the view object `view.context`
Comment: You must be calling this from a place where `this` is ambiguous, like inside a lambda or listener.
Answer: This is one way to go about it.
fun onButtonLogoutClicked(view: View){
  if (user != null){
       auth.signOut()
  } else {
       Toast.makeText(this@MyActivity, "there is no logged-in user",
       Toast.LENGTH_SHORT).show()
      }
  }

another is using the context.


jFugue + Gervill: using different soundbanks the sounds doesn't change

Question: I'm trying to use jFugue + gervill to create music with Java 7. I've the following code
<code>Soundbank soundbank = MidiSystem.getSoundbank(new File("/home/morelli/tmp/SoundBanks/JR_elepiano.sf2"));
    Synthesizer synt = MidiSystem.getSynthesizer();
    synt.loadAllInstruments(soundbank);
    synt.open();
    Player player = new Player(synt);
    Pattern pattern = new Pattern("$PP=0 T120 V0 I42 C4ww V1 I[PP] C5w+E5qq_G5qq C5w+E5qq_G5qq C5w+A5qq_g5qq C5w+A5qq_g5qq V2 I43 G3q G3q G3q G3q G3q G3q G3q G3q V9 81q");

    Rhythm rhythm = new Rhythm();
    rhythm.setLayer(1, "O..oO...O..oOO..");
    rhythm.setLayer(2, "..*...*...*...*.");
    rhythm.setLayer(3, "^^^^^^^^^^^^^^^^");
    rhythm.setLayer(4, "...............!");
    rhythm.addSubstitution('O', "[BASS_DRUM]i");
    rhythm.addSubstitution('o', "Rs [BASS_DRUM]s");
    rhythm.addSubstitution('*', "[ACOUSTIC_SNARE]i");
    rhythm.addSubstitution('^', "[PEDAL_HI_HAT]s Rs");
    rhythm.addSubstitution('!', "[CRASH_CYMBAL_1]s Rs");
    rhythm.addSubstitution('.', "Ri");
    Pattern rpattern = rhythm.getPattern();

    rpattern.repeat(2);
    pattern.add(rpattern);
    player.play(pattern);

    player.saveMidi(pattern, new File("/tmp/music-file.mid"));

   //System.out.println(Arrays.toString(synt.getLoadedInstruments()));
   for (javax.sound.midi.Instrument l: synt.getLoadedInstruments()) {
       System.out.println(l.toString());
   }
</code>
The problem is that if I change the soundbank, the instruments sound doesn't change and the instruments printed are always the same. What I wrong?
Answer: I find the solution (I think :-)). I've to invert the open and loadAllInstruments calls:
synt.open();
   synt.loadAllInstruments(soundbank);


Finding expected value from expectation of squared distance

Question: This problem is actually a part of a much larger biology problem that I am working on. However, I will leave out the unrelated parts.
Consider a sequence of points $\{(x_j, y_j)\}$ where neighboring points $(x_j, y_j)$ and $(x_{j + 1}, y_{j + 1})$ are connected with edges of length $1$. Furthermore, assume the direction of each edge is random so that the angles which the edges form with the $x$-axis are independent uniformly distributed random variables on $[0, 2\pi)$. I would like to find the square root from the expectation of the squared distance between $(x_0, y_0)$ and $(x_n, y_n)$.
Does anyone know how I might be able to approach this problem? Any help is appreciated.
Answer: You don't say how big $n$ is. When $n$ is not very small, the squared distance distribution will be a multiple of $\chi^2_2$.
By the Central Limit Theorem, $(X_n,Y_n)$ will be approximately bivariate Normal with mean zero and covariance matrix $nV$, where $V$ is the covariance matrix of $(X_1, Y_1)$. Since $X_1$ and $Y_1$ are uncorrelated, $(X_n,Y_n)$ are uncorrelated and thus asymptotically independent, so $X_n^2+Y_n^2$ is approximately $n\sigma^2\chi^2_2$, where $\sigma^2/2$ is the trace of $V$. And $V$ has diagonal elements $1/2$ and off-diagonal elements 0, so $\sigma^2=1/2$.
Thus $X_n^2+Y_n^2$ is approximately $(n/2)\chi^2_2$.
Check by simulation in R
<code>n<-10
theta<-matrix(runif(n*10000,0, 2*pi),ncol=n)

deltax<-cos(theta)
deltay<-sin(theta)
x<-rowSums(deltax)
y<-rowSums(deltay)
dist<-2*(x^2+y^2)/n
summary(dist)
summary(rchisq(10000,2))

qqplot(dist, rchisq(10000,2),ylab=expression(chi[2]^2/2))
abline(0,1,col="blue")
</code>
For small $n$ (eg $n=5$), the true distribution has a noticeably lighter right tail than the approximating $\chi^2_2$, but the approximation improves as $n$ increases.
Comment: I want to use this quantity to approximate the expectation for the distance between $(x_0, y_0)$ and $(x_n, y_n)$ as it's a lot easier to calculate. However, I was wondering if there may be a better solution/approximation with the updated title.
Comment: Ok, the distribution is the square root of what I said. There isn't a standard name  (as far as I know). There might be some special trick to simplify it, but I don't know of one.
Comment: (approximately, as $n$ increases). By the Central Limit Theorem. It's a sum of independent random variables.


Limit of $(\cos1/n)^{n^2}$ when $n\to\infty$

Question: I've been trying to solve this limit:
$$\lim_{n\to \infty} \left(\cos\left(\frac{1}{n}\right)\right)^{n^2}$$
I solved it using l'hopital but I have to try in another way.
I tried to make the expression:
$$ \lim_{n \to \infty}\exp\left(n^2\ln\left(\cos\left(\frac{1}{n}\right)\right)\right)$$
but it didn't work out for me...
Comment: $\lim_{x\to\infty} \cos\left(\frac{1}{n}\right)^{n^2} = \cos\left(\frac{1}{n}\right)^{n^2}$, since it doesn't depend on $x$.  Did you mean to write $\lim_{n\to\infty}$?
Comment: Maybe a better title is in order? Something... that might reflect the actual content of the question?
Comment: See what @Asaf meant?
Comment: Your'e absolutely right. edited.. thanks!
Answer: $$
\lim_{n\to\infty}n^2\ln\left(\cos{1\over n}\right)=
\lim_{n\to\infty}{\ln\left(1-\left(1-\cos{1\over n}\right)\right)
\over1-\cos{1\over n}}\cdot{1-\cos{1\over n}\over(1/n)^2}=
-1\cdot{1\over2}=-{1\over2}.
$$
Comment: You have a typo. The last expression  should be $(-1)\cdot\frac{1}{2}$ as the log limit is $-1$.
Comment: Right, thanks! Corrected now.
Answer: How about this
\[
\cos(1/n)=1-\frac{1}{2n^2}+O\left(\frac{1}{n^4}\right)
\]
Then use the relation \[\lim_{n\rightarrow\infty}\left(1+\frac{x}{n}\right)^n=e^x\]
Combining the two one gets
\[
\lim_{n\rightarrow\infty}[\cos(1/n)]^{n^2}=\lim_{n\rightarrow\infty}\left(1-\frac{1}{2n^2}\right)^{n^2}=e^{-1/2}=\frac{1}{\sqrt{e}}
\]
Comment: I only saw your answer after I posted mine.
Comment: No worry.  That has happened to me a number of times.
Answer: Using $\cos(1/n)=1-\frac{1}{2n^2}+O\left(\frac1{n^4}\right)$, we have
$$\begin{align}
\cos^{n^2}(1/n)&=\left(1-\frac{1}{2n^2}+O\left(\frac1{n^4}\right)\right)^{n^2}\\\\
&=\left(1-\frac{1}{2n^2}\right)^{n^2}\,\left(1+\frac{O\left(\frac{1}{n^4}\right)}{1-\frac1{2n^2}}\right)^{n^2}
\end{align}$$
Next, we note that $\lim_{n\to \infty}\left(1-\frac{1}{2n^2}\right)^{n^2}=e^{-1/2}$ from the definition of the exponential function.
Finally, inasmuch as
$$\lim_{n\to \infty}\left(1+\frac{O\left(\frac{1}{n^4}\right)}{1-\frac1{2n^2}}\right)^{n^2}=\lim_{n\to \infty}\left(1+O\left(\frac{1}{n^4}\right)\right)^{n^2}=1$$
we arrive at the coveted limit
$$\lim_{n\to \infty}\cos^{n^2}(1/n)=e^{-1/2}$$
And we are done!
Answer: $$\lim_{n\to\infty}\left(\cos\dfrac1n\right)^{n^2}=\lim_{n\to\infty}\left(1-\sin^2\dfrac1n\right)^{n^2/2}$$
$$=\left(\lim_{n\to\infty}\left(1-\sin^2\dfrac1n\right)^{-\frac1{\sin^2\frac1n}}\right)^{-\lim_{n\to\infty}\frac{n^2\sin^2\frac1n}2}$$
Set $-\sin^2\dfrac1n=\dfrac1m$
$$\lim_{n\to\infty}\left(1-\sin^2\dfrac1n\right)^{-\frac1{\sin^2\frac1n}}=\lim_{m\to\infty}\left(1+\dfrac1m\right)^m=?$$
For exponent set $\dfrac1n=h$ to get $$-\lim_{n\to\infty}\frac{n^2\sin^2\frac1n}2=-\dfrac12\left(\lim_{h\to0}\dfrac{\sin h}h\right)^2=?$$
Answer: If $L=\lim_{x \to a} f (x)^{g (x)} $ assumes the form $1^{\infty} $ we can always write it as $L=e^{lim_{x\to a}g (x)(f (x)-1)} $. Now here let $\frac {1}{n}=u $ so as $n \infty ,u\to 0$. So we have $L=e^{\lim_{x \to 0}\frac{\cos(u)-1}{u^2}}=e^{\frac {-1}{2}} $ . The proof of the first statememt can be added if you want.
Answer: $$\lim_{n \to \infty}\exp\underbrace{(n^2\ln(\cos(\frac{1}{n}))}_{a})\\$$exp is continous functio ,so find limit $a$
$$\lim_{n \to \infty}n^2\ln(\cos(\frac{1}{n})=\\
\lim_{n \to \infty}\frac{\ln(\cos(\frac{1}{n}))}{\frac{1}{n^2}}=\\hop\to
\lim_{n \to \infty}\frac{\frac{\frac{-1}{n^2}\sin (\frac{1}{n})}{(\cos(\frac{1}{n})}}{\frac{-2}{n^3}}=\\
\lim_{n \to \infty}-\frac{\frac{\sin (\frac{1}{n})}{2\cos(\frac{1}{n})}}{\frac{1}{n}}=\\\frac{-1}{2}$$now
$$a=\frac{-1}{2} \implies exp(a)=e^{\frac{-1}{2}}$$


Pandas : Changing a column of dataset from string to integer

Question: One Column of my dataset is like this:
0        10,000+
1       500,000+
2     5,000,000+
3    50,000,000+
4       100,000+
Name: Installs, dtype: object

and I want to change these 'xxx,yyy,zzz+' strings to integers.
first I tried this function:
df['Installs'] = pd.to_numeric(df['Installs'])

and I got this error:
ValueError: Unable to parse string "10,000" at position 0

and then I tried to remove '+' and ',' with this method:
df['Installs'] = df['Installs'].str.replace('+','',regex = True)
df['Installs'] = df['Installs'].str.replace(',','',regex = True)

but nothing changed!
How can I convert these strings to integers?
Comment: Don't use `regex=True`, but `regex=False`, or use a correct regex.
Answer: With regex=True, the + (plus) character is interepreted specially, as a regex feature. You can either disable regular expression replacement (regex=False), or even better, change your regular expression to match + or , and remove them at once:
df['Installs'] = df['Installs'].str.replace('[+,]', '', regex=True).astype(int)

Output:
>>> df['Installs']
0       10000
1      500000
2     5000000
3    50000000
4      100000
Name: 0, dtype: int64

Comment: I think you're proficient enough! You somehow answer more questions a day, it seems, than I do. ¯\\_(ツ)_/¯
Comment: Maybe. I have to increase my typing speed (and my English level). lol
Answer: + is not a valid regex, use:
df['Installs'] = pd.to_numeric(df['Installs'].str.replace(r'\D', '', regex=True))

Comment: Thanks! I'm too slow typing on a phone :p


Layout weight not changing in xml

Question: I have a XML code here:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="100"

    >
    <fragment
        android:name="com.powergroup.split.view.powerListFragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/powerlist_fragment"
      android:layout_weight="45"

        >
    </fragment>
    <fragment
        android:name="com.powergroup.split.view.powerViewerFragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/powerview_fragment"
        android:layout_weight="55"
       >
    </fragment>
</LinearLayout>

but if I change the value of layout_weight it doesnt take any effect and always shows the same, how can i figure it out?
Answer: You need to set fragments' layout_width to 0dp in order for weight to kick-in. See below:
android:layout_width="0dp"

Comment: I did, but no change is happening
Comment: did you set it to both fragments?
Answer: *layout_weight* is appliable only to "unused" pixel distribution. All of your fragments have fill_parent as width. So, there are no "unused" pixels in this case. Try to set layout_width="0dip".

Layout weight not changing in xml


Can I use Indy10 as-is, without installing a package

Question: When I need to move to a new build of Indy 10, the instructions are to remove files in all sorts of places, download, reinstall, etc. Even when the version itself does not change. I get very nervous about this, since things have gone wrong in the past and I am not at all familiar with packages.
I am not using the IDE components. Is it an option in that case to just add the Indy source files to my project and let Delphi do the compilation/linking?
Delphi 10.1 Berlin; Indy 10.6.2 build 5341.
Comment: yes you can simply add the source to your project
Answer: Yes, you can do that. You need the packages only if you want to install the components into the IDE.
Simply add the source code to your project(s) and you are ready to go.
I would still make sure to remove any old Indy sources and DCUs from the search path(s) in the IDE to avoid compiling stale sources (in particular: Ancient include files). It has burned me too many times.


How to make a collection be "n" elements long using extension methods?

Question: So, here is my issue, I have a given object which is an IEnumerable and I have been guaranteed that said collection will always have at most 4 elements. Now, for a reason that is not important, I'd like to be able to, in some elegant way, "force" the collection to contain 4 elements if it has any less.
I've already done some research and the most convincig candidate is Zip, but it stops zipping after it reaches the shortest collection's end.
Is there any way of doing this without making my own extension method?
To better explain myself:
var list1 = new List<Dog> {
    new Dog { Name = "Puppy" }
}
var list2 = new List<Dog> {
    new Dog { Name = "Puppy1" },
    new Dog { Name = "Puppy2" },
    new Dog { Name = "Puppy3" },
    new Dog { Name = "Puppy4" },
}

var other1 = list1.ExtendToNElements(4).ToList();
//Now other1's first element is an instance of Dog with Name = "Puppy"
//And the following 3 elements are null, or have a Dog with no name
//I don't really care about that

var other2 = list2.ExtendToNElements(4).ToList();
//other2 is the same as list2, nothing got added.

Thanks in advance!
Answer: Quick one-liner (which should count as "doable without an extension method"):
public static IEnumerable<TItem> Extend<TItem>(
            this IEnumerable<TItem> source,
            int n)
{
    return source.Concat(Enumerable.Repeat(default(TItem), n))
                 .Take(n);
}

Since Repeat takes an explicit count, passing in n gives a reasonable upper bound. The elements are generated on-demand anyway. Using source.Count() would force execution of source which isn't ideal.
Slightly more overengineered and flexible version:
public static IEnumerable<TItem> Extend<TItem>(
            this IEnumerable<TItem> source,
            int n,
            Func<TItem> with)
{
    return source.Concat(
        from i in Enumerable.Range(0, n) select with()
    ).Take(n);
}

public static IEnumerable<TItem> Extend<TItem>(
            this IEnumerable<TItem> source,
            int n,
            TItem with = default(TItem))
{
    return source.Extend(n, with: () => with);
}

Comment: I thought OP was asking how to do that without writing his own extension method?
Comment: Really simple and useful, thanks a lot! Even though I was trying to avoid writing a extension method, I can just use it inline =)
Comment: @SergeBelov My first implementation is a one-liner. Copy-paste the body where desired, substitute `default(TItem)` with a hardcoded padding value.
Answer: You can use MoreLinq's Pad method: http://code.google.com/p/morelinq/ (NuGet: http://www.nuget.org/packages/morelinq)
This will append the default value for the type (null in this case):
var other1 = list1.Pad(4).ToList();

Or if you want to supply a default value:
var other1 = list1.Pad(4, "Puppy_null").ToList();

Or if you want to have those numbered puppies:
var other1 = list.Pad(4, (count) => "Puppy" + count).ToList();

The Pad method will not add additional entries if its length is already equal to or greater than your pad size.
Here's the Pad implementation specifically if you want to incorporate/adapt it without bringing in the entire project: http://code.google.com/p/morelinq/source/browse/MoreLinq/Pad.cs
Comment: @lazyberezovsky Thanks for pointing that out, I added the NuGet link.
Answer:     class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string>();
            list.Capacity = 4;
            var items = list.TakeOrDefault(4);

        }
    }

    public static class EnumerableExtensions
    {
        public static IEnumerable<T> TakeOrDefault<T>(this IEnumerable<T> enumerable, int length)
        {
            int count = 0;
            foreach (T element in enumerable)
            {
                if (count == length)
                    yield break;

                yield return element;
                count++;
            }
            while (count != length)
            {
                yield return default(T);
                count++;
            }
        }
    }


How do I compute row-wise minimum (least) in prestodb?

Question: I am trying to get the minimum of a couple of fields within a row with presto. In other SQL implementations like MySql this function is called LEAST. What is the equivalent function in Presto?
Answer: Since Presto 0.100 you can use least:
SELECT LEAST(a, b);

For versions prior to that, use this equivalent:
SELECT (CASE WHEN a > b THEN b ELSE a END);


Redirect to a specific page in ajax callback

Question: How can I redirect to a specific page in an ajax callback using Drupal 7, I've already tested this method:
function my_ajax_callback($form, &$form_state) {
  if (!user_is_anonymous()) {
    return $form['my_fieldset'];
  }
  else {
    drupal_goto('login');
  }
}

but that code doesn't redirect to /login when current user is anonymous.
Comment: Do you know that the function is called. Try to call a die statement to see if it is called.
Comment: Even `die()` in an ajax callback can't be used it will generate only an ajax error popup, ajax callback should return something as I guess but using `drupal_goto()` does not return any statement, so no change will be applied while calling `drupal_goto()`, the redirection should be done differently I guess but I don't have any idea how to resolve that.
Comment: Isn't it because ajax callbacks are handled on the `system/ajax` menu route and thus issuing a `goto` won't have any effect? I would see if you could set a form state property and check that value in the form building method, if TRUE, try the goto.
Comment: Smart idea Kevin but sadly it generate an ajax error popup too, this time the source path of error is `/system/ajax`, what I did is in `my_ajax_callback()` I add `$form_state['redirect'] = TRUE;` instead of `drupal_goto()` call, and in my form builder I add `if (isset($form_state['redirect']) && $form_state['redirect']) { drupal_goto('login'); }`
Answer: I had the same problem. You should try this:
ctools_include('ajax');
ctools_add_js('ajax-responder');
$commands[] = ctools_ajax_command_redirect('login');
return array('#type' => 'ajax', '#commands' => $commands);

Comment: This should be marked as the right answer, works like a charm. Thanks @davide-bruner.


Learning error metrics

Question: We're using a decision tree based classifier that assigns record to one of two classes (true /false).
Model is producing answers with probability of this value.
So to check how good are answers the squared error is used
<code>(expected{0, 1} - result{0.0 .. 1.0})^2
</code>
This method gives quite good picture of learning curve, but the business problem is defined as find records that can be classified as "true" with highest probability. So from the business point of view even drastically biased results are ok, as long as records that are expected to be "true" gets even slightly higher ranks that those that are expected to be false.
My question is:
How to define metric to measure quality of this model from business point of view?
Answer: The business value may relate to some monetary value of wrong/bad decisions. You can introduce the prices of:

false positive
false negative
true positive
true negative

Then you can quantify the expected/average value of the classifier for any threshold. As a result, you can get the optimal threshold.
From the business perspective, it makes sense to evaluate also the quality of the existing decision-making mechanism and compare it with your classifier.

Learning error metrics


What is "\$@" in ssh command

Question: I am trying to do some ssh based git clone. While at it, I ran into a ssh command syntax some of which I don't understand:
ssh -i $pwd/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no "\$@"

What is this "\$@"?
Thanks!
Answer: $@ means all the parameters passed to the script, but this may be interpretted too early.
For passing it originally to ssh params, you need to escape it, and the simplest way is to escape the $ sign, which results in "\$@".

What is "\$@" in ssh command


Can I use output of classifier A as feature for classifier B?

Question: This is likely to be a confused question, but I'm curious if this is a valid way to combine classifiers.
I have a classification data set, i.e. column of labels and N columns of features, and I use a classifier (A) to generate a column of predicted labels. Can I turn around and use those labels as another feature for a second classifier (B)? That is, can I classify using classifier B with N+1 features, where the +1 feature is the output of classifier A? (Question 1)
A similar question was asked here about neural networks, but I think the answer was geared to unsupervised learning. I'm wondering if this is a valid way to combine classifiers for supervised learning, and why / why not.
If it is valid, is there any advantage / disadvantage to this "sequential" combination compared to simply combining the predictions of classifiers A and B "after the fact"? That is, predict labels with A, predict labels with B, and average or otherwise combine the predictions. (Question 2)
Comment: Yes, it's called stacking: https://en.wikipedia.org/wiki/Ensemble_learning#Stacking
Answer: Yes, using outputs of one model as inputs of another is possible, and this concept is used to some extent in some approaches.
If you stack models on top of each other, in the application case the model at position $n$ in the chain essentially does preprocessing/feature derivation for the model at position $n+1$. One advantage of this is that  more preprocessing and feature derivation conceptually increases the power of whole setup (lets just assume it's this way for simplicity) - hence more complex problems can be solved with such chains. But this will also make training more complex. The question will usually be: how to train this chain of models? Both at the same time? One after another? If supervised - which target variable to use for models not at last position in the chain?
Such thoughts lead to e.g. what we currently see in deep learning: one core concept of deep neural networks (deep nets) is that there are many layers, where each layer is an additional feature preprocessing/feature derivation that is embedded right into the model (therefore increases the models power). Conceptually, all layers could be trained together - which would lead to straight, supervised learning. But in practice, complexity issues usually prevent this. This is why some deep nets learn some layers individually, some learn parts in supervised manner, some in unsupervised manner, and most mix those concepts. Consider e.g. the learning process and information flow in deep believe networks, convolutional neural nets, or deep autoencoders. My guess is that those might get pretty close to what you had in mind when asking your question.
Sidenote: you might also want to look into the concept of boosting if you are not familiar with it yet. Boosting does not "chain" any models, but it uses the training error of one model to influence training of subsequent models - which turned out to be very effective in the past. Boosting in a nutshell: it assigns a weight to each sample at the start of training. After a model is trained and evaluated, samples that were classified wrong get their weights increased, while sample that were classified correctly get their weight decreased. The subsequent model uses those new weight in training, therefore lays more weight on samples that were classified wrong before. This process is repeated, and this way each model is influenced by its predecessor and focuses on the part of data that is "currently difficult to classify".


How to cast an output of a Filter in VTK in C++ with QT?

Question: I am using VTK to render an depth image, and have set up the connections. However, when it comes to saving the output of the renderer as png file I get the warning, that the PngWriter only supports unsigned char and unsigned short inputs.
vtkSmartPointer<vtkPNGWriter> imageWriter = vtkSmartPointer<vtkPNGWriter>::New();
imageWriter->SetInputConnection(zFilter->GetOutputPort());
imageWriter->SetFileName( qPrintable(QString("outdepth_%1.png").arg(i)) );
imageWriter->Write();

This is my code (inside a loop) , basically I need sth like (unsigned short) zFilter->GetOutputPort() - which of course does  not makye any sense at all, it is just for clarification what should be casted
Answer: You can use vtkImageCast to cast image from scalar type that zFilter produces to unsigned short.
For that purpose you can use vtkImageCast::SetOutputScalarTypeToUnsignedShort().
Your code will then look something like this:
vtkSmartPointer<vtkImageCast> cast = vtkSmartPointer<vtkImageCast>::New();
cast->SetInputConnection(zFilter->GetOutputPort());
cast->SetOutputScalarTypeToUnsignedShort();
vtkSmartPointer<vtkPNGWriter> imageWriter = vtkSmartPointer<vtkPNGWriter>::New();
imageWriter->SetInputConnection(cast->GetOutputPort());
imageWriter->Write();


Null value in DB displays content on page

Question: I have a blank category box on the bottom of the following page (http://www.suncorstainless.com/stainless-steel-hardware) and it appears that it's caused by a Null value in a table somewhere in my DB. I'm not the developer of this website and am having a hard time determining where this issue is in the DB.
Are there any tools available to determine the DB table that is displaying content on a page?
Thanks-in-Advance
Answer: Use the Devel module and enable it's database query log. See this question.
Comment: Thanks Thomas4019, Now I just have to figure out all of the output on that page. There are a ton of SELECt statements
Comment: Yes, Drupal does use many queries one a single page. Given your page I would look for queries that include something like "body", "title" or "image". You can also try executing the SELECT statements and see what they look like.


Need help with a second derivative question

Question: I am supposed to find the double derivative of
$$ f(x)=5x^2 + 2^x(\ln(3x)) $$
I got that the first derivative is
$$ 10x+2^x(1/x)+2^x*(\ln(2))(\ln(3x)) $$
I am stuck on the second derivative, I know I am supposed to use the product rule but I am unsure whether I did that rule correctly.
What I ended up with was the following:
$$10+ (2^x \ln(2))(1/x)+(2^x)(-1/x^2)+ (\ln(2))^2) 2^x (1/x) + ((2^x)(\ln(2)^2)) \ln(3x)$$
I know that the notation above looks weird and long, so please tell me if you have issues with the notation
Comment: See [this](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) typesetting guide to make your question clearer and easier to read.
Comment: is $y = 5x^2 + 2^x\, \ln(3x)$ this what you got?
Comment: that is the equation that I am supposed to find the second derivative for
Comment: why don't you do them separately; $5x^2$ first and  then $2^x\ln(3x)$ add the results up.
Comment: That is what I did. the 5x^2 is fairly simple and ends up being 10 in the second derivative. What I am having issues with is verifying that the second derivative of 2*ln(3x) was done right. It is everything to the right of the 10 in that last equation.
Comment: I think I see one mistake, the $(ln(2))^2$ next to the $2^x \cdot \frac{1}{x}$ . That particular term should be just $ln(2) \cdot 2^x \frac{1}{x}$.
Answer: it will make life easier if we call $\ln 3 = b, \ln 2 = a.$ i will find the second derivative of $$y = 2^x \ln(3x) = b 2^x + 2^x \, \ln x \\
y' = ba  2^x + 2^x \frac 1 x + a 2^x \ln x\\
y'' = ba^2 2^x -\frac {2^x}{x^2} + a\frac{2^x}{x} +a^2 2^x \ln x +  a\frac{2^x}{x} =  ba^2 2^x -\frac {2^x}{x^2} + 2a\frac{2^x}{x} +a^2 2^x \ln x$$
Answer: Introducing$$\begin{gathered}
  u(x) = 5{x^2},u'(x) = 10x,u''(x) = 10 \hfill \\
  p(x) = {2^x},p'(x) = \ln (2){2^x};p''(x) = \ln {(2)^2}{2^x} \hfill \\
  q(x) = \ln (3x),q'(x) = {x^{ - 1}},q''(x) =  - {x^{ - 2}} \hfill \\
  f(x) = u(x) + p(x) \cdot q(x) \hfill \\
\end{gathered}$$
and$$f''(x) = u''(x) + p''(x) \cdot q(x) + 2p'(x) \cdot q'(x) + p(x) \cdot q''(x)$$
for second derivative we get:
$$f''(x) = 10 + (\ln {(2)^2} \cdot \ln (3x) \cdot {x^2} + \ln (4) \cdot x - 1) \cdot \frac{{{2^x}}}{{{x^2}}}$$
The second derivative for product rule is a simply application of binomial theorem:
$$\frac{{{d^2}}}{{d{x^2}}}p \cdot q = \sum\limits_{k = 0}^2 {\left( {\begin{array}{*{20}{c}}
  2 \\
  k
\end{array}} \right)}  \cdot \frac{{{d^k}}}{{d{x^k}}}q \cdot \frac{{{d^{2 - k}}}}{{d{x^{2 - k}}}}p$$


calling a block views by ajax

Question: I have a views with three displays which sorts comments of a node in newest, oldest and most popular order. These views are shown below the content and works with contextual filters. I have used ajax_comment and rate and vote api module in order to add/reply comments by ajax and let users vote other people's comments too. Now I want to load one of these views at a time so I have created an HTML like this:
<select name="sort" onChange="return sort1()">
    <option value="newest">newest comments</option>
    <option value="oldest">oldest commenst</option>
    <option value="popular">most popular comments</option>
</select>

and a jquery code like this:

But it does not work.
I have tested quicktabs module too but comment reply link does not work with ajax_comment then. I have seen JQuery AJAX Load module too but it needs a url to load.
If my code is incorrect please correct it or if you have a better solution please let me know it.
Comment: When you say it doesn't work, what  part doesn't work? What debugging have you tried, for example did you test if the ajax call is being called?
Answer: I post my answer for anyone who is facing this problem. After all it worked by some changes:

newest comments

oldest commenst

most popular comments

<?php print views_embed_view('comments_views', 'block_3'); ?>

and jQuery code is:
function sort1(){
var nid='<?php echo $node->nid; ?>';
$.ajax({
    url: 'http://www.yoursitename.com/views/ajax',
    type: 'post',
    data: {
        view_name: 'comments_views', //view name
        view_display_id: 'block_3', //view display
        view_args: nid,   //view contexuall filter
    },
    dataType: 'json',
    success: function(response){
        //alert(response[1].data);
        $('#cm').html(response[1].data);
    }
});
    return false;
}

for each of the sort functions above it must be exist.

calling a block views by ajax


Distributing half a deck of cards

Question: 2 cards each are dealt to 5 persons from a half a deck of cards (with just 2 suits).
How many hands are there in which none of the 5 get a face card pair (KK, QQ or JJ), and what is the probability of such a hand ?
I am finding it difficult to count because of numerous branches.
Comment: This seems like an ideal problem on which to use the inclusion-exclusion formula.
Answer: Use inclusion/exclusion.  Let
$$\eqalign{
  {\cal U}&=\{\hbox{all possible deals}\}\cr
  K&=\{\hbox{deals in which someone gets two kings}\}\cr
  Q&=\{\hbox{deals in which someone gets two queens}\}\cr
  J&=\{\hbox{deals in which someone gets two jacks}\}\ .\cr}$$
Then the number of hands you want is
$$|\overline K\cap\overline Q\cap\overline J|=|{\cal U}|-|K|-|Q|-|J|
  +|K\cap Q|+|K\cap J|+|Q\cap J|-|K\cap Q\cap J|\ .$$
I'll calculate some of these and leave the rest for you.
To count $\cal U$,

choose two cards from $26$ for the first person. . . . . $C(26,2)$ ways
choose two cards from $24$ for the second person. . . . . $C(24,2)$ ways
and so on.

Hence
$$|{\cal U}|=C(26,2)C(24,2)C(22,2)C(20,2)C(18,2)\ .$$
To count $K\cap Q$,

choose the person who receives two kings. . . . . $5$ ways
choose the person who receives two queens. . . . . $4$ ways
choose cards for the others as above.

Hence
$$|K\cap Q|=5\times4\times C(22,2)C(20,2)C(18,2)\ .$$
See how you go with the rest.

Distributing half a deck of cards


data url image save as png

Question: Lets say I have this data url from Apple:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAANCAYAAABy6%2BR8AAAAlElEQVR42oWQQRHEIAxF10ElVAISVgo3bCABCUhYCZWAhEpAQpoD6bzJhNnDO0DyyA8fEXkppXyVCpLViDUfyqVIQN9JFMY637hrlCySFauL21E7KVWbAIGx56rnSLqc5KPXSLo3kySalPhTygFhRDtFC09EIsMeZJSGBj7Qveh3OJW89syImiH%2BIO2BOJX0XwA2%2BQEL4pAhSX4aBQAAAABJRU5ErkJggg%3D%3D

That I want to save as a png file.How do I do That?
Rightclicking and 'Save image as' is not working(Why?)
So I thought I should use a PHP script with the 'base64_decode' function:
    $img = "iVBORw0KGgoAAAANSUhEUgAAA9QAAAAkCAMAAABfcIIyAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAHVQTFRFAAAA%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F5YtmQAAAACd0Uk5TAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmZiD6WAAAAdlJREFUeF7t3btuFEEQheFzunotGYkIERA4spn3fyeHiAgEEtsXB82s2eEJavR%2F0Wjyo75XWfHpw4MkSXNqCkA2lr2%2B%2Fvz63n15qpI0x5yTSAM52XaxJLVXf%2FkoaY6xQk2sgXy8Ql2KJf3wS5HG6HMMQg3kZNkuxVGKNLxJo48%2BxhxTpBrIx7JcXEqUKJI3zd77CjWLaiAle4U6Iixv6q33MfocTL%2BBlCy7OEqJqCFvs%2FV2m3%2BTaiAd6zb7rlHtrbc1VA%2Bm30BSa%2B%2B7RNSo4a21thbVTL%2BBnCy7rCV1rdXbtbXW%2B%2Bh%2Ft78BZLM2v6NE1Fov%2FrpC3Zl%2BA2l5H6lrrRe%2FXNu%2BqCbUQE57qGvsoW5t9D4H028gJculOKLUWuvFz%2B16O9NipAZSsm8nWpfq53ZlTQ3k9s%2BamlADZ0CogZMh1MDJEGrgZAg1cDL%2Fh5ojLSC1%2ByMtLp8A2R0un3BNFEjv%2FpooDzqA9O4fdPD0Esju8PSSIglAdsciCZQzArI7lDOat30yCg8CGe2FB1eovZcI7oMSwUBSq0TwWlQHxfyBEzgW86ftDpDase0ODfKA7A4N8mhlC2R318r2px%2BeQqLpPJDae9P5%2FmrVz491%2FWekBlKy7PXVfn9rb9xXsMD2wdOcAAAAAElFTkSuQmCC";

header("Content-type: image/png");
echo base64_decode($img);

That is giving me back the broken image icon :

How should I solve this problem and save a data url image to a file?
Answer: Your code is fine, but your base64 is urlencoded. I urldecoded it for you: iVBORw0KGgoAAAANSUhEUgAAAA0AAAANCAYAAABy6+R8AAAAlElEQVR42oWQQRHEIAxF10ElVAISVgo3bCABCUhYCZWAhEpAQpoD6bzJhNnDO0DyyA8fEXkppXyVCpLViDUfyqVIQN9JFMY637hrlCySFauL21E7KVWbAIGx56rnSLqc5KPXSLo3kySalPhTygFhRDtFC09EIsMeZJSGBj7Qveh3OJW89syImiH+IO2BOJX0XwA2+QEL4pAhSX4aBQAAAABJRU5ErkJggg==
or do it yourself:
base64_decode(urldecode($img));
Comment: It works fine now -- you can paste it [somewhere like here](http://www.motobit.com/util/base64-decoder-encoder.asp) to test.

data url image save as png


Chamar a mesma função duas vezes

Question: estou testando uma função que abre pop-up para determinado link, e gostaria de chamar ela para 2 links em seguida, basicamente sua chamada é assim:
jsPopunder(URL);

Eu tentei criar um array com as URLs e chamar a função usando um laço de acordo com a quantidade, porém só funciona com a última URL  do array, como se tivesse reescrito todas as chamadas anteriores, como posso fazer a chamada da mesma função 2 vezes? como se fosse 2 locais diferentes na memoria.
Comment: Esse `jsPopunder` só permite 1 pop-up de cada vêz?
Comment: Infelizmente eu encontrei o script na net, não tem documentação, aparentemente sim.
Answer: como você não deu detalhes sobre o script jsPopunder.

var jsPopunder = function (url) {
  window.open(url);
};

[
  'http://google.com',
  'http://pt.stackoverflow.com',
  'http://example.com'
].forEach(jsPopunder);
Answer: Da um olhada nesse fiddle: jsFiddle
Abre as popup's conforme o número de itens no array:
var arr = ["http://www.google.com", "https://www.stackoverflow.com/"];

$("#links").click(function() {
  arr.forEach(function(e) {
    window.open(e, e, 'width=500,height=500');
  });
});

Answer: Para abrir as popups em locais diferentes na página
function jsPopunder() {
    window.open("http://www.google.com","PAGINA1",'scrollbars=no,width=235,height=155,left=100,top=200,screenX=100,screenY=200');
    window.open("https://www.stackoverflow.com/","PAGINA2",'scrollbars=no,width=235,height=155,left=1000,top=200,screenX=1000,screenY=200');
    //window.open("http://www.dominio.com/","PAGINA3",........
    //window.open("http://www.dominio.com/","PAGINA4",........
}

HTML
<button onclick="jsPopunder()">Abrir</button>

Chamar a mesma função duas vezes


Related Rates Cylinder - Increasing volume and calculating the rate that the height increases

Question: The question reads "Consider a circular cylinder of radius 1m and height 6m. We are filling the cylinder with oil at a rate of  $0.5  m^3 s^{-1}$. Assume the cylinder is sitting on its base. How quickly is the height changing when the liquid fills a quarter of the container?"
My attempt at the solution:
$V = \pi r^2h$
$\frac{dV}{dt} = \pi 1^2 \frac{dh}{dt}$
Substituting $0.5m^3s^{-1}$ for $\frac{dV}{dt}$
$0.5 = \pi \frac{dh}{dt}$
$\frac{dh}{dt} = \frac{0.5}{\pi}$
So I've arrived at a value for the rate of the increase of height, but I haven't used the fact that the question states that "the liquid fills a quarter of the container"
I'm not sure how to proceed from here to continue with the question.
Comment: I believe the quarter of the container part is simply extra information to confuse you and is unnecessary to solve the problem since the rate of fill is constant. The amount filled would only be necessary if the rate of fill varied with time as a way to determine how long it had been filling.
Answer: You have found that
$$h'(t) = \frac 1{2 \pi}$$
There's no $t$ on the right hand side, which means that $\frac 1{2 \pi}$ is the change in height regardless of the value $t$. So even if we call the time at which the liquid fills a quarter of the container $t_0^*$, we will still get $h'(t_0^*) = \boxed{\frac 1{2 \pi}}$.

*Extra credit: if we wanted to find $t_0^*$, what equation would we need to solve?


Displaying nested objects from JSON response

Question: This may be a simple fix but I'm new to react so I appologize in advance. I have nested data that I would like to display on a list. The data is being pulled and displayed below.
data: [
{
  "id": 1,
  "domain_url": "localhost",
  "created_on": "2020-05-26",
  "config": [
    {
      "test_name": "test",
      "test_description": "test",
    }
  ]
}
]

I can get the domain_url and created_on displaying just fine but nothing I've tried gets any of the config items to appear.
below is the current method I'm using.

  {this.props.data.map((data) => (

    {data.domain_url}

      {data.config.map((sub) => {
        sub.test_name;
      })}

    {data.created_on}

    ...

how can I get the test name from the config array to display? Any help would be appreciated. Thank you!
Comment: Your `data.config.map()` is not returning anything. Change the line to `return sub.test_name;`
Comment: thank you, I was unaware that I needed to return it very new to this. This solved it.
Comment: You can alternately eliminate the surrounding `{}`, like this: `data.config.map((sub) => sub.test_name)`. That does an implicit return of `sub.test_name`.
Answer: Your code looks right - I think you just need to add a 'return' in front of your 'sub.test_name;'


Learning a new piece -- tips to make sure to get all the notes accurately from the start (piano)

Question: As a self-learning piano beginner, I make tons of colored markings in the score of a new piece. First I must highlight all the notes that are included in the key signature so as not to forget they should be played with accidentals (since they don't have # or b directly next to them). Also, e.g. for Mozart's K545, 2nd movement, I need to mark to distinguish the variations of alberti basses, because the difference (or the lack thereof) from one to the next is hard to discern visually. Also I need to highlight when the lower staff changes from bass to treble or vice versa (sometimes I missed the change and played it wrong). I doubt anyone has scores with so many colored markings! (it's like using a diligent hand to help a lazy mind)
Is this common or not? Do others have the same issues as I do?  How to keep remembering the accidentals that are only universally included in the key signature? What about the subtle alberti bass change? etc.
What do you do to deal with such issues?  Thanks in advance.
Answer: If you have to do things like this in the beginning that's totally fine! It's awesome that you are learning and trying to improve.
The first thing I would recommend doing, is trying to slowly wean yourself off of writing in the accidentals from the key signature. When you feel ready, try looking up what the scale of that key signature is, and practice playing the scale, getting use to what it sounds like. With time, you will be able to know in general what something should sound like, and if you play a wrong note, you will be able to tell. The only exceptions to this sound in your head, will be the accidentals that are written into the score. This will come with training your musical ear, by playing more music and learning some theory.
When you eventually feel ready, I recommend learning what major and minor scales are, learning how they sound, and what some of the functions of particular notes in the scale are. Learning their shapes, the whole and half step patterns, and what notes have tendency towards other notes. This will really start reinforcing the information. (Important examples would be the leading tone and the tonic)
When I was younger (up through high school), and didn't know any theory, key signatures bothered me, and in my own transcriptions, I omitted them. Now I understand them and really like them. Hopefully that can be encouraging. Best of luck to you!
Not sure if this will have all you need, but this is a great free theory book to have as a resource on hand. http://musictheory.pugetsound.edu/mt21c/frontmatter.html
Comment: Thank you! I should remember this is music, not math... the ears should be used more than the eyes... Now I see how some knowledge of theory will help me..
Answer: The primary thing is to establish key notes before even trying to play. So work out what key the piece is in, then run up and down the scale involved, also arpeggios of at least I IV and V, hands separate and together if you can. That puts you in the right ball park for most of the notes - and tells which notes probably won't be played.
You won't be the first to use higlighters on the charts. I used to do the same with notes mentioned in the key signature. Nowadays, with a new piece of music, the first thing I do is mark repeats, DS/DCs and codas. Much easier to navigate when the whole thing is taking shape.
Comment: Thanks! And glad to know I'm not the only one using the highlighters... Will definitely start playing the scales on the key signature before playing the piece.
Answer: It is ok  to mark the lines and spaces as a reminder, but like Tim says you should play the scales and fundamental chords of each key before reading and practicing a piece! The goal is that you will train your ear and hear immediately when you miss an accidental or a key assignment, because you are "in the key" and know which is the home chord and its dominant and subdominant.
And alternatively I want to add that the best will be to notate the scale and chords by handwriting on a sheet before starting playing. Later you can also notate the chord progression on this sheet and try to memorize what you've been playing and compare it with the original.
Comment: As long as you need to mark the key signs and note names I'd notate the chords and also the names right at the place where the note heads are sitting, write whole note values. Later it will be  ok just to write the chord names above the staff of the original sheet, this analyze will help.
Comment: may be you it will provide you some insight studying this site:
https://music.stackexchange.com/questions/5382/what-is-the-difference-between-a-mode-and-a-scale
Comment: I've found that I've posted already my advices (I've promised to give you the other day) in my answer to this question: https://music.stackexchange.com/questions/53835/how-do-i-manage-internalizing-foundation-for-chords-scales-hamonies-and-voicin
Comment: Thanks. I still need to get familiar with the chord names. Right now I simply remember them using solfege "do so mi so", "re so fa so"..... must be very amateurish...
Comment: I will post you in the next days a copy of the basics that I gave to my school classes to become familiar with music system. Meanwhile you can look up some sites about music basics, elementary theory, scales, triads.
Comment: Look up also this answer: https://music.stackexchange.com/questions/94666/efficient-exercises-to-learn-scales
Comment: Thank you very much! So far I have read some about each scale and practiced the fingering of them. But I was only learning them separately and didn't connect them to the actual learning a piece, and the "sound" (I'm a math person). I did not understand the significance of learning each scale, major, minor, chord name, etc.. Until you mentioned, I didn't even know people notated the scores. I look forward to your post. Many thanks! --Thanks for the link; I'm going to read it.
Comment: Thank you for the helpful link! Especially the 2nd answer there by Robusto seems to be what I've been very much missing: thinking of the theories in terms of how things sound to the ear. Robusto mentions a Bernstein masterclass on youtube but that video is unavailable. What keywords should I use to search for more resources about this topic? 'tonality'?
Comment: Found the Bernstein masterclass: https://www.youtube.com/watch?v=8fHi36dvTdE


Combination: Selecting at least two cards, at least one from two non-exclusive sets.

Question: I'm trying to figure out probabilities of certain hands for a game I've been considering.  An example is the probability of having a card that is an Ace or King and a card that is a Heart or a Diamond, but it can't be just a single Ace of Diamonds alone.  There must be a card from each set.  It can be an Ace of Diamonds and an Ace of Hearts, though.  I.e. one fulfilling the rank and one fulfilling the suit.
I can figure the combinations that fulfill either set.  Assuming a 7 card hand:
Ace, King: ${52 \choose 7} - {52-4*2 \choose 7}$
Heart or Diamond: ${52 \choose 7} - {52-13*2 \choose 7}$
My issue is figuring at least one from each set, excluding ones where there is only one match, total, common between both sets.
I tried finding the combinations of the exclusive sets, the union with two, the union and each exclusive, but the non-exclusiveness and overlapping I've not been able to figure out.  I've gone through my probability and statistics books and tried searching the web, but the examples I could find were all for exclusive poker hands, etc.  I'm frustrated because I'm convinced it is so simple and yet I can't see it.
I'm also trying to figure out the probabilities of this success in various different sized hands to see what a reasonable hand size is.  I also have other success sets in mind, like the one above but also requiring say at least one Queen, etc., but I figure I can glean how to figure that if I knew how to think this one through the logic.
Thank you for considering this.
EDIT: re true blue anil, AH with AD would be a success.  As long as there is at least one unique card fulfilling each set, it is a success.
EDIT: My current line of attack is dividing the space into unique groups of hands: no good cards, 1+ cards in Set A but none in B, 1+ cards in set B but none in A, 1+ cards in A-B and 1+ cards in B-A, 1 card in A intersecting B but none outside of it, etc.  Then just add up the success hands.  I don't know if that will work, but I'm at a loss.
EDIT: See the accepted answer below, but wanted to post what I had figured as well for posterity.
I broke the space into four sets.
A $[2, .., Q] \oplus [\heartsuit, \diamondsuit]^T$
B $[A, K] \oplus [\spadesuit, \clubsuit]^T$
C $[A, K] \oplus [\heartsuit, \diamondsuit]^T$
D $[2, ..., Q] \oplus [\spadesuit, \clubsuit]^T$
Good hands are:
1) two or more C
$${A + B + C + D \choose 7} - \left( {A + B + D \choose 7 } + {C \choose 1} \times {A + B + D \choose 6} \right) $$
I count the number of ways to get only hands with no card in C at all and hands with one of the C cards and 6 cards from anything but C.  I subtract this from the total hands, and I have the hands with two or more C cards.
2) one C and any from A or B
$${C \choose 1} \times \left({A + B + D \choose 6} - {D \choose 6} \right)$$
Here, I count the number of hands having one of the C cards with the rest of the hand selected from and remaining cards not in C, but excluding hands that are only made of cards from D (leaving subsets with at least one A or B)
3) none from C and at least one from A and B each
$${A+B+D \choose 7} - \left( {A + D \choose 7} + {B + D \choose 7} \right)  + {D \choose 7}$$
Here I create my sub set of hands from all hands that don't contain C.  I then remove any hands that do not contain a B and any hands that do not contain an A.  I have to add back the same number of hands that contain only cards from D because I subtracted those hands in removing the A and B exclusions twice.
The accepted answer is much more concise, but I wanted to also show my work in case it helped someone somehow on a search of this.
Comment: "...excluding ones where there is only one match, total, common between both sets.", Does this mean that if you get $AH$ alone it's not ok, but two such, e.g. $AH$ and $AD$ is ok ?
Comment: Yes, as long as there is a card for each set, it's ok.  AH with AD is a success.
Answer: Calling aces and kings "high" cards and others "low", divide the cards as follows:
$A_1: 4\;$ high cards from hearts or diamonds
$A_2: 4\;$ high cards from spades or clubs
$B_1: 22\;$ low cards from hearts or diamonds
$B_2: 22\;$ low cards from spades or clubs
We shall count hands that don't fulfill both criteria, and then find the complement:
All $7$ from $(B_1\cup B_2)\cup(A_2\cup B_2): \binom{44}7 +\binom{26}7 -\binom{22}7$
$1$ card from $A_1$ and $6$ from $B_2:\binom{4}1\binom{22}6$
Now take the complement, $$\text{thus number of good hands}\; =\binom{52}7 - \left[\binom{44}7 + \binom{26}7 - \binom{22}{7} + \binom41\binom{22}6\right]$$
Comment: I think this allows for both cards to only come from one of the two sets, while none came from the other.  There must be a at least one unique card from set A and at least one unique card from set B.  i.e. two Hearts and no Ace or King is a failing case.
Comment: I have recast the answer.
Comment: Thanks.  I figured out a less sophisticated way and this gives to same results so I feel like there's a solid solution here.
Comment: Good for you :)


Show that $f_n(x)=\sqrt n\, x^n$ diverges in $\big( {\cal C}[0,1], d_2\big)$

Question: let $f_n\in{\cal C}[0,1]$ be given by
$f_n(x)=\sqrt n\, x^n$.
We choose a $g \in \mathcal C[0, 1]$, we know that $\|g\|_2 \geq 0$ and $\|g\|_2 \in \mathbb R$. We denote $\|g\|_2 = a \geq 0$.
I tried to calculate $d_2(f_n, g)$:
\begin{align*}
        d_2(f_n, g) & = \|g - f_n\|_2 \\
        % & = \left( \int_{0}^1 \left| g - f_n \right|^2 \right)^{1/2} \\
        & \geq \Big| \|g\|_2 - \|f_n\|_2 \Big| \qquad \text{ By Reverse Triangle Inequality}\\
        & = \left| \left( \int_{0}^1 |g|^2 \right)^{1/2} - \left( \int_{0}^1 |f_n|^2 \right)^{1/2} \right| \\
        & = \left| a - \sqrt{\frac{n}{2n + 1}} \right|
    \end{align*}
However, when $a = \frac{1}{\sqrt 2}$, that the above expression converges to 0 when $n \to \infty$. I can't seem to find an $\epsilon > 0$ such that $d_2(f_n, g) \geq \epsilon$ for all $g \in \mathcal C[0, 1]$.
How can I prove that $f_n(x)=\sqrt n\, x^n$ diverges in $\big( {\cal C}[0,1], d_2\big)$ if using the Reverse Triangle Inequality is not the correct way to prove it?
Comment: notice the norm / integral of $f_n$ might converge, but that does not mean that $f_n$ converges to a function in $C[0,1]$ in $d_2$. Notice that a limit is also a point wise limit almost everywhere. So the only candidate for limit is the zero function. But the distance to zero is...? :)
Answer: The point-wise limit is $0$ for $x <1$. If the sequence converges in $d_2$ the limit has to be $0$. But $\int|f_n(x)|^{2} dx =\frac n {2n+1} \to  \frac  1 2$. Hence the sequence does not converge.
$e^{t} \geq t$ for all $t \geq 0$. Put $t=n\ln (\frac 1 x)$ to get $\frac  1 {x^{n}} \geq n\ln (\frac 1 x)$ or $0 \leq \sqrt n x^{n} \leq \frac  1{ \sqrt n \ln (\frac 1 x)}$.  Hence the point-wise limit is $0$.
Alternative proof of almost everywhere convergence: If $y >1$ the $y^{n} =(1+(y-1)^{n}) >n(y-1)$ by Binomial expansion of $(1+(y-1))^{n}$. Hence $\frac {\sqrt n} {y^{n}} <\frac {\sqrt n} {n(y-1)} \to 0$. Put $y=\frac 1  x$ to see that $f_n(x) \to 0$ for all $x \in [0,1)$.
Comment: Can you elaborate on "the point-wise limit is 0" and "the sequence converges in $d_2$ the limit has to be 0"? I know that $d_2(f_n, 0) = \sqrt{\frac{n}{2n+1}}$. The limit for $d_2(f_n, 0)$ is $\frac{1}{\sqrt{2}}$. Thus, $f_n$ does not converge to the zero function.
Comment: @Benjamin Answer edited.


Specifying the type property in a link statement

Question: In a HTML file when linking to a stylesheet document, not specifying the type property makes any difference to the output or makes it more time efficient?
For example:
<link rel="stylesheet" type="text/css" href="mystyle.css">

and
<link rel="stylesheet" href="mystyle.css">

Comment: Posible duplicate https://stackoverflow.com/questions/5409114/is-type-text-css-necessary-in-a-link-tag
Answer: You can find discussion about type attribute relevance here.
From that, you can deduce that this attribute is not required. Before HTML5 it was required, but in HTML5 it was dropped.
It doesn't make any difference if you are using this attribute or not.
Answer: It's not required with the HTML5 spec, but for older versions of HTML is it required.
I have run so far into no problems with compatibility even when testing older versions of IE.


Delete link in gridview deleting all row

Question: I am facing a problem with my gridview as the Delete link is deleting all the rows where i want to delete one by one. I have record my screen that may exolain more about my problem
https://www.youtube.com/watch?v=VAh0A-UOafU&feature=youtu.be
  <asp:GridView ID="FavoritGRDSHOW" runat="server" AllowPaging="True"
       DataKeyNames="FavID" DataSourceID="FavoriteGRDView"
       PageSize="6" Width="600px">
       <Columns>
          <asp:CommandField ShowDeleteButton="True" ButtonType="Image"
               DeleteImageUrl="~/iconsimg/Delete2.png" />
          <asp:BoundField DataField="FavID" HeaderText="FavID"
               InsertVisible="False" ReadOnly="True" SortExpression="FavID" />
          <asp:BoundField DataField="AdsID" HeaderText="AdsID"
               SortExpression="AdsID" />
          <asp:BoundField DataField="UID" HeaderText="UID" SortExpression="UID" />
          <asp:BoundField DataField="AdsTit" HeaderText="AdsTit"
               SortExpression="AdsTit" />
       </Columns>
   </asp:GridView>
   <asp:SqlDataSource ID="FavoriteGRDView" runat="server"
        ConnectionString="<%$ ConnectionStrings:BeravaConnectionString %>"
        SelectCommand="SELECT [FavID], [AdsID], [UID], [AdsTit] FROM [favourite]
                        WHERE ([UID] = @UID)"
        OldValuesParameterFormatString="original_{0}"
        DeleteCommand="DELETE FROM [favourite] WHERE [FavID] = FavID" >
        <SelectParameters>
          <asp:SessionParameter Name="UID" SessionField="UsrNme" Type="String" />
          </SelectParameters>
    </asp:SqlDataSource>

Answer: Your delete statement:
DELETE FROM [favourite] WHERE [FavID] = FavID

Is equivalent to this, because every record is going to match its own fields:
DELETE FROM [favourite]   // deletes all rows in the table

You need to specify which ID to delete and pass it as a parameter:
<asp:SqlDataSource ID="FavoriteGRDView" runat="server" ConnectionString="<%$ ConnectionStrings:BeravaConnectionString %>"

     DeleteCommand="DELETE FROM [favourite] WHERE [FavID] = @FavID">

     <DeleteParameters>
         <asp:Parameter Name="FavID" Type="Int32" />
     </DeleteParameters>

</asp:SqlDataSource>

You can read more here.
Answer: use this:
<asp:SqlDataSource ID="FavoriteGRDView" runat="server" ConnectionString="<%$ ConnectionStrings:BeravaConnectionString %>"

     DeleteCommand="DELETE FROM [favourite] WHERE [FavID] = @FavID">

     <DeleteParameters>
         <asp:ControlParameter ControlID="FavoritGRDSHOW" PropertyName="SelectedValue" Name="FavID" Type="Int32" />
     </DeleteParameters>

</asp:SqlDataSource>