Nginx config for multiple Laravel applications always returns just one

Question: I want to use single server to host multiple Laravel applications with Nginx and PHP-FPM.
The problem is that only one application is being loaded no matter the domain.
I have an A DNS record for each app:

a.example.com
b.example.com

When i visit a.example.com i get into the A application. But when i visit b.example.com, A application responds again!!
On the server, there are 2 Nginx configs, taken from the official documentation
#/etc/nginx/sites-enabled/a.example.com

server {
    listen 80;
    listen [::]:80;
    server_name a.example.com;
    root /var/www/a/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

and
#/etc/nginx/sites-enabled/b.example.com
server {
    listen 80;
    listen [::]:80;
    server_name b.example.com;
    root /var/www/b/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

The most interesting part is that when I rename /etc/nginx/sites-enabled/a.example.com to /etc/nginx/sites-enabled/c.example.com and restart Nginx, then the situation is opposite, I always end up in the B application
So my question is - what am i missing?
Comment: whats in your `nginx.conf`? also, is that just a typo where your config file extension is `.com` instead of that `.conf` or is that how you pull the files inside your `nginx.conf`
Comment: `nginx.conf` is default i.e. it wasnt changed from a fresh install.

As for file extension it's not a typo. Configs inside of sites-enabled does not have to have any extension or can have any extension. Most tutorials i stumbled upon name their config as per server_name but it could be a.example.com or a.conf or just a.
Answer: this /etc/nginx/sites-enabled/ is not a default nginx set-up, this kind of set-up mostly taken from apache configuration, I've seen many nginx tutorials that follows this config, and it can be more confusing if you are not familiar with nginx.
the default configuration of /etc/nginx/nginx.conf only includes config files located inside /etc/nginx/conf.d
you'll see that at the end line of nginx default http block
http {
    .
    .
    .
    include /etc/nginx/conf.d/*.conf;
}

the fact that your configuration file is not properly working, it appears like its only pulling one config file which sets as the default server.
I'd always advise you'd stick with the default nginx config set-up and make sure your http block has this line include /etc/nginx/conf.d/*.conf;
then put your config file inside /etc/nginx/conf.d directory that should have a .conf extension
i.e.
/etc/nginx/conf.d/0000-default.conf  - contains server block for your default server, any domain pointed on your server without config file will use this.
/etc/nginx/conf.d/b.example.com.conf - server block for b.example.com
/etc/nginx/conf.d/c.example.com.conf - server block for c.example.com
Comment: Actually, in my /etc/nginx/nginx.conf i see that it loads both *.conf and sites-enabled:
# Virtual Host Configs
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
Comment: try moving your config inside `/etc/nginx/conf.d/` your set-up only loads the first file inside sites-enabled for some reason, you see it only loads `a` config and when you change the file name from `a` to `c`, the `b` will become the first file and load as default


LogisticRegression with GridSearchCV not converging

Question: I'm trying to find the best parameters for a logistoic regression but I find that the "best estimator" doesn't converge.
Is there a way to specify that the estimator needs to converge to take it into account?
Here is my code.
# NO PCA
cv = GroupKFold(n_splits=10)
pipe = Pipeline([('scale', StandardScaler()),
    ('mnl', LogisticRegression(fit_intercept=True, multi_class="multinomial"))])

param_grid = [{'mnl__solver': ['newton-cg', 'lbfgs','sag', 'saga'],
               'mnl__C':[0.5,1,1.5,2,2.5],
               'mnl__class_weight':[None,'balanced'],
              'mnl__max_iter':[1000,2000,3000],
              'mnl__penalty':['l1','l2']}]

grid = GridSearchCV(estimator = pipe, param_grid=param_grid, scoring=scoring, n_jobs=-1, refit='neg_log_loss', cv=cv, verbose=2, return_train_score=True)

grid.fit(X, y, groups=data.groups)

# WITH PCA
pipe = Pipeline([(
    ('scale', StandardScaler()),
    ('pca', PCA())
    ('mnl', mnl)])

param_grid = [{'pca__n_components':[None,15,30,45,65]
            'mnl__solver': ['newton-cg', 'lbfgs','sag', 'saga'],
              'mnl__max_iter':[1000,2000,3000],
             'mnl__C':[0.5,1,1.5,2,2.5],
              'mnl__class_weight':[None,'balanced'],
              'mnl__penalty':['l1','l2']}]

grid = GridSearchCV(estimator = pipe, param_grid=param_grid, scoring='neg_log_loss', n_jobs=-1, refit=True, cv=cv, verbose=2)

grid.fit(X, y, groups=data.groups)

On the first case, the best estimator found is with an l2-lbfgs solver, with 1000 iterations, and it converges. The second one, the best estimator found is with saga solver and l1 penalty, 3000 iterations. I feel it has to do with the solver... but anyways, is there a straightforward way to state that it has to converge to accept it as best?
Comment: cross-posted at https://stackoverflow.com/q/64197663/10495893.
The last part of the question belongs there, but the rest of it fits well here.
Answer: I wouldn't advise making that constraint.  Failure of the solver to converge just means it hasn't reached the global optimum* to within the specified tolerance.  If you're getting better cross-validation scores, then you should probably be "close enough" to that optimum to not worry about it.  Increase max_iter for the refit, if you'd like.
*(In logistic regression the loss is convex, so there's just one global optimum, barring collinear features or perfect separation.)
In a similar spirit, I wouldn't search over solvers (except maybe as a convenient way to deal with different solvers being capable of using different regularization penalties), or maximum number of iterations.  After fixing the regularization type and strength, there's unique optimal coefficients (again, barring degenerate cases), and running different solvers should produce the same results unless (1) the solver goes off the rails somehow, or (2) difference in precision causes some difference.  And the number of iterations should just be set high enough to reach convergence (note that it's "maximum" number of iterations; if a solver gets within its tolerance before that, it won't keep chugging).
Answer: This is more than likely a problem with your data not being appropriate for this approach, rather than your code being incorrect. Especially since you arent constructing your own silver or anything I would really check out your data more thoroughly.
Comment: What does "constructing your own silver" mean?
Comment: how should I check it for this purpose?
Comment: I think he meant solver?


Notepad++: reemplace ocurrences of characters before other character

Question: I have a file with text like this:

"Title" = "Body"

And I would like to remove both " before the =, to leave it like this:

Title = "Body"

So far I managed to select the first block of text with:

.+(=)

That selects everything up to the =, but I can't find how to reemplace (or delete) both " .
Any suggestions?
Comment: Try `(?:\G(?!^)|^(?=.*=))[^"=\v]*\K"` and replace with an empty string.
Answer: You could use a capture group in the replacement, and match the double quotes to be removed while asserting an equals sign at the right.
Find what:
"([^"]+)"(?=\h*=)

" Match literally
([^"]+) Capture group 1, match 1+ times any char other than "
" Match literally
(?=\h*=) Positive lookahead, assert an = sigh at the right

Regex demo
Replace with:
$1

To match the whole pattern from the start till end end of the string, you might also use 2 capture groups and use those in the replacement.
^"([^"]+)"(\h*=\h*"[^"]+")$

Regex demo
In the replacement use $1$2
Answer: You can use
(?:\G(?!^)|^(?=.*=))[^"=\v]*\K"

Replace with an empty string.
Details:

(?:\G(?!^)|^(?=.*=)) - end of the previous successful match (\G(?!^)) or (|) start of a line that contains = somewhere on it (^(?=.*=))
[^"=\v]* - any zero or more chars other than ", = and vertical whitespace
\K - omit the text matched
" - a " char (matched, consumed and removed)

See the screenshot with settings and a demo:


My dynamic website is not responding to specific button click

Question: whilst making the function on my dynamic single page web app which allows the user to upload images I have come across quite a large issue. In order to simplify and find the root of the issue, I have simplified by function. All the function is meant to do right now is take values from a form and display them in the console however at the moment it is just seems to restart the page and return to the home page. This error is so confusing as I have already programmed functions for some of my other pages which work completely fine. I used a similar code structure to those functions for this function but it just did nothing. I understand that the amount of code I'm posting may not be sufficient to understand the error but I don't feel comfortable posting heavy chunks of my code on here , but am willing to show them over chat. Thank you. This is my code:
client.js
.
.//code for other pages functions
.
async function ImageHandler(event){
    event.preventDefault();
    var name =document.getElementById('username').value;
    var title =document.getElementById('titleofimage').value;
    console.log(name);
    console.log(title);
    imgform.reset();

}

const imgform= document.getElementById("image-form");
imgform.addEventListener("submitImage", ImageHandler);

index.html

pictures

            <form id='image-form'>

                    username
                    <input class='form-control' name='name' id='username' required>

                    Tile
                    <input class='form-control' name='title' id='titleofimage >

                <input type='file' id='image' required>

                <button type='submitImage' class='btn btn-primary'>submit Image</button>
            </form>

     .(//other pages code)
     .
     .

Comment: The event name should be `"submit"` and no such type "submitImage" for a button.
Comment: You mentioned "This error is so confusing", can you share the error? Are you seeing any other errors or warnings in the browser console?

Are all of your network calls resolving successfully?

Have you tried adding some trace level logs at the top and bottom of the event listener?

What browser(s) are you using?
Comment: @EthanRadford there is no error as such just that whenever I press the submit image button it seems to refresh the entire website rather than log the values to console and reset  the form.I am using google chrome. The error is so confusing because I have written entire client server functions which are still working fine and this function is written in the same way as them so I don't understand why it doesn't work. Im not sure what your other suggestions mean
Comment: Your `console.log` statements do not appear until halfway down the listener. Have you tried placing any console output statements as the very first line in you listener? That should at least tell you if your listener is executing and failing or not executing at all. WRT to the absence of errors, if the page is refreshing, your console and network logs will clear out on the page load, unless you've specifically selected options to preserve them. Are you preserving logs currently?
Comment: @EthanRadford I added a console.log at the start of the function and I think the function is not being called at all as it still doesn't log the message I added to the start.
Comment: Nice catch! This should be the accepted answer.
Answer: You are missing an apostrophe in one of the inputs:
titleofimage' >
As @charlietfl mentioned, to submit the form, you can only use the button type submit, submitImage will not work. You could also omit it, as a button within a form will always submit it.
The same thing needs to be corrected in the js File, imgform.addEventListener("submit", ImageHandler) instead of ..submitImage...


Not all content showing up after uploading to live server

Question: I have been working on a site for a client and I have ran into a bit of an issue. I built the site locally and then pushed it to a staging server to show the client and everything is running fine. When we got to the point of launching the site, we did what our team normally does and everything seems to be working fine until you look at the page content... It only shows the first sentence.
Here is an example of what's going on:
staging server:
live server:
My head is hurting from trying to figure this one out. I am using a custom theme and using  to display the data on the left hand side like we always do, so that shouldn't be the problem. I am just at a loss, any little help would be awesome!
Comment: do u have devel module ?
Comment: do u check all of the file ( template) uploaded correctly? I suggest you   change the theme for a drupal default and check it,
Comment: @zhilevan I do not have the devel module installed and I am going to try that now.
Comment: @zhilevan I set the theme to Bartik and the content is showing up the same way. Do you think it could be a database problem? When you go to edit the copy, it shows all the content.
Comment: if it shows the complete node on edit, it should not be database proble
Comment: I wonder if you can share the site url.
Comment: @arpitr it is the complete node. I did just get an error that I haven't encountered before: Warning: file_get_contents() [function.file-get-contents]: http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in drupal_build_js_cache() (line 4943 of /www2/avalonweddingsbcs/includes/common.inc).
Comment: @arpitr the test server is: avalonbcs.tmgdev.co/venue (warning, it's a little slow) live server: avalonweddingsbcs.com/venue
Comment: @MichaelNichols checking
Comment: can you try disabling your js aggregation
Comment: https://drupal.org/node/1802394
Comment: @arpitr I disabled the js aggregation and cleared my cache and ran cron... nothing.
Comment: @MichaelNichols do you have chat access on skype or somewhere else?
Comment: @arpitr yes, skype:mumptastic
Answer: It could be a control character that would remain or be not there when moving from one platform to another. Line breaks in Windows, UNIX and Macintosh text files all are different. If you have moved the database from one platform to another care should be taken to insure cr lf couplets are considered.
A similar situation could result from a database conversion that did not take into account these differences.
Comment: A quick test would be to go to the edit screen change to plain text, copy that text and then paste into a text editor like notepad++ for Windows or other like product. Then look for control characters by changing code types. The characters in question should be following the text that is visible in the "viewed" node.
Comment: Thanks for your help! I ended up taking the content and editing it in my text editor. When I did that I noticed that it was adding ETX next to the text, once I took that out and reposted the content it worked! Thanks for all y'alls help on my first post!
Comment: If the above testing shows where the problem is and you want a quick fix - you can go to each page with the problem and do the process as described but delete each incidence of the culprit character (if one is missing you would need to provide such instead of deleting) and then re-paste the text back into the node in plain text mode.  This could be quicker than finding the cause of problem and re-porting the data.

You could then locate the misstep and insure future moves that are similar are processed properly.
Answer: I think  the problem isn't about themes, I think the problem occur form database's data, If you can  export live database and test  it in another instance of local version and if them problem exist in it, I tell you upload good version of database version to live database again.


Question about inequalities in the proof of Rado's theorem

Question:
This is the proof of Rado's theorem in Rudin's PMA.
The first claim of the proof is a nonzero set $\Omega$ is dense in $U$. This is okay for me.
However, the application of maximum modulus theorem for $\Omega$ seems strange for me.
Specifically, author says: given $\alpha \in \Omega$
$$ |f(\alpha)g(\alpha)^n| \leq \| fg^n\|_{\partial\Omega} = \| fg^n\|_T \leq \|f\|_T \|g\|^n_T$$, but it seems not always true. The first inequality is okay, by the maximum modulus theorem, but how can we say that $\| fg^n\|_{\partial\Omega} = \| fg^n\|_T$? Although we have shown the density of $\Omega$, saying $\bar\Omega = \bar U$, we can only deduce $T = \partial \bar U = \partial \bar \Omega \subseteq \partial \Omega$. This is because $\partial \bar A \subseteq \partial A$ in general and not vice versa.
This may be a very minor problem, but it seems to be an important part of the proof. Any help would be appreciated.
** $T$: Unit circle, $U$: Open unit ball in $\mathbb{C}$
Comment: @Eric Wofsey U is an open unit ball, and T is a unit circle
Answer: You know that $fg^n=0$ everywhere on $\partial\Omega\cap U$.  So, if you're computing $\|fg^n\|_{\partial\Omega}$, you can ignore the points in $U$; the value of $|fg^n|$ at those points (which is $0$) cannot be larger than the largest value it takes on $T$.


Views PHP: Comparing two Field and display Answer

Question: I tried to build a soccer magazine website. I want to display Match Win/Loss/Draw in the Match Result Page with the score result. I want to display it like:
if [field_score1] > [field_score2] display 'Win'
if [field_score1] < [field_score2] display 'Loss'
if [field_score1] = [field_score2] display 'Draw'
Im stuck please Help.
Answer: First,  In your Match Results view, add a Global: Custom text field and just leave it blank/empty. (we will use this field to print the outcome)
You can override the view's display through your themes template file.
Go to sites/all/themes/YOURTHEME/  look for template.php and open it. You probably have other code inside there, so make extra space by hitting enter at the bottom and add the following code.
<code>function YOURTHEME_preprocess_views_view_fields($vars){

      if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['fields']['field_score1']->raw > $vars['fields']['field_score2']->raw){
        $vars['fields']['nothing']->content = print 'Win';
      }

      else if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['fields']['field_score1']->raw < $vars['fields']['field_score2']->raw){
        $vars['fields']['nothing']->content = print 'Loss';
      }

      else if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['fields']['field_score1']->raw == $vars['fields']['field_score2']->raw){
        $vars['fields']['nothing']->content = print 'Draw';
      }

}
</code>
Replace YOURTHEME with your actual theme name
Replace VIEWNAME with your view machine name. (example: match_results)
Replace DISPLAY with your display machine name. (example: block, block_1 ) You can find the name by looking at your view. (see picture below). If you're using the Master view, then the machine name is "default"
.jpg


How to load a specific code regarding the current page?

Question: I'm building a complex web app and to keep things simple, I made various modules (objects) in various files. Those modules can be required on some page, and not on others.
For that reason, I'd like to avoid loading all the modules for any pages, increasing the amount of useless requests.
So far, I work like this :

I include all needed libraries
After that, I instantiate these librairies in jQuery(function() {}); with specifics #ids or .classes arguments for that current page

Everything works fine, but since my app is growing beyond easy, I'd like to manage my JS with RequireJS.
And that's where things start to be a little confusing for me.
I know I can load my module when required, using require(['module1', 'module2', 'etc'], function (module1, module2, etc) {}), but how can I say :

"on this page, you load these modules, and instantiate them with those #ids and .classes"

and

"on this other page, you load only that module, with this #other-id"

?
module1 will, for example, load data from the api, and list them to a specific table given as parameter :
// in page 1
var mod1 = new Module1($('#content>table');
mod1.init(); // will load the data from the api with the url located at

// in page 2
var mod1 = new Module1($('#content .items>table'); // The table where we want the data to be populated is not at the same position!
mod1.init();

That means, depending on the page, I'll have to load my modules differently. That's how I don't know how to do using RequireJs :/
Comment: @Cyril N. Not sure if I understand what you want. Can you provide an example of what you expect requirejs do for you? Because the module1 it self will be responsable to instantiate the libraries with #ids and .classes etc. Those libraries will be modules too.
Comment: I answered an question about requirejs and multi-page apps, maybe help: http://stackoverflow.com/questions/11674824/how-to-use-requirejs-build-profile-r-js-in-a-mult-page-project/11730147#11730147
Comment: @devundef your idea of adding a `data-start` attribute is very interesting and would solve also my problem I believe! thanks :)
Comment: (I updated my question regarding your first comment @devundef)
Answer: What you need is a javascript file for each page. That file will be responsible to execute your page-specific code.
I'll assume that you will use r.js to optmize and pack your code.
We can interpret Module1, Module2 etc. as libraries, because they will be used on multiple pages. To avoid browser do one request for each library module you can include this modules on your optimized main file:
Configure the "modules:" attribute of your build profile like this:
...
modules: [
   {
       name: "main" // this is your main file
       includes: [
          "module1",
          "module2",
          "etc..."
       ]
   }
]
...

By doing this you tell to requirejs something like this: Optimize my "main.js" file and include in it all its dependencies, also includes the "module1", "module2" etc.
You have to do this because on your main file you do not include these modules on the require()/define() call, but you still want they available in case the page-specific module needs them. You don't have to do this for every library module you have, just for those that will be used by most of your pages.
Then, you create a javascript file for your page to use those modules:
define(function(require, exports, module) {
   var $ = require("jquery"),
       module1 = require("module1");

   var mod1 = new Module1($('#content>table'));
   mod1.init();

   //other page specific-code.
});

And then on the html file:

So, when page loads, it will make a request for require.js, then another for main.js and then another for home.js and that's all.
I'll put the link for the another question so this answer get some context: How to use RequireJS build profile + r.js in a multi-page project
Comment: That's very interesting to do like this, I'll try that! Thanks! :)
Comment: It's a bit confusing in the beginning but gets better after :) I updated my answer on the other question with additional information about per-page optimization, take a look.
Answer: The creator of RequireJS actually made an example project that uses page-specific main files: https://github.com/requirejs/example-multipage


Facebook Like Button with show_faces=1 only showing up to three avatars

Question: I'm not sure how to debug this. I paste the code from Facebook as it is given to me including the option to show faces of those that like the page.
I've clicked 'Like' using multiple Facebook accounts (more than three) but I only see three faces, never any more than three.
I searched stackoverflow and the facebook support threads and haven't found much mentioning this.
Could this be a URL scoping issue? The URL for the Like Button is for page other than the one it is on.
If someone could simply recommend how to begin debugging this, I would be very grateful.
I have tried both the iframe embed and the fbml version with the same end result.
http://extremelypublic.com/of/privacy#exposure
Answer: I've had this happen when there aren't very many Likes (less than 300-500)?


Saber qual botão foi clicado

Question: Amigos,
Tenho 4 botões tipo <input tupe="button">, cada um tem uma classe diferente pois são formatados de formas diferentes. Ambos botões tem a mesma ação, com valores diferentes apenas. gostaria de saber como pegar esses valores desses botões em uma função jquery, pois o id é único, a classe é diferente.
Obrigado.
Answer: Com jQuery podes fazer simplesmente:
$('button[type="button"]').on('click', function(){
   // e aqui, o this é o botão clicado
   var id = this.id;
   var classes = this.classList;
});

Se quiseres fazer só com JavaScript nativo podes fazer assim:
var botoes = document.querySelectorAll('button[type="button"]');
for (var i = 0; i < botoes.length; i++){
  botoes[i].addEventListener('click', function(){
       // e aqui, o this é o botão clicado
       var id = this.id;
       var classes = this.classList;
  });
}

Nota:

repara que tens tupe em vez de type.
lembra-te que as IDs devem ser unicas, e as classes partilhadas. No teu texto dizes "cada um tem uma classe diferente [...] o id é único", se calhar está certo mas a descrição dá-me ideia que não

Saber qual botão foi clicado


Downloading a File in Swift without caching it

Question: I am using NSURLSession to download a file from a specific url. I have come to the conclusion after several tests that the app itself caches the file, so when I try to download it again the app overrides my instructions and shows me the cached file. Is there a way to say to the program not to cache files? I have searched and haven't found anything... :(
Thank you in advance!
Comment: Look at NSURLRequest cachepolicy.
Answer: When you inititalize the NSURLRequest you'll use with the Download Task, make sure to pass NSURLRequestCachePolicy.ReloadIgnoringLocalCacheDataas the value for the cachePolicy argument.


Skip confirmation page on node delete

Question: I'm trying to skip delete confirmation page only for a content type in my site.
I found this question but I can't figure out how to modify this code to affect only a nodes in a content type.
This is the code i found:
function mymodule_menu_alter(&$items) {
  $items['node/%node/delete']['page callback'] = 'my_node_delete_function';
  $items['node/%node/delete']['page arguments'] = array(1);
  $items['node/%node/delete']['module'] = 'mymodule';
}

function my_node_delete_function($node) {
  // Taken from node modules node_delete_confirm submit handler
  node_delete($node->nid);
  watchdog('content', '@type: deleted %title.', array('@type' => $node->type, '%title' => $node->title));
  drupal_set_message(t('@type %title has been deleted.', array('@type' => node_type_get_name($node), '%title' => $node->title)));

  // Do a drupal goto here to preserver the 'destination' parameter
  drupal_goto();
}

Comment: You can use rules module to set a rule to redirect to certain path after deleting a node from specific content type.
Answer: Just checking the node's type should be enough, and you can default to returning the standard deletion form:
function my_node_delete_function($node) {
  // If the node is of your custom type, delete it straight away.
  if ($node->type == 'my_type') {
    node_delete($node->nid);
    // ...
    drupal_goto();
  }
  else {
    // Otherwise, serve the standard node delete page.
    module_load_include('inc', 'node', 'node.pages');
    return drupal_get_form('node_delete_confirm', $node);
  }
}

Comment: With this code if I try to delete content of another content type I have only a white page in return
Comment: Try the updated code...

Skip confirmation page on node delete


Key signature and chord progressions

Question: I was studying a blues song (Bessie's Blues) in all keys and I seem unable to understand something that seems quite basic.
So, in the typical progression for a Bb organ we have C7-F7-C7-C7-F7-F7 etc.
We are in the key of C so all is natural except B in C7 and E in F7 which are flatted since they are mixolydian mode.
But then it occurred to me: does the key signature define which notes are sharpened/flattened or the chord in each separate meter? If we follow the key then the chord becomes something else. If we follow the chord, why need a key signature.
Things get worse if we transpose it to E7-A7-E7-E7-A7-A7 etc. since the bigger the number of sharps and flats the more the complications with the signature.
I'm fairly new to this so it's a bit of a struggle to express myself coherently.
Thank you in advance!
Answer: This really about jazz harmony and chord symbols versus staff and key signatures.
There are many online charts and guides about reading jazz chord symbols.

https://en.wikipedia.org/wiki/Jazz_harmony
https://bretpimentel.com/jazz-chord-symbols-a-primer-for-the-classically-trained/
etc.

Of course the issue is how to know the specific quality of the numbered intervals like 7, 9, 6, 5, etc.. Are they major, minor, or diminished?
Other that just memorizing a jazz chord chart a rule of thumb that seems to work is consider the chord as built on a dominant with all the chord tones being diatonic. All the added chord symbols are relative to this basic dominant chord.
If the symbol is C7, consider that a C dominant seventh chord where the 7th is minor (in terms of key it would be in F major using a B flat.) C9 would be a C dominant ninth chord with a diatonic, major 9th (in the key of F major the 9th above C would be a D natural.)
As you point out, the confusing thing about jazz oriented lead sheets is the main melody may be written on a staff with a key signature, but the chord symbols are NOT written relative to that key signature. The chord symbols are relative to the letter given in the symbol.
To illustrate this point imagine a lead sheet with a melody notated in C major and the chord symbol E9 was used. Rather than being an E minor 7th ♭9 (E,G,B,D,F all naturals), that should be an E dominant ninth chord where in terms of key it would be the dominant of A major (E,G#,B,D,F#.) It could also be considered a ninth chord built on the tonic of E mixolydian, but I don't think that makes it easier to understand. We have to do some mental juggling to keep track of the chord and interval qualities and accidentals for different keys.
If you practice in all keys, eventually the intervals of a dominant will 'sink in.' But a quick list might help. Let's switch to a G dominant (the key would be C major.)
INTERVAL ----- QUALITY - LETTER

Root --------- n/a ----- G
13th (6th) --- major --- E
11th (4th) --- perfect - C
9th ---------- major --- A
7th ---------- minor --- F
5th ---------- perfect - D
3rd ---------- major --- B
Root --------- n/a ----- G

All the additional chord symbols are from that diatonic dominant chord reference point.
If the base triad is not major but minor, a symbol is added: Gmin or Gm or G-.
If the seventh is not minor but major, a symbol is added: Gmaj7 or G∆7
Continue from the this diatonic dominant chord for other intervals.
The 5th is normally perfect so b5 is added for a diminished 5th: G7b5.
The 9th is normally major so b9 could be added for a minor 9th: G7b9, or #9 for an augmented 9th `G7#9.
Comment: Quite informative thank you! I intent to uovote as soon as I am permitted
Answer:
does the key signature define which notes are sharpened/flattened or
  the chord in each separate meter?

The key signature only effects the notes on the staff, it does not impact the chord symbols. So the F7 will have an Eb regardless of the key signature, but the notes in the staff will still be controlled by the key signature.
For example, here is a lead sheet for "Billie's Bounce" by Charlie Parker

Look at the 3rd measure of the 2nd line - the first note is an A, even though the chord symbol is Bb7 (which contains Ab). When playing this tune, you will play the note A during the melody, but the rhythm section will play the Bb7 chord (which has an Ab). During solos, you will treat the chord like any other Bb7 chord.
Answer:
We are in the key of C so all is natural except B in C7 and E in F7 which are flatted since they are mixolydian mode.

Actually, if someone wanted to notate a melody in C-mixolydian mode, there should be a key signature of one flat (b-flat).
The real reason these notes are flatted is that the 7 chord symbol denotes a chord in the form of a dominant seventh, comprising a root, a major third, a perfect fifth, and a minor seventh.
To denote a chord with a major seventh on top (i.e., like the ones in the question but with b-natural and e-natural instead, called a major seventh chord), one uses maj7, as in Cmaj7 or Fmaj7.
As noted correctly by the other answers, the key signature does not affect the chord symbols.

Key signature and chord progressions


Using gvim to print diffs?

Question: Is there a way to print out the diffs like they show when you open them with "gvim -d", with all the common code folded away and only the diffs showing in context?  I tried the print menu option, but it printed the entire file that I was currently "in", rather than printing the folded diffs.
Answer: I dont think theres a way to get a side by side printout of the two files being diffed. But, you could use Vim's "Convert to HTML" tool on each of the two files being diffed and print those out separately. You could then stack them side by side to get the same effect.
Convert to HTML is kind of "pretty printing" - it saves all of the visual colour/syntax/fold  information.
:he convert-to-HTML

Comment: That's not what I was hoping for, but I guess it will have to do.
Answer: I have had luck using a combination of diff and a2ps:
$ diff -y --suppress-common-lines oldfile newfile | \
  a2ps -l 130 --columns 1

Answer: First, TOhtml plugin @Gowri was talking about, is able to output one HTML with both files shown (unless you have set g:html_diff_one_file to 1). Second, if you are not fine with output of TOhtml you can try my own formatvim (command to use in this case: :Format diffformat (may be truncated to :Format d)). It has a bit more features in html output, but the main reason why I bothered with writing it is that you can write your own output format specification, all things connected to html are kept in one place.

Using gvim to print diffs?


Use exposed filters to reorder nodes?

Question: Just wondering whether I can use exposed filters to re-order a list of nodes rather than eliminating ones that don't fit the desired criteria.
E.g. If I filter for 'Monday' and have a list of nodes [Sunday, Saturday, Friday, Thursday, Wednesday, Tuesday, Monday], then I would like the list of nodes to return as Monday, Sunday, Saturday, Friday, Thursday, Wednesday, Tuesday.
At the moment my result when I filter for the term 'Monday', is just 'Monday'.
Any thoughts?
Cheers!
Answer: Depending on your display requirements, you might be able to use a table format.  When using a table format, you have the option to set columns to "sortable".
Format section:

Sorting settings:
Comment: This way would allow you to sort alphabetically, but you just add your fields and select which ones should be sortable in the format settings.  If you needed something other than alphabetical sorting, you would want to write a custom module with a custom views sort handler.
Comment: There are a million jquery sort/filter plugins.  You could likely find one that fits your specific needs and just drop it on top of your existing setup.
Comment: That's a good idea! What's the next step though? How do I make it sortable in the way I'd like?
Comment: I might have to do that, as I need sorting by an input.

The user says 'Monday' and I need to bring 'Monday' to the top of the list.
Comment: So you're talking not a module, but chucking it in the code instead?
Comment: Liam, that's what I would do. I've frequently created an additional, hidden table column that contains concatenated or calculated values, and I set that column to be the default sort (the radio button on the right side of Patrick's picture.

In your case, I suppose I'd give the days numeric values starting from Monday and sort by those. (Check out [Bergmark's answer here][1] for a good way to do that.)
[1]: http://stackoverflow.com/a/11497447

Use exposed filters to reorder nodes?


Insert/create user in database using login form

Question: I know its dump question, using login form and insert user in database.
Actually, I have an API that includes users of company/organization and these users already have registered on other applications. So, using such API I can get user info using username and password.
Of course, we need to logged in users directly (without registration) who already have account on other applications.
For logging in, I need to, first, insert the user info in data (before insertion, I can fetch username and password from API) so user can get in the site as logged in user.

After fetching from API, how to create user in the database with
username and password field only?
It should be done without email info.
Comment: `mail` is a required property, you can't have a Drupal account without an email address
Comment: It can be done without email address. See my answer.
Answer: It is not possible to create a user account in Drupal without writing an email account.
An example of how you can create a user programmatically is:
<code> $new_user = array(
  'name' => 'name',
  'mail' => 'firstname.lastname@example.com',
  'pass' => 'password', // note: do not md5 the password
  'status' => 1
 );

 //custom fields
 $new_user->field_name_lasname['und'][0]['value'] = 'Name and Last Name';
 //custom fields ( custom fields)
 $new_user->field_referenced_field_['und'][0]['target_id'] = 0;

 user_save(null, $new_user);
</code>
Please excuse me my English is not good
Comment: It can be done without email address. See my answer
Answer: According to my question requirements, it can be done by using the user_external_login_register and user_external_load Drupal APIs. See the custom module below for more understanding. I hope this will help someone who needs the same requirement(s).
<code><?php
/**
* Implementation of hook_form_FORM_ID_alter
*/
function hook_form_user_login_alter(&$form, &$form_state) {
    _subscribe_user_login_form_alter($form, $form_state);
}
function _subscribe_user_login_form_alter(&$form, &$form_state) {
    $saveForm = $form;
    $form = array();
    // overrides the default validator
    foreach( $saveForm as $key => $value ) {
        if( $key == '#validate' ) {
            $form[ $key ] = array();
            foreach( $value as $validator ) {
                if( $validator == 'user_login_authenticate_validate' ) {
                    $validator = 'MODULENAME_authenticate_validate';
                }
            $form[ $key ][] = $validator;
            }
        } else {
            $form[ $key ] = $value;
        }
    }
}

function MODULENAME_authenticate_validate( $form, &$form_state ) {
    $name = $form_state[ 'values' ][ 'name' ];
    $pass = $form_state[ 'values' ][ 'pass' ];
    // use Drupal authentication for this user
    if ($name == 'admin'){
        return user_login_authenticate_validate($form, $form_state);
    }
    $authenticated = api_check_user($name, $pass);
    if ($authenticated == TRUE){
        //save external user if don't exist
        user_external_login_register($name, "MODULENAME");
        // we must set the 'uid' to pass back.  this looks up the logged in user and sets the Drupal UID
        $account = user_external_load($name);
        $form_state['uid'] = $account->uid;
        drupal_set_message(t('an error has occured'));
    }else{
        drupal_set_message('Error displayed'); // do nothing, Drupal will handle the errors
    }
}
function api_check_user($name, $pass){
    //write code to authenticate user from API
    //if username and password match then API returns true/false
    //if we get true
    return TRUE;
}
</code>


How do I assign different handler to one event listener like the click addEventListener. This is what I have being doing

Question: Var a = document.querySelectorAll("img")
For(i = 0; i < a.length; i++) {
    Var b = a[i].addEventListener ("click", tee, bee);

    Function tee () {
        Console.log("Hello")
    }

    Function bee () {
        Console.log("world")
    }

Comment: You can bind one function, which will then call `tee` and `bee`. E.g: `addEventListener("click", () => {tee(); bee();})`, you can pass through the event object if needed
Answer: First of all case matters in JavaScript. addEventListener accepts single listener.
You can call the second function inside the function:

var a=document.querySelectorAll("img")
for(i=0; i<a.length; i++){
  var b = a[i].addEventListener("click", tee);
}
function tee (){
  console.log("Hello")
  bee();
}

function bee (){
  console.log("world")
}

Comment: Thanks alot, I appreciate


Is it possible to rollback only nested transaction for autotesting

Question: Consider the following code:
ExecuteSQL("UPDATE ...");

using (var t = new TransactionScope())
{
    ExecuteSQL("UPDATE ...");

    if (SomeCondition)
        t.Commit();
    else
        t.Rollback();
}

var result = ExecuteSQL("SELECT ...");

Then we write an auto test using outer TransactionScope to rollback changes after each test:
[TestInitialize]
public override void Initialize()
{
    _transaction = new TransactionScope();
}

[TestCleanup]
public override void Cleanup()
{
    _transaction.Dispose();
}

It's not possible to write a correct test for a case when SomeCondition is false. Because nested transaction ROLLBACK rollbacks the whole outer transaction including the first UPDATE statement.
Do you know any workarounds?
Answer: No. You can rollback to a savepoint, see Exception Handling and Nested Transactions but that is not the same as what you want.
What is what you're really trying to achieve? Testing should occur under similar conditions to production. Adding an uber transaction and testing methods in inner transactions is nothing like how the system would behave in production.
Answer: SQL Server doesn't really support nested transactions.  It just has one transaction that has seen multiple start transaction statements, and requires multiple commit transaction statements before it really commits.
As a workaround, don't nest the transactions. It is possible to run two transactions simultaneously on different connections.
Answer: Unnamed rollback rolls all thansactions back up to the top of the stack.
The only thing which can help is to use named SAVE TRANSACTION
Warning: Does not work with distributed transactions.
Comment: Are there any TransactionScope wrappers that use SAVE TRANSACTION?
Comment: @alexey Try to pass the command itself to server, without any wrappers
Comment: @alexey ... and notice, that TransactionScope is SERIALIZABLE by default and VERY distribution tran friendly 8-)


How to insert a new column into mysql field data table?

Question: How would I insert a new column into mysql field data table? For example, if I have a field (myfield) with the mysql table field_data_field_myfield having the following columns'entity_type', 'entity_id', 'revision_id', 'bundle', 'delta', 'language', 'myfield_value' and 'myfield_format'...how could I add the column mynewcolumn as type varchar?
Answer: For adding new column in table, please check this discussion Correct way to add custom column to user table?.
Please check this discussion also https://www.drupal.org/node/2616250
Comment: Thanks Vijay! I had already find the answer... It looks the same, so I will give you a check


Fechar menu mobile ao clicar em rolagem

Question: Para ter uma melhor noção do que preciso o site seria esse. Precisava que no menu quando acessado via mobile ao clicar em um link fechasse o menu e deslizasse para a seção, porém ele rola perfeitamente mais o menu fica aberto.

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        Menu

                    </button>

HOME

DIFERENCIAL

SERVIÇOS

QUEM SOMOS

FALE CONOSCO

2° Via Boleto

Answer: Adicione o seguinte bloco de script para que ao clicar em um link do menu ele realize o colapse
$('.navbar-nav a').on('click', function(){
  $('.collapse').toggleClass('in');
});

Comment: Você é o cara!!! muito obrigado!

Fechar menu mobile ao clicar em rolagem


Can I use PHP for a mobi site?

Question: I have been doing some research on mobile websites, and thus far it seems to me that PHP is not supported by most handsets.
I am trying to create multiple form's that lead up to a auto email response, which would be fairly simple if I could use PHP.
Is there any other way of achieving this?
Comment: @kielie: No... you're not. When you submit a form through your mobile handset's browser, the response is sent back to the server as a POST variable. Your *server* then parses this, and the PHP interpreter on your *server* stuffs it into a nice easy to access `$_POST` variable. You have a big misunderstanding here.
Comment: Are you trying to run PHP directly on the handset or are you using it to power a website to be viewed by the handset?
Comment: I am trying to pass form values via POST to PHP functions, so I am trying to use it directly on the handset.
Comment: Oh ok, I see, didn't know that, I'm still learning, please forgive my lack of knowledge.
Comment: This is being asked frequently on SO, check the search for previous questions on the issue. A quick search turns up this one: http://stackoverflow.com/questions/1607047/best-practice-for-developing-webpage-for-mobile-phone
Answer: PHP is server side language, your server has to be support for it. handsets should support html or whatever you output with php.
Answer: PHP is usually executed on the server, not the handset itself, so the question is more if your PHP spits out HTML unsuited for a handset.
Comment: Cool, thanx for the info! It makes much more sense now.
Answer: Yes - its perfectly possible to write WML using PHP, only vaveat is that you need to add a custom header to set the mimetype if your default behaviour for PHP files is to return text/html. And, of course you need to understand WML - which is quite different from HTML.
These days a lot of handhelds can now cope with HTML although don't expect javascript.

PHP is not supported by most handsets

Eh? What's that got to do with it? PHP runs on the server - not on the client.
C.
Comment: That is what I read on a few forums actually, no jokes, but now that you've all cleared that up for me, I don't know how the heck they could ever have said something like that, next time I'll just post the question on SO first!
Answer: Have a read up on the basic request/response cycle for a web page.
Assuming by "mobile website" you mean "a normal website that is tailored for display on a mobile device" the answer is that PHP runs on the server not the client, the client only displays HTML given to it by the server.
Comment: Yeah basically.
Will do, thanx for the info.

Can I use PHP for a mobi site?


populate drop down from results using ajax

Question: I am having a problem trying to get ajax functioning properly, everytime I do a call i get
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /system/ajax
StatusText: Internal Server Error
ResponseText:

What am i trying to do is have the drop down fill with the results of a function from api. The function works perfectly it gets the results when needed however the problem is with the ajax I even try to print out hello world and still got the 500 error.
this is the code I currently have, any advice is appreciated.
function autotitleform($form, &$form_state){

    $form['vehicle_info'] = array(
        '#type' => ('fieldset'),
        '#title' => t('Vehicle Information'),
    );

    $form['autoinfo']['vehicle_year'] = array(
        '#type' => 'select',
        '#title' => t('Vehicle Year'),
        '#options' => auto_title_year_api(),
        '#ajax' => array(
            'callback' => 'auto_title_make_api_callback',
            'wrapper' => 'api_make'
        ),
    );

    $form['autoinfo']['wrapper'] = array(
        '#prefix' => '
',
        '#suffix' => '
',
    );

    $options = array('- Select Make -');
    if(isset($form_state['values']['vehicle_year'])){
        $options = auto_title_make_api();
    }

    $form['autoinfo']['wrapper']['make_description'] = array(
        '#title' => t('City'),
        '#type' => 'select',
        '#options' => auto_title_make_api(),
  );

    if(isset($form_state['values'])){
        $form['page_output'] = array(
        '#markup' => autotitledb_submit($form, $form_state)
        );
    }
    return $form;
}

function auto_title_make_api_callback($form, $form_state) {
  return $form['autoinfo']['wrapper'];
}

function auto_title_make_api(){
$url_make = 'https://test.api.800loanmart.com/Loanmartservice.svc/soapssl'; // SOAP 1.1
$post_str_make = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetVehicleMakes xmlns="http://tempuri.org/">
<customerId>73c858f0-791c-454e-b4d5-5634bf13621d</customerId>
<authenticationId>3074940f-7efe-447c-a7ff-3c152acdf8c4</authenticationId>
<year>2000</year>
</GetVehicleMakes>
</s:Body>
</s:Envelope>';

    $headers_make = array(
        'Content-type: text/xml; charset="utf-8"',                      // For SOAP 1.1 - JHW Jan 26, 2013
        "Accept: text/xml",
        "Cache-Control: no-cache",
        "Pragma: no-cache",
        "SOAPAction: \"http://tempuri.org/ILoanmartService/GetVehicleMakes\"",
        "Content-length: ".strlen($post_str_make)       // Amount of data in bytes to be posted
    );

      $options_make = array(
          CURLOPT_RETURNTRANSFER => true,         // return web page / XML result
          CURLOPT_HEADER         => 0,          // 1/0 return/don't return headers 0 for production or 1 for debug
          CURLOPT_HTTPHEADER     => $headers_make,          // post headers
          CURLOPT_FOLLOWLOCATION => true,         // follow redirects
          CURLOPT_ENCODING       => "",           // handle all encodings

          // Browser/User Agent String
          CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'],

          CURLOPT_AUTOREFERER    => true,         // set referer on redirect
          CURLOPT_CONNECTTIMEOUT => 120,          // timeout on connect
          CURLOPT_TIMEOUT        => 120,          // timeout on response
          CURLOPT_MAXREDIRS      => 10,           // stop after 10 redirects
          CURLOPT_POST           => 1,            // We are sending post data needs to be = '1'
          CURLOPT_POSTFIELDS     => $post_str_make,     // this is the XML post data
          CURLOPT_PORT           => 443,                    // SSL Port, probably unnesecery

          CURLOPT_SSL_VERIFYHOST => false,        // Don't verify ssl on either side
          CURLOPT_SSL_VERIFYPEER => false,        // dito, don't verify ssl on either side

          CURLOPT_VERBOSE        => 1,            // Set to 1 for debug
        );

    $soap_do_make = curl_init($url_make);
    curl_setopt_array($soap_do_make, $options_make);
    $result_make = curl_exec($soap_do_make);

$sls_make = simplexml_load_string($result_make);
$sls_make->registerXPathNamespace('a', 'http://schemas.datacontract.org/2004/07/LM.API');
$sls_list_make = $sls_make->xpath('//a:MakeDescription');
foreach($sls_list_make as $sls_list_make_child){

$sls_list_make_child_result[] = sprintf("%s", $sls_list_make_child);}
dpr($sls_list_make_child_result);
$sls_list_make_child_results = array_combine($sls_list_make_child_result, $sls_list_make_child_result);

        // Close cURL
        curl_close($soap_do_make);

 return $sls_list_make_child_results;
}
function auto_title_year_api(){
$url_year = 'https://test.api.800loanmart.com/Loanmartservice.svc/soapssl'; // SOAP 1.1
$post_str_year = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetVehicleYears xmlns="http://tempuri.org/">
<customerId>73c858f0-791c-454e-b4d5-5634bf13621d</customerId>
<authenticationId>3074940f-7efe-447c-a7ff-3c152acdf8c4</authenticationId>
</GetVehicleYears>
</s:Body>
</s:Envelope>';

    $headers_year = array(
        'Content-type: text/xml; charset="utf-8"',                      // For SOAP 1.1 - JHW Jan 26, 2013
        "Accept: text/xml",
        "Cache-Control: no-cache",
        "Pragma: no-cache",
        "SOAPAction: \"http://tempuri.org/ILoanmartService/GetVehicleYears\"",
        "Content-length: ".strlen($post_str_year)       // Amount of data in bytes to be posted
    );

      $options_year = array(
          CURLOPT_RETURNTRANSFER => true,         // return web page / XML result
          CURLOPT_HEADER         => 0,          // 1/0 return/don't return headers 0 for production or 1 for debug
          CURLOPT_HTTPHEADER     => $headers_year,          // post headers
          CURLOPT_FOLLOWLOCATION => true,         // follow redirects
          CURLOPT_ENCODING       => "",           // handle all encodings

          // Browser/User Agent String
          CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'],

          CURLOPT_AUTOREFERER    => true,         // set referer on redirect
          CURLOPT_CONNECTTIMEOUT => 120,          // timeout on connect
          CURLOPT_TIMEOUT        => 120,          // timeout on response
          CURLOPT_MAXREDIRS      => 10,           // stop after 10 redirects
          CURLOPT_POST           => 1,            // We are sending post data needs to be = '1'
          CURLOPT_POSTFIELDS     => $post_str_year,     // this is the XML post data
          CURLOPT_PORT           => 443,                    // SSL Port, probably unnesecery

          CURLOPT_SSL_VERIFYHOST => false,        // Don't verify ssl on either side
          CURLOPT_SSL_VERIFYPEER => false,        // dito, don't verify ssl on either side

          CURLOPT_VERBOSE        => 1,            // Set to 1 for debug
        );

    $soap_do_year = curl_init($url_year);
    curl_setopt_array($soap_do_year, $options_year);
    $result_year = curl_exec($soap_do_year);

$sls_year = simplexml_load_string($result_year);
$sls_year->registerXPathNamespace('a', 'http://schemas.datacontract.org/2004/07/LM.API');
$sls_list_year = $sls_year->xpath('//a:Year');
foreach($sls_list_year as $sls_list_year_child)
{$sls_list_year_child_result[] = sprintf("%s", $sls_list_year_child);}

$sls_list_year_child_results = array_combine($sls_list_year_child_result, $sls_list_year_child_result);

        // Close cURL
        curl_close($soap_do_year);

 return $sls_list_year_child_results;
}

Edit #1
The errors I am gettings are
Notice: Undefined index: #options in form_select_options() (line 2661 of /home/loansdotorg/public_html/includes/form.inc).

And

Warning: Invalid argument supplied for foreach() in form_select_options() (line 2668 of /home/loansdotorg/public_html/includes/form.inc).

Edit #2 I think I have this working although I will need to test it out more.
Comment: What does your server log say?  Do you see a real error message if you browse directly to the AJAL URL?
Comment: I took a look at the report log and it isnt giving any errors back. I am clueless as to what the problem is, and as for going to the ajax url, do you mean site.com/system/ajax? Because if so I did go to that url and it was just a white screen. Any other suggestions?
Comment: If you are getting a 500 error, then the error should be in the apache error log.  The white screen is a 500 error too.  Check out http://drupal.org/node/158043 and report back.  My guess is either the cURL or the simplexml is barfing.
Comment: Actually I see i am gettings errors now, I must have missed them. I posted the error above in a edit
Comment: Neither of those should generate a 500.
Comment: What's the reason for these lines: `if(isset($form_state['values']['vehicle_year'])){
        $options = auto_title_make_api();
    }`? You're explicitly setting `'#options' => auto_title_make_api(),` immediately after...
Answer: If you look at function "form_select_options()" it also sets the selected item so
set '#default' => 0 for your dropdown form variable and you wont see see that warning anymore!
$form['autoinfo']['vehicle_year'] = array(
        '#type' => 'select',
        '#title' => t('Vehicle Year'),
        '#options' => auto_title_year_api(),
        '#default' => 0, //this was missing and hence the warning,
        '#ajax' => array(
            'callback' => 'auto_title_make_api_callback',
            'wrapper' => 'api_make'
        ),
    );

Answer: I'd suggest using devel module and dd() that return value just before the return to ensure it is correctly structured. with devel enabled a drupal_debug.txt file will be created on server in /tmp
Answer: When I call a web service from php I do something like this:
  $client = new SoapClient("Your URL .svc?WSDL");
  $result = $client->MethodName(array('param' => 'value'));
  $result_object = $result->MethodNameResult;

Then you don't need to make the whole soap body and envelope. If you need to pass credentials in the header you can use:
$client = new SoapClient("some.wsdl", array('login'          => "some_name",
                                            'password'       => "some_password"));


Instrumentation run failed due to 'java.lang.OutOfMemoryError' if I use solo.takeScreenshot

Question: I'm having an OutOfMemoryException when I enable taking screenshot during my test with Robotium.
[2014-01-09 10:53:28 - MyAppTest] Test run failed: Instrumentation run failed due to 'java.lang.OutOfMemoryError'

At the end of this message you can find the logcat error.
As you can see in the code below I've a variable that let me decide if I want to take screenshot or not; if I enable taking screenshot I've the error above after I run about 10 test methods (I take from 1 to 10 screenshot for each test).
This is the code I run:
public class TestApk extends ActivityInstrumentationTestCase2{
    private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME="com.xxx.xxxnew.activities.XxxActivity";
    private static Class launcherActivityClass;

    private static final boolean ENABLE_SCREENSHOT_CAPTURE = true;
    private static final int SLEEP_TIME = 4000;

    static{
        try{
            launcherActivityClass = Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
        } catch (ClassNotFoundException e){
            throw new RuntimeException(e);
        }
    }

    @SuppressLint("NewApi")
    public TestApk()throws ClassNotFoundException{
        super(launcherActivityClass);
    }

    private Solo solo;

    @Override
    protected void setUp() throws Exception {
        solo = new Solo(getInstrumentation(),getActivity());
    }

    @Override
    public void tearDown() throws Exception {
        solo.finishOpenedActivities();
    }

    public void test_login_001(){
    // ... some Robotium code
    if(ENABLE_SCREENSHOT_CAPTURE){
            solo.sleep(SLEEP_TIME);
            solo.takeScreenshot("login_001_c");
        }
    // ... some Robotium code
    if(ENABLE_SCREENSHOT_CAPTURE){
            solo.sleep(SLEEP_TIME);
            solo.takeScreenshot("login_001_c");
        }
    }

    public void test_login_002_a(){
    // ... some Robotium code
    if(ENABLE_SCREENSHOT_CAPTURE){
            solo.sleep(SLEEP_TIME);
            solo.takeScreenshot("login_002_a");
        }
    // ... some Robotium code
    if(ENABLE_SCREENSHOT_CAPTURE){
            solo.sleep(SLEEP_TIME);
            solo.takeScreenshot("login_001_2");
        }
    }

    //other test methods
}

This is the error from LogCat:
01-09 11:16:55.619: I/dalvikvm-heap(13717): Forcing collection of SoftReferences for 8294416-byte allocation
01-09 11:16:55.659: D/dalvikvm(13717): GC_BEFORE_OOM freed 10K, 14% free 112688K/129624K, paused 37ms, total 38ms
01-09 11:16:55.659: E/dalvikvm-heap(13717): Out of memory on a 8294416-byte allocation.
01-09 11:16:55.659: I/dalvikvm(13717): "main" prio=5 tid=1 RUNNABLE
01-09 11:16:55.659: I/dalvikvm(13717):   | group="main" sCount=0 dsCount=0 obj=0x40e68b38 self=0x40e4a0b8
01-09 11:16:55.659: I/dalvikvm(13717):   | sysTid=13717 nice=0 sched=0/0 cgrp=apps handle=1074288092
01-09 11:16:55.659: I/dalvikvm(13717):   | state=R schedstat=( 0 0 0 ) utm=1943 stm=453 core=0
01-09 11:16:55.659: I/dalvikvm(13717):   at android.graphics.Bitmap.nativeCopy(Native Method)
01-09 11:16:55.659: I/dalvikvm(13717):   at android.graphics.Bitmap.copy(Bitmap.java:471)
01-09 11:16:55.659: I/dalvikvm(13717):   at com.jayway.android.robotium.solo.ScreenshotTaker.getBitmapOfView(ScreenshotTaker.java:215)
01-09 11:16:55.659: I/dalvikvm(13717):   at com.jayway.android.robotium.solo.ScreenshotTaker.access$400(ScreenshotTaker.java:32)
01-09 11:16:55.659: I/dalvikvm(13717):   at com.jayway.android.robotium.solo.ScreenshotTaker$ScreenshotRunnable.run(ScreenshotTaker.java:326)
01-09 11:16:55.659: I/dalvikvm(13717):   at android.os.Handler.handleCallback(Handler.java:725)
01-09 11:16:55.659: I/dalvikvm(13717):   at android.os.Handler.dispatchMessage(Handler.java:92)
01-09 11:16:55.659: I/dalvikvm(13717):   at android.os.Looper.loop(Looper.java:137)
01-09 11:16:55.659: I/dalvikvm(13717):   at android.app.ActivityThread.main(ActivityThread.java:5328)
01-09 11:16:55.659: I/dalvikvm(13717):   at java.lang.reflect.Method.invokeNative(Native Method)
01-09 11:16:55.659: I/dalvikvm(13717):   at java.lang.reflect.Method.invoke(Method.java:511)
01-09 11:16:55.659: I/dalvikvm(13717):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
01-09 11:16:55.659: I/dalvikvm(13717):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
01-09 11:16:55.659: I/dalvikvm(13717):   at dalvik.system.NativeStart.main(Native Method)
01-09 11:16:55.659: D/AbsListView(13717): [unregisterDoubleTapMotionListener]
01-09 11:16:55.659: I/MotionRecognitionManager(13717):   .unregisterListener : / listener count = 0->0,
01-09 11:16:55.659: D/AbsListView(13717): unregisterIRListener() is called
01-09 11:16:55.659: D/AndroidRuntime(13717): Shutting down VM
01-09 11:16:55.659: W/dalvikvm(13717): threadid=1: thread exiting with uncaught exception (group=0x40e67ac8)
01-09 11:16:55.669: E/AndroidRuntime(13717): FATAL EXCEPTION: main
01-09 11:16:55.669: E/AndroidRuntime(13717): java.lang.OutOfMemoryError
01-09 11:16:55.669: E/AndroidRuntime(13717):    at android.graphics.Bitmap.nativeCopy(Native Method)
01-09 11:16:55.669: E/AndroidRuntime(13717):    at android.graphics.Bitmap.copy(Bitmap.java:471)
01-09 11:16:55.669: E/AndroidRuntime(13717):    at com.jayway.android.robotium.solo.ScreenshotTaker.getBitmapOfView(ScreenshotTaker.java:215)
01-09 11:16:55.669: E/AndroidRuntime(13717):    at com.jayway.android.robotium.solo.ScreenshotTaker.access$400(ScreenshotTaker.java:32)
01-09 11:16:55.669: E/AndroidRuntime(13717):    at com.jayway.android.robotium.solo.ScreenshotTaker$ScreenshotRunnable.run(ScreenshotTaker.java:326)
01-09 11:16:55.669: E/AndroidRuntime(13717):    at android.os.Handler.handleCallback(Handler.java:725)
01-09 11:16:55.669: E/AndroidRuntime(13717):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-09 11:16:55.669: E/AndroidRuntime(13717):    at android.os.Looper.loop(Looper.java:137)
01-09 11:16:55.669: E/AndroidRuntime(13717):    at android.app.ActivityThread.main(ActivityThread.java:5328)
01-09 11:16:55.669: E/AndroidRuntime(13717):    at java.lang.reflect.Method.invokeNative(Native Method)
01-09 11:16:55.669: E/AndroidRuntime(13717):    at java.lang.reflect.Method.invoke(Method.java:511)
01-09 11:16:55.669: E/AndroidRuntime(13717):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
01-09 11:16:55.669: E/AndroidRuntime(13717):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
01-09 11:16:55.669: E/AndroidRuntime(13717):    at dalvik.system.NativeStart.main(Native Method)

Answer: You can reduce the memory used by saving a lower-quality image for the screenshot.
int quality = 50; // On a scale of 1-100
solo.takeScreenshot("login_001_c", quality);

But there may be a memory leak in robotium that's causing the problem. If so you should file an issue here https://code.google.com/p/robotium/issues/list
Comment: I tryed reducing quality but I have the same error.
Could you give me a link to the issue about memory leak? I can't find it.
Comment: There is no link to the issue. I was suggesting that you should report it :-)


Copying hierarchy in Core Data

Question: I have the following model:

And I want the user to be able to duplicate a drawing so he has a new one with all the triangles, edges and vertex than the original.
At first I thought I would go trough all attributes (copying there values) and relationships (creating new entities). Bus as you can see there are some recursive relationships and I don't think that would work.
Answer: Simply do it in two steps:
First create the new objects, copying the attribute values.
In this step, also store, e.g in a NSMutableDictionary the mapping from original object to copied object: for each object that you copy do [targetObjects setObject:copiedObject forKey:[originalObject objectID]].
(You have to use objectID because NSManagedObjects can not be used as dictionary keys.
You can then recreate the relationships in a second step using the information from the original relationships and from the targetObjects dictionary.

Copying hierarchy in Core Data


Exemplar MLE for negative binomial?

Question: I recently compared MLE estimates for a negative binomial fit using two different pieces of software, and got different results.  I'd like to determine which (if either) is correct.
To do that, I'd like an example of a simple set of data along with the corresponding MLE solution.  I'd really like an analytic proof of the optimality of the MLE solution, since determining it with some third software library seems a bit circular.  However, we are free to choose any data that might make the analysis work out nicely.
For the record, I noticed the discrepancy through these snippets of code (first library in R, second library in Python).  The data was {2,4} (i.e., I only fit two data points).
library(MASS)
x=fitdistr(c(2,4),"Negative Binomial")
p = x$estimate['size'][[1]] / (x$estimate['size'][[1]] + x$estimate['mu'][[1]])
# Results:
# > p
# [1] 0.9708738
# > x
#      size         mu
#   100.00020     3.00000
#  (505.70845) (  1.24298)

and
import fit_nbinom
x = fit_nbinom.fit_nbinom(np.array([2,4]))
mu = ((1.0-x['prob'])/x['prob'])  * x['size']
# Results:
# In []: x
# Out[]: {'prob': 0.98892868281051893, 'size': 270.37321834245245}
#
# In []: mu
# Out[]: 3.026899423427535

Comment: It's not apparent that you did get different results: the differences are well within the reported standard errors, suggesting the explanation may lie with floating point imprecision.  Indeed, if you rerun the `r` version with different starting values or different precision and accuracy requirements, you will get different results, too. In such circumstances it can help to provide input data where you have an exact *analytical* solution available for comparison. Have you worked out the exact solution for your sample data?
Comment: I think this is precisely my question, @whuber, (i.e., could somebody please help me find an exact analytical solution).  The errors appear to be about 1% in the mean (and a factor of >two in the "size" parameter), so it seems surprising if this were a function of floating point precision.  (At least for the Python code, I would expect errors several orders of magnitude smaller.)
Comment: In this case $\hat{\mu} = 3$ IS the MLE, so that 3.0268... from Python is wrong.  (It is always the case that the sample mean is the MLE for $\mu$ in that parameterization of the NB.)   A roughly 1% relative error when you only have two data points of the same order of magnitude is pretty large... I suspect the code iterates to a not-very-tight convergence criterion.  Iteration is required for the solution of the MLE equations for the NB, so you won't find an exact analytic solution.
Answer: The negative binomial density is:
$$f(x) = \Gamma(x + n )/(\Gamma(n) x!) p^n (1-p)^x$$
So for your sample:
$$L([2,4]) = f(2)f(4) \propto \Gamma(2 + n )\Gamma(4 + n )/2\Gamma(n)( p^{2n} (1-p)^6 ) $$
which we are to maximize
The mean is 3 by default as others have noted. Define a few useful R wrappers:
loglik <- function(size) sum(dnbinom(c(2,4), size=size, mu=3, log=T))

and just visualize what happens over a range of "size"
plot(1:1000, sapply(1:1000, loglik), type='l', xlab='Size parameter', ylab='Trace of log likelihood')

You can see the likelihood approaches an asymptote and has no unique, finite maximum.
Comment: As a follow-on comment - the sample variance (1) is less than the sample mean (3), which I believe always causes the MLE to exhibit this behavior.

Exemplar MLE for negative binomial?


Fade out na div mãe mas não nos seus filhos com jQuery

Question: Eu tenho este código, mas gostaria que a #navBar sofresse o fadeOut, #menuBt e #hi ficassem sempre visíveis, é possível?
HTML:

menu

jQuery:
$('#navBar').stop().fadeOut(500);

Comment: http://meta.pt.stackoverflow.com/questions/297/quando-se-deve-colocar-o-nome-da-linguagem-no-t%c3%adtulo/1911#1911
Comment: Acho que só tirando de dentro do `#navBar`.
Answer: A única forma de fazer isso é retirando os nós internos ao navBar de dentro do navBar. Uma forma é adicioná-los após o navBar quando a animação terminar:
$('#navBar').stop().fadeOut(500,function(){
  $(this).after($(this).children());
});


How is Kleene's T predicate defined?

Question: What I don't understand is how to extract information from the number that encode the computation history.
I know it's defined in Kleene's Introduction to Metamathematics. But what page?
References are welcome. More information on Kleene's T predicate can be found here.
Answer: There is also a more indirect proof method, which is to first show that any computable relation is definable in arithmetic and then note that the relation represented by the T predicate is computable. In fact the relation is primitive recursive, but the computability is easier to see, via Church's thesis. Also, not only the computable relations are definable, all the arithmetical relations are also definable.
The proof that every primitive recursive relation (or function) is representable in arithmetic is somewhat easier than a proof specifically for the T predicate, because you can ignore details of Turing machines. Essentially the only issue is proving that one can quantify over finite sequences. There is a complete proof in many textbooks and in section 2.2 of these lecture notes by Stephen Simpson: http://www.math.psu.edu/simpson/notes/fom.pdf .
There is also a proof in section 49 of Kleene's Introduction to metamathematics, at least for primitive recursive functions. The general result for arithmetical relations follows immediately by simply adding quantifiers and using the normal form theorem from computability to show that one-quantifier relations are definable.  This may require proving that the T predicate is primitive recursive, but this is easier than proving it is representable in arithmetic, because one can use primitive recursion freely without having to worry about the $\beta$ function at the same time.
Comment: > easier than a proof specifically for the T predicate, because you can ignore details of Turing machines. Essentially the only issue is proving that one can quantify over finite sequences

But is not the Godel enumeration for sequences (computation history) just the same for Turing machines?
Answer: The description given on Wikipedia is adequate for most purposes:

The ternary relation $T_1(e,i,x)$ takes three natural numbers as arguments. The triples of numbers $(e,i,x)$ that belong to the relation (the ones for which $T_1(e,i,x)$ is true) are defined to be exactly the triples in which $x$ encodes a computation history of the computable function with index $e$ when run with input $i$, and the program halts as the last step of this computation history. That is, $T_1$ first asks whether $x$ is the Gödel number of a finite sequence $\langle x_j \rangle$ of complete configurations of the Turing machine with index $e$, running a computation on input $i$. If so, $T_1$ then asks if this sequence begins with the starting state of the computation and each successive element of the sequence corresponds to a single step of the Turing machine. If it does, $T_1$ finally asks whether the sequence $\langle x_j \rangle$ ends with the machine in a halting state. If all three of these questions have a positive answer, then $T_1(e,i,x)$ holds (is true). Otherwise, $T_1(e,i,x)$ does not hold (is false).

A more thorough (but still somewhat informal) discussion is given in Enderton's chapter of the Handbook of Mathematical Logic. Formal details of Gödel coding are given in Smorynski's chapter of the same Handbook. Before embarking on this, Smorynski writes:

The details of an encoding are fascinating to work out and boring to read. The author wrote the present section for his own benefit and his feelings will not be hurt if the reader chooses to skip it.

Wikipedia also gives details on Gödel numbering for sequences.
My recommendation is that you work out your own encoding in full detail. This is a valuable and interesting exercise that is best done in private...
Comment: Regarding your statement "...that best done in private", I once heard a quote of similar spirit from Paul Halmos: "Never integrate in public." I think this could be altered here to "Never program (a Turing machine) in public."
Answer: Shoenfield's Recursion theory also contains a detailed construction of Kleene's $T$ predicate. It can freely be downloaded from Link
Comment: It is on page 22. However to fully appreciate all the details, you'll need to read much more than a single page.
Comment: I got the book. On which page is it?

How is Kleene's T predicate defined?


Microsoft Visual Studio 2008 version generator

Question: Is there any smart solution to auto number build version.
Every build should increment version number and store it somewhere in executable project, and read this number during program execute.
Im using VS 2008 - Project for mobile device with .NET CF 3.5
Answer: In your AssemblyInfo.cs, simply have:
[assembly: AssemblyVersion("1.0.*")]

(and no AssemblyFileVersion)
This will auto number the third and fourth parts of the version based on date and time - you can still adjust the major and minor builds to match up with your marketing team's idea of the version number...


Update no sqlite nao atualiza dados

Question: Olá, alguém poderia me auxiliar ,o update não esta atualizando os dados!
Segue o botão que chama o método:
@Override
    public void onClick(View v) {

        Receita rec = new Receita();
        String dosradio = null;
        switch(rg.getCheckedRadioButtonId()){
        case R.id.rbCmp:
            dosradio = "cmp";
            break;
        case R.id.rbMl:
            dosradio = "ml";
            break;

        }
         if (getIntent().getExtras() == null){

        rec.setMedicamento(txtMedi.getText().toString());
        rec.setDosagem(txtDos.getText().toString());
        rec.setHorario(spn1.getSelectedItem().toString());
        rec.setVencimento(txtDt.getText().toString());
        rec.setdosradio(dosradio.toString());
        bdhelper.insertRec(rec);
         }
         else{

             rec.setMedicamento(txtMedi.getText().toString());
                rec.setDosagem(txtDos.getText().toString());
                rec.setHorario(spn1.getSelectedItem().toString());
                rec.setVencimento(txtDt.getText().toString());
                rec.setdosradio(dosradio.toString());
                bdhelper.updateReceita(rec);

         }

     }

        public void updateReceita(Receita rec)
       {
          db = getWritableDatabase();
          ContentValues editContact = new ContentValues();
          editContact.put("medicamento", rec.getMedicamento());
          editContact.put("dosagem", rec.getDosagem());
          editContact.put("dosradio", rec.getdosRadio());
          editContact.put("horario", rec.getHorario());
          editContact.put("venciment", rec.getVencimento());

          db.update("tab", editContact, "_id=" + rec.getId(), null);
          db.close();
       } //

Comment: @ThiagoRiderAugusto suas edições não estão melhorando o entendimento da pergunta(que por sinal não está muito clara por si). Por esta razão rejeitei suas edições.
Comment: Matheus, sua pergunta está um pouco confusa, edite-a explicando melhor o problema enfrentado.
Comment: Poderia adicionar o método **updateReceita** ?? É lá que ñ está funcionando, correto?
Comment: ok editei a Pergunta
Comment: problema resolvido...obrigado
Answer: Tente realizar o update da seguinte forma:
db.update("tab", editContact, "_id = ?", new String[]{rec.getId().toString()});
db.close();

Você pode incluir ? na cláusula WHERE, que será substituído pelos valores do quarto parametro.
Os valores serão vinculados como String.
Segue a documentação.

Update no sqlite nao atualiza dados


Irreducible polynomials of degree 3 and 5

Question: Two part question:
1) There are three irreducible cubic polynomials $\mathbb F_2$
Aproach: Bruteforce, there are not as much cubic polynomials, just 8 of them:
$x^3$
$x^3+1$
$x^3+x$
$x^3+x+1$
$x^3+x^2$
$x^3+x^2+1$
$x^3+x^2+x$
$x^3+x^2+x+1$
Only three of them are irreducible(??): $x^3+1$,$x^3+x+1$ and $x^3+x^2+1$
Reality check - do i miss point of irreducible polynomial here, and should consider adding $x^3+x^2+x+1$ to irreducible list? It is reducible, bit different way then other polynomials: $x^3+x^2+x+1=(x+1)^3$
2) Only irreducible polynomial of degree 2 over $\mathbb F_2$ is $x^2+x+1$. Does it help, with conjuction of part 1, to find all irreducible polynomials of degree 5?
Answer: A polynomial in a field of degree two or three is irreducible if and only if it has no root. In $\mathbb F_2$ it is quite easy to check if a polynomial has a root:

$0$ should be no root $\Leftrightarrow$ the constant coefficient is $1$.
$1$ should be no root $\Leftrightarrow$ the number of non-zero coefficients is odd.

Both conditions can only be satisfied for non-constant polynomials if we have at least three non-zero coefficients. Five coefficients is too much for a polynomial of degree at most three. So we are looking for the polynomials with exactly three non-zero coefficients which are

$x^2+x+1$,
$x^3+x^2+1$,
$x^3+x+1$.

In particular your polynomial $x^3+1$ is reducible since $1$ is a root.
Interesting side note:
Let $p,q$ be primes. It is quite easy to determine the number of irreducible polynomials in $\mathbb F_p[x]$ of degree $q$. Because each element in $\mathbb F_{p^q}\setminus \mathbb F_p$ is of degree $q$ and every irreducible polynomial of degree $q$ with leading coefficient $1$ is the minimal polynomial of exactly $q$ elements in $\mathbb F_{p^q}\setminus \mathbb F_p$ we get that the number of irreducible polynomials in $\mathbb F_p[x]$ of degree $q$ with leading coefficient $1$ is
$$\frac{p^q-p}{q}.$$
So the total number of irreducible polynomials in $\mathbb F_p[x]$ of degree $q$ is
$$\frac{(p^q-p)(p-1)}{q}$$
because we can multiply each of the former polynomials with one of the $p-1$ many units of $\mathbb F_p$.
Application:
Using this result we get for $p=2$ and $q=2,3,5$ that there are
$$\frac{2^q-2}{q} = 1,2,6$$
irreducible polynomials of degree $q$ in $\mathbb F_2[x]$ which answers the question.
Comment: this is great info, thanks

what about reducibility of degree 5?
Comment: @TimoJunolainen See my edit.
Comment: thanks a lot!
feeling little fuzzy on subject, this clears a lot of things up


Meta content type

Question: Drupal core allows creating content types. I wish to have several different content types, all with the same structure.
For example:

Food
Italian food
Sicilian food

Each content type would share the same structure; if I add, or remove, a field the change should be reflected to each content type.
The reason I seek to use a parent content type, instead of using a taxonomy term field is that I could then adjust blocks to each child content type (for example a block about food in general, a block about general Italian food, a block about Sicilian food).
Is there a core way to do that?
Comment: Short and sweet, but: no, there's no way to do that in core. There's no concept of inheritance/template/meta-structure as you're describing for entity types
Comment: This sounds like taxonomy, food is food, food has subtypes (terms).
Comment: This will not help you manage the addition/deletion of fields, but there are entity bundle types, which are useful if you already created several content types with the same set of fields and want to share code among them: https://www.drupal.org/node/3191609
Answer: I think you can use the Entity Inherit module which will allows entities to inherit certain fields from another entity.

How it works
You tell Entity Inherit, in /admin/config/entity_inherit
which fields are used to define an entity's parent. For example you
might create an entity reference field named
field_entity_inherit_parent for this purpose.
Then, every time any entity is modified:
If other entities inherit from it, and have the same fields, and the
child's field has the same values as the parent field before it was
changed, the "child" entities' fields are updated to reflect the
parent entity's new value.

Meta content type


I have a compiler error for Cmake, what should I do?

Question: For the past two days, I've been trying to start coding C++ on CLion and I've been running into problems with Cmake. Any recommendations would be appreciated. I tried deleting CLion and redownloading, and I've tried putting in different Cmake options I found online for C++. Any help would be appreciated.
Short video of problem
Comment: Welcome to Stack Overflow! Please be **specific** about what you are trying to accomplish. Right now, your question is very broad. Please provide your C++/CMake code and any relevant **error** messages you may be encountering, and describe the **specific** steps you have taken to produce them. A video is helpful, but prefer to use **textual** code/logs and descriptions of the problem, as links to such videos may grow stale over time. Also, many viewers, such as myself, can't even view the video. Consider reading through the [How to Ask](https://stackoverflow.com/help/how-to-ask) page.
Answer: You have to install a compilers into command line as well. I guess the XCode is already installed. In addition you need to install command line tools via 'xcode-select --install' (maybe with sudo) to get while compilers toolchain in console too.
You can check if compiler works in terminal via e.g. 'clang --version' etc.
Anyway, please keep clear info about your dev. environment when you are asking..
Answer: I needed to install XCode as XCode includes the compiler.
invalid active developer path


Google Cloud platform - Migration

Question: I have a question about the Google Cloud Platform migration.
We currently have one GCP project which is  dedicated for one customer. We would like to move this project (and all components attached to it) to a new/different Google project.
Is this scenario possible?
Comment: Do you mean to move the billing/organization of the project?
Comment: Hi Thanks for your reply. No it's more if we can move a project to an another root organisation.
Comment: If it's inside an organization it should be possible to transfer the rights to another one. The same way you can do with the billing.
Comment: hi @night-goldno it's outside the current organisation
Comment: Is this what you are looking for? https://cloud.google.com/resource-manager/docs/migrating-projects-billing
Answer: Here [1] you can see the official procedure to follow in case you would like to migrate a project from an Organization or even a project from a NO-Organization project(Handling special cases).

Create a migration plan
Assign permissions
Configure organization policies
Perform the migration

[1] https://cloud.google.com/resource-manager/docs/project-migration

Google Cloud platform - Migration


Toast inside onClick method in Fragment

Question: I have a following Fragment:
public class FragmentSocial extends Fragment implements ActionBar.TabListener, OnClickListener
{

private Fragment mFragment;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActivity().setContentView(R.layout.fragment_social);
}

public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // relevant code...
}

public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    // relevant code...
}

public void onTabReselected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub

}

public void onClick(View v) {
    switch(v.getId())
    {
    case R.id.imgBtnFB:
        Toast.makeText(this, "FB pressed", Toast.LENGTH_LONG).show();
        break;
    case R.id.imgBtnTwitter:
        Toast.makeText(this, "Twitter pressed", Toast.LENGTH_LONG).show();
        break;
    }

}

I have a few image buttons in my fragment_social layout. For now I just want to make a Toast message to see what button was pressed. However, if I use this as context, I'm getting this error message:
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (FragmentSocial, String, int)
I tried to change this to FragmentSocial.this, to FragmentSocial.this.getActivity(), tried to create private Context mContext and to instantiate it to mContext = (I tried various options here) inside the onCreate method - but nothing worked. I either didn't have an error message, but also didn't see the Toast, or got other errors.
So how can I create a Toast here?
Thank you!
Answer: use:
getActivity().getBaseContext();

Comment: Do you mean like that: `Toast.makeText(getActivity().getBaseContext(), "FB pressed", Toast.LENGTH_LONG).show();`? Tried it, still didn't work... Also tried `Toast.makeText(FragmentSocial.this.getActivity().getBaseContext(), "FB pressed", Toast.LENGTH_LONG).show();` - didn't work, didn't see the Toast.
Comment: right. that should work. Put Log.d("test", "test") inside the onClick() and see if you have a message in Logcat. You would know then whether your onClick() method is called or not.
Comment: Nop, I didn't see the Log message. Guess I'm doing something wrong here... I also tried to do something like that in the onCreate method: `findViewById(R.id.imgBtnFB).setOnClickListener(this);` but I don't even have the `findViewById` method available for some reason.
Comment: Try to inflate your layout from onCreateView():
Comment: Remove everything from onCreate (keep super only) and create onCreateView() like this: @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  View view = inflater.inflate(R.layout.fragment_social, container, false);
        return view;
    }
Comment: Yes, just did, wanted to write here that the problem is solved :) After that I registered the buttons for onClickListener like that: `view.findViewById(R.id.imgBtnFB).setOnClickListener(this);` and everything finally worked like it should! Thank you very much! :)
Comment: I used getApplication() instead of getActivity() in Toast.makeText(getActivity().getBaseContext(), "FB pressed", Toast.LENGTH_LONG).show();, so I used Toast.makeText(getApplication().getBaseContext(), "FB pressed", Toast.LENGTH_LONG).show(); and it worked for me
Answer: If you are using fragment then use this code
Toast.makeText(getActivity(), "You have insufficient points", Toast.LENGTH_LONG ).show();

Comment: This is the shortest and simplest solution.
Answer: Either of the following lines work.
Toast.makeText(getActivity(), "hello",Toast.LENGTH_LONG).show();
Toast.makeText(getActivity().getApplicationContext(),"Hello",Toast.LENGTH_LONG).show();

Answer: Extending the answer by Marcin S., you could also setup the constructor inside the Fragment and pass in a context variable. You can then use this context anytime you wish to reference the activity. This method is also slightly quicker then getActivity().getBaseContext()
Add this to your FragmentSocial class:
Context context;
public FragmentSocial(Context context) {
    this.context = context;
}

When you ever say FragmentSocial fragmentSocial = new FragmentSocial(); in your main activity class, add the paramter this into the () to make it look like FragmentSocial fragmentSocial = new FragmentSocial(this);
Comment: I tried it and got this error message: *Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead* I also had to create an empty constructor, as I had more errors (I have this code in my onTabSelected method - `mFragment = new FragmentSocial();`)
Comment: @Igal Check my revised answer.
Answer: This is way i do in fragment
//edit
 YourActivity activity;

@Override
public void onAttach(Activity activity) {
   this.activity = (YourActivity) activity;
}

@Override
public void onClick(View v) {
    Toast.makeText(this.activity, "message", Toast.LENGTH_LONG).show();
}

Comment: The drawback of this approach is that you are mapping fragment to an activity. So it is not reusable with other activities.

Toast inside onClick method in Fragment


Why is Selenium's explicit wait not working in C#?

Question: The following code is using Selenium library. The problem is the trace command never gets printed given that it should be printed n times until the element becomes visible.
WebDriverWait wait = new WebDriverWait(new SystemClock(), driver, TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(500));
driver.Navigate().GoToUrl("test.com");
//  Thread.Sleep(1000);
wait.Until(_ =>
{
    Trace.WriteLine("aa");
    return ExpectedConditions.ElementIsVisible(By.XPath("//button[@data-a-target='change-country-button']"));
});

When I activate the commented line it works (most of the time).
Comment: How are you executing the application or test? This can make a difference, since the trace output might be directed to a different place depending on how you execute the program.
Comment: Debug; put a breakpoint on the Trace line. See if execution is paused. Then you can look where Trace is routing its output.
Comment: The trace is outputting to the console, I tried it and it's working . Breakpoints doesn't work neither on the trace line or the output line.
Comment: What are you trying to test exactly? If you're trying to see if the wait occurs, you would be better off just putting the log after the wait. If you really need that to happen, you might look into using the `PollingInterval` setting when instantiating your WebDriverWait.
Comment: Also as a heads up, but `ExpectedConditions` is the old way to do waits, and has been marked for deprecation, see this for the updated way https://www.selenium.dev/documentation/webdriver/waits/
Comment: the internal code block should be called at a constant interval untill the expected conditions return true. the problem is that the internal code block never gets called
Comment: the code beneath these lines never gets reached untill a timeout exception happens
Comment: I tried the other method written in the documentation `Until(driver => driver.FindElement(By.Name("q")))` still not working
Comment: Is the element within an iframe? If so you will need to switch to that context before the element can be waited upon.
Answer: The wait object is ideally used inconjunction with ExpectedConditions only and ExpectedConditions doesn't work in loops.
Hence, the 2 lines within Until doesn't get executed in any loop neither aa gets printed in loop as you are expecting.

Update
Ideally the line of code incorporating WebDriverWait should have been:
WebDriverWait wait = new WebDriverWait(new SystemClock(), driver, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(5));
IWebElement myElement = wait.Until(e => e.FindElement(By.XPath("//button[@data-a-target='change-country-button']")));

In a single line:
IWebElement myElement = new WebDriverWait(new SystemClock(), driver, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(5)).Until(e => e.FindElement(By.XPath("//button[@data-a-target='change-country-button']")));

Comment: Could you pls provide an example of the correct code
Comment: I tried that before and didn't work sadly
Comment: also I don't have any loops in my code but the documentaion says that explicit wait will call the function at equal intervals untill the element shows up


Conjecturing when $M$ is good

Question:
We say an integer $M>1$ is good if whenever $n^n \equiv 1 \mod M$ then we also have  $n \equiv 1 \mod M$ and bad otherwise, for any integer $n\ge 2$ . Prove that  all odd $M$  are bad. Find all good $M$ .

My progress: First taking example, we get Among $M \in \{2,3,4,5\}$ $  , 2,4$ are good.
Now for all odd $M$ , consider $(M-1)^{M-1}$ , note that $(M-1)^{M-1}\equiv -1^{M-1}\equiv 1 \mod M-1$ , since $M-1$ is even .But $M-1 \equiv -1 \mod M $. This proves the first part.
For second part I thought that it would be true for all even M, but then $9^9\equiv 1 \mod 14$ . However I got $2,4,6,8,10,12$ good.
Also $M=42$ is good too . Here's the proof showing $M=42$ is good:
If $n^n\equiv 1\mod 42 \implies n^n\equiv 1\mod 2 \implies n$ is odd . Also we have $n^n\equiv 1\mod 6 \implies n\equiv 1\mod 6$. Now for $n^n \equiv 1 \mod 7 \implies n \equiv \text{1 or 6} \mod 7 $. If $n=6 \mod 7 $ , then by CRT $n\equiv 13 \mod 42$ which is not possible as $13^{13} \equiv 13 \mod 42 $ ( Thanks! @Ross Millikan for correction )
I couldn't formulate a conjecture about when $M$ is $good$. Any hints? Thanks in advance!
Comment: MathJax hint:  for multicharacter exponents, enclose them in braces, so 13^{13} gives $13^{13}$ compared to 13^13 which gives $13^13$  It works for fractions, subscripts, etc.
Comment: Note (from your example for 14) that $9^9 \equiv 1 \pmod{7}$, so I think $n \equiv 1, 6 \pmod{7}$ does not follow from $n^n \equiv 1 \pmod{42}$. 42 still seems good though.

More generally, I think the solution to $n^n \equiv 1 \pmod{p}$ may be something $\pmod{p(p-1)}$ rather than something $\pmod{p}$.
Comment: @SunainaPati Thanks for the updates. FYI, a somewhat more direct way to state your question is that an integer $M \gt 1$ is *good* if there exists a positive integer $n \not\equiv 1 \pmod{M}$ where $n^n \equiv 1 \pmod{M}$, else $M$ is *bad*. Also, for any prime $p$ and $1 \le k \le p - 1$, with $n = (p - 1)(p - k) = (p - k - 1)p + k$, then Fermat's little theorem gives $n^n \equiv \left(k^{p-1}\right)^{p - k} \equiv 1 \pmod{p}$. Thus, $n^n \equiv 1 \pmod{7}$ means $n$ can be congruent to $1$ through $6$, inclusive, $\mod 7$.
Comment: The problem statement is fine now, but if $n \equiv 1 \bmod 6$ and $n \equiv 6 \bmod 7$, then $n \equiv 13 \bmod 42$.  As $13^{13} \equiv 13 \bmod 42$ you are fine.
Comment: Sequence is on OEIS: https://oeis.org/A239063 with no useful information (unless you consider the first 10000 terms useful)
Comment: Upon further inspection, the above sequence is NOT the sequence you seek, since for $2 \le n \le 46$, $n^n \not \equiv 1 \pmod {46}$, but $55^{55} \equiv 1 \pmod {46}$. Therefore it appears that this sequence is not on the OEIS.
Answer: This is the complete solution.

Theorem: Let $\phi(M)$ be the Euler totient value of $M$. Then $M$ is good if and only if $\operatorname{sqrf}(\phi(M))\mid M$, where $\operatorname{sqrf}(\cdot)$ denotes the squarefree part.

For the "if" part, this follows because given $n\not\equiv 1\pmod M$ but coprime to $M$, then $\operatorname{ord}_M(n)>1$; however,
$$n^n\not\equiv 1\pmod M\,,$$
because otherwise, we would have that $\operatorname{ord}_M(n)\mid n$ whereas $\gcd(n,\phi(M))=1$.
For the "only if" part, suppose $p\mid\phi(M)$ but $p\nmid M$. Thanks to Cauchy's Theorem (see https://en.wikipedia.org/wiki/Cauchy%27s_theorem_(group_theory)) we can find a natural number $m$ such that $\operatorname{ord}_M(m)=p$. Now let $v:= \operatorname{ord}_M(p)$ and define $n:=p^vm$. Clearly $n\not\equiv 1\pmod M$; however,  $$n^n=(p^vm)^{p^vm}= p^{v(p^vm)}m^{p^vm}\equiv 1\pmod M\,,$$
which completes the proof.
Comment: nice one!!!! well.. we could have also defined M such for every prime p|M , we have q|M for each prime factor q of p-1 ( skipping the term square free ?)
Comment: Yes, that's correct.

Conjecturing when $M$ is good


How to reset jquery wait cursor after form load?

Question: I have this code in the master page  (using Ajax Update Panel) which turns into a wait swirl after submitting
<code>$("form").submit(function () {
     $("*").css("cursor", "wait");
});
</code>
However that swirl reappears whenever cursor is moved to some parts outside of divs.
I was hoping this would reset cursor after the grid has been loaded
<code>$("form").load(function () {
     $("*").css('cursor', 'auto');
});
</code>
But it does not. Is there any simple way of achieving this ?
Answer: UpdatePanel have their javascript function to signaling the partial update, and the end of it, and so your code can be as:
<code><script type="text/javascript">
   $(document).ready(function () {
       var prm = Sys.WebForms.PageRequestManager.getInstance();
       prm.add_initializeRequest(InitializeRequest);
       prm.add_endRequest(EndRequest);
    });

    function InitializeRequest(sender, args) {
       $("*").css("cursor", "wait");
    }

    function EndRequest(sender, args) {
       $("*").css('cursor', 'auto');
    }
</script>
</code>