get unread messages on particular channel pubnub php sdk

Question:
Goal:- to get unread messages on particular channel.

User login to the upitch website.
Once he will go to the Message page we are maintaining the message_page_visited_count = 1
when user routs from message page to any other page we are updating message_page_visited_count = 0 and updating time stamp.
now for updating timestamp we are using mysql function strtotime("now") something like this.
$this->Userlink->updateAll(
                    array('pubnub_time_stamp' => strtotime("now")), array('Userlink.id' => $loggedInUser)
            ); // updating timestamp for logged in user 1455687812

Which updates 1455687812  ten digits timestamp into our database for logged in user.

As discussed with the pubnub team, pubnub team said to add 7 zeros to
  the right end of my timestamp. Which turns to be 14556878120000000

i have integrated php-sdk pubnub
include_once './vendor/autoload.php';
use Pubnub\Pubnub;
$publish_key   = publish_key
$subscribe_key = subscribe_key
$pubnub = new Pubnub($publish_key, $subscribe_key);

I found the way to implement history something like this.
history(
string $channel,
integer $count = 100,
boolean $include_token = null,
integer $start = null,
integer $end = null,
boolean $reverse = false)

By implementing that:-
$result= $pubnub->history(
"2242_2272_1116", //my channel
null,
true,
null,
14556878120000000, //endtime token with 7 zeros
null);
echo "
";
print_r($result);die;

By printing why i am getting all messages ?? instead of getting messages after given time-token ??
Reason can be adding 7 zeros is not accepted by pubnub if so kindly suggest me to convert my time-stamp(1455687812) to
pubnub time token(17 Digits).
or please point out me what i am doing wrong here?
Your help will be appreciated thanks in advance.

EDIT

I fetch the messages and its time-token something like this..
    // TIMETOKENS AND MESSAGES
14556879844588614  Really want some more levels
14556879769565496  The fact I can see
14556871094404310  Haunted
14556871091411782  Hello
14556870983775230  Hello

$result= $pubnub->history(
"2242_2272_1116",
null,
true,
null,
14556871094404310, null);
echo "
";
print_r($result);die;

I am passing the 3rd message's time token that is 14556871094404310 and message is Haunted Now expected output would be
14556879844588614  Really want some more levels
14556879769565496  The fact I can see

Why its returning all the message instead of 2 message ?
Note:- This time i did not add any zero's and used originally generated timetoken by pubnub.
Even doing this also returning all the messages!
still no luck.
Comment: @pubnub Can you please look into this issue ?
Comment: As we discussed privately, I run your script and it return 3 messages, not all 5, with either of the timetokens.
Answer: We discussed this privately in your support ticket and it just came down to the timetokens you use and the parameters you use in the PubNub history API.
The given timetoken is not the exact publish timetoken of the message you seek so the results may not be what you might expect.
See the PubNub PHP Storage tutorial docs for full details and consult PubNub Support for further assistance.


Azure Functions app not giving any kind of output & eventually giving error

Question: When I try to run my nodejs based Azure Function, I'm experiencing an issue where it doesn't generate any feedback and in some cases, I end up getting the following message:
2017-04-05T00:18:15.969 Exception while executing function: Functions.AddAuthor. Microsoft.Azure.WebJobs.Script: Thread was being aborted.

All my function code is publicly available, you can see it here.  The library it's using works locally.  I'm at a bit of a loss as to why it doesn't want to work in Azure Functions.
I originally posted this over at the Azure Functions github repo, but it was suggested that I maybe ask here.
Additionally, it seems like even a simple context.log won't even work.
Comment: Your Function code calls anecdoteService.close().  Where is anecdoteService declared?
Comment: It's all part of this library, and `close` is found here: https://github.com/atrauzzi/anecdote-engine/blob/master/src/Engine/Service.ts#L50 - Although this library deliberately doesn't have anything functions specific inside of it.
Comment: Sorry, I am not familiar with the library, so anecdote.service is different from anecdocteService?
Comment: What I meant to ask is - are the methods close() and addAuthor(...) from the same class? If yes, shouldn't the object name be the same?  You have anecdote.service.addAuthor(..) but anecdoteService.close().
Comment: I've updated it, but I'm still getting the same result.  Moreover, I'm also not able to trigger any output even if I replace all my code with something like `context.log`.  It just feels like the whole thing is dead.
Answer: One thing I notice - context does not exist in this scope: https://github.com/atrauzzi/anecdote-azure/blob/master/functions/index.js#L13
If I set up a similar function I see:

2017-04-12T17:06:55.433 Exception while executing function:
  Functions.ManualJS. mscorlib: ReferenceError: context is not defined
      at Object. (D:\home\site\wwwroot\ManualJS\test.js:1:63)

Also, 'anecdoteService' is not defined in this scope.
anecdote.service
    .addAuthor(author)
    .then(function () { anecdoteService.close()})
    .then(function () { context.log("End of line")})

Does the function work with the azure-functions-cli?
Looking at the gist you provided, did you provide a function?
// index.js
module.exports = function(context) {
  context.log('hello');
  //there needs to be a context.done or your function will not finish
}

or was it simply
// index.js
context.log('hello'); // there's no context object, no function, etc

Comment: I know it sounds strange, but I'm not using the Azure Functions CLI.  In part because I haven't set it up, but also in part because I really wish they'd release a platform independent version.  I don't mind proprietary, but platform independence is a must.  I think the larger issue here is that I'm not getting any actionable feedback from the Functions portal though.
Comment: As I mentioned above, one issue is that even if I remove all my code and replace it with `context.log("hello?!")`, I still end up with no output.  It's like the whole thing is dead.
Comment: Wasn't sure what to make of the gist, edited my answer above for the code formatting.
Comment: You can see the full code here: https://github.com/atrauzzi/anecdote-azure/blob/master/functions/AddAuthor/index.js#L24


How to send email to "anonymous" user when a new node is created

Question: I've been looking at a couple of modules and none of them seem to work the way I want to.
I'd like to display a textfield for an anonymous user to enter his email. Everytime a node of a certain type (blog post) is created, an email would be sent to every person who gave their email.
How could I achieve that in Drupal 7 ?
Thanks
Answer: Simplenews looks like it would work perfectly for this.

Simplenews publishes and sends newsletters to lists of subscribers. Both anonymous and authenticated users can opt-in to different mailing lists. HTML email can be sent by adding Mime Mail module.
Answer: You can write your own custom module. If you are showing form as a block, you can use
hook_block_info() or hook_block_configure() hooks
Then use YOURMOUDLE_form api to create form and implement the submit handler for the form i.e YOURMODULE_form_submit() where you write insert queries
Now to send the email you can use hook_node_insert() hook to do your things after the node is inserted in the tables
Comment: use [simplenews module](http://drupal.org/project/simplenews). You wont need custom coding
Answer: Use rules module with the following information. Create a field for that content type called email.
Events
After saving new content
Conditions
Content is of type "select your content type"
Actions
Send mail - and in the to section use your field token like [node:field-email] with an appropriate subject and message.
Comment: I checked rules, but did not understand how to send email to anonymous users. Any hint ?
Comment: @Ebpo checkout the videocast for rules as it is very framework and you will end up using it time and again. So take some time and run through all the videos http://nodeone.se/sv/node/32
Comment: Didn't realize it was this big! I will look for sure :) Thanks for the info.


Plot a well known double well surface

Question: I am trying to plot a well known energy landscape from physics, the Muller Brown potential.
Taken from the literature (https://arxiv.org/abs/1701.01241):

With my contour plot, however, I cannot see the two wells, it looks as if it was just a single Gaussian.
Am I doing something wrong?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mp

# Parameters of Muller Brown Potential (cf. Bonfati & Cob 2017)
A = np.array([-200, -100, -170, 15])
a = np.array([-1, -1, -6.5, 0.7])
b = np.array([0, 0, 11, 0.6])
c = np.array([-10, -10, -6.5, 0.7])
x_m = np.array([1, 0, -0.5, -1])
y_m = np.array([0, 0.5, 1.5, 1])

x = np.linspace(-1.5, 1, 1000)
y = np.linspace(-0.5, 2, 1000)
XX, YY = np.meshgrid(x, y)

Z =A[0]*np.exp( a[0]*(XX-x_m[0])**2 + b[0]*(XX-x_m[0])*(YY-y_m[0]) + c[0]*(YY-y_m[0])**2 )
+  A[1]*np.exp( a[1]*(XX-x_m[1])**2 + b[1]*(XX-x_m[1])*(YY-y_m[1]) + c[1]*(YY-y_m[1])**2 )
+  A[2]*np.exp( a[2]*(XX-x_m[2])**2 + b[2]*(XX-x_m[2])*(YY-y_m[2]) + c[2]*(YY-y_m[2])**2 )
+  A[3]*np.exp( a[3]*(XX-x_m[3])**2 + b[3]*(XX-x_m[3])*(YY-y_m[3]) + c[3]*(YY-y_m[3])**2 )

fig, ax = plt.subplots()

c=ax.contourf(XX, YY, Z)
plt.colorbar(c)
ax.set_xlabel('x')
ax.set_ylabel('y')

edit: Setting the limits of the plot region to the ones the authors does not seem to help.
If I use
x = np.linspace(-2, 0, 1000)
y = np.linspace(0, 2, 1000)

I see this:
Comment: Your limits are not quite right for one thing
Comment: If I choose the limits form the original image, my plot is not fully visible. As if they were using a bias or something.
Comment: You can set the limits via the appropriate linspace bounds
Comment: see the edit, it does not seem to be the problem.
Answer: You forgot the parantheses around the expression for Z so that you effectively evaluated only the first summand.
x = np.linspace(-1.5, 0.2, 1000)
y = np.linspace(0, 1.9, 1000)
XX, YY = np.meshgrid(x, y)

Z = (A[0]*np.exp( a[0]*(XX-x_m[0])**2 + b[0]*(XX-x_m[0])*(YY-y_m[0]) + c[0]*(YY-y_m[0])**2 )
    +A[1]*np.exp( a[1]*(XX-x_m[1])**2 + b[1]*(XX-x_m[1])*(YY-y_m[1]) + c[1]*(YY-y_m[1])**2 )
    +A[2]*np.exp( a[2]*(XX-x_m[2])**2 + b[2]*(XX-x_m[2])*(YY-y_m[2]) + c[2]*(YY-y_m[2])**2 )
    +A[3]*np.exp( a[3]*(XX-x_m[3])**2 + b[3]*(XX-x_m[3])*(YY-y_m[3]) + c[3]*(YY-y_m[3])**2 ))

Bonus:
m1 = (-0.558223634633024, 1.441725841804669)
m2 = (-0.050010822998206, 0.466694104871972)
s1 = (-0.822001558732732, 0.624312802814871)
plt.plot(*m1, 'm*'), plt.text(*m1, "  Min 1")
plt.plot(*m2, 'm*'), plt.text(*m2, "  Min 2")
plt.plot(*s1, 'bo'), plt.text(*s1, "  Saddle 1")

Comment: for reference: https://docs.python.org/3/reference/lexical_analysis.html#line-structure, esp. sections 2.1.5 and 2.1.6 ([PEP8](https://peps.python.org/pep-0008/#maximum-line-length) recommends parantheses)
Comment: Thank you, Stef!!! I did not know that this was a thing. Strange that the line breaks stop the parsing of the equation.

Plot a well known double well surface


Fazer com que combinador de classes abra a página em aba separada

Question: Galera tenho um código no qual ele me cria uma página como se fosse um tema, pegando aleatoriamente as classes css, porém o que ele faz é criar o "tema" dentro da página que esta o botão, e gostaria que ele abri-se uma nova página com o tema selecionado.
Segue o código js
Código que gera as classes
var classesRM = ['fundoRomantico', 'fundoRomantico1', 'fundoRomantico2'];
var classestopoRmt = ['topo-romantico', 'topo-romantico1', 'topo-romantico2'];
var classesmenuRmt = ['romantico-menu-01', 'romantico-menu-02', 'romantico-menu-03'];
var classesfootRmt = ['footer-romantico', 'footer-romantico1', 'footer-romantico2'];

var classesFontTexto = ['font-romantico', 'font-romantico1', 'font-classica', 'font-classica1', 'font-moderno', 'font-moderno1'];
var classesFontTitulo = ['font-titulo-romantico', 'font-titulo-romantico1', 'font-titulo-classica', 'font-titulo-classica1', 'font-titulo-moderno', 'font-titulo-moderno1'];
var classesMenu = ['menu-01', 'menu-02', 'menu-03'];
var classesTexto = ['textoBranco', 'textoPreto', 'textoCinza'];
function sorteia(arr) {
    var rand = Math.floor(Math.random() * arr.length);
    return arr[rand];
}

Código do botão
document.getElementById('troca').addEventListener('click', function() {
    var classeRM = sorteia(classesRM);
    var classetopoRmt= sorteia(classestopoRmt);
    var classemenuRmt= sorteia(classesmenuRmt);
    var classeFontTexto = sorteia(classesFontTexto);
    var classeFontTitulo = sorteia(classesFontTitulo);
    var classeTexto = sorteia(classesTexto);
    var classeMenu = sorteia(classesMenu);
    var elemento = document.getElementById('navbar');
    elemento.className = classemenuRmt;
    var elemento = document.getElementById('nav-bar');
    elemento.className = classeMenu;
    var elemento = document.getElementById('titulo');
    elemento.className = classeFontTitulo;
    var elemento = document.getElementById('topo');
    elemento.className = classetopoRmt;
    var elemento = document.getElementById('body');
    elemento.className = classeRM + ' ' + classeTexto + ' ' + classeFontTexto;
});

Comment: Queres que abra uma nova página ou na mesma página?
Comment: quero que abra em nova pagina, tipo os botões ficarem em uma tela e quando clicar o tema gerado seja aberto em uma pagina diferente sem os botões
Comment: Ok, e o conteúdo dessa página é o mesmo que a primeira?
Comment: Sim sim, pq esse é para ser o modelo, então eu conseguindo fazer com que abra em nova pagina, ja começo para ver o conteudo
Answer: Se mudares a tua lógica um pouco consegues fazer como queres.
Usa o event handler só para abrir uma nova página:
document.getElementById('troca').addEventListener('click', function() {
  var win = window.open(location.origin, '_blank');
  win.focus();
});

e depois dentro de cada página correr o resto do código no load da página:
window.onload = function(){
    var classeRM = sorteia(classesRM);
    var classetopoRmt= sorteia(classestopoRmt);
    // etc...

O código completo poderia ser:
(function () {
    var classesRM = ['fundoRomantico', 'fundoRomantico1', 'fundoRomantico2'];
    var classestopoRmt = ['topo-romantico', 'topo-romantico1', 'topo-romantico2'];
    var classesmenuRmt = ['romantico-menu-01', 'romantico-menu-02', 'romantico-menu-03'];
    var classesfootRmt = ['footer-romantico', 'footer-romantico1', 'footer-romantico2'];

    var classesFontTexto = ['font-romantico', 'font-romantico1', 'font-classica', 'font-classica1', 'font-moderno', 'font-moderno1'];
    var classesFontTitulo = ['font-titulo-romantico', 'font-titulo-romantico1', 'font-titulo-classica', 'font-titulo-classica1', 'font-titulo-moderno', 'font-titulo-moderno1'];
    var classesMenu = ['menu-01', 'menu-02', 'menu-03'];
    var classesTexto = ['textoBranco', 'textoPreto', 'textoCinza'];

    function sorteia(arr) {
        var rand = Math.floor(Math.random() * arr.length);
        return arr[rand];
    }
    window.onload = function () {
        document.getElementById('troca').addEventListener('click', function () {
            var win = window.open(location.origin, '_blank');
            win.focus();
        });

        var classeRM = sorteia(classesRM);
        var classetopoRmt = sorteia(classestopoRmt);
        var classemenuRmt = sorteia(classesmenuRmt);
        var classeFontTexto = sorteia(classesFontTexto);
        var classeFontTitulo = sorteia(classesFontTitulo);
        var classeTexto = sorteia(classesTexto);
        var classeMenu = sorteia(classesMenu);
        var elemento = document.getElementById('navbar');
        elemento.className = classemenuRmt;
        var elemento = document.getElementById('nav-bar');
        elemento.className = classeMenu;
        var elemento = document.getElementById('titulo');
        elemento.className = classeFontTitulo;
        var elemento = document.getElementById('topo');
        elemento.className = classetopoRmt;
        var elemento = document.getElementById('body');
        elemento.className = classeRM + ' ' + classeTexto + ' ' + classeFontTexto;
    }
})();

Seria interessante optimizar esse código para não ser tão extensivo. Ou seja fazer o mesmo mas com menos linhas de código. Não mexi nisso, fica para outra pergunta.
Comment: O código window.onload eu coloco ele aonde?
Comment: @VictorSaul editei a resposta. Assim podes colocar em qualquer lado dentro do HTML.
Comment: Desculpa mas esse código não funcionou, ele abre direto ja a tela com o tema e quando clica no botão para fazer o embaralhamento ele abre a tela porém sem conteudo
Comment: @VictorSaul tens isso online? ou podes recriar o problema num jsFiddle com o teu código para eu poder ajudar mais?
Comment: Tenho no jsFiddle um exemplo do meu código, claro que no meu local ele esta mais elaborado com imagens em bg e tal mas a estrutura dele é essa https://jsfiddle.net/jpcaja7t/18/
Comment: @VictorSaul acho que devia ter usado `.pathname`. É assim que queres? -> http://jsfiddle.net/p2rmre5z/1/show/
Comment: Isso, porém não quero que apareça os botões na tela que foi gerada, quero que os botões fiquem em uma tela e ao clicar ele gere o tema sem os botões
Comment: @VictorSaul outra coisa... esse código está a dar-me dores de ver... posso mudar o HTML? Manter isso vai ser impossivel...
Comment: @VictorSaul perdi algum tempo a fazer isto -> http://jsfiddle.net/jafxrpkv/ Acho que o código devia estar assim. Já não tenho tempo de olhar para o resto. Mas no fundo podes passar no url o estilo numa query string e o JS ir ver se há algo para ler e esconder ou não os botões. Amanhä dou uma olhada aqui de novo.
Comment: OK, eu só preciso mesmo que consiga abrir o tema que me der em uma nova aba sem aparecer os botões


Do SIT (stay-in-tune) brand strings really stay-in-tune better than any others?

Question: Do SIT (stay-in-tune) brand strings really stay-in-tune better than other brands of strings?  I have bought them on occasion and did not really notice any length of time in-tune difference from the Ernie Balls that I usually use.  There are guys that I know that swear they really stay in tune longer, but that could be:
1) Person bias
2) A side-effect of being a local company (Akron, Ohio)
3) A real difference on different (lower quality?) guitars
I usually play a good quality Stratocaster that stays in tune quite well anyways, so maybe this is not the best guitar to judge these strings by.
The company does state that they add a special "stay-in-tune" process to the manufacturing, but that could be:
1) total BS
2) a chemical treatment?
3) a special grind operation?
4) something else?
Does anybody know?  Have any hunches?
Comment: I have since talked to someone who claims to know that the special process is pre-stretching before packaging.
Answer: 1) Total BS.
Your question is more about physics and engnieering than music but I'll answer anyway..
As far as I can tell they have no patents and make no effort to give any explanation as to what the "stay in tune" process entails which strongly suggests it does not exist at all.
A chemical treatment could be used to reduce friction, Though, this would not be unique to SIT and is a poor, band aid solution to the problem, you wouldn't cover your car in oil and hope the parts that need lubrication get it would you? No, you apply the correct lubrication where it is needed.
Only ground wound strings are ground, all other strings are extruded. Generally, extrusions have a better surface finish (therefore lower friction coefficient) than ground surfaces so any grinding is a step in the wrong direction.
Either way, it doesn't matter, the string itself is almost never the cause of tuning instability. I have heard of dud strings though they are very rare, I've never had one in >300 sets of strings.
99% of the time it is caused by one of these:

binding at a poorly cut nut
Too greater break angle
Binding at a string tree
Poorly wrapped string post
Low quality machine heads

I wont bother mentioning the other 1% but none of them are the string itself.
If you are interested in a detailed analysis of the physics of keeping at string in tune you should try physics.stackexchange, though you need to do your own research first, here are some places to start:
http://en.wikipedia.org/wiki/Elasticity_(physics)
http://en.wikipedia.org/wiki/Friction
(both static and kinetic friction are involved)
Comment: I would expect that some string materials could have different coefficients of elasticity than others, and that a string with a lower coefficient of elasticity would stay in tune better than one with a higher coefficient.
Comment: @supercat In a perfect world variation in Young's Modulus ('E') may have an effect, but here in the real world where friction is the main cause of instability I would bet it has no effect. If you can explain a viable mechanism by which E will affect stability I'm interested. (please don't bring up nylon string instability, there are so many other material property differences between steel stings it's not conclusive)
Comment: Excessive friction at the nut will certainly cause problems, and I'm not sure that a lower E would help with those, but many instruments also have problems with things like dimensional stability under changing temperature and humidity conditions.  I would expect that cutting E in half would reduce by half the amount by which an instrument is put out of tune by a 0.01" change in length.
Comment: Tuning changes due to temp. changes is a function of the thermal expansion coefficient, Tuning changes due to humidity changes is a function of the coefficient of hygroscopic expansion. Neither of theses are related to Young's Modulus.
Comment: If the two ends of the guitar are moved apart by e.g. 0.1", I believe (correct me if I'm wrong) that with typical strings at typical tension levels, the increase in tension [which is a function of Young's modulus] will raise the pitch significantly more than the change in length will reduce it.  If Young's modulus were lower, then the change in tension *resulting from the change in length* would be reduced.
Answer: I bought them at my local music store from a 19 year old who scoffed at the idea that they would Stay in Tune, but they did - for five years. After that I tried to buy them again, but all the 19 year old know-it-all's talked so many people out of these SIT strings that I can't find them locally anywhere.
Answer: They stay in tune for me, as long ad I leave the bass in the stand. I have a soft case, so the pegs get turned, so I kills it for me. I will say that they stay bright much longer than any other string I've used though!


bundle format unrecognized, invalid, or unsuitableCommand > /usr/bin/codesign failed with exit code 1

Question: I am trying to run my existing code from one system to another and facing continue following error :

bundle format unrecognized, invalid, or unsuitableCommand
  /usr/bin/codesign failed with exit code 1

How to resolve this error ? I didn't change a single line of code. However in my existing system, its working like a charm. Any hep appreciate.
Answer: This is the error you are getting because of some system settings changed. You can solve it by following below steps :

This error will say for which pod you are facing this issue. So select that pod file.
Now select Target for that Pod
Now got To General
Tap on Choose info.plist File
It will show you pods-yourprojectnae-acknowledgements.plist, so select that option
Now Build and check
you will not find this error again

This solution works for me. Try once.
Comment: Hey its saved my day. Thanks @kalpesh


Move code from template file to custom module

Question: I would like to move portions of code from template files to custom module. But i fail do find descriptive guide for such task. Idea is to migrate complex db queries and EntitiyFieldQuery out of the tpl.php files. For example:
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'predmet_clanak')
  ->fieldCondition('field_taxonomy_choose', 'value', 1 , '=')
  ->fieldCondition('field_vrsta', 'tid', 241);

$result = $query->execute();
$nodes = entity_load('node', array_keys($result['node']));
foreach ($nodes as $node) {
  print ('

');
  print drupal_render(node_view($node, 'teaser'));
  $nodelink = ltrim(url('node/' . $node->nid), "/");
  print ('
');

  $imageLink = '';
  print l($imageLink, $nodelink, array('query' => array('iframe' => 'true', 'width' => '800', 'height' => '700', 'format' => 'popup'), 'attributes' => array('class' => t('colorbox-load gumb')), 'html' => TRUE));
  print ('
');
}

This code fetches collection of nodes (when conditions are met) in custom tpl.php file. I have been advised not to create complex queries in tpl files, but do not know yet best practices to do so.
I guess, module will firstly need to know context where i want this to occur? And after i do  this in the module, do i need to pass this to the template.php first?
Comment: Is this like a block? a page? or something else? How would you best describe where this content maps to something in drupal?
Comment: It is itended to show in various tpl.php pages. I have few content types, and i display node collections depending on context (im detecting that context by examining taxonomy field that was set for that node). More detailed, those are sliders with Node collections in it.
Answer: I think you should go through the module developer guide.
You can use hook_preprocess_HOOK() in your template.php. So if your code was placed in the node template, the hook will be themename_preprocess_node($vars) and then you can check for a particular node type and create a variable like $vars['custom_variable'] = 'the query stuff'; and this variable will be available in your template.
Comment: hook_preprocess_HOOK() will allow you to inject variables in your templates. Or replace existing value with your own. You also have hook_process_HOOK(). See documentation of the theme() function for all the available hook and their order.
Comment: Thanks for this, i already looked into that, but i need advice in my case, i already know how to create module (files etc) but i am puzzled how to make logic chain for the code.
Comment: Thanks for further suggestions! I hope with little documentation examination i will be able to migrate my php voodoo where it belongs :D


What are the applications of taking the output of an amp with a microphone?

Question: Last Saturday I attended Skinny Living concert in Cologne, and some stage setup puzzled me.  What is the purpose of taking the output of an amp with a microphone, such as on this picture?

The venue is relatively small but well equipped, there were about 60-70 persons in the public and a stage of the corresponding size, if this is relevant.
Comment: @Tim Because tape sounds better than digital?
Comment: related question about why there's a bit of tape stuck to the front of a guitarist's amp.
Answer: This is standard procedure for electric guitars. See, a guitar amp is almost rather part of the instrument than just a loudspeaker: it critically shapes the sound. You might say the speaker cabinet is a substitute for the body of an acoustic guitar: its primary purpose may be to just get you heard, but there's a lot more than just loudness to the art of building well-sounding guitars. You want to boost a wide range of frequencies, but some more and some less†.
So, you get a very different result if you just plug the guitar into the PA, compared to the "proper" amp sound that's usually desired. Of course, if the amp is loud enough to get to all the audience then you don't need a PA at all for guitar – but such a loud amp can be quite a pain for the other performers on stage. It also isn't great for overall band sound because it bleeds in the vocal mics etc.. And for bigger venues, even a couple of Marshall stacks may not be able to get the guitar sound satisfyingly to the back rows. Modern PAs are much more effective at this.
Hence it's usually better to have only a relatively quiet guitar amp (merely loud enough so everybody on stage can hear it enough, particularly the guitarist herself) but use a mic to bring its sound to the audience too, much like you could use a mic to bring the sound of an acoustic guitar to the audience. (Just, because even a quiet amp is much louder than an acoustic guitar, it's much easier to actually get it heard well.)
What's a bit strange about this particular setup is that this seems to be an acoustic-guitar amp. Acoustic amps are different from electric-guitar amps: they are designed to not shape the frequency response much, but give the clearest possible representation of the guitar's own sound. Hence it makes IMO little sense to mic an acoustic-guitar amp. But some guitarist prefer to do it this way nevertheless.See RockinCowboy's comment below.

†Most electric-guitar cabinets are strong in the midrange (with different scoops and peaks), which is good for a powerful presence in the mix, but they cut off the high treble range rather strongly. This is particularly important for the distorted sounds typical of rock/metal guitar; those would be really annoying if you played directly into the PA.
Comment: @MichaelGrünewald it's certainly possible to route the signal from an amp straight on to the PA; you can still use the amp's speaker for monitoring. But the line-out on electric-guitar amps is not intended to be plugged right into a mixing console. It's intended for extra effects and/or another guitar amp. This output signal sounds really nasty over full-range speakers. An output that can be plugged into the PA will be labelled _DI out_. Acoustic-guitar amps have them and modern bass amps too, but electric-guitar amps usually don't.
Comment: Great detailed answer.  But as far as I know the Roland "Cube" amp pictured is an electric amp and looking at Roland web site under products, Cube amps only appear under Electric and Bass amps.  Roland makes some great acoustic amps but they are not "Cubes".  Some of the Cube model amps have an acoustic simulator built they all offer channels for clean or distorted electric.  The newer Cube amps have iOS connectivity as well as a phone/recording out jack.
Comment: Voted up. Very well put. There is a whole sound science around this. The OP should have googled a bit more, I think.
Comment: Thank you very much for your detailed answer! Still some amps (if not all) have an output line that could be plugged into the PA – but then the musicians would not hear the instrument – only the mix – which also speaks for the setup I took a picture of, right?
Comment: Many modern guitar amps have DI outs with a speaker emulation circuit. They can't stand up fully to a well-miked amp, but if you are limited in your selection of mikes (e.g. as a visiting engineer), then you can get quite some mileage out of them. The are often also wired *before* the main volume knob which gives you a consistent level even if the guitarist turns up his amp over the course of the gig (as they invariably do).
Comment: Worth noting that the choice of microphone as well as its placement also has a large impact on the final sound.  Many characteristic guitar "tones" comes from a combination of instrument, effects chain, amp, cabinet, microphone, and microphone placement.
Comment: @RockinCowboy I have a micro cube and it does have one "model" in its model selector that is meant for clean amplification for acoustic guitars or keyboards or whatever. It doesn't sound very clean but it also doesn't sound like a guitar amp. Either way, in the pictured situation, I'd guess a model suited for electric guitars was selected.
Answer: There are many electrical advantages to "air-gapping" the PA from the backline. You avoid ground loops and other kinds of issues that arise from connecting equipment directly. Even more important, changing from one band to another is much easier when you just move the mic out of the way, let the guitarist/tech set up the back line, and then place the mic. No impedance matching, ground lifting, adapter cable finding, or other annoying tasks required.
I suppose this isn't as true as it once was, but for many amplifiers, you have no choice but to put a mic in front of them! Classic all-tube amps almost never had any kind of output that could be run to a mixer. Modern tube amps and of course digital modeling amps can often have "recording outs" or "main outs" that can be run to a mixer, but they usually sound pretty lame at best.
Also the microphone is an extension of the PA system, which is kind of like an instrument played by the FOH engineer. As an engineer, it helps a lot to get to know a set of mics really well, and then use those mics in ways such that you can control the sound coming into the mixer with great detail - like getting familiar with a certain guitar. Using the same mic for all the guitar amps that you see from different bands helps put a similar sonic stamp on the electric guitar sound, which really helps make mixing decisions quickly.
I greatly prefer a stage setup where everything is miked and nothing is on a DI. Usually keyboard players do not bring an amp, and I suppose that for a lot of gigs, a DI from the bass head is best if you can get it, but there is always that annoying part of figuring out how to plug the bass DI in.
Comment: Good answer as usual, though I definitely don't agree with your preference for miking everything up. Nowadays it's fortunately getting standard to have properly matched DI outs included in bass amps, and higher-end keyboards also start employing XLR outputs. Why it hasn't always been done this evades me – a good DI connection is so much more reliable than anything involving a mic! Plugging an XLR cable in a bass amp is also significantly faster yet than properly aligning a mic to a guitar amp's speaker. Really, guitar-cabinet sound signature is the only good argument for a mic.
Comment: Good answer.  So far nobody has mentioned one other advantage to miking a guitar cabinet.  You can alter and shape the sound through the PA (to get the sound you want) by simply changing the placement of the mic in front of the cabinet.  The distance, the angle and the part of the cabinet the mic is pointed at will all affect the sound of the output.  You don't have that ability with a DI connection to the PA.
Comment: For a fact, many digital amp simulations are horrible. In particular, they often seem to be designed to sound good when playing just guitar alone over headphones (perhaps the problem is just that the owners set up their presets in just this way). The result, as you say, is that such a guitar will never properly sit in the mix. But it's not fair to generalise this to "_all_ digital cabs don't sit well in a mix". My dream setup for live guitar would be: a nice small tube combo on stage, DI parallel to the speaker through convolution response (recorded from the same amp under studio conditions).
Comment: @RockinCowboy: yes, but that too can actually be a big disadvantage, at least live. When you're in a hurry to get the backline ready for the show, the last thing you need is lots of millimetre trial-and-error till the guitar sounds right. In practice the mic will often just be jammed somehow in front of the speaker ("that'll have to do"), and the sound only fine-adjusted through the mixer channel EQ while the band is already performing. In this regard, a digital convolution cabinet is just as flexible while eliminating the error potential.
Comment: @leftaroundabout In *my* practice I don't just plunk the mic down, but I also don't worry about millimeters. I use experience and intuition to place the mic, with a few go-to placements. Of course there is "error potential" when working live sound, but audiences can be very forgiving, especially if the instruments can sit well together. That's one area where digital modeling really shows its difference - it just doesn't sit in a mix as easily - even when miked! Also, I have found DIs from bass heads to be **less** reliable than mikes, because you don't know where that head has been!
Answer: This looks like an guitar amplifier. The amplifier is a key part of the sound of an electric guitar. If you want to capture that sound, you need to mic the amp, rather than using a DI.
I believe you can get amp modelling pedals, but I've mostly seen microphone setups like your picture.
A counterexample would be a keyboard amp. The amp here is usually not part of the desired sound, so we bypass it with a DI. Note that this is not true for some keyboard sounds (organ with Leslie, some electric pianos like Rhodes and Wurlitzers).


Assistance with Java's grid bag layout?

Question: Well I'm trying to set it up to where the "enter your name" JLabel is displayed right next  along the left hand side of the JTextField, sadly it's displayed at the center. What I'm talking about is the first JLabel and the first JTextArea, please disregard the rest of the code.
import java.awt.*;
import javax.swing.*;

public class practice extends JFrame  {

    public static void main(String[] args){
        new practice();
    }

    public practice(){
        JPanel jp = new JPanel();

        jp.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        jp.add(new JLabel(""),gbc);

        gbc.gridx=0;
        gbc.gridy=1;
        jp.add(new JLabel("Enter your name\n"),gbc);

        gbc.gridx=0;
        gbc.gridy=0;
        jp.add(new JLabel(" "),gbc);

        gbc.gridx=0;
        gbc.gridy=0;
        jp.add(new JLabel(" "),gbc);

        gbc.insets = new Insets(30,0,0,0);
        gbc.gridx=0;
        gbc.gridy=1;
        jp.add(new JTextArea(3,30),gbc);

        gbc.insets = new Insets(10,0,0,0);
        gbc.gridx=0;
        gbc.gridy=2;
        jp.add(new JTextArea(3,10),gbc);

        gbc.insets = new Insets(10,0,0,0);
        gbc.gridx=0;
        gbc.gridy=3;
        jp.add(new JTextArea(3,10),gbc);

        gbc.gridx=0;
        gbc.gridy=0;
        jp.add(new JRadioButton(""),gbc);

        gbc.gridx=0;
        gbc.gridy=0;
        jp.add(new JRadioButton (""),gbc);

        gbc.gridx=0;
        gbc.gridy=0;
        jp.add(new JRadioButton(""),gbc);

        this.add(jp);
        setTitle("Card");
        setSize(700,500);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }
}

Answer: I recommend creating a GridBagConstraints for each Swing component you want to put in the GUI.  That way, you don't have to remember any defaults and you specify each of the parameters for every component.
Here's a JDialog where I used the GridBagLayout.

And here's the code for the JDialog.
package com.ggl.sudoku.solver.view;

import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class SolutionDialog {

    protected static final Insets   buttonInsets    = new Insets(10, 10, 0, 10);

    private int                     singleCount;
    private int                     guessCount;

    private long                    elapsedTime;

    private JDialog                 dialog;

    private SudokuFrame             frame;

    public SolutionDialog(SudokuFrame frame, int singleCount, int guessCount,
            long elapsedTime) {
        this.frame = frame;
        this.singleCount = singleCount;
        this.guessCount = guessCount;
        this.elapsedTime = elapsedTime;
        createPartControl();
    }

    private void createPartControl() {
        dialog = new JDialog(frame.getFrame(), "Statistics");
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        JPanel resultsPanel = new JPanel();
        resultsPanel.setLayout(new GridBagLayout());

        int gridy = 0;

        JLabel singleCountLabel = new JLabel("Cells with one possible number:");
        addComponent(resultsPanel, singleCountLabel, 0, gridy, 1, 1,
                buttonInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        String s = singleCount + " cells";
        JLabel singleCountString = new JLabel(s);
        addComponent(resultsPanel, singleCountString, 1, gridy++, 1, 1,
                buttonInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel guessCountLabel = new JLabel("Cells where the solver guessed:");
        addComponent(resultsPanel, guessCountLabel, 0, gridy, 1, 1,
                buttonInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        s = guessCount + " cells";
        JLabel guessCountString = new JLabel(s);
        addComponent(resultsPanel, guessCountString, 1, gridy++, 1, 1,
                buttonInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        JLabel elapsedTimeLabel = new JLabel("Elapsed Time:");
        addComponent(resultsPanel, elapsedTimeLabel, 0, gridy, 1, 1,
                buttonInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        s = elapsedTime + " milliseconds";
        JLabel elapsedTimeString = new JLabel(s);
        addComponent(resultsPanel, elapsedTimeString, 1, gridy++, 1, 1,
                buttonInsets, GridBagConstraints.LINE_START,
                GridBagConstraints.HORIZONTAL);

        mainPanel.add(resultsPanel);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());

        JButton okButton = new JButton("OK");
        okButton.setAlignmentX(JButton.RIGHT_ALIGNMENT);
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                dialog.setVisible(false);
                dialog.dispose();
            }
        });
        buttonPanel.add(okButton);

        mainPanel.add(buttonPanel);

        dialog.add(mainPanel);
        dialog.pack();
        dialog.setBounds(getBounds());
        dialog.setVisible(true);
    }

    private void addComponent(Container container, Component component,
            int gridx, int gridy, int gridwidth, int gridheight, Insets insets,
            int anchor, int fill) {
        GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
                gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
        container.add(component, gbc);
    }

    protected Rectangle getBounds() {
        Rectangle f = frame.getBounds();
        Rectangle d = dialog.getBounds();
        d.x = f.x + (f.width - d.width) / 2;
        d.y = f.y + (f.height - d.height) / 2;
        return d;
    }

}

Answer: gridx and gridy define which cell of the grid the object is going to be placed. It's essentially a coordinate system ... like a spreadsheet.
You are placing many components at (0,0) and, in the specific instance you ask about, you are putting both your "enter your name" label and a JTextArea (which is different from a JTextField) in the same cell at (0,1). Thus they get placed on top of each other.
Answer: If you want to put it next to the other you should try doing this:
gbc.gridx = 0;
gbc.gridy = 0;
Container.add(//Your Label);

gbc.gridx = 1;
gbc.gridy = 0;
Container.add(//Your TextField);

Also read about anchors, cause I didn't saw you used them, you can use:
gbc.anchor = GridBagConstraints.LINE_START;

For displaying the objects since the Line Start and not since the center.
And Finally I recommend you creating a method for adding objects to your window to avoid that large pile of code.
Heres a very good DEITEL'S example I use:
import java.awt.

public Yourclass{

JPanel Container;
GridBagLayout yourlayout;
GridBagConstraints gbc;

//Initialize them in the constructor.. Ex: Container = new JPanel();
}

private void addobjects(Component object, int gridx, int gridy, int width, int heigth){

gbc.gridx = gridx;
gbc.gridy = gridy;

gbc.gridwith = width;
gbc.gridheight = height;

yourlayout.setConstraints(object, gbc);
Container.add(object);

}

So now you only need to do this:
addobjects(YourJLabel, 0, 0, 1, 1);
addobjects(YourTextField, 1, 0, 1, 1);

Be sure to give a value to widht and height because if not, the constructor won't now where to add the objects.
And also be sure of declaring the method in the same class in wich your constructor is.
If I have some grammar errors sorry, but I'm proud of having a Nopal in the front of my head. Jajaja.
I wish this answer could help you.

Assistance with Java's grid bag layout?


VM deployement error in Azure

Question: I was getting error while deploying a Windows VM in Azure. This VM image was created from a custom VHD.
Error:
Provisioning failed. OS provisioning for VM did not finish in the allotted time. The VM may still finish provisioning successfully. Also, make sure the image has been properly prepared (generalized).*...
Provisioning State Error Code: ProvisioningState/failed/OSProvisioningTimedOut
Anybody knows why it's failing?
Answer: That error can have multiple reasons as you can see in the following documentation
https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/error-messages
Besides those reasons, I've seen times that you get that error but the VM itself is deployed and works just fine.
Comment: VM status shows running but RDP connection does not work/shows error.
Comment: Try to redeploy it https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/redeploy-to-new-node-windows
Comment: Problem was with the VHD. It was re-created from an running VM.

VM deployement error in Azure


Probability: Rolling a pair of dice

Question: In a gambling game, a woman rolls two fair dice. If she rolls a double $6$, she will win $\$50$, If she get a double other than $(6, 6)$, she will win $\$5$. she loses otherwise. How much should she pay to play if the game is fair? (round it to the nearest cents)
choose the best answer:
  $$\$2.08\\
  \$3.00\\
  \$5.00\\
  \$2.22$$
Answer: a fair price is equal to the expected payout . since every double has a probability $\frac{1}{36}$ we have ..
$$E(x) = \sum_i x_iP(x_i) = 50(\frac{1}{36}) + 5(\frac{5}{36})= \frac{75}{36} $$

Probability: Rolling a pair of dice


JasperReports 6.x: What to use instead of deprecated JRTextExporterParameter.LINE_SEPARATOR

Question: I update JasperReports library from 4.8.0 to 6.3.0 version.
But exporter doesn't have method like as setLineSeparator.
JRTextExporter.setParameter(JRTextExporterParameter.LINE_SEPARATOR) is deprecated.
Settings like this doesn't work:
Exporter exporter = new JRTextExporter();
((JRTextExporter)exporter).getParameters().put(JRTextExporterParameter.LINE_SEPARATOR, "\r\n");
exporter.setExporterOutput(new SimpleWriterExporterOutput(outputFile, characterEncodingProp));

Setting as property in jrxml also doesn't work:
<property name="net.sf.jasperreports.export.text.line.separator" value="
"/>

or
<property name="net.sf.jasperreports.export.text.line.separator" value="\r\n"/>

How I can set line separator?
Answer: Instead of using deprecated JRTextExporterParameter.LINE_SEPARATOR property we should use TextExporterConfiguration.getLineSeparator method.
In case using SimpleTextExporterConfiguration (this is concrete implementation of TextExporterConfiguration interface) class the code will be like this:
JRExporter exporter = new JRTextExporter();

SimpleTextExporterConfiguration configuration = new SimpleTextExporterConfiguration();
configuration.setLineSeparator("#");

exporter.setConfiguration(configuration);

exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporterOutput = new SimpleWriterExporterOutput(file);
exporter.setExporterOutput(exporterOutput);
exporter.exportReport();

With help of net.sf.jasperreports.export.text.character.width and net.sf.jasperreports.export.text.character.height we can set character width and height.
The snippet of jrxml header:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" ..>
    <property name="net.sf.jasperreports.export.text.character.width" value="7.2"/>
    <property name="net.sf.jasperreports.export.text.character.height" value="14.0"/>

Comment: I used SimpleTextReportConfiguration.
I also need such methods as

    configuration.setCharWidth(10f);
    configuration.setCharHeight(20f);

But SimpleTextExporterConfiguration  hasn't these methods.
Comment: This is another question, but I've added info to my post :)
Answer: Thank's. Code like this also solved the task:
Exporter exporter = new JRTextExporter();
final SimpleTextReportConfiguration txtConfiguration = new SimpleTextReportConfiguration();
txtConfiguration.setCharWidth(10f);
txtConfiguration.setCharHeight(20f);
exporter.setConfiguration(txtConfiguration);
SimpleTextExporterConfiguration configuration = new SimpleTextExporterConfiguration();
configuration.setLineSeparator("\r\n");
exporter.setConfiguration(configuration);


modifying a cloned element and reinserting in dom - jquery

Question:     //dom

Some name

    //js
        $(function () {
            //creating a clone
            var _clone = $('#toBeCloned').clone(true);
    // target element
            var _target = $('#targetElm');

    //now target element is to be filled with cloned element with data of span changed
            var _someData = [1, 2, 3, 4];

    //loop through data
            $.each(_someData, function (i, data) {
                var _newElm = {};
                $.extend(_newElm, _clone);//copy cloned to  new Elm
                _newElm.find('span').html(data); //edit content of span
                alert('p'); // alert added to show that append in next line inspite of adding new element to dom just updating the previous one
                _target.append(_newElm);//update target
            });
        });

expected Result:
1 2 3 4
resut iam getting is
4

Comment: i just created another question to simplify my question

http://stackoverflow.com/questions/2452397/clonning-an-element-and-adding-it-to-dom-multiple-times-jquery
Answer: You just want to clone the element on each iteration. A DOM object is not a normal JS object (Well it is, but it has more to it which is why you have to use createElement in raw JS to create a new one):
$(function () {
    // element to be cloned
    var _clone_me = $('#toBeCloned');
    // target element
    var _target = $('#targetElm');

    //now target element is to be filled with cloned element with data of span changed
    var _someData = [1, 2, 3, 4];

    //loop through data
    $.each(_someData, function (i, data) {
        var _newElm = _clone_me.clone(true); // clone copy
        _newElm.find('span').html(data);  //edit content of span
        _target.append(_newElm); //update target
    });
});

Why your code failed, is though you were "extending" an empty object on each iteration, it was still always referring to the same DOM node. You kept changing its value, and appending it to #target. Additionally, the way append works actually moves the object, so you weren't getting duplicate objects.
Comment: i just created another question to simplify my question

http://stackoverflow.com/questions/2452397/clonning-an-element-and-adding-it-to-dom-multiple-times-jquery

although your solution is somewhere near my requirement


Term for a 'flat' circuit in a graph

Question: Graphs can contain circuits, i.e. paths which start and end at the same node. Most circuits are 'non-flat', like this:

I'm trying to find a term that describes a particular type of circuit. You might describe it as 'flat', 'zero-volume' or 'doubling-back'.
The circuit visits some nodes in the following order: $[n_{1}, n_{2}, \dots, n_{x-1}, n_{x}, n_{x-1}, \dots, n_{2}, n{1}]$.
Here's an illustration of the same concept:
Comment: A simple graph has undirected edges, and only a single edge between any two vertices. So, among simple graphs, any path could be deemed a 'flat' circuit, should you so choose. A directed graph similarly tends to have a single edge between any two vertices. But, that edge may be unidirectional or bidirectional. If every edge is bidirectional, then every path yields a 'flat' circuit. So, it is not entirely clear what you are looking for. Depending on the context, there could be more than one name for what you want.
Answer: The terminology I see most commonly used is as follows:
A closed walk is a sequence of adjacent vertices which starts and ends at the same vertex (your second example is a closed walk).
A cycle is a closed walk with no repeated edges or vertices, except the start and end vertex (your first example is a cycle).
So your 'flat circuits' would be referred to as 'closed walks with no induced cycle'.

Term for a 'flat' circuit in a graph


How to change the date format of maillog?

Question: The format of the dates of my maillog logs looks like this:
May 12 04:12:54

I need to include the year on this date. Is it possible to make this kind of change?
Answer: After a little more research and some tests, I found the solution I need.
My server works with CentOS 7.6, which use rsyslog to log.

Edit the file /etc/rsyslog.conf and add the following template before the section "RULES":

$template MailLogFormat, "%timestamp:::date-year%-%timestamp:::date-month%-%timestamp:::date-day% %timestamp:::date-hour%:%timestamp:::date-minute%:%timestamp:::date-second% %hostname% %syslogtag%%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n"

Search for the line:

# Log all the mail messages in one place.
mail.*       -/var/log/maillog

and change to:
# Log all the mail messages in one place.
mail.*       -/var/log/maillog;MailLogFormat

Restart rsyslog:

systemctl restart rsyslog

Done. The logs in the /var/log/maillog file will be printed with the date in the format: Year-Month-Day Hour:Minute:Second
Comment: On Ubuntu my Postfix log file is `/var/log/mail.log` but for the rest it all works.
Answer: A possibly better answer is to employ the newer syslog standard to all rsyslog generated logs.....see
 http://support.pimpmylog.com/kb/softwares/rsyslog-protocol-23-format

The configuration is quite close to the RFC 5424 standard.
This is done by putting the following line in your rsyslog.conf file:
 $ActionFileDefaultTemplate RSYSLOG_SyslogProtocol23Format

A given line in a syslog file would appear as follows:
 <27>1 2014-01-12T20:06:05.783312-05:00 somebody smbd 3752 - -  [2014/01/12 20:06:05.783190,  0] printing/print_cups.c:487(cups_async_callback)

Notice the full time and date are included as well as the TimeZone on the timestamp.
Answer: Thanks to dioo, the following worked for me in Ubuntu Server 20.04

Goto rsyslog conf
sudo nano /etc/rsyslog.conf

Under Global Directives, comment out the existing style such as $ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat and add the below line

$template CustomFormat, "%timestamp:::date-year%-%timestamp:::date-month%-%timestamp:::date-day% %timestamp:::date-hour%:%timestamp:::date-minute%:%timestamp:::date-second% %hostname% %syslogtag%%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n"

Save and close the file. Goto the default-conf file in the below location
sudo nano /etc/rsyslog.d/50-default.conf

Append "CustomFormat" after each log line you wish to change your timestamp
user.*                          -/var/log/user.log;CustomFormat

Restart the service
sudo systemctl restart rsyslog

The final timestamp is as follows

2020-12-22 22:50:19


Content list empty to Administrator

Question: Using Drupal7, I am logged in as administrator, and I am getting an empty content list, even if  there are many nodes created by the administrator user before this.
Even if I add nodes as administrator, the list is still empty.

Here is the content view configuration's screen

Why does this happen? How can I fix it?
Comment: Best guesses is that it's a cache issue or permission issue. Maybe you have some permission setup that allows admin to see the content page but not the actual content. This shouldn't be possible in vanilla Drupal 8
Comment: But if I access `admin/content/node` then I can able to see the list, the list is empty for `admin/content`
Comment: Is this about Drupa 8 or Drupal 7? Looks more like it's a 7, judging from the screenshot. @DevidasKadam : Can you clarify? And also, whether you are using the Administration Views module? (see answer from kiamlaluno below). Please, update your question accordingly.
Comment: updated question, this is drupal7
Comment: Great. This still requires lots of guessing, kiamlaluno is working hard in his answer below. @DevidasKadam : Could you provide a screenshot of the admin/content View configuration screen where we can see what filters or advanced settings (e.g. relations) are in effect?
Comment: @StefanosPetrakis I have updated with admin/content View configuration screen
Comment: A few more guesses(after checking the views config): Can you check the author (uid) property of one of the nodes you would expect to appear in this list? Can you check if the relationship "Content: Author" is marked as required?
Answer: From the screenshot you show, it's clear that you installed and enabled the Administration Views module. In fact, for a fresh Drupal 7 installation, the admin/content page would appear as in the following screenshot.

I installed it on my test, and it works fine for me.

Once you install and enable the module, that administrative page is replaced from a view. If you changed the view, it could be it is filtering out the nodes to show in that page.
Go to admin/structure/views/view/admin_views_node/edit and check the filter criteria aren't too much restrictive. By default, that view has only exposed filter criteria; if you find any not-exposed criterium, that is something manually added to the view, and it could be causing the issue you are seeing. A filter for the content type can cause what you see, but so a filter for the creation date, and many other filters.
As reference, this is the setting page for the view as it comes after installing the Administration Views module.

Also, the view has a setting for caching it (as any view); if it has been changing from None to Time-based, then either the query results or the render output could be cached for too long. The default values are 1 hour for both.

The other reason could be that the view is being filtered by the author name. If I put three spaces in the Author field, and then I click Apply, I get the following.

Now the list says No content available. even if I still have those two nodes you saw in the previous screenshot. That is because the author name doesn't contain three spaces.
The same happens if I enter three spaces in the Title field.
To be sure the exposed filter criteria aren't causing any issue, click on the Reset button right to the right of the Apply button. That will reset the values for those filters.
Comment: it just means the view could filter too much. The default admin/content page doesn't use any view, so it cannot filter too much.
Comment: Removed filters, there are only `title,type,published` filters, changed `caching: time-based | 1 hour/1 hour`. still showing empty list
Comment: removed author filter.
Comment: Notice that I was not suggesting to change the cache to _Time-based_. I was just saying that a cache set to _Time-based_ could cause the view to be cached for too long, which means the view could not be updated to the recent changes. Since you don't say which is that setting for the view, and when those nodes were created (e.g. a year ago), I could not exclude that was the reason you could not see any node.
Comment: Also, I am not suggesting to remove filters, but to see if there is any entered value for those exposed filters.
Comment: I am getting content list after disabling [Administration Views](https://www.drupal.org/project/admin_views) module.

Content list empty to Administrator


predicate logic - translating from human language

Question: "Everyone in the world love themselves"
"Someone loves their own self"
x, y are everyone in the world
1) ∀x∃y(love(x, y) /\  (x=y))
2)∃x∃y(love(x, y) /\  (x=y))
I'm thinking along the lines of "everyone/someone loves someone, and that someone is themselves"
am i correct? and can those two be shortened?
thank you
Answer: If the function love$(x,y)$ is defined as $x$ loves $y$ and that the relation $x=y$ mean that $x$ is the same person as $y$, then (1) translate to "for every one in the world, there exist someone such that $x$ loves $y$ and that $x$ is the same person as $y$ ". The second one is "there exists two person in the world such that they loves each other and they are the same".
If you are trying to say "Everyone in the world love themselves", then I would go with $\forall x(\text{love}(x,x))$. And for "Someone loves their own self", $\exists x(\text{love}(x,x))$.
Note that this is more or less subjective and depend on how the function love$(x,y)$ is defined.
Hope that help!


Does Duckworth-Lewis Method consider "free-hit" situations?

Question: Say Team-A has a certain score and Team-B is batting with 4 balls remaining. Bowler gives a no-ball. It starts raining heavily and play is stopped immediately with 4 balls (including the free-hit) remaining.
Now match result has to be decided based on Duckworth-Lewis Method.
Let us take some hypothetical state where:
Case (1) : If Team-B has 4 normal balls, it looses.
Case (2) : If Team-B has 5 balls, it wins.
I know that these two cases have happened.
Does Duckworth-Lewis consider a case like the following ?
Case (3) : If Team-B has 3 balls and 1 free-hit, it wins.
Stating it another way : Is there a numerical value attached to free-hit, which can change the outcome of the final result ?
Intuitively, Case (3) is better than Case (1), so Duckworth-Lewis should consider it.
Answer: The free-hit rule is more recent than Duckworth–Lewis so the original D/L method (which came into force in English domestic cricket 1997) would not have taken this into consideration. I have been following cricket for many years in England and I'm not aware of any changes to the D/L system taking the free-hit into account.
However, it is worth noting that Duckworth–Lewis does take into account wickets lost by the batting side: the more wickets you lose, the steeper your run chase will be. If you have a free hit, you are less likely to lose a wicket; this in itself should be a slight advantage to the batting side, even if Duckworth–Lewis does not consider free hits in its calculations.
Comment: +1 : Correct , D/L was before free-hits, so it will not account for that unless updated. With free-hits, wickets can not be lost easily ; Runs are easier to get ; Hence it is a real advantage which might change the result. That is why I wondered if the rules had been updated recently.
Comment: @Prem What happens if there is a run-out on free hit? There is no advantage if there is a free-hit available while we are going to calculate D/L method to decide who is the winner?
Comment: @Gunaseelan , on a normal ball, there are many ways a bowler can get a batsman out, but on a free-hit, the batsman has the advantage and might even decide to not run, thereby ensuring no loss of wicket.
Comment: @Gunaseelan You can be out off a free hit (I didn't say you can't), but only in three ways: run out, handled the ball, or obstructing the field (where the obstruction prevents a run out). The advantage of a free hit (from a wicket-taking point of view) is not that you can't be out but that you are much less likely to be out than off a normal delivery.
Comment: @Prem I accept that there are several ways a batsman can get out on a normal ball. As per the question, We like to know that whether free-hit playing a part in D/L method or not? If yes, please tell me the rule where they mention it?
Comment: @Gunaseelan , I am not getting your comment : Are you asking which rule in D/L takes free-hit account ? That is the exact question I am asking !
Comment: I would like to get the reference for that from @GeorgeLaw. He explained clearly but I would like to have the reference to improve the answer.
Answer: You can look up the D/L regulations and tables published by the ICC.  It only talks about balls remaining and wickets in hand as resources.  So free hits are not considered.
In order to model an end-of-game scenario like that accurately, you could arguably also want to consider who is on strike, who is bowling, whether you have any DRS reviews left, and so on.  That is clearly not feasible.
Comment: +1 , valid point about DRS reviews. (Power-Play and other such things can also complicate the calculations). Also agree : only balls and wickets are considered.


Change windows DatePicker's pressed state style

Question: I am developing an application for Windows Phone 8.1. I am trying to edit the windows default DatePicker style. I have succeeded in adding an image in place of the DatePicker using this style

But when the DatePicker is pressed, it still shows the old DatePicker style instead of the new style that I have set. I tried to figure out how to set the pressed state style of the date picker but I couldn't figure it out. I want the same normal state style to be used for the datepicker for all its states. How can I achieve this?
Answer: Instead of setting the background of the button(FlyoutButton) set the content template of the button(FlyoutButton).
Here is the code:


assign a attribute using getattr

Question: I try to assign value to attributes of some calss
like the following:
for name in dir(modelType):
      if request.get(name):
            getattr(model, name) = request.get(name)

but get the excption:
"can't assign to function call"
how can I change attributes without knowing them at complie time?
Comment: This is very unsafe. What if someone passes an id= parameter in the URL? They would overwrite existing data. Is this Django or a similar framework? You should use proper form handling to save data.
Answer: You use setattr() to assign values to attributes.
See:  http://docs.python.org/library/functions.html#setattr
Comment: :-)  Never boring here on SO.
Comment: Exactly, I was about to post the same thing but was blocked out for answering too fast!
Answer: setattr(model, name, request.get(name))

but I'd recommend saving request data in a dictionary, dedicated class, or accessing it directly - unless you're doing specific metaprogramming/introspection, setattr is often the wrong tool for the job.

assign a attribute using getattr


Como criar uma palete de cores e colorir uma div consoante a cor escolhida

Question: Onde encontro conteúdo para criar um site com uma paleta de cores para personalizar um produto?
Por exemplo: Você clica em uma cor e essa cor aplica ao produto, clico em outra cor e troco a cor que havia escolhido anteriormente.
E qual o nome que se aplica ao criar esse processo em um site?
Comment: O nome em Inglês dessa funcionalidade é _**color picker**_. Em português talvez seja _escolhedor de cores_...
Answer: Aqui fica um exemplo. Uma palete com cores a escolher, um campo onde a cor é mostrada, e botões que guardam o código da cor no .value.
Este exemplo faz o que queres: "Você clica em uma cor e essa cor aplica ao produto, clico em outra cor e troco a cor que havia escolhido anteriormente".

var cores = ["#003366", "#336699", "#3366CC", "#003399", "#000099", "#0000CC", "#000066", "#006666", "#006699", "#0099CC", "#0066CC", "#0033CC", "#0000FF", "#3333FF", "#333399", "#669999", "#009999", "#33CCCC", "#00CCFF", "#0099FF", "#0066FF", "#3366FF", "#3333CC", "#666699", "#339966", "#00CC99", "#00FFCC", "#00FFFF", "#33CCFF", "#3399FF", "#6699FF", "#6666FF", "#6600FF", "#6600CC", "#339933", "#00CC66", "#00FF99", "#66FFCC", "#66FFFF", "#66CCFF", "#99CCFF", "#9999FF", "#9966FF", "#9933FF", "#9900FF", "#006600", "#00CC00", "#00FF00", "#66FF99", "#99FFCC", "#CCFFFF", "#CCCCFF", "#CC99FF", "#CC66FF", "#CC33FF", "#CC00FF", "#9900CC", "#003300", "#009933", "#33CC33", "#66FF66", "#99FF99", "#CCFFCC", "#FFFFFF", "#FFCCFF", "#FF99FF", "#FF66FF", "#FF00FF", "#CC00CC", "#660066", "#336600", "#009900", "#66FF33", "#99FF66", "#CCFF99", "#FFFFCC", "#FFCCCC", "#FF99CC", "#FF66CC", "#FF33CC", "#CC0099", "#993399", "#333300", "#669900", "#99FF33", "#CCFF66", "#FFFF99", "#FFCC99", "#FF9999", "#FF6699", "#FF3399", "#CC3399", "#990099", "#666633", "#99CC00", "#CCFF33", "#FFFF66", "#FFCC66", "#FF9966", "#FF6666", "#FF0066", "#CC6699", "#993366", "#999966", "#CCCC00", "#FFFF00", "#FFCC00", "#FF9933", "#FF6600", "#FF5050", "#CC0066", "#660033", "#996633", "#CC9900", "#FF9900", "#CC6600", "#FF3300", "#FF0000", "#CC0000", "#990033", "#663300", "#996600", "#CC3300", "#993300", "#990000", "#800000", "#993333"];

var visualizar = document.getElementById('visualizar');
var escolhas = document.getElementById('escolhas');
cores.forEach(function(cor) {
    var button = document.createElement('button');
    button.value = cor;
    button.type = 'button';
    button.style.backgroundColor = cor;
    button.addEventListener('click', handler(button));
    escolhas.appendChild(button);
});

function handler(el) {
    return function() {
        visualizar.style.backgroundColor = el.value;
    }
}
#escolhas button {
    padding: 10px;
    border: 1px solid white;
}

#escolhas button:hover {
    cursor: pointer;
    border: 1px solid black;
}

#visualizar {
    width: 100%;
    height: 100px;
    border: 1px solid black;
}

Comment: jsFiddle caso seja útil: http://jsfiddle.net/oy2cguz3/


Transfer a site from SQLite to MySQL

Question: Is it possible to transfer the content of a site that I develop locally with SQLite as a database to the live site which uses MySQL or PostgreSQL when it is finished?
I don't want to have to install MySQL or PostgresSQL locally on my laptop. Can backup_migrate module do it or does it export raw MySQL instructions?
Answer: You are looking for the DBTNG Migrator module.

This module is a UI and Drush interface to replicate a database from one database to another independant of what kind of database server they are. So long as ther are support by Drupal, you can migrate to them, including non-SQL stuff!
Comment: Works like a charm. Thanks. I migrated two drupal installations from sqlite to mysql and I noticed a performance improvement. Just a couple of notes (if they might be of help), take the site offline before doing the migration and in my case at least, I had to disable secure pages, Locale and uninstall the Spanish language pack, then reinstalled them back again. In general, disable any unnecessary module/feature that might interfere with the migration process (I think they are very few).
Answer: i have a lot of trobles doing that. So finnaly i did it, so what do you need to do migration goes well:

Delete other languages from site, exept english
disable locale, and localization update module.
Make migration in empty mysql database with dbtng migration module
You will have trobles with enable languages at new database, so
create a fresh install of drupal and make export tables trought
phpMyadmin: languages, locales_sorce and locales_target.
Import them to new mysql migration website database

Hope it help somebody

Transfer a site from SQLite to MySQL


Why a traceroute to a dynamic ip is different from static ip addresses?

Question: Sorry I can't show you an output of a traceroute atm. Anyways, i find it strange when i try pinging a dynamic ip from the same ISP and get a good route and ping times. Where if i pinged their static ip address, it would takes longer or maybe a bad route to it. Is that normal? Are these dynamic and static ip addresses configured seperately from the ISP?
Comment: "Static" or "dynamic" is not a property of the IP address. (Or in a sense, all IP addresses are static: 18.104.22.168 is always 18.104.22.168. Incidentally, the system it is assigned to can change over time.)
Comment: I don't care whether it's dynamic or static. my route changes completely when i use either one of them. Either way, both work differently on deciding where to pick the required routes. So how can you explain that?
Answer: An ISP that do network attribution change nothing, as each modem cable and such gear report to the ISP server upstream.
Having a static IP just mean your router is not configured to ask an IP from a DHCP server from the ISP, but the packet, or the route use the same physical line to get to the ISP gear to reach the internet backbone.
A good example is ISP with multiple technology, like DOCSYS3 and lower. Usually they are configured to have different type of switch to support both technology on the physical layer to reach the backbone, but the path stay almost the same, just the technology is not the same.
Your result simply depend of where and what you tested it over. Someone with a static, but on a slow modem cable versus a dynamic on a fiber ISP in example could make your test result not ok.
Comment: You tell me that the cable between your house and the ISP concentrator is not routed the same as someone near you going in the same concentrator ?
Comment: That's not the point, and that doesn't answer my main question. Still why my traceroute shows completely a different route only to their static ip but not the dynamic ones? That not normal at all.
Comment: Any router in between can *not* accept to reply the ICMP request for the trace route output to work. For the static versus dynamic IP, it's the same network, see my answer.
Comment: Wrong, that's not the case. But It's ok, I'll be waiting for more answers.
Comment: Ops sorry, but i've changed my mind. I don't like your answer anymore.
Comment: @Semphie94 I work for an ISP, then read a book and learn before trolling
Comment: Ok. That a little bit messed up. But thanks anyway. i'll try to read your answer one more time to be sure. i'll accept it though! :)


Diverge? $\lim_{n \to \infty} \sin(n)+ \sin(n^2)=?$

Question: I encounter with a problem that is to find:
$$\lim_{n \to \infty, n \in \mathbb{N}} \sin(n)+ \sin(n^2)=?$$
So I do know the set $\{\sin n: n \in \mathbb{N}\}$ is dense in $[-1,1]$ and also knowing that $\lim_{n \to \infty} \sin(n^2) $ does not converge and it even has infinite limit points. However, I'm running in a trouble that is proving that if $\sin(n)+ \sin(n^2)$ converges, and exists such a subsequence $\{n_k\}_{k\geq 1} \subset \mathbb{N}$,  $\lim_{k \to \infty} \sin(n_k^2) = a$ then: $$\lim_{k \to \infty} \sin(n_k) \neq L - a$$.
Comment: I have just edited for clarification.
Comment: Thank you! What is the source of this problem? At first glance it looks highly non-trivial.
Comment: Is the limit here taken over integers or reals? When you say '$\lim_{n\to\infty}\sin(n^2)$' doesn't even have infinite limit points', why do you say that?
Comment: I am just self-learning about dense set and fascinated that $\sin n$ is dense and $\sin f(n)$ has infinite limit points for $f(x) \in \mathbb{Z}[x]$ so I just wonder what would happen if we add them together.
Comment: Yep it's true. However, my struggle is to prove it rigourously
Comment: That is likely to be a _very_ big struggle; I'm not sure that this is even known rigorously. I suspect you can prove lack of convergence (and probably even density) in the real case without too much trouble just by looking at the right sorts of subsequences, but for the limit through integers it's unclear how to even proceed.
Comment: Note that we can rewrite this as $\lim_n 2\sin(\frac12(n^2+n))\cos(\frac12(n^2-n))$, but without being able to determine the (possible) correlation between these two factors this doesn't really offer much help.
Comment: Yes sir, it's kinda trivial for the real case. Here is a bit troublesome since one has to consider $\pmod{2\pi}$ for $n$ and $n^2$. I suspect that some ways of using Pigeonhole principle can be applied for $(0,1)$ and using $ \vert \sin x - \sin y \vert \geq \vert x-y - \frac{1}{3!} (x^3 - y^3)\vert, x,y \in [0, 2 \pi)$.
Answer: If we assume the results mentioned in Terence Tao's answer to a related question, there's an easy proof that the limit does not exist.
Pick some suitably large natural number $ N $ and define the random variables $ X(k) = \sin(k) $, $ Y(k) = \sin(k^2) $ on the set of positive integers from $ 0 $ to $ N-1 $ seen as a probability space with the uniform measure. Tao's results say that for "almost all" values of $ N $ (in the sense of natural density, for instance) we have the bounds $ \mathbb E[X] = \mathbb E[Y] = o(1) $ as well as $ \mathbb E[X^2] = \mathbb E[Y^2] = 1/2 + o(1) $. (Here I don't mean that the expectations over $ X $ and $ Y $ are equal, just that they are both in the same asymptotic class.) Suppose we pick such an $ N $. In this case, we have that
$$ \mathbb E[(X+Y)^2] = \mathbb E[X^2] + \mathbb E[Y^2] + 2 \mathbb E[XY] = 1 + \frac{2}{N} \sum_{k=0}^{N-1} \sin(k) \sin(k^2) + o(1) $$
$$ = 1 + \frac{1}{N} \sum_{k=0}^{N-1} (\cos(k^2 - k) - \cos(k^2 + k)) + o(1) $$
The partial sums of both $ \cos(k^2 - k) $ and $ \cos(k^2 + k) $ are also $ O(\sqrt{N}) $ by the same result of Tao, and so we find that $ \mathbb E[(X+Y)^2] = 1 + o(1) $ for most values of $ N $. On the other hand, we also know that $ \mathbb E[X+Y] = o(1) $ for most values of $ N $. No convergent sequence can have both of these properties at once, so we conclude that $ \sin(n) + \sin(n^2) $ does not converge.
Comment: @NguyễnQuân You said you'd come up with this problem yourself — there are a _lot_ of problems that can be posed using undergraduate terminology but not solved by it.
Comment: @NguyễnQuân here's a great example of an undergrad-looking problem whose solution, if found, will likely make use of non-undergrad methods: "Prove or disprove that the Flint-Hills series $\sum_{n=1}^\infty \frac{1}{n^3\sin^2(n)}$ converges."
Comment: @StevenStadnicki Fermat's last Theorem can be stated easily using only first semester terminology.
Comment: The approach is truly interesting sir. However, the point is that I don't have a strong background in probability theory to begin with in order to understand your argument. And also the problem would probably at Undergrad math level so there would be an "elementary" way I suppose.


Partially consuming a Publisher

Question: I am writing a org.springframework.cloud.gateway.filter.GatewayFilter (spring-cloud-gateway), that attempts to consume a response that follow a certain arbitrary protocol. The response body goes along the lines of:
200\n
header1:value1\n
header2:header2\n
\n
<the actual body>

The idea is, the entire response metadata from the downstream service is in the response body (much like how a SOAP envelope encloses the real body). The client of the gateway should receive a modified unwrapped response.
I've been following how ModifyRequestBodyGatewayFilterFactory and ModifyResponseBodyGatewayFilterFactory as guide, but I don't think they fit my use case.
I believe I can achieve this by returning a subclass of ServerHttpResponseDecorator, but I can't wrap my head yet on how to go about implementing:
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
   // unwrap status code
   // unwrap headers
   // let it continue as usual
}

Answer: I was able to achieve this with:
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
   return Mono.from(body).flatMap { buffer ->
      val size = readUtf8Line(buffer)
      // recompute 'Content-Length', if applicable

      super.writeWith(Mono.just(buffer))
   }
}

The readUtf8Line is just my own method, that consumes the DataBuffer until it reaches a line break. It is also important to return the number of bytes read (i.e., size), because the Content-Length needs to be recomputed, if present.
Comment: Can u pls share the code to read the response from the buffer?

Partially consuming a Publisher


Projection of a vector on orthogonal subspaces

Question: Let $H$ be a Hilbert space, $G\subset H$ a subspace, i.e. a complete linear manifold, and $$F = \{ f'\in H\mid\forall g'\in G:(f',g')=0 \}$$ the orthogonal complement of G.
Consider a vector $h\in H$. Since $G$ is a subspace, there is one and only one projection $g\in G$ of $h$ onto $G$. I have already proved that $F$ is a subspace, too. So there is one and only one projection $f\in F$ of $h$ onto $F$.
I want to prove that $$h=g+f.$$ So, I have already shown that $h-g\in F$. Now, I have to prove that $h-g$ is the projection of $h$ on $F$. How can I prove it?
Answer: Projection $Ph$ of $h$ onto $F$ is characterized by the properties

$Ph \in F$
$h - Ph \perp F$, that is $h - Ph \in G$

For $h-g$ we indeed have $h - g \in F$ and $h - (h-g) = g \in G$ so $Ph = h-g$.
Answer: What you have shown is that $h = g + f'$ for some $f'\in F$. You can similarly show that $h = g'+f$ for some $g'\in G$ (since $G$ is the orthogonal complement of $F$). Then $g+f'=g'+f $, which means that
$$ g-g' = f-f' \in G\cap F$$
so $(\underbrace{g-g'}_{\in G},\underbrace{g-g'}_{\in F}) = 0$, by the definition of $F$. Hence,  $g-g'=0=f-f'$ and $f'=f$, and thus $h=g+f$.


Algorithm recommendation: Short string classification/matching (fuzzy string matching or machine learning ?)

Question: I have a product categories tree with names like apparel, jeans, beauty & wellness etc.
I need to 'match' external categories with this category tree.
For example, I'd need to match: lenses color to lens colour.
I currently use a fuzzy string matching approach (using python and FuzzyWuzzy), and when there is no match, it is done manually and saved as a synonym.
I was wondering if a machine learning classification method would make sense here since:

We're talking about single words (or 2 to 3 words like in beauty & wellness). It seems like classification works better on sentences, or words inside sentences.
There are very few examples for each 'class'. Even after gathering a lot of synonyms, there aren't more than 4 or 5 ways to say a category. So not sure the training will be consistent.

I'm more familiar with neural nets than other machine learning techniques, but maybe someone is familiar with this matter and will suggest other techniques.
Answer: I would use word stemming.
That means we map words like indexer, indexing, indexes all to index. There are several possible approaches for this.
Check Wikipedia for a good summary on algorithms that do that: https://en.wikipedia.org/wiki/Stemming
Comment: It would be better to give a fuller answer rather than relying on an external link. There seems little in the original question to suggest that this would solve his/her problem though.


Is there a numerical solution to a mixture model of two normal distributions?

Question: I'm building a mixture model with the two normal distributions
$\mathcal{N}(\mu_1,\sigma_{1}^{2})$ and $\mathcal{N}(\mu_2,\sigma_{2}^{2})$.
So, the density function is
$$
f(x) = p_1 N(x; \mu_1, \sigma_1^2) + p_2 N(x; \mu_2, \sigma_2^2),
$$
where $p_1+p_2=1$, and
$$
N(x;\mu,\sigma) = \frac{1}{\sqrt{2\pi \sigma^2}}\exp\left\{-\frac{(x-\mu)^2}{2\sigma^2}\right\}.
$$.
Suppose I have all the sampling data, is there some numerical solution or formula that could derive $p_1$, $\mu_1$, $\sigma_1$ and $p_2$, $\mu_2$, $\sigma_2$?
Comment: The standard approach to estimating the parameters of a mixture of normal distributions is to use an Expectation-Maximisation algorithm.
Answer: The approach depends on whether the sampling data includes or not an indicator variable that specifies from which normal distribution each observation is issued.
If the data includes this indicator variable you might simply split the data in two sub-samples corresponding to the distribution from which the data originates, and fit the two normal distribution separately using maximum likelihood. The parameters $p_1$ and $p_2$ can be estimated by the proportion of samples that come respectively from the first and second normal distribution.
If the data doesn't include this indicator variable, which is most common in practice, then you might use the Expectation-Maximization (EM) algorithm.
The classical example with a mixture of two normal distributions is explained here.


Componente Select com uma requisição Angular

Question: Tenho um componente select
<select class="selectpicker" data-live-search="true">
        <option data-tokens="distrito">Distrito</option>
        <option data-tokens="bairro">Bairro</option>
        <option data-tokens="municipio">Município</option>
</select>

e, em cada <option> quero colocar uma requisição do Angular que esta em um href
Busca Municípios

Comment: está meio confusa sua pergunta, no `click` do `option` vc quer dizer? a link da requisição que está em um `href`?
Comment: sim, o link da requisição está em um `href` e quero por em um componente `select` que ao ser selecionado chama aquela requisição
Answer: Existem algumas formas de fazer o que desejas, a primeira é invocar o click no change, dessa forma:

document.getElementsByClassName('selectpicker')[0].addEventListener('change', handleEvent);

function handleEvent() {
  console.log(this.value);
  switch (this.value) {
    case 'Município':
      document.getElementById('municipio').click();
  }
}
<select class="selectpicker" data-live-search="true">
            <option data-tokens="distrito">Distrito</option>
            <option data-tokens="bairro">Bairro</option>
            <option data-tokens="municipio">Município</option>
</select>

Busca Municípios

Uma segunda opção é controlar no Angular. Exemplo:

angular.module('select', []).controller('ctrl', function($http, $scope) {

  $scope.handleEvent = function() {
    console.log($scope.opcao);
    switch($scope.opcao) {
      case 'Município':
        // efetuar uma requisicao http
        break;
    }
  }
});

  <select class="selectpicker" data-live-search="true" ng-model="opcao" ng-change="handleEvent()">
        <option data-tokens="distrito">Distrito</option>
        <option data-tokens="bairro">Bairro</option>
        <option data-tokens="municipio">Município</option>
</select>

  Busca Municípios


Prove $X^*$ is reflexive then $X$ is reflexive

Question: Prove $X^*$ is reflexive then $X$ is reflexive
My attempt:
Let $J : X \to X^{**}$ and $J_*: X^* \to X^{***}$ be the canonical injections. Suppose by contradiction that $X$ isn't reflexive, then exists $f\in X^{**}$ such that for all $x\in X$  such that $J(x)=f$, in other words:
$J(X)\not \subset X^{**}$
Here i'm stuck, can someone help me?
Comment: If you prove that reflexivity $X^\ast$ follows from reflexivity $X$, then your statement will turn out as a simple consequence.
Answer: Hint: If $X^*$ is reflexive, prove that $J^*\colon X^{***} \to X^*$, the dual of $J$, has to be the inverse of $J_*$. In particular, $J^*$ is an isomorphism. Deduce that $J$ has to be an isomorphism.


How to update $auth.user properties in Nuxt.js?

Question: When I want to update $auth.user.balance:
methods:{
   test(){
      this.$auth.user.balance = 10;
   }
}

But it returns error:
Error: [vuex] do not mutate vuex store state outside mutation handlers.

How can I update these vuex properties in Nuxtjs?
Answer: Nuxt provides $auth.setUser() method to set user.
Use $auth.setUser() like so:
const userToUpdate = {...this.$auth.user}
userToUpdate.balance = 10;
this.$auth.setUser(userToUpdate)

Data updating in store always should be immutable.
So create a new reference of object before passing it to setUser to avoid the reactivity issue.
Comment: In my case, when using this.$auth.user in a computed variable it was not updating the DOM, i've needed to use this.$auth.user directly.
Answer: When you're using Vuex you should only mutate your state throught your mutations, in your Vuex you should create a mutation like this :
  setBalance(state, payload) {
    auth.user.balance = payload;
  },

and in your component you need to map your new mutation in your methods,
 ...mapMutations('auth', ['setBalance']),

don't forget to import the mapMutations from vuex
import { mapMutations } from 'vuex';

and in your component when you want to set a new value to balance you call
 test(){
         let newValue = 10;
         this.setBalance(newValue);
       }

You can learn more about mutations in Vuex store here in Vuex documentation


CentOS partitioning

Question: I have a CentOS server with two 1 TB disks. However, it is badly partitioned.
Please check below:
[root@p16282558 ~]# fdisk -l

Disk /dev/sdb: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0xd4f28eb2

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1               1         523     4194304   fd  Linux raid autodetect
Partition 1 does not end on cylinder boundary.
/dev/sdb2             523         784     2097152   82  Linux swap / Solaris
Partition 2 does not end on cylinder boundary.
/dev/sdb3             784      121602   970470104   fd  Linux raid autodetect
Partition 3 does not end on cylinder boundary.

Disk /dev/sda: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x724abfe3

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1         523     4194304   fd  Linux raid autodetect
Partition 1 does not end on cylinder boundary.
/dev/sda2             523         784     2097152   82  Linux swap / Solaris
Partition 2 does not end on cylinder boundary.
/dev/sda3             784      121602   970470104   fd  Linux raid autodetect
Partition 3 does not end on cylinder boundary.

Disk /dev/md3: 993.8 GB, 993761296384 bytes
2 heads, 4 sectors/track, 242617504 cylinders
Units = cylinders of 8 * 512 = 4096 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x00000000

Disk /dev/md1: 4294 MB, 4294901760 bytes
2 heads, 4 sectors/track, 1048560 cylinders
Units = cylinders of 8 * 512 = 4096 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/vg00-usr: 4294 MB, 4294967296 bytes
255 heads, 63 sectors/track, 522 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/vg00-var: 4294 MB, 4294967296 bytes
255 heads, 63 sectors/track, 522 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x00000000

Disk /dev/mapper/vg00-home: 4294 MB, 4294967296 bytes
255 heads, 63 sectors/track, 522 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x00000000

When I ran the DF command:
[root@p16282558 ~]# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/md1              4.0G  4.0G     0 100% /
/dev/mapper/vg00-usr  4.0G  1.5G  2.4G  38% /usr
/dev/mapper/vg00-var  4.0G  880M  2.9G  23% /var
/dev/mapper/vg00-home
                      4.0G  136M  3.7G   4% /home
none                  7.9G  556K  7.9G   1% /tmp

/opt is within /, and no space left in /
When i ran, /etc/fstab
/dev/md1        /               ext3    defaults        1 1
/dev/sda2   none            swap    sw
/dev/sdb2   none            swap    sw
/dev/vg00/usr   /usr            ext4    defaults        0 2
/dev/vg00/var   /var            ext4    defaults,usrquota   0 2
/dev/vg00/home  /home           ext4    defaults,usrquota   0 2
devpts          /dev/pts        devpts  gid=5,mode=620  0 0
none            /proc           proc    defaults        0 0
none            /tmp    tmpfs   defaults        0 0

So there is a full md1 disk, and a non-utilised Disk /dev/md3 with 993.8 GB free??
But,
[root@p16282558 ~]# df -h /dev/md3
Filesystem            Size  Used Avail Use% Mounted on
-                     7.9G  204K  7.9G   1% /dev

Results of PVS and LVS.
[root@p16282558 ~]# pvs
  PV         VG   Fmt  Attr PSize   PFree
  /dev/md3   vg00 lvm2 a--  925.51g 913.51g

[root@p16282558 ~]# lvs
  LV   VG   Attr      LSize Pool Origin Data%  Move Log Cpy%Sync Convert
  home vg00 -wi-ao--- 4.00g
  usr  vg00 -wi-ao--- 4.00g
  var  vg00 -wi-ao--- 4.00g

Does this mean /dev is not being mounted at system start (as per fstab)  ?
My problem is: /opt and /var should be mounted in a disk/partition with more space.
How can i restructure the disk to utilize all disk space in an efficient way?
Please help.
Thanks,
Sash
Comment: Can you add the outputs of `pvs` and `lvs` into your question?
Answer: It appears you are using LVM on /dev/md3 and that you have only allocated 12GB out of the 1TB available there.
If /opt is where you are spending most of the capacity, you can create a new logical volume and call it vg00-opt. Once that has been created, you can mount it temporarily on /mnt/whatever and move the files from /opt into the new logical volume. Finally you can mount vg00-opt on /opt.
The df -h /dev/md3 command that you typed only told you how much space is used and available on the filesystem used for /dev. Both /tmp and /dev are using tmpfs which will use RAM and/or swap to store the files. Those directories will be empty at boot, but entries in /dev are automatically generated by a deamon started at boot. By default the capacity of a tmpfs is half the amount of RAM, so those two are 8GB in size because you have 16GB of RAM.
Comment: Hi, i have done the following: # create a new 5gb logical volume
lvcreate -n opt -L 5G vg00

# format it as ext4
mkfs.ext4 /dev/vg00/opt

# move the old dir out of the way
mv /opt /opt.orig

# mount the new logical volume
echo "/dev/vg00/opt /opt ext4 defaults 0 2" >> /etc/fstab
mkdir /opt
mount /opt

# move all data into the new mount
mv /opt.orig/* /opt
rmdir /opt.orig
Comment: But after these steps when i ran df -h it doesn't show /dev/mapper/vg00-opt???
Comment: My best guess is that /etc/mtab is not completely up to date with actual mounts. It is possible that the disk was so full, there wasn't free space enough to update /etc/mtab.

If you have freed up some space, you can try to umount /opt and then mount it again.

CentOS partitioning


Labels do not fit correctly on Pie

Question: In effort to learn D3.js, I took this example and made a plunker out of it
http://plnkr.co/edit/ynWB0GznvrMMRmqkaqaA?p=preview
Problem?
The data doesn't fit correctly and you can see that data is incomplete
How shall I fix it?
Answer: First thing is that your labels are incorrect. So change this:
  .text(function(d) {
    return 'd.data.age'; });

to this:
  .text(function(d) {
    return d.data.age; });

and you'll get the correct labels.
Second, the labels are getting cut off. This appears to be to do with the sizes specified for the pie chart. You can either increase the width specified (looks fine at 360 say):
var width = 360,
height = 300,
radius = Math.min(width, height) / 2;

Or bring the labels in closer to the graph:
.attr("transform", function(d) {
    return "translate(" + ( (radius -50) * Math.sin( ((d.endAngle - d.startAngle) / 2) + d.startAngle ) ) + "," + ( -1 * (radius - 50) * Math.cos( ((d.endAngle - d.startAngle) / 2) + d.startAngle ) ) + ")"; })

Where it says radius - x determines how close or far the labels will appear to the graph. The bigger x is, the closer they will be.

Labels do not fit correctly on Pie


Image styles - How to resize uploaded images and force an aspect ratio

Question: I'm looking for a solution to resize uploaded images while maintaining a desired aspect ratio instead of cropping them.
We can configure some preset Image styles, but it seems we can only :
Resize : Will force an exact set of width/height dimensions which can cause images to be stretched or shrunk disproportionately and loose.
Scale and crop : will maintain the original aspect-ratio of the uploaded image, which can be different from the desired aspect ratio.
So is there a way to force a certain aspect ratio to uploaded images, by adding a white background for instance ?
Comment: " Resize : which cause images to be stretched or shrunk disproportionately." <- What do you mean? And what are the settings you are using that are causing this undesired effect?
Comment: Thanks for the remark, I edited my question to clarify that part. Right now i'm using the "scale and crop" image style which resizes uploaded images to a specific width/height size but in order to keep the aspect ration I want, some uploaded images are cropped so we don't see the entire image. It looses part of its top/bottom or right/left sides.
I'm thinking maybe there's a way to set a specific resize dimensions and adding white background to the top/bottom or right/left sides instead of cropping.
Comment: This is usually done with CSS, not with image manipulation tools.
Answer: If you want to resize the image while maintaining the desired aspect ratio, this is actually two steps.

Get the image in the appropriate aspect ratio.
Resize the image.

One way to do this is with the Image Widget Crop module.  This module allows you to decide which aspect ratios to crop to.
You can use one or multiple aspect ratios, and you can set which aspect ratios are usable for which image fields.
This adds a "cropping" step when you upload an image to set each required crop.  There is an Automated Crop module available that may be able to help do this automatically but I haven't used it.
Potential dealbreaker
I do not think it is possible to use Image Widget Crop to set a crop that is larger than the image (to add a white background, for example).  Instead, you have to crop the image within the "frame" of the image itself.
Other modules
Another module of note in this area is Image Effects, which will give you more scaling and resizing options, as well as many other useful things like adding watermarks.