Issues updating from 9.4.3 with composer

Question: I have a project that wasn't updated since a few months and I am stuck on 9.4.3 with composer refusing to update.
Here is my composer.json
{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 9 projects with Composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "php": ">=7.3",
        "buzzingpixel/twig-switch": "^1.0",
        "composer/installers": "^1.9",
        "cweagans/composer-patches": "^1.7",
        "drupal/admin_toolbar": "^3.0",
        "drupal/auto_entitylabel": "^3.0@beta",
        "drupal/better_exposed_filters": "^5.0@beta",
        "drupal/better_social_sharing_buttons": "^3.2",
        "drupal/ckeditor_media_embed": "^1.11",
        "drupal/ckeditor_youtube": "^1.3",
        "drupal/components": "^2.2",
        "drupal/console": "~1.0",
        "drupal/core-composer-scaffold": "^9.1",
        "drupal/core-recommended": "^9.1",
        "drupal/devel": "^4.1",
        "drupal/editor_advanced_link": "^2.0",
        "drupal/eu_cookie_compliance": "^1.19",
        "drupal/fontawesome": "^2.18",
        "drupal/gin": "^3.0@beta",
        "drupal/gin_toolbar": "^1.0@beta",
        "drupal/google_analytics": "^4.0",
        "drupal/jquery_minicolors": "^1.3",
        "drupal/mailchimp": "^2.0",
        "drupal/migrate_plus": "^6.0",
        "drupal/migrate_source_csv": "^3.5",
        "drupal/migrate_tools": "^6.0",
        "drupal/paragraphs": "^1.12",
        "drupal/pathauto": "^1.8",
        "drupal/quick_node_clone": "^1.14",
        "drupal/rabbit_hole": "^1.0@beta",
        "drupal/radix": "^4.10",
        "drupal/recaptcha": "^3.0",
        "drupal/search_api": "^1.20",
        "drupal/search_api_db": "^1.20",
        "drupal/search_api_page": "^1.0@beta",
        "drupal/signature_field": "^2.1",
        "drupal/token": "^1.9",
        "drupal/views_bootstrap": "^4.3",
        "drupal/views_bulk_edit": "^2.5",
        "drupal/views_bulk_operations": "^4.1",
        "drupal/views_simple_math_field": "^3.0",
        "drupal/webform": "^6.0",
        "drupal/weight": "^3.3",
        "drush/drush": "^10.3",
        "kint-php/kint": "^3.3",
        "twig/twig": "2.15.2",
        "vlucas/phpdotenv": "^5.1",
        "webflo/drupal-finder": "^1.2"
    },
    "require-dev": {
        "drupal/core-dev": "^9.1",
        "zaporylie/composer-drupal-optimizations": "^1.2"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "discard-changes": true,
        "sort-packages": true,
        "allow-plugins": {
            "composer/installers": true,
            "dealerdirect/phpcodesniffer-composer-installer": true,
            "drupal/console-extend-plugin": true,
            "cweagans/composer-patches": true,
            "drupal/core-composer-scaffold": true,
            "zaporylie/composer-drupal-optimizations": true
        }
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ],
        "files": [
            "load.environment.php"
        ]
    },
    "scripts": {
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "drupal-scaffold": {
            "locations": {
                "web-root": "web/"
            }
        },
        "installer-paths": {
            "web/core": [
                "type:drupal-core"
            ],
            "web/libraries/{$name}": [
                "type:drupal-library"
            ],
            "web/modules/contrib/{$name}": [
                "type:drupal-module"
            ],
            "web/profiles/contrib/{$name}": [
                "type:drupal-profile"
            ],
            "web/themes/contrib/{$name}": [
                "type:drupal-theme"
            ],
            "drush/Commands/contrib/{$name}": [
                "type:drupal-drush"
            ]
        },
        "composer-exit-on-patch-failure": true,
        "patchLevel": {
            "drupal/core": "-p2"
        },
        "patches": {
            "drupal/devel": {
                "Brings back the Available Methods & Properties tabs for Kint dumps — Issue #221": "https://raw.githubusercontent.com/politsin/snipets/master/patch/kint.patch"
            },
            "drupal/better_exposed_filters": {
                "Fix error with exposed filters arguments": "https://www.drupal.org/files/issues/2020-09-18/3159875-8.patch"
            },
            "drupal/better_social_sharing_buttons": {
                "HTMLSpecialChars error on login page": "https://www.drupal.org/files/issues/2021-06-22/3216304-4.patch"
            },
            "drupal/search_api_page":  {
                "PHP 8.1 strpos() error": "https://www.drupal.org/files/issues/2022-05-31/3274050-4-php-8-warning-pathprocessorsearchapipage.patch"
            }
        }
    }
}

If I run the following, it just doesn't update anything.
$ composer update "drupal/core-*" --with-all-dependencies

So I tried:
$ composer why-not drupal/core 9.4.12
drupal/core-recommended  9.4.3  requires  drupal/core (9.4.3)

And also:
$ composer prohibits drupal/core-recommended 9.4.5
drupal/core-recommended         9.4.5        requires          drupal/core (9.4.5)
drupal-composer/drupal-project  dev-develop  does not require  drupal/core (but 9.4.3 is installed)

And also with 9.5.7 which is the recommended version I see from the admin:
$ composer prohibits drupal/core-recommended 9.5.7
drupal/core-recommended         9.5.7        requires          drupal/core (9.5.7)
drupal-composer/drupal-project  dev-develop  does not require  drupal/core (but 9.4.3 is installed)
drupal/core-recommended         9.5.7        requires          laminas/laminas-diactoros (~2.14.0)
drupal-composer/drupal-project  dev-develop  does not require  laminas/laminas-diactoros (but 2.11.3 is installed)
drupal/core-recommended         9.5.7        requires          laminas/laminas-stdlib (~3.11.0)
drupal-composer/drupal-project  dev-develop  does not require  laminas/laminas-stdlib (but 3.7.1 is installed)
drupal/core-recommended         9.5.7        requires          symfony/polyfill-ctype (~v1.27.0)
drupal-composer/drupal-project  dev-develop  does not require  symfony/polyfill-ctype (but v1.25.0 is installed)
drupal/core-recommended         9.5.7        requires          symfony/polyfill-iconv (~v1.27.0)
drupal-composer/drupal-project  dev-develop  does not require  symfony/polyfill-iconv (but v1.25.0 is installed)
drupal/core-recommended         9.5.7        requires          symfony/polyfill-intl-idn (~v1.27.0)
drupal-composer/drupal-project  dev-develop  does not require  symfony/polyfill-intl-idn (but v1.25.0 is installed)
drupal/core-recommended         9.5.7        requires          symfony/polyfill-intl-normalizer (~v1.27.0)
drupal-composer/drupal-project  dev-develop  does not require  symfony/polyfill-intl-normalizer (but v1.25.0 is installed)
drupal/core-recommended         9.5.7        requires          symfony/polyfill-mbstring (~v1.27.0)
drupal-composer/drupal-project  dev-develop  does not require  symfony/polyfill-mbstring (but v1.25.0 is installed)
drupal/core-recommended         9.5.7        requires          symfony/polyfill-php80 (~v1.27.0)
drupal-composer/drupal-project  dev-develop  does not require  symfony/polyfill-php80 (but v1.25.0 is installed)
drupal/core-recommended         9.5.7        requires          twig/twig (~v2.15.4)
drupal-composer/drupal-project  dev-develop  requires          twig/twig (2.15.2)

Any idea what is going on? I am having a hard time figuring out what prevents the update.
Comment: I think it's not a good idea to post an entire composer.json before it was cleaned up. For example, why did you pin twig/twig to a specific version, why you still need aporylie/composer-drupal-optimizations, are all beta versions still maintained?
Comment: @4uk4 Thanks for the feedback. I had to require that specific Twig version because of an issue with one of the themes (Claro). I have disabled the theme now and removed Twig but still no luck.
Answer: As soon as you remove twig/twig from your composer.json it will work.
$ composer remove twig/twig --no-update
$ composer update "drupal/core-*" --with-all-dependencies

(You then need to update the patches, but that's a different issue. Also move drupal/devel and kint-php/kint to require-dev, this should never land on prod. Aaand you should also update your PHP and update the PHP requirement in the composer.json then.)
Comment: Unless you're comfortable working through this stuff yourself, it's probably best to bite the bullet, delete composer.lock, run composer install, and deal with testing the changes to any contrib module updates that result. Trying to debug and work through this in a back-and-forth in the comments here isn't likely to get anyone a useful a result
Comment: Oh boy! Thanks @Clive, that actually did the trick. I deleted the lock file, ran `composer install` and it locked all modules, upgraded what needed to be upgraded, including `Upgrading drupal/core-recommended (9.4.3 => 9.5.7)` and all seems fine! If you wish to provide this as an answer, feel free! Thanks
Comment: Most times a simple `composer update` will do the trick, too. After of course, you've resolved the main problem, the twig/twig version @leymannx successfully reproduced, and after removing all outdated packages.
Comment: Thanks but still no luck. I am on PHP 8.1.9 now, and updated the PHP requirement to `"php": "^7.3||^8.0"` but running the composer update leads to *Nothing to install, update or remove*.
Comment: @MrUpsidown – I used your composer.json when trying. There must be errors that are different than `no luck` . Please update your question with the progress.
Comment: Hi, yes, I agree. I am still on it and still haven't found what the issue is but it's difficult to update my question with all my attempts. I undesrtand it's not a great question and it's hard to deal with it. I'll try what @Clive suggested. I have tried replacing the modules that are in beta but so far no progress.
Comment: @MrUpsidown Glad you got it sorted :) I'd tend to agree with 4k4, the strict answer to the question is what leymannx has provided here - composer install/update is kind of Composer's equivalent of Drupal's "clear the cache"
Comment: All right. Thanks everyone for your help!


Postfix port 25 unavailable

Question: Is there a condition or state that Postfix can enter that will prevent connectivity on port 25?
Am using Javamail to send to postfix as the local MTA, which works about 99% of the time. However, I will occassionally see an exception like:
<code>javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
    java.net.ConnectException: Connection refused
</code>
So, is it possible one of the queues is filling up and causing this? Is there a state Postfix could be in that will actively refuse a local connection?
Thanks in advance!
Comment: Anything in the postfix logs?
Comment: Could you explain slightly more what your program is doing? If you're trying to send thousands of emails programmatically, it is possible you're flooding postfix with too many connection requests? More info generally would help.
Comment: Have you tried turning it off and on?
Comment: Yuo need to show the *postfix* logs pertaining to this issue.
Comment: Going to get access to the logs. It is on a system where the log location has been restricted, so I need to get access via someone else.
Answer: Connection refused usually means that the service is not listening on that port. In your case postfix was not running when you have seen that exception.
If postfix is to slow you will receive a timeout exception.
When an application is slow and is listening, the TCP connection will be established by the TCP subsystem, the kernel will dispatch the request to the application. The client will wait for the server answer until a timeout will occur (timeout that is configured in the application).
Comment: It means you received a TCP RESET packet.  The OS will send one of those if the server is not listening on that port but there are other reasons they can be sent, such as TCP errors and firewall rules.
Comment: I know. But, if nothing was changed at the network level, then the application is not listening. It could be also ICMP port unreachable or ICMP destination host unreachable.
Answer: If the connection is refused you need to check the logs to find out why.
If it works 99% of the time, then it's not a firewall issue. Postfix should be able to handle most loads without dying on you...if this is intermittently showing up in the logs, then it seems to be recovering. I'd look at the timestamp on the failed connection and match it to your logs in Postfix and see what happens around that time.

Postfix port 25 unavailable


Is it possible to run the same set of independent variables with different outcome variables?

Question: I was wondering if it is possible to make any economic implications by regressing the same set of independent variables with different outcome variables.
For instance, running [Industry, Years, Production Level] on [Revenue, Profits].
If it is, what are the appropriate regression models? Are there any concerned issues regarding the results?
Given the above variables, if both models are significant, what would be the implications? Does it imply that [Industry, Years, Production Level] can be used to explained both the change of [Revenue, Profits].
Comment: I think there are potential on-topic statistical questions here, but you may want to narrow & focus your question more. Be aware that there is an [economics.SE] SE where you can ask questions about the theoretical implications of different results. Those questions are off-topic here, & conflating the statistical issues with economic ones muddles both.
Answer: Your question belongs to a well-studied statistical (or machine learning) problem, called multi-task learning, which

learns a problem together with other related problems at the same time, using a shared representation. ... It does this by learning tasks in parallel while using a shared representation; what is learned for each task can help other tasks be learned better.

The above states the rational of multi-task learning.
Depending on the type of your outcome variables, linear or logistic regression models are both applicable to multi-task learning. The design matrix (formed by your independent variables) will be used in separate regressions for each of your outcome variables, with the coefficients grouped across the outcomes. Therefore, this problem would be transformed into a grouped variable selection problem, which is among the hottest research topics in statistics in high-dimensional settings. Existing R packages (like grpreg) that conduct grouped variable selection (using methods like group lasso, group MCP, etc.) can be used for your purpose.
For your last part of question,

Given the above variables, if both models are significant, what would be the implications? Does it imply that [Industry, Years, Production Level] can be used to explained both the change of [Revenue, Profits].

The answer would be "Yes" based on your assumption.
Note that under the grouped variable selection setting, it's possible to also formulate this problem as what's equivalent to bi-level variable selection. In that case, some coefficients of [Industry, Years, Production Level] will be allowed to be zero for different task, meaning different sets of variables explain the change of different task.


Gerar tags com constantes usando XStream em Java

Question: Olá preciso gerar um xml com tags em maiúsculas que teriam que ser necessariamente atributos final na classe modelo para gerar o xml.
Para fazer isso, estou tentando utilizar a API XStream do Java.
Porém sendo estas tags final não consigo gerar, um construtor nem criar seus sets, pois são privadas?
Há alguma maneira de eu resolver com XStream mesmo ou seria melhor outra API Java para resolver o problema?
Aqui o modelo de classe que eu precisaria.
Se eu deixar os atributos sem final, ficariam estranho por necessitar que minhas tags no xml, obrigatoriamente precisem ser maiúsculas?
public class Metadados {
  private final String NOME_USUARIO;
  private final String IDADE_USUARIO;
  private final String NUMERO_PROTOCOLO;
}

Meu XML precisaria sair assim:
<NOME_USUARIO>Paulo</NOME_USUARIO>
<COD_USUARIO>36</COD_USUARIO>
<COD_PROTOCOLO>20170111092247</COD_PROTOCOLO>

Answer: Uma opção pra não precisar declarar seus atributos em letra maiúscula e com modificar de acesso final, seria a utilização da anotação @XStreamAlias("nome do atributo").
Exemplo:
@XStreamAlias("NOME_USUARIO")
private String nomeUsuario;

Veja mais na documentação.

Se o atributo precisa ser necessariamente final, não faz sentido existir um setter pois o modificador de acesso "final" indica que o valor de seu atributo não pode ser alterado após ser inicializado.
@XStreamAlias("metadados")
public class Metadados {

    private final String NOME_USUARIO;
    private final String IDADE_USUARIO;
    private final String NUMERO_PROTOCOLO;

    public Metadados(String NOME_USUARIO, String IDADE_USUARIO, String NUMERO_PROTOCOLO) {
        this.NOME_USUARIO = NOME_USUARIO;
        this.IDADE_USUARIO = IDADE_USUARIO;
        this.NUMERO_PROTOCOLO = NUMERO_PROTOCOLO;
    }

    public String getNOME_USUARIO() {
        return NOME_USUARIO;
    }

    public String getIDADE_USUARIO() {
        return IDADE_USUARIO;
    }

    public String getNUMERO_PROTOCOLO() {
        return NUMERO_PROTOCOLO;
    }
}

Gerando o xml com XStream:
XStream xstream = new XStream(new DomDriver("UTF8", new NoNameCoder()));
xstream.processAnnotations(Metadados.class);
String xml = xstream.toXML(new Metadados("nome", "20", "123456"));
System.out.println(xml);

Resultado:
<metadados>
    <NOME_USUARIO>nome</NOME_USUARIO>
    <IDADE_USUARIO>20</IDADE_USUARIO>
    <NUMERO_PROTOCOLO>123456</NUMERO_PROTOCOLO>
</metadados>


Adjacent JSX elements must be wrapped in an enclosing tag React Native

Question: I'm a beginner in React Native trying to test out TouchableOpacity. I keep getting this error code 'Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...? (16:4)'
The issue seems to be at the opening TouchableOpacity tag.
I've already tried putting fragments around it but it didn't work does anyone know how I fix this??
import React from 'react';
import { Text, StyleSheet, View, Button, TouchableOpacity } from 'react-
   native';

const HomeScreen = () => {
  return (

  <View>
    <Text style={styles.text}>Sup boiz</Text>
    <Button
      onPress={() => console.log('Button pressed')}
      title="Go to components demo"
    />
    <TouchableOpacity onPress={ () => console.log('List Pressed')>
        <Text>Go to List demo</Text>
    </TouchableOpacity>

  </View>

  );
};

const styles = StyleSheet.create({
  text: {
    fontSize: 30
  }
});

export default HomeScreen;

Comment: You're missing the closing curly brace in your `onPress` call in the TouchableOpacity tag.
Comment: You have syntax errors in your code, that's probably the issue
Comment: bruh, use a linter.
Comment: damn i didnt even see that thanks
Answer: <TouchableOpacity onPress={ () => console.log('List Pressed')}>
        <Text>Go to List demo</Text>
</TouchableOpacity>

Simple syntax error. It should be onPress={ () => console.log('List Pressed')}
You missed }


online radio with jQuery and the jPlayer

Question: I followed the instructions as given on this site http://www.catswhocode.com/blog/how-to-create-an-online-radio-using-jquery-and-jplayer and made the radio as stated in the link but i have a question that i want to do shoutcast streaming with the help of http://www.listen2myradio.com/ on the same jplayer but i want any one to help me with the code as i want jplayer to stop playing from database automaticaly when shoutcast starts streaming and when streaming is off it should again start playing form the database.
2nd thing is that the jplayer randomly selects the song for every listener so its kind of unusual for a radio as radio plays one song at a time for all listeners so i want to know is their any way that jplayer randomly select a song from database and play it for all listeners and repeat the same procedure.
Comment: You want to make it play the same song but a random song for all users? You can do it when the first song is started, maybe put it in the database and get it back for all other users... But i don't think it's the right way to create an online radio
Answer: If you want a traditional internet radio service (all users hearing the same thing at the same time) you should encode a stream server-side.  Clients then connect to the server which sends them the stream data as it is being encoded.
Typically, you will use SHOUTcast/Icecast for this.  For encoding, you can use a variety of software.  I personally use Edcast.  For audio playback, I typically use VLC.


Creating Preprocess function to add extra classes dependent on field value

Question: I have a content type called "article" and I have a field called "text color" and I want to add this text color field's value as a class to either the body or content container and change the text color of the content.

Which preprocess function should i go about using?
Is it possible to just do an inline style using the text color field's value so i don't have to also edit my css file too?
Or is there another elegant way of doing this without using a preprocess function?
Answer: You can add the class to the body from the node field value in hook_preprocess_html
Something like:
/**
 * Implements hook_preprocess_html
 */
function THEME_preprocess_html(&$vars){
  // Check if on an article node page
  if($node = menu_get_object('node') && $node->type == 'article'){
    // Get field values
    if($text_color = field_get_items('node', $node, 'field_text_color')){
      // Add first text_color value to body class
      $vars['classes_array'][] = drupal_html_class(reset($text_color));
    }
  }

}


Categorical Data Analysis or ML methods?

Question: What is the difference between classical categorical data analysis (as taught by e.g. Agresti's book Categorical Data Analysis) and the classification-related methods from ML (as taught by e.g. The Elements of Statistical Learning: SVM, Bayesian classifiers, etc )?
Based on what little I know, they both seem to deal with statistical regression-like problems where $Y$ is categorical, so what are the differences in the methods taught and their applications?
Somebody told me that the ML-approach is the modern approach that everybody is using these days, and the Agresti-book is outdated, theoretical stuff that I shouldn't bother with. Is this correct?
Answer: In my field (sociology) Machine Learning techniques are very very very rare, and the techniques from Agressti's book are dominant, and I don't expect that to change. I don't think one is replacing the other, they are different tools for different problems. Roughly speaking Machine Learning is good when you want to predict, categorical data analysis is good when you want to explain. My field is much more interested in explaining.
In specific fields there is a lot of enthusiasm about Machine Learning, but at the risk of sounding old: we have seen such phases before. (anybody remember fractals and chaos theory) The good thing about such a phase is that a lot of work on that specific topic gets done. However, the enthusiasm will eventually die down when it becomes clear that the results will be nowhere near is world changing as initially prophesied. After that the topic will find it's own niche, and be useful in that niche.
Comment: ML is a "niche" used in "specific fields"? It's already used all over the place - the most obvious example being every time you go online you're interacting with ML algorithms. I'd recommend reading "The Master Algorithm" for a more - up to date - perspective on ML. It may not end up being the cure all some claim, but it's already an enormously useful tool in many many areas and likely will make its way into your field. Without being rude, when CDA started to make its way into your field, I'm sure there were people talking about it like you are taking about ML right now.
Comment: "when CDA started to make its way into your field, I'm sure there were people talking about it like you are taking about ML right now" That is incorrect. I wasn't there myself, but I have talked to many people who were there, and they reported a ready acceptance of these techniques, and I find that plausible. My sub-field is very methodologically interested. One could legitimately argue too much so, as it takes too much time away from the actual substance. However, the new method has to add something to our understanding of the problem, and ML just isn't made for that.
Comment: This isn't a critique of ML, just as it isn't a critique of a hammer that it is awful at dealing with screws.
Comment: I accept you know infinitely better about your field than I ever will. So it may only find it's "niche" in your field, although I suspect it could be more significant than that as future developments come, but it's already bigger than a niche in general, and growing rapidly. I'm more just surprised about your broad claims outside of your field, which are already demonstrably not correct.


Nested Dictionary - Targeting Individual Keys

Question: I appreciate there are lots of this type of question around here but I've not been able to find a feasible answer.
Put simply, I need to get an array of Prices for all products within a chosen category.
Here is my pList:
<key>Product Category</key>
    <dict>
        <key>Product 1</key>
        <dict>
            <key>Image</key>
            <string></string>
            <key>Large Image</key>
            <string></string>
            <key>Detail</key>
            <string></string>
            <key>Price</key>
            <integer>100</integer>
        </dict>
        <key>Product 2</key>
        <dict>
            <key>Image</key>
            <string></string>
            <key>Large Image</key>
            <string></string>
            <key>Detail</key>
            <string></string>
            <key>Price</key>
            <integer>200</integer>
        </dict>
    </dict>

I have no idea how to target deep within a hierarchy like this. Here is my attempt so far:
NSString *detailPListPath = [[NSBundle mainBundle] pathForResource:@"detail" ofType:@"plist"];
NSDictionary *detailDictionary = [NSDictionary dictionaryWithContentsOfFile:detailPListPath];
currentDetail = [[NSMutableArray alloc] init];

for (id object in [detailDictionary objectForKey:indication]) {
    [currentDetail addObject:object];
}

But then currentDetail just shows Product 1, Product 2 etc.
Thanks for any help you can offer!
Answer:
currentDetail just shows
  Product 1, Product 2 etc.

Since fast enumeration of a NSDictionary iterates over the keys, you are adding the keys to the array. Hence, your output shows Product 1, Product 2, etc.

I need to get an array of Prices for
  all products within a chosen category.

You need to use these keys (Product 1, Product 2, etc.) to retrieve the associated product dictionary and then retrieve the value associated with the Price key:
NSDictionary *detailDict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"detail" ofType:@"plist"]];
NSDictionary *categoryDict = [detailDict objectForKey:@"Product Category"];
NSMutableArray *pricesArray = [NSMutableArray arrayWithCapacity:[categoryDict count]];
for (NSString *key in categoryDict) {
    [pricesArray addObject:[[categoryDict objectForKey:key] objectForKey:@"Price"]];
}

Bear in mind that the resulting pricesArray is in no specific order.
Comment: You didn't just show me a solution, you taught me a lot about how to access deep dictionaries. Cheers mate, your a lifesaver!


A/B split/bucket testing with three or more variants

Question: Let's say I have three search engine e.g. search engine A, search engine B and search engine C.
Each search engine is given a set of queries Q (e.g. apple,banana,carrot....), this set Q remains the same for each engine.
Each engine then provides a set of results for each query in the form a SERP (search engine results page).This means for every query (q) we have three search engine results pages (SERPs).
We have recruited 4 users lets say, and each user is given multiple sets of queries and their paired SERPs, and asked to rank each SERP for a query all of the queries in terms of relevance on a scale of 1-4 (1 being not relevant, 4 being very relevant).
So user one will see and rank accordingly:
query 1(apple), SERP A (relevance 1), SERP B(relevance 1), SERP C(relevance 4)
query 2(banana), SERP A (relevance 2), SERP B(relevance 2), SERP C(relevance 4)
query 3(carrot), SERP A (relevance 3), SERP B(relevance 2), SERP C(relevance 3)

User two will see and rank as follows:
query 1(apple), SERP A(relevance 1), SERP B(relevance 2), SERP C(relevance 3)
query 2(banana), SERP A(relevance 1), SERP B(relevance 2), SERP C(relevance 4)
query 3(carrot), SERP A(relevance 3), SERP B(relevance 2), SERP C(relevance 3)

User three will see and rank as follows:
query 1(apple), SERP A(relevance 1), SERP B(relevance 2), SERP C(relevance 3)
query 2(banana), SERP A(relevance 2), SERP B(relevance 2), SERP C(relevance 3)
query 3(carrot), SERP A(relevance 3), SERP B(relevance 3), SERP C(relevance 4)

I was wondering if there was a measure that I could use to say which search engine produced the most relevant search results over a set of queries, based on the the scores the users gave. Would Chi-squared or an analysis of variance (ANOVA) be appropriate?
At a quick glance if this was A/B split testing I guess I would say results generated by search engine C provided better results than A or B, whilst B provided better than A. Am I correct in saying this and what would be the best to test to formally write this down??
Answer: It looks like a Friedman Test would be most suitable if I average all scores for each user for each search engine.


Javascript: Difference in Regex String and Regex

Question: I have to put a given variable into a regular expression. When I do it with hard coded data it works. Here is my code for that
/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9@#$-/:-?{-~!"^_`\[\]])+((?!ccarn).)*$/

This should ( and does ) look for a word (password in this case) that is case sensitive, has at least one capitol and one lowercase letter, and one number or symbol. It cannot, however, contain the word "ccarn" in it. Again when I put this in as my regex all works out. When I try to turn it into a string that gets passed in, it doesn't work. Here is my code for that
var regex = new RegExp('/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9@#$-/:-?{-~!"^_`\[\]])+((?!' + $scope.username + ').)*$/');

I feel like I may just be missing something in translation/transition, but can't seem to get it right. TIA
Comment: Unrelated, but personally if just check the string for `ccarn` outside of the regex. Might even just check for the presence of the character classes in question in a less-complex way. I'm a big fan of regexes, but sometimes they're hard to think about and troubleshoot.
Answer: When you use the new RegExp() constructor to construct a regex from a string, you shouldn't include the leading and trailing / within the string. The /.../ form is only to be used when specifying a regex literal, which isn't what you're doing here.
When you do, say, var r = new RegExp('/foo/'), the regex you're actually getting is equivalent to doing var r = /\/foo\//, which clearly isn't what you want. So your constructor should actually look like this:
var regex = new RegExp('^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9@#$-/:-?{-~!"^_`\[\]])+((?!' + $scope.username + ').)*$');
//                     ↑↑                                                                                ↑↑
// no "/" at the locations pointed to above

You probably also need to double your backslashes (since backslashes are escape characters in strings, but not in regex literals). So, [0-9@#$-/:-?{-~!"^_`\[\]]</code> needs to become <code>[0-9@#$-/:-?{-~!"^_`\\[\\]].
Answer: If you look closely the '/' character gets delimited when you give it inside the quotes so essentially the
var regex = new RegExp('/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9@#$-/:-?{-~!"^_`\[\]])+((?!' + $scope.username + ').)*$/');

The regular expression would be like this
/\/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9@#$-\/:-?{-~!"^_`[]])+((?!ccarn).)*$\//

The right way to go is to remove the '/' character from the RegEx and it should work
var regex = new RegExp('/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9@#$-/:-?{-~!"^_`\[\]])+((?!' + $scope.username + ').)*$/');

The output for the above would be
/^(?=.*[a-z])+(?=.*[A-Z])+(?=.*[0-9@#$-\/:-?{-~!"^_`[]])+((?!ccarn).)*$/

which is exactly what you need ?
Hope it helps
Answer: Please before doing anything else, read a regex tutorial!
Mistakes:

A lookahead is a zero width assertion ( in other words, it's only a test and doesn't match anything ), putting a quantifier for a zero width assertion doesn't make any sense: (?=.*[a-z])+ (it is like repeating something empty, zero or more times. Note that the regex engine will protest if you write something like this.)
When you use the oop syntax to define a pattern (ie:var pattern = new RegExp("...), you don't need to add delimiters. You need to put double backslashes instead simple backslashes.


How to get a louder voice - layman

Question: I don't make music anymore and particularly, I am not a singer, but simply would like to train my voice intensity and clarity. Singing was recommended to me so I made an attempt using this Vocal Match App to hit the right pitch and start singing aloud.
There is a similar question on this topic though, but as I pointed out, I am completely new and also aim at a clearly understandable voice.
My question is: Does this method suffice to achieve a stronger and clearer voice or should I also learn the advanced breathing techniques? And how much would I have to practice?
Comment: I'm voting to close this question as off-topic because it asks for advice to improve speaking voice and not musical performance.
Comment: Proper breathing technique is key here. If you learn to sing from the diaphragm you will find it much easier to project your voice. All of singing basically boils down to whether you have got the proper breathing technique down.
Answer: If you are new to singing, there is no better way to learn than to pay for weekly lessons with a qualified voice teacher. Right now you do not know what is wrong, right, or even harmful to your voice -- a teacher could work with you interactively and give you a great deal of help in this area. I doubt that using apps, watching instructional videos, or reading written descriptions of vocal technique will be of any help to you. You need live feedback, regularly, from a qualified teacher, to correct the things you are doing wrong and to show you how to improve your voice bit by bit.
My second suggestion is that, if at all possible, you should join a community chorus or a church choir that accepts all comers, and commit to their rehearsal schedule. You will learn a great deal about singing and music in general; this will probably be free or only cost a small annual membership fee. You may even make friends while doing it.
Comment: I didn't mention that my goal is not singing in a chorus, but a better voice for _talking_ (my voice is too low). Futher, I don't think I'd have enough time for a chorus or similar. However, thank you for this answer!
Answer: You edited your answer to indicate that you are not looking to improve your singing voice, but rather to improve your speaking voice. (Your comment "it's too low" is ambiguous: do you mean only that the volume of your voice is too low, meaning that your voice is too soft and weak in character, or do you also mean that the pitch is too low and you want to speak in a higher register? You may well mean both.)
In that case, my earlier suggestion about singing in a choir might not be the most appropriate to your situation.
Since this is "Music: Practice & Theory", voice coaching for speaking is something that the participants here may have little experience with.
I have no direct experience with this, but I would also recommend that you investigate taking private lessons with a voice coach who specializes in helping people with their speaking voices. There are voice coaches for public speakers, rather than for singers. For more serious cases, there are also occupational therapists for the voice that specialize in rehabilitating speaking voices that have suffered damage due to injuries, infections, the effects of years of excessive caffeine or tobacco or alcohol, medical ailments, rehabilitation after surgery on the larynx or vocal chords, and so on. Do a Google search for occupational therapy vocal rehabilitation -vocational. The "-" (minus sign) I have included is to exclude search results that refer to "vocational rehabilitation", as that is something else altogether and search engines seem to confuse "vocal" with "vocational". If you go this route, you want to learn about vocal rehabilitation.
Answer: Your best bet would be to find a personal voice teacher, or at least join a choir.   You will want to practice every day to optimize your voice, and it's important that you don't fall out of practice, because otherwise, you will lose your experience and it will become harder for you to pick it up again.  Also, doing yoga or breathing exercises wouldn't hurt either.

How to get a louder voice - layman


Optimize Drupal Composer Workflow via Gitlab

Question: I have the following workflow for one of my product based on Drupal 8:
I use three custom private dependencies via composer ( two modules , one theme) , a lot of contrib modules and obviously drupal core. We git-ignore core drupal, contrib and custom modules/theme delivered via composer.
When I commit to one of my custom modules/theme, I have a lot of operations to do to update all  projects :

I commit and push my modification to the custom module/theme
I have to composer update project, one by one, to the new release, via composer update
I commit, one by one, a composer.lock
I have to composer install project in live stage ( not really great ).

Others issues :

My colleague must composer install when they are back to the project to get the update.

Environnement:
We use Gitlab.com for all projects that use our product. We have access to Gitlab CI/CD but it's not used at this time.
How optimize this workflow ? Any tools ? Gitlab CI/CD examples ? We can reconsider the full workflow too.
Comment: Eventually I used git subtress to share modules and theme into multiple drupal instances.
Answer: Thats an interesting question.

"I commit and push my modification to the custom module/theme". (Obviously you cannot skip that part)
Then you will update your module version number.
Then you will push your branch to gitlab repo.
That should start a CI pipeline.

This pipeline will do everything you have to do manually for now :

Getting your branch code
Running composer install (as your module version number has changed, this would trigger an module download, depending on how you had set the updating strategy, this could requires some tweaking).
Commiting composer.lock, vendors and modules to a build (it could be a branch commit, or a compressed package)
Running tests if you have any (you should)
Pushing the branch, the tag or the package to your integration platform

You need to consider your gitflow and your environment to start writing a gitlab CI pipeline. I'm using Gitlab so I cannot give you example.
You probably need to create or use a Docker image on which your code will run, and with the appropriate tooling (composer, obviously, maybe npm if you have SCSS, curl, gzip, whatever...).
Local environments will still need to run composer install manually. You could use docker and script the building process locally but that's a different subject.
Comment: Thanks and how other projects that used the updated dependencies are triggered when I update the dependency ?
Comment: Well, I think you will have to start pipelines for those. Each branch has its own pipeline so you could sort of propagate an update to some explicit dependencies. IRL, if you update a dependencies, it's the responsability of each projet using it to update or not. In your case, as you manage all aspects, you have to decide how ro replicate this behavior. Either in each pipeline, or in a custom script outside the project.


Patching together a Drupal project

Question: I'm trying to basicly glue/patch/fix a Drupal project so that I can edit it simpler. There's too much duplicated code which I want to make into the same function.
To do this I have to, from my own knowledge, handle modules. What I'm curious about is: What is the ideal way to structure these new functions?
Should I create a module called global_fixes, or should I add new functions to the existing modules? Feel free to share your solutions if you have been given a similiar situation.
Comment: Mostly in custom, I believe
Answer: Assuming that you inherited the custom modules along with the site, and there is no external maintainer of those, you should refactor the modules.
For contributed modules (i.e. modules maintained - or in some cases not - at drupal.org/projects), the options are more complicated.  I don't recommend creating yet another module (global_fixes) to deal with this.  You'll have problems keeping this in sync with new releases of the contributed modules you feel the urge to "fix".
Instead:

If you're community oriented person, raise an issue in the module's project issue queue for what you consider duplicated code (or other defects). If you fix the problem yourself, make your fix a patch, and add the patch to the issue queue.
If you don't want the hassle of dealing with module maintainers and the community, make a local fork where you essentially turn a contributed module into a custom one, and do whatever you like with it.  This also means that you will no longer be able to download improved versions of this module drupal.org/projects. You'll have to maintain it yourself (just like any other custom module).

If you want to follow the community route, you'll probably notice that not all Drupal project maintainers are prepared to resolve your issues or commit your patches in a timely manner.  So if you decide to create and submit patches, I strongly recommend that you install git and maintain a local repository that let you work with the code locally (independent of the repository at Drupal.org).  Just do a merge whenever there is a new commit available at the central repository.
If you're really community minded, and discover that all the fine patches you create and submit to a project's issue queue appearently fall into a black hole, you may want to read up on this: Dealing with unsupported (abandoned) projects.
Comment: I often prefer to do things on my own. Thanks for giving me an insight of the ideal workflow in Drupal contrib modules, but I think I'll be using more customs personally.

Patching together a Drupal project


How can Serializable.class not be assignable from Class.class?

Question: In org.springframework.core.SerializableTypeWrapper (version 5.2.3), there is the following code at line 112:
    if (GraalDetector.inImageCode() || !Serializable.class.isAssignableFrom(Class.class)) {
        // Let's skip any wrapping attempts if types are generally not serializable in
        // the current runtime environment (even java.lang.Class itself, e.g. on Graal)
        return providedType;
    }

I'm curious about the second check (!Serializable.class.isAssignableFrom(Class.class)): is it possible for it to evaluate to true (that is, for Serialazable.class to be not assignable from Class.class)?
Here is what Class#isAssignableFrom() javadoc says:

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

Looking at the code of Class, I see the following:
public final class Class<T> implements java.io.Serializable

So Serializable is a superinterface of Class and should always be assignable from Class. But the check in the Spring code suggests that sometimes it's not.
How come? In what situations can this happen and why don't they violate the Java Language Specification?
Comment: The code comment inside the `if` block would appear relevant: "_Let's skip any wrapping attempts if types are generally not serializable in the current runtime environment (even java.lang.Class itself, e.g. on Graal)_". By "Graal" I assume they mean [GraalVM](https://www.graalvm.org/), which has its [limitations](https://github.com/oracle/graal/blob/master/substratevm/LIMITATIONS.md#serialization) when creating native images. I'm guessing on GraalVM maybe `Class` _does not_ implement `Serializable`? And they use that to test if the current environment is Graal. But I'm not sure.
Comment: @Slaw I've compiled a test program with the following line `System.out.println("Is assignable: " + java.io.Serializable.class.isAssignableFrom(Class.class));`; it outputs `true` both when run with `java` (OpenJDK and GraalVM versions) or when I build a native image from this program with GraalVM's `native-image` tool. So (at least with the current version of Graal), this does not seem to be possible in a native image (unless there are some special conditions...).
Answer: A custom class loader is a possible (if unlikely) mechanism for the expression to return false.  Custom class loaders can do some crazy things, including loading their own versions of standard Java classes. Some things to know about class loaders:

Custom class loaders can be configured to load any class, even including Java standard library classes (it's discouraged of course, but still possible)
Custom class loaders will typically be configured to delegate to the system class loader for classes that they don't know how to load.
When class A has a reference to class B, the reference will be resolved using whichever class loader was used to load class A
More than one class loader can be configured to handle the same class, which can lead to multiple versions of a class getting loaded into the JVM, with the actual implementation you get depending on which class loader you ask

Suppose there is a custom class loader that, for whatever reason, is configured to load java.io.Serializable by itself, but delegates to the system class loader for loading other classes, including java.lang.Class.
Now suppose this custom class loader is used to load SerializableTypeWrapper.  This means it will also be used to resolve the reference to java.io.Serializable in SerializableTypeWrapper.  With the reference to java.lang.Class, the custom class loader will delegate this to the system class loader.  The system class loader will be used to load java.lang.Class, but it will also be used to load the reference to java.io.Serializable from within java.lang.Class.
So now we can ask the question - is java.io.Serializable [custom] assignable from java.lang.Class [standard]?  And the answer is no - java.lang.Class does implement java.io.Serializable [standard], but it does not implement java.io.Serializable [custom].
Comment: Thank you for the explanation. I wonder what `Class.class instanceof Serializable` would produce in your example. It would probably still be `true` because the right-hand side expression is not a class instance (which may be different for different classloaders) but a class name (at runtime, a member of constant pool, probably), is it correct?
Comment: The RHS must be a reference type, not a simple class name string.  You're right though about it being looked up in the constant pool.  But, the constant pool is per-class, and the lookup is performed using the class loader that loaded the class.  So it would be the same result - it'll return `false` if the `Serializable` known to the class loader is different than the `Serializable` implemented by `Class`.
Comment: JVM spec has some good details, if you're interested: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.instanceof
Also, on class resolution:  https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-22.214.171.124


PHP SplFixedArray bugged or slow performance?

Question: So I made this simple script to test the SplFixedArray object to see how good it performs.
Traditional method with array
ini_set('memory_limit', '2048M');
$start    = microtime(true);
$memStart = memory_get_peak_usage(true);
$loop     = 1000000;
$array    = [];

for ($i = 0; $i < $loop; ++$i) {
    $arr       = ['a'];
    $array[$i] = $arr;
}

$end    = microtime(true);
$memEnd = memory_get_peak_usage(true);
echo 'Time: ' . ($end - $start) . "\n";
echo 'Mem: ' . ($memEnd - $memStart) / 1024 / 1024 . 'Mb';

//Display: Time: 0.037514925003052 Mem: 28Mb

With SplFixedArray
ini_set('memory_limit', '2048M');
$start    = microtime(true);
$memStart = memory_get_peak_usage(true);
$loop     = 1000000;
$array    = new SplFixedArray($loop);

for ($i = 0; $i < $loop; ++$i) {
    $arr       = new SplFixedArray(1);
    $arr[0]    = 'a';
    $array[$i] = $arr;
}

$end    = microtime(true);
$memEnd = memory_get_peak_usage(true);
echo 'Time: ' . ($end - $start) . "\n";
echo 'Mem: ' . ($memEnd - $memStart) / 1024 / 1024 . 'Mb';

//Display: Time: 0.21888899803162 Mem: 142Mb (slower by 5x)

From the documentation, isn't SplFixedArray promise to have better performance and memory? Why is it behaving that way. So exactly in what situation should we use it?
Comment: Micro-optimizations like this tend to be a silly rabbit hole to go down. Three hundredths of a second over 100k iterations? I wouldn't worry about it.
Comment: @ceejayoz I updated the question with 1 millions. It's micro-optimizations or not depends on how you see it. I don't want the script to consume 1Gb of memory when I can't optimize it with some line of code to make it 100Mb.
Comment: You still create multiple `SplFixedArray` objects instead of **just one**. Please read again my post with the explanation.
Answer: The SplFixedArray is a special type of object that in general behaves as an array, but with the following restrictions:

Unlike the regular array - SplFixedArray has fixed size.
Unlike the regular array - SplFixedArray's keys can be only integers.

Because of those two characteristics - the implementation of the methods on arrays for the SplFixedArray can be faster.
As for your example - note that in the second example you created 100000 new SplFixedArray objects (unlike the first example, where you created only 1 array).
Taking your example - when removing the creation of the new SplFixedArray inside the loop, and just setting the value a to each element of the array - this is what I get:
$start = microtime(true);
$memStart = memory_get_peak_usage(true);
$loop = 100000;
$array = new SplFixedArray($loop);

for ($i = 0; $i<$loop; $i++) {
    $array[$i] = 'a';
}

$end = microtime(true);
$memEnd = memory_get_peak_usage(true);
echo "Time: " . ($end - $start) . "\n";
echo "Mem: " . ($memEnd - $memStart)/1024/1024 . 'Mb';

// Time: 0.0023539066314697 Mem: 2Mb

note that I changed to microtime

One more important thing to remember here - the "faster array implementation" that is mentioned in the documentation is related to the array-like-functions that can be used on the SplFixedArray object.
Comment: Please read the entire explanation. The "faster implementations" is regarding the specific array-related methods - sorting/splitting/accessing elements. Don't test only one thing - test everything. Read/write are completely different, and also - there is a huge difference between small and large objects. Also - in my example the memory was 2Mb (and yours was 4Mb).
Comment: I changed `'a'` into `['a']` or even `$arr = ['a']; $array[$i] = $arr;` The result is still the same. Version used `SplFixedArray` cost more time and memory
Comment: I will read, ty for suggestion. I also test with 1 million of loop. The object version took 142 Mb of memory versus 28 Mb.
Comment: your second example (which is wrong test) or my test?
Comment: I updated the question with good test. Still show standard array outperform object array (mostly in term of memory)
Answer: SplFixedArray is more efficient for the specific use cases it was designed for. If it was faster and used less memory for everything, it would simply be implemented as the default for all arrays, and indeed PHP 7 automatically chooses between multiple implementations depending on how you use each array.
The idea of having a fixed length array is that by setting the length in advance, the engine doesn't need to guess how much memory to allocate, and rearrange memory when you make the array longer or shorter. So to compare them, we need to use a benchmark where that would make a difference, such as starting with an empty array and adding a million elements to it:
$loop     = 1000000;
$array    = [];

for ($i = 0; $i < $loop; ++$i) {
    $array[] = 42;
}

vs
$loop     = 1000000;
$array    = new SplFixedArray(1000000);

for ($i = 0; $i < $loop; ++$i) {
    $array[$i] = 42;
}

Note that I'm only ever creating one array, or one SplFixedArray, as creating many small arrays is not the case we're testing.
On a PHP 7.2 box I have to hand I get the following benchmarks:

Array: 220ms, 32Mb
SplFixedArray: 211ms, 15Mb

On PHP 5.6, the difference is even more striking, showing how much the internal array implementation has improved in recent versions:

Array: 450ms, 138Mb
SplFixedArray: 320ms, 53.75Mb

Like most benchmarks, this probably doesn't resemble real-world code, but it shows one scenario where using an SplFixedArray would give a definite advantage.
You could play around and probably find even larger differences, e.g.

Assigning to elements at random, rather than in order, so it's harder for PHP to guess the final length.
Removing elements as well as adding them.
Reading from the array, or iterating over it with foreach

Conversely, we can simplify your test case to see where the slow down is, by not assigning to an outer array at all:
$loop     = 1000000;

for ($i = 0; $i < $loop; ++$i) {
        $array    = new SplFixedArray(1);
}

This takes 1.5 seconds or more to run on my PHP 7.2 machine, vs 0.2 seconds if I write $array = []. Clearly, there is a cost to creating new SplFixedArray instances which needs to be taken into account when choosing whether to use them.
For "multi-dimensional arrays", this is likely to be a significant factor, because there is no way to pre-allocate the multiple dimensions, you have to create new instances for each item in the outer array. A different structure could be implemented to optimise that case, but none is built into PHP as of version 7.4.
Comment: This works because you are using an array of 1 dimension. If you use 2 or more dimension like I did, the result is different.
Comment: @ThanhTrung Read the first sentence of this answer. `SplFixedArray` is optimised _for a particular scenario_, and your test doesn't demonstrate that scenario. Note that neither PHP arrays nor `SplArrayObject` instances can be "multi-dimensional" in a strict sense (i.e. they don't lay out any kind of matrix in memory), they can simply have elements that happen to be other arrays, or other `SplArrayObject` instances. The main cost in your benchmark is running `new SplFixedArray(1)` a million times; and that's simply not the usage it's optimised for.
Comment: Ok so your point is when we do `$array = []` in the loop it doesn't create a million of time an array? What does it creates then, one unique array in the memory?
Comment: @ThanhTrung No, your example creates a million arrays and a million `SplFixedArray` objects, and compares the speed and memory. Creating a million arrays turns out to be faster and less memory-intensive than creating a million `SplFixedArray` objects, but that shouldn't be surprising, because creating a million single-element arrays isn't how `SplFixedArray` is intended to be used. It feels like you're still looking for reasons your original benchmark is giving "the wrong result", but it's not; it's just giving a result that's not very relevant to what that object is for.


etcd in CoreOS not listening on port 4001

Question: When starting etcd in CoreOS it does not listen to port 4001.
Only when starting from the prompt:

$ sudo systemctl start etcd.service
$ ps aux|grep etcd
etcd      9364  0.1  0.8 267980  4880 ?        Ssl  05:43   0:00 /usr/bin/etcd
$ sudo lsof -i|grep LISTEN
systemd    1 root   26u  IPv6  14958      0t0  TCP *:ssh (LISTEN)
$ sudo -u etcd /usr/bin/etcd
$ sudo lsof -i|grep LISTEN
systemd    1 root   26u  IPv6  14958      0t0  TCP *:ssh (LISTEN)
etcd    9387 etcd    6u  IPv6 194642      0t0  TCP *:4001 (LISTEN)
etcd    9387 etcd    7u  IPv6 194643      0t0  TCP *:afs3-callback (LISTEN)
Comment: Are yiu saying it fails to start automatically when the system starts ? If so are there any relevant log messages ?
Comment: Things to check: Running the initscript through `bash -x` (if it is a bash script), ogling the environment and command line options of the process.
Answer: etcd and fleet only start by default if specified in a cloud-config parameter:
#cloud-config
coreos:
  units:
    - name: etcd.service
      command: start
    - name: fleet.service
      command: start

If you have this in your cloud-config already, journalctl -u etcd should indicate why.
Comment: Thanks.  journalctl -u etcd was indicating that no other hosts could be reached in the cluster. I had been starting and stopping servers with the same unique discovery token in cloud-config. **By using a new unique discovery token solved the problem.**


When using pandas, how to drop a row by its values and not by its label?

Question: I am trying to drop certain rows from a CSV file, but not by its label. I need to drop rows with certain values.
In this csv file, how would I drop every row with categroy == Physics?
Comment: `df[df['Category'].ne('Physics')]`
Answer: Try this
df = df[df['Category'] != 'Physics']

Answer: Assuming you read the CSV into a dataframe df, we can do:
filtered = df[df["Category"] != "Physics"]


Dash navbar menu is cut off when on the right side

Question: New to dash and trying to design a layout for a dashboard. Following some examples online I am leaning towards navbar. The problem is that if i add a dropdown menu on the right side when the dropdown is activated half of the list is not viewable. What am I doing wrong?
import dash_bootstrap_components as dbc
from dash import Dash, html

app = Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
header = dbc.Navbar(
    dbc.Container(
        [
            html.A(
                dbc.Row(
                    dbc.Col(dbc.NavbarBrand("Analytics", className="ms-2")),
                    align="center",
                    className="g-0",
                ),
                href="/",
                style={"textDecoration": "none"},
            ),
            dbc.Row(
                [
                    dbc.NavbarToggler(id="navbar-toggler"),
                    dbc.Collapse(
                        dbc.Nav(
                            [
                                dbc.NavItem(dbc.NavLink("Home")),
                                dbc.NavItem(dbc.NavLink("Page 1")),
                                dbc.NavItem(
                                    dbc.NavLink("Page 2"),
                                    # add an auto margin after page 2 to
                                    # push later links to end of nav
                                    className="me-auto",
                                ),
                                dbc.NavItem(dbc.NavLink("Help")),
                                dbc.NavItem(dbc.NavLink("About")),
                                dbc.DropdownMenu(
                                    [
                                        dbc.DropdownMenuItem("Home"),
                                        dbc.DropdownMenuItem("Some Long Item"),
                                    ],
                                    class_name="mr-1",
                                    label="Menu",
                                ),
                            ],
                            # make sure nav takes up the full width for auto
                            # margin to get applied
                            className="w-100",
                        ),
                        id="navbar-collapse",
                        is_open=False,
                        navbar=True,
                    ),
                ],
                # the row should expand to fill the available horizontal space
                className="flex-grow-1",
            ),
        ],
        fluid=True,
    ),
    dark=True,
    color="dark",
)

app.layout = html.Div(
    [header, dbc.Container(html.P("This is some content"), className="p-5")]
)

if __name__ == "__main__":
    app.run_server(debug=True)

Here is a screenshot of what this looks like:

What am I missing? How do i get the dropdown to be fully visible when located on the far right and also having fluid=True?
Answer: You can control the alignment of items using the align_end keyword on DropdownMenu(). The relevant documentation is here.
In your MVE shown above, make the change as follows:
dbc.DropdownMenu(
    [
        dbc.DropdownMenuItem("Home"),
        dbc.DropdownMenuItem("Some Long Item"),
    ],
    class_name="mr-1",
    label="Menu",
    align_end=True
)

Comment: I overlooked that in the documentation. It worked beautifully, thank you!


Where is $g(x)=x\lfloor x+1 \rfloor$ continuous?

Question:
Determine the points of continuity of $$g(x)=x\lfloor x+1 \rfloor$$

I know the point of continuity of $f(x)=\lfloor x+1 \rfloor$ are $x \in (a,a+1)$ where $a \in \mathbb{Z}$. But how do I determine the points of continuity of $x\lfloor x+1 \rfloor$? One idea I have is to consider the graph of $x(x+1)$ but I'm not sure how to proceed.
Comment: Hint: Let $n\in\mathbb Z$. Consider one-sided limits $\lim_{x\to n-}g(x)$ and $\lim_{x\to n+}g(x)$, which you can explicitly calculate. Prove they are equal to each other if and only if $n=0$.
Comment: @SarveshRavichandranIyer pardon me, but isn't floor function discontinuous at every integer point?
Comment: The points of continuity of $f(x)$ is not what you have currently written in your post.
Comment: @Ellie_Wong Sure, but you have incorrectly translated that from English to the mathematical language. (Your $b$ has got to be $a+1$.)
Comment: @Ellie_Wong careful. Take $b=3$ and $a=1$,  then $2\in (a,b)$ .
Comment: You're right, @Ellie_Wong, but then you've got to write $(a,b) \setminus \mathbb Z$. Now you can take on the hint in the second comment.
Comment: @StinkingBishop thanks. I have edited the post
Answer: Let $\;a\in\Bbb Z\,.$
Since $\;\lfloor x+1\rfloor=\begin{cases}a&\text{for any }\;x\in[a-1,a)\\a+1&\text{for any }\;x\in[a,a+1)\quad,\end{cases}$
it follows that
$\lim\limits_{x\to a^-}g(x)=\lim\limits_{x\to a^-} x\lfloor x+1\rfloor=a^2\;\;$ and
$\lim\limits_{x\to a^-}g(x)=\lim\limits_{x\to a^-} x\lfloor x+1\rfloor=a(a+1)=g(a)\;.$
On the other hand,
$a^2=a(a+1)\;$ if only if $\;a=0\;,\;$ consequently,
the only point of continuity of the function $\,g(x)\,$ which belongs to $\,\Bbb Z\,,\;$ is $\,a=0\,.$
Moreover, in any point $\;x_0\in\Bbb R\setminus\Bbb Z\,,\,$ the function $\,g(x)\,$ is continuous because both $\,\varphi(x)=x\,$ and $\,\psi(x)=\lfloor x+1\rfloor\,$ are continuous in $\,x_0\,,$ indeed $\;x_0\in\big(\lfloor x_0\rfloor,\lfloor x_0\rfloor+1\big)$ and $\;\psi(x)=\lfloor x+1\rfloor=\lfloor x_0\rfloor+1\;$ is a constant function on the interval $\big(\lfloor x_0\rfloor,\lfloor x_0\rfloor+1\big).$
Hence the function $\,g(x)\,$ is continuous on $\big(\Bbb R\setminus\Bbb Z\big)\cup\big\{0\big\}.$
Answer: Case.(1) $x\in [n+\delta,n+1-\delta]$, $g(x)=x\cdot(n+1)$, so $g$ is continous inside each invertal.
Case.(2) at each integer point $n$,
$$\lim_{x\to n^+}g(x)=n(n+1),~~~\lim_{x\to n^-}g(x)=n\cdot n$$
therefore,
$$\lim_{x\to n^+}g(x)=\lim_{x\to n^-}g(x)\Longleftrightarrow n=0$$
Namely, $g$ is continuous at $n=0$, and discontinuous at other integer points $n\neq0$
Here is a plot for function $g$


python manage.py syncdb não funciona!

Question: Ao tentar seguir um tutorial
Não consigo continuar porque o banco não foi criado, pode me ajudar?
Erro:
Unknown command: 'syncdb'
Type 'manage.py help' for usage.

Comment: Se utilizar o comando `help`, como recomendado, qual é a saída?
Comment: Anderson, aparecem várias palavras reservadas mas nenhuma delas é syncdb, encontrei outros posts que tem o mesmo comando com syncdb, por isso, resolvi postar aqui. Imagino que pode ser algo faltando no meu ambiente ou algo parecido.
Comment: Na sessão anterior, "Criando um projeto Django", é usado o comando `python ../manage.py`, enquanto nesse é apenas `python manage.py`. Os dois arquivos existem?
Comment: Sim existem, o manager.py está no primeiro diretório webserver, tentei executar python ../manage.py syncdb, dá o mesmo erro. Tentei voltar um nível no diretório, dá o mesmo erro.
Comment: Achei a resposta[http://stackoverflow.com/questions/28685931/unknown-command-syncdb-running-python-manage-py-syncdb], o syncdb foi removido é para usar migrate
Answer: Na verdade, o comando correto é:
./manage.py migrate --run-syncdb

ou
python manage.py migrate --run-syncdb

Comment: Valeu Victor, como havia funcionado nem me preocupei de verificar no manual.
Comment: Fico feliz em ter ajudado!
Answer: encontrei a resposta
O comando syncdb foi retirado do Django, agora use migrate.
python manage.py migrate

Testei aqui e funcionou!!!

python manage.py syncdb não funciona!


Views: Use default value from URL for contextual filter, THEN show all if default value empty?

Question: Short version, general question: You want to pipe in a 'Default value', specifying a URL argument, to a contextual filter in Views 3. You also want all results (the full unfiltered view) to be displayed if this argument in the URL is empty. However, "Default value" and "Display all rows if empty" settings in Views contextual filters are mutually exclusive, and the default if nothing is passed to the filter is to show nothing.
How can you achieve this?

Full version with case specifics: I'm using a Context View with a contextual filter on a Search API index to search based on search terms in a URL: path like "/search/my%20search%20terms, loaded into a Page Manager panels page as a page context so that bits of the view can be dispersed across the page regions. Pretty standard use of Search API Views.
Since you can't specify what arguments or contexts to pass to a context view in Page Manager / Panels when loaded as contexts in the Contexts form (unlike block views etc, loaded as content, where you can explicitly pass in arguments or contexts), I need to tell it which URL argument it will find the search terms in using the 'Provide default' options under Contextual Filters in the Views settings for the view.
This works, but has an unintended side effect - if someone goes to the search page without any terms (navigates to /search or submits an empty search box), they get nothing. I'd like this path to show the full unfiltered view (it's full of search facets and such so just navigating to it without search terms works like a drill-down browse/advanced search page).
If this was a block or loaded as content in panels/page manager, I could set "If no filter value is provided" to show all rows and use panels/page manager to pass in the current URL argument. But, in Views UI, default values and 'Show all' are mutually exclusive.
So, how to use a default value for a contextual filter, then show all if that default value isn't present or is empty?
Answer: Even faster:
PHP is not even needed to just display all values...

Under "When the filter value IS available or a default is provided
Tick "Specify validation criteria" Choose 'Basic validation'
Under "Action to take if filter value does not validate", choose "Display all values"
Answer: Here's something that works, not sure if it's the best way (can only be done by admins with Views UI PHP priviledges):

Under "When the filter value IS available or a default is provided" tick "Specify validation criteria"
Choose PHP code and enter: return empty($argument) ? false : true;
Under "Action to take if filter value does not validate", choose "Display all values"

So, it displays everything if it gets an empty ('' or null) default value.
It works fine, but feels like a cludge - I might be missing some way to pass contexts/args in page manager or some simpler way to achieve this in Views.
Comment: Excellent, thanks for sharing this. In my case, I needed a placeholder value for a date (yyyy-mm) argument. Just a little PHP did the trick: `if ($argument == 'current') { $handler->argument = date('Y-m'); } return TRUE;`
Now, when I use the word 'current' as the first argument, it will default to the current month and views will accept all additional arguments.


How to put backslash escape sequence into f-string

Question: I want to write something as simple as
"{}MESSAGE{}".format("\t"*15, "\t"*15)

using
f"{'\t'*15}MESSAGE{'\t'*15}" # This is incorrect

but I get the following error:
>>> something = f"{'\t'*6} Weather"
  File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash
>>> something = f"{\'\t\'*6} Weather"
  File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash

How can I do this?
Comment: Show the error and you got a good question
Comment: Unfortunately, you cannot have a backslash inside an f-string expression. You could assign the tab character to a variable and then use that.
Answer: As the error messages says, backslashes are not compatible with f strings. Simply put the tab character in a variable and use this.
tab = '\t' * 15
f"{tab}MESSAGE{tab}"

Answer: You're probably seeing this:
>>> f"{'\t'*15}MESSAGE{'\t'*15}"
  File "<stdin>", line 1
    f"{'\t'*15}MESSAGE{'\t'*15}"
                                ^
SyntaxError: f-string expression part cannot include a backslash

For simplicity's sake, f-string expressions can't contain backslashes, so you'll have to do
>>> spacer = '\t' * 15
>>> f"{spacer}MESSAGE{spacer}"
'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tMESSAGE\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'
>>>

Answer: You could assign the 15 tags to a variable and then use the variable in the f-string:
>>> tabs = "\t"*15
>>> f"{tabs}MESSAGE{tabs}"
>>> f"{tabs}MESSAGE{tabs}" == "{}MESSAGE{}".format("\t"*15, "\t"*15)
>>> True


Given that $x^y=y^x$, what could $x$ and $y$ be?

Question: It's not too difficult to figure out that $x$ and $y$ can both be 1, and also $x$ can be 2 and $y$ can be 4 (and vice versa). But I can't rule out if there are other solutions. Does it have anything to do with inverse functions? Is there a way to see the solutions by graphing, or algebraically?
Comment: Are $x$ and $y$ integers or not?
Comment: @user121270 The question doesn't say, but I would say that probably $x$ and $y$ do not have to be integers.
Comment: Negatives would also be another case to consider here.
Answer: Here's a good way to look at this:
$$
x^y = y^x \implies \\
y \ln x = x \ln y \implies\\
\frac{\ln x}x = \frac{\ln y}y
$$
So one way of solving this is looking at the graph of $y = \frac{\ln x}{x}$ and seeing where it hits a particular value twice.
However, I'm going to go a step further.  I will say that I want my solution $(x,y)$ of $x^y = y^x$ to be of the form $(x,ax)$ so that $y = ax$ for some value $a$.  Furthermore, I'll assume that $x \neq y$ so that $a \neq 1$ (of course, $x = y$ is always a solution if $x^x$ is defined). With that, we have
$$
\frac{\ln x}x = \frac{\ln (ax)}{ax} \implies (\text{assume } x\neq 0)\\
\ln x = \frac{\ln (ax)}{a} \implies\\
\ln x = \frac{\ln (a)}{a} + \frac{\ln x}{a} \implies\\
\frac{a-1}{a}\ln x = \frac {\ln(a)}{a} \implies (\text{we assumed }a \neq 1)\\
\ln x = \frac{\ln(a)}{a-1} \implies\\
x = a^{\frac{1}{a-1}}
$$
So, for any value $a \neq 1$, the pair $x = a^{1/(a-1)},$ $y = a \cdot a^{1/(a-1)} = a^{a/(a-1)}$ will give you a solution to the original equation.
For example, plugging in $a = 2$ gives you $x=2$ and $y = 4$.  Try some other values.
Comment: I should mention that the solution I gave is one I had seen [here](http://mathforum.org/library/drmath/view/53229.html) a long while back. Even used the same letter $a$.
Comment: Hm, parametrics, didn't think of that one!
Comment: Hehehe, since you did parametrics, I did polar.  ;D
Comment: @Omnomnomnom There exists a question in your solution. When you let $y=ax$, you have assumed that $y$ is a linear function with respect of $x$. But how you know this? Why the function, or the relation between $y$ and $x$ can't be of another case?
Comment: @mengdie1982 It's been a while since you asked, but here's an answer. I am not assuming that "$y$ is a linear function with respect of $x$"; indeed, the relation $y = ax$ that I use here is not linear since $a$ depends on $x$ (and/or on $y$, depending on your perspective). The more accurate way to describe what I've done is to say that I've made a "change of variables".  That is, instead of describing the curve as a relation on $x,y$, I'm describing it as a relation on $a,b$ where
$$
\begin{cases}
a = y/x,\\
b = x.
\end{cases}
$$
This is similar to changing to polar coordinates.
Answer: There is an explicit solution to this equation given by $$y = -\dfrac{x \operatorname{W}\left(-\dfrac{\log(x)}{x}\right)}{\log(x)}$$
where $\operatorname{W}(x)$ is the Lambert W-function.
Consider: $$x^y = y^x$$
Take the logarithm of both sides
$$y\log(x) = x\log(y)$$
$$\dfrac{y\log(x)}{x} = \log(y)$$
Multiply by $-1$ and exponentiate
$$\exp\left(-\dfrac{y\log(x)}{x}\right) = \dfrac{1}{y}$$
Multiply each side by $-\dfrac{y\log(x)}{x}.$
$$-\dfrac{y\log(x)}{x}\exp\left(-\dfrac{y\log(x)}{x}\right) = -\dfrac{\log(x)}{x}$$
Solve using the properties of the $\operatorname{W}$ function.
$$-\dfrac{y\log(x)}{x} = \operatorname{W}\left(-\dfrac{\log(x)}{x}\right)$$
$$y = -\dfrac{x \operatorname{W}\left(-\dfrac{\log(x)}{x}\right)}{\log(x)}$$
Comment: Wow good answer but a little beyond high school level$\ldots$ Is there a way by graphing?
Comment: An iterative method comes to mind quicker than anything that has to do with graphing. The best way to find solutions graphically is to pick a value of $y$ that you want a solution for and then plot $x^y - y^x$ looking for when the graph hits the $x$-axis. There is no way (that I know of) to graphically find all of the solutions at once on a Ti-84.
Comment: I feel like saying the W Lambert function solves it is almost a tautology. I've never been satisfied with such solutions. It's almost like saying "the solution is the solution!" from my perspective.
Comment: @CameronWilliams If your area of expertise led you to use and understand the Lambert W-function regularly, you would probably be quite satisfied with it.  Same goes for much of mathematics: if you're an algebraist, then a topological solution to your problem will probably feel unsatisfactory, whereas if you're a topologist it's great.
Comment: Are you looking for solutions by way of a graphing calculator?
Comment: Well, graphing in general, but yes would be graphing with trusty TI-84 or Mathematica
Comment: That's a good idea! Thanks!
Comment: I feel similarly about graphical solutions. In my mind, the best way to solve this equation would be to implement the W function on the Ti-84 and write a program to solve it. That or any other iterative method.
Comment: @zibadawatimmy I understand it well enough but a common theme on this site is people presenting special functions as solutions to equations without being a bit more honest about their genesis. It is a bit tautological but the Lambert W function has really nice properties and it is quite interesting.
Answer: If we convert everything to polar form, we end up with
$$(r\cos\theta)^{r\sin\theta}=(r\sin\theta)^{r\cos\theta}$$
Take the $r$th root of both sides and you'll get
$$(r\cos\theta)^{\sin\theta}=(r\sin\theta)^{\cos\theta}$$
$$r^{\sin\theta}(\cos\theta)^{\sin\theta}=r^{\cos\theta}(\sin\theta)^{\cos\theta}$$
$$r^{\sin\theta-\cos\theta}=\frac{(\sin\theta)^{\cos\theta}}{(\cos\theta)^{\sin\theta}}$$

$$r=\left(\frac{(\sin\theta)^{\cos\theta}}{(\cos\theta)^{\sin\theta}}\right)^{1/(\sin\theta-\cos\theta)}$$

which is the curve you are interested in.  A graph may be found here.
Plugging in $\theta=\arctan(0.5)$ will yield the rectangular coordinate $(4,2)$.
Answer: Hint:
Algebra says that after taking $\ln$ both sides,
$$y\ln(x) =x\ln(y) $$
This implies $\ln(x) /x=\ln(y) /y$
What can you say about the function $x\to \ln(x)/x $?
Comment: Well, $x\rightarrow\ln(x)$ is the inverse of $x\rightarrow e^x$, right?
Comment: @yroc typo on my part,  updated
Comment: OK, thanks. Now your suggestion makes sense and is similar to others' suggestions.
Comment: I don't quite understand this answer, could you elaborate?
Answer: For finding solutions by graphing, take the logarithm of both sides of the equation to get $y\cdot\log(x)=x\cdot\log(y)$. Assuming $x$ and $y$ are not zero, divide by them and get $\frac{\log(x)}{x}=\frac{\log(y)}{y}$ and consider the map $f:(0,\infty)\rightarrow \mathbb{R}, x\mapsto \frac{\log(x)}{x}$. Now your question is equivalent to finding values $x,y$ with $f(x)=f(y)$.


HTML5 Audio scrub troubles

Question: I think that this will be a fairly easy answer but I am unsure of why it works great in Chrome and FF but in Safari does not. It seams that the way the HTML5 audio player is designed that it blocks my function from firing. Again this is only in Safari. I wonder if there is a keyword that I am missing that Safari uses to distinguish there player scrub.
<code>if(video != '') {
    $("#<?php echo $track_id ?>").mousehold(function(){
        video.currentTime = this.currentTime;
        video.pause();
    });
    $("#<?php echo $track_id ?>").mouseup(function(){
        video.currentTime = this.currentTime;
        video.pause();
    });
}
</code>

So what happens is when the user drags the audio scrub bar it also scrubs the video.
Thanks in advance all.
Comment: Nevermind... I just fixed your code block and I see your real selector now.
Comment: Are you really using $("#") as a selector?
Comment: Thank you ithcy, I was trying to figure out how to do that.
Answer: Maybe mousehold doesn't work in Safari... Try using mousedown instead?
Comment: Sorry that does not work either. Mouseup is what I am currently using as backup to focus the video to where it should be, but that only works if I click on the scrubbing area where the handle is not, but once the handle focus the mousehold does not work. I am not sure why mousehold would not work though? It is a plugin to add to the header of a file ()
Comment: I was not sure about mousehold because it is not a valid DOM event; I would have read your link with great pleasure, but it's a dead one.
Comment: [link](http://remysharp.com/2006/12/15/jquery-mousehold-event/) This one works now, sorry about that. I formatted it wrong.

HTML5 Audio scrub troubles


hook_taxonomy_term_update(), where does it get invoked in drupal's core code?

Question: I looked after a module_invoke_all('taxonomy_term_update') in the taxonomy module (and more in the entire Drupal core) but I didn't find anything.
Where does that hook get invoked in the code?
Answer: It's invoked from taxonomy_term_save().
The reason you can't find it is because the hook gets invoked via an interpolated string, depending on the current operation (insert or update):
module_invoke_all("taxonomy_term_$op", $term);

Comment: Thanks dude! Even while searching for `invoke` in the code I saw nothing... I need new glasses!


Relations and functionss

Question: I am unsure how to do this, is it possible someone could give me a step by step guide so I can have a good understanding of it.
f(x) and g(x) are defined over the real number set R as follows:
$g(x) = 1-x+x^2$ and $f(x) = ax + b$. if  $g(f(x)) = 16x^2-12x+3.$
determine all the possible values of a and b.
Comment: So if $f(x)=ax+b$ and $g(x)=x^2-x+1$, what is $g(f(x))$?
Comment: That was the question I was given, sorry I can't tell you more
Comment: Sure, but you are expected to solve it. The first step, now set out in the Answer below is to find out what $g(f(x))=g(ax+b)$ is. What do you think?
Comment: I am unsure what it is g(ax +b) to answer it do i have to find x or a and b as im only used to doing these when finding the value of x
Comment: You expand $g(ax+b)$ and collect powers of $x$ together to get it into the form $cx^2+dx+e$. Then you compare with the form given in the question $16x^2-12x+3$. So you set $c=16,d=-12,e=3$ and solve those equations to find all possible values of $a,b$.
Comment: I'm sorry ive just started doing this and its hard for me to understand i appreciate your help very much
Comment: The expression $g(f(x))$ means that every place you see an $x$ in the expression for $g(x)$, you need to replace it with $f(x)$.  Since $f(x) = ax + b$ and $g(x) = 1 - x + x^2$, $$g(f(x)) = g(ax + b) = 1 - (ax + b) + (ax + b)^2$$
Comment: Thank you, that looks like the answer but im unsure.
Answer: Hint: Start by plugging the expression for $f$ into the expression for $g$. That is, simplify the expression $g(ax+b)=1-(ax+b)+(ax+b)^2$. Then set this equal to $16x^2-12x +3$.
Comment: the part i dont understand is the = 1 part

Relations and functionss


How to save node text and comment text to session or cookie while typing

Question: This site does a great job saving the text input even when a question or answer hasn't been posted.
Is there a similar feature available in Drupal?
Answer: There was by crell: module Autosave. Not ported to d7 though.
Here is a quote about it (from the module's project page):

...  automatically saves a snapshot of your content type form using AJAX. If the user's browser or machine dies while editing a node; the edits will be presented to the user the next time they return to the node. The user may toggle back and forth between the last saved version and the version with the edits that were lost and select which of these they would like to continue with.
How often a form is autosaved as well as which content types to enable autosave for are admin configurable.


True or False The image of the unit square under one-to-one matrix operator is a square

Question: The image of the unit square under one-to-one matrix operator is a square is this true or false
Answer: False. Consider the dilation
$$\begin{pmatrix} a \ 0 \\ 0 \ b \end{pmatrix}$$
where $a \neq b$.


Como detectar o mouse, em Lua?

Question: Recentemente consegui resolver um problema relacionado ao controle de coordenadas de tela em um terminal (graças à resposta encontrada aqui no SOpt). Agora preciso detectar os movimentos e cliques de um dispositivo apontador (mouse).
É hora de pensar e um toolkit gráfico, ou existe alguma alternativa mais simples?
Comment: A biblioteca padrão de Lua é super simplezinha, e basicamente só expõe coisas que vem da biblioteca padrão de C. Assim como no caso das coordenadas de terminal, você vai ter que usar alguma biblioteca para mexer com o mouse.
Comment: Obrigado hugomg. Estou experimentando o IUP. Com relação às coordenadas na tela, eu utilizei essa resposta [link] http://pt.stackoverflow.com/questions/23176/como-controlar-coordenadas-de-tela
Comment: Achou alguma solução? Poste como resposta para ajudar outras pessoas.
Comment: Resolvi o meu problema utilizando o IUP (ambiente gráfico)... Mas, de fato, não consegui resolver o problema do mouse em modo terminal. :(
Answer: Uma solução para detectar os movimentos do mouse com Lua e em modo terminal seria utilizar o wxLua, que costuma já vir integrado em algumas implementações.
Basicamente, você chama:
pt = wx.wxGetMousePosition()
io.write(pt.x) -- é a posição em x do ponteiro
io.write(pt.y) -- é a posição em y do ponteiro

Exemplo
require("wx")

-- Loop que vai atualizar o mostrador da posição do mouse:
while true do

    -- wx.wxGetMousePosition() retorna a posição do mouse na tela
    pt = wx.wxGetMousePosition()

    -- atualiza o mostrador:
    io.write("x = " .. pt.x .. "\ny = " .. pt.y .. "\n")
    os.execute("cls") -- ou os.execute("clear") em Unix
end

Como detectar o mouse, em Lua?


What is the standard location of piano pedals?

Question: My digital piano has a separate pedal block that can be placed at any distance from the keyboard. However I think makes a lot of sense to position it in a standard way, how it is typically positioned. As it tends to slide, I am now screwing it to the floor and need to know the recommended location.
What is a typical standard distance of the piano pedal block, measured from the front of the white keys to the tip, or root, of the pedals?
Answer: There isn't really a standard for that. Every piano I've seen has a different key height, pedal position and sensitivity. Especially upright pianos suffer from some physical limitations. Also they need to fit players of every size. That's why many piano pedals are actually L shaped. It usually takes some time to get used to playing a piano for the first time.
Since digital piano pedals are not L shaped it is better to align with your foot to the most comfortable position and do not copy real piano measures directly. As a general measure, you should adjust it to your own standing position. It should be comfy to reach with a little effort without extending for it, but also shouldn't bother your foot while not in use. Sustain pedals are positioned a little right from the center. You can place it aligned with your right foot (or toe) in your standard position, a few centimeters ahead. Do also a Google Image search for "piano position".

Ah, also before screwing it to the floor, use double side tapes and play for a while and ensure the position is comfortable. There is no such standard, it is better that you play comfortably.
NOTE: I couldn't get the Preformatted text to work. Adding a crappy screenshot instead.
Answer: Before making holes in the floor, attach a strip of carpet or similar to the underside of the pedal, long enough for your foot to rest on the carpet while the pedal is in a comfy position. Your foot will keep it from sliding away. Where it goes is more important for your comfort than to be in a standard position, and there's no industry standard.


Two different views with common URL

Question: I want to have an URL which calls a View, for instance:
www.example.com/products

This will be the URL for a View called products_list
If I want to filter the products by category, I could clone the View page, add a Contextual filter based on Taxonomy, and with a URL indicated as /products/% I could use
www.example.com/products/Brand-1

to filter the products of brand "Brand 1".
But what if I want to use a completely different View, with a layout different from the above, for just the special case of some brands, i. e.,
www.example.com/products/Special-Brand

I want the above URL to use a completely different View. How can I manage to do that in the simplest possible way?
Comment: I do not know whether this answer will be helpful or not in this case, but yesterday I asked same kind of question, to combine 5 - 10 views using pager. I am attaching the link of my that question, you can read and if you get idea from that, just for try. Here he told me to add another view using add-page from view (http://drupal.stackexchange.com/questions/191633/how-to-add-pager-at-the-bottom-which-allow-shifting-between-views/191637#191637)..
Comment: Thanks for the link. I was unable to understand why to use different views for that case. Not what I am looking for, in any case. The problem lies with completely different views and same basic URL, with different set of parameters, the solution must lie in the discrimination of parameters by Drupal with some extra module, some configuration or some hook code. The hook code is what I am using, with views_embed_view, but I look for a straighforward answer.
Answer:
Exactly, that is the point. I need just 2 Views, which one shows some
completely different data than the other, and for different kind of
brands. But all of these brands can be grouped in 2 big groups. Now I
solve it by using views_embed_view in template.tpl.php, and using a
View or other in the function via database logics, but I was not sure
if there was an ideal way of doing without "hard code", via Rules,
Context or something.

Here is an alternative.
Create taxonomy terms.
go to   /admin/structure/taxonomy

Add Vocabulary, call it Products
Then click on list terms (/admin/structure/taxonomy/products) and add terms

Brand A with url alias /products/brandA
Brand B with url alias /products/brandB

Then on your actual products content type (lets pretend it's Articles) add a term reference field of Bundle Type: Products.
Then edit your Article and select A or B for that node.
Create 2 block views (one for each type)

under advance, add relationship of terms on node

Then Add a contextual filter of Taxonomy Term Name

Provide Default Value

Fixed Value

Brand A

Then go to blocks, and find your 2 view blocks and configure them.

I only showed A here, repeat steps for B.
Comment: Well, spirit is similar to my approach. It can be done entirely in Drupal UI (thanks again) w/o a single line of code. But my site data comes from huge database, and site is multi-(domain/language) with thousands of products, it can be a real nightmare to administer all of that using a Drupal-UI-only approach. At the very end, the hard code solution is not far from this spirit, though I use contextual relationship with no fixed value, I set that value in the `views_embed_view` and the part of deciding which view to use is similar to the "block filtering" that you used. Very interesting indeed.
Comment: Ok, but the discussion has been very very valuable. Thanks.
Comment: Thank you very much, very detailed answer. Now I see it.
Comment: The only problem I see is that the URL /products/brandA also displays the list of products belonging to that taxonomy, so I get a kind of "duplication" of content. A solution could be to create the URL with `hook_menu` and somehow override the taxonomy listing. I will research into that.  Thanks again!!
Comment: OR you could create 2 nodes of content type Article and use URL alias of /products/brandA & /products/brandB instead of using the taxonomy term page. (change the urls of term page).
Comment: @Cesar go with whatever works best for you =)
Answer: You add a new view by clicking Add Page

This will clone your original view. Then click on fields and at the top select this page override as you don't want to affect all views.

Then click the remove button, to remove the fields.
Do this for everything, so you can remove everything and start from scratch.
Comment: The problem lies in the parameters. I have two views. I need one to show for a given kind of parameters, and the other view with the other set of parameters. All for same basic URL. Don't think it is quite trivial.
Comment: @Cesar define `parameters` because I am not getting it.
Comment: Well, URL parameters. So if we have these 2 different URLs: `/products/brandA` and `/products/brandB`, I call parameter to "brandA" and "BrandB" in each URL. Now, depending on the parameter being "brandA" or "brandB", I would like to apply one View or other completely different View. The problem I get and where I am stuck is that defining a working URL for a View, you can only define /URL/%, and the placeholder "%" will not discriminate among values of brandA or brandB. If I restrict to putting the exact URL I won't be able to dynamize the URLs and have "kind" of products.
Comment: [...continue...] The solution could be to define some kind of token, for example, URL of the View #1: `/products/[categoryA]` , URL of the View #2: `/products/[categoryB]` and [categoryA] would be some kind of placeholder for "% but restricted to products of kind A" and [categoryB] placeholder for "% but restricted to products of kind B".
Comment: @Cesar so what you're saying is that you have many brands, A, B, C, D, E, F, G, etc.. so making a view page for each of them with an exact url is not ideal?
Comment: Exactly, that is the point. I need just 2 Views, which one shows some completely different data than the other, and for different kind of brands. But all of these brands can be grouped in 2 big groups. Now I solve it by using `views_embed_view` in template.tpl.php, and using a View or other in the function via database logics, but I was not sure if there was an ideal way of doing without "hard code", via Rules, Context or something.
Comment: In detail: I now get the arg(2) parameter in the URL, which is the brand, get the group of the brand by `db_query`, and according to the value, use a view name or other for the `views_embed_view` function.

Two different views with common URL


How to join two tables based on two columns and verifying that one column is existing in both

Question: I have a table A and a table B. The tables can be joined based on the columns (say x and y in both).
I want to join both tables based on x and y to find out all rows in table A where the couple (x,y) doesn't exist in the table B.
What I do now is:
SELECT * FROM A a
LEFT JOIN B b
ON a.x = b.x AND a.y = B.y
WHERE b.x IS NULL AND b.y IS NULL;

And the result is ok...
But me I want to have couples (x,y) in A that don't exist in B and be sure only for couple where x exist in B...
Any idea?
I have the idea to do the following:
SELECT * FROM A a
LEFT JOIN B b
ON a.x = b.x AND a.y = B.y
WHERE b.x IS NULL AND b.y IS NULL
AND x in (SELECT x FROM B);

And that works but it seems for me not a good way...
Sample data would be:
in A, we have (x,y):
(1,2)
(1,5)
(2,3)
(3,7)
in B, we have (x,y):
(1,4)
(1,5)
(3,9)
expected result is:
(1,2)
(3,7)
Comment: Can you post some sample data and expected result.  [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve)
Answer: SELECT A.*
FROM A
WHERE NOT EXISTS (SELECT 1
                  FROM B
                  WHERE B.x = A.x
                    AND B.y = A.y)
  AND EXISTS     (SELECT 1
                  FROM B
                  WHERE B.x = A.x)

This return all rows from A, where

B doesnt have A(x,y)
B have A(x)
Answer: In my experience, subqueries outside of the FROM clause have generally poor performance, this would probably be faster:
SELECT *
FROM (SELECT DISTINCT x FROM B) AS bsAs
INNER JOIN A AS a ON bsAs.x = A.x
LEFT JOIN B AS b ON a.x = b.x AND a.y = B.y
WHERE b.x IS NULL AND b.y IS NULL
;

Edit: Don't forget the DISTINCT in the subquery, otherwise you'll get your results for each x value duplicated for every instance of that x value in B.
Comment: Yes that's why I said I know it's not the better way because I guess it decreases performance


Eclipse Error: Could not find or load main class opencv

Question: I keep getting these error every time I try to run the jar file I follow most of the questions that have been asked here haven't worked :(
and every time I export the jar file I got these warning
enter image description here
and this is my MANIFEST.MF
Manifest-Version: 1.0
Class-Path: .
Main-Class: gui_rec.Main

any suggestions?
Answer: Try to specify in your MANIFEST.MF classes to include in the Class-Path header field in the manifest file of an applet or application. The Class-Path header takes the following form:
   Class-Path: jar1-name jar2-name directory-name/jar3-name

For more info go to link