Exibir dados de um arquivo Json em HTML

Question: Estou empacado em uma situação onde eu não consigo transformar os blocos de dados do arquivo JSON em HTML, não aparece nada. Abaixo colocarei os códigos para vocês darem uma olhada
OBS: Se puderem me indicar um site legal sobre JSON também preciso saber sobre filtrar e adicionar posts, pois cada bloco JSON é um.
UPDATE DO PROBLEMA
Pessoal fiz abaixo os updates da resolução que tive para mostrar o conteúdo JSON no HTML, agora só falta o fazer o filtro que tem que ser a partir de dados como popularidade, Data e comentário, vou seguir a ajuda do amigo e se conseguir faço mais um update por aqui!!
Código HTML(UPDATE)
<!DOCTYPE html>

<link rel="stylesheet" href="css/style.css" />

    <input id="filtro" type="text" placeholder="Busca Rápida">

CÓDIGO DO FILTRO EM JAVASCRIPT(funcionando)

Arquivo JSON(UPDATE)
window.onload=function(){
data = { person: [
    {
    author: 'Nobtaka Nukui',
    title: 'Want people to use your product? Use it yourself',
    url: 'http://www.medium.com',
    category: 'Product Design',
    comments: '4 coments',
    created_at: '43 minutos atrás',
    classcor: 'corUm',
    foto: '',
    upvotes: 11 },
  {
    author: "Danil Ishutin",
    title: "Font Size Idea: px at Root, rem for Components, em for Text Elements",
    url: "http://www.css-tricks.com",
    category: "UX Theory",
    comments: '7 coments',
    created_at: '5 minutos atrás',
    classcor: 'corDois',
    foto: '',
    upvotes: 9},
    {
    author: "Kenny Schrub",
    title: "Some things cant be prototyped",
    url: "http://www.mika.el",
    category: "Opinion",
    comments:'25 coments',
    created_at: '7 minutos atrás',
    classcor: 'corTres',
    foto: '',
    isOwner: true,
    upvotes: 4
        },
    {
    author: "Jacky Mao",
    title: "How to prototype without any tools",
    url: "http://www.jackymao.wix",
    category: "Opinion",
    comments: '0 coments',
    classcor: 'corTres',
    foto: '',
    upvotes: 4
        },

    {
    author: "Christopher Alesund",
    title: "Case study: Redesigning the Folyo landing page",
    url: "http://www.medium.com",
    category: "Case Study",
    comments: '0 coments',
    classcor: 'corQuatro',
    foto: '',
    created_at: '7 hours ago',
    upvotes: 3
  },
  {
    author: "Pasha Biceps",
    title: "Don't let bad process or structure kill great interfaces",
    url: "http://www.medium.com",
    category: 'Product Design',
    comments: '0 coments',
    classcor: 'corUm',
    foto: '',
    created_at: '2 days ago',
    isOwner: true,
    upvotes: 2
  }

    ]};

data.person.forEach(function(p){

  var post = "
"+p.upvotes+"
"+p.url+"
"+p.title+"
"+p.category+"
"+p.foto+""+p.author+""+p.created_at+""+p.comments+"

";

  document.querySelector('#dados').innerHTML += post;

});
}

Comment: Brother, qual a sua dúvida sobre Json? JSON é um array de objetos. Se você der um console.log na variável data o verá em seu estado original e aí poderá percorrê-lo sem dificuldade.
Comment: Assim é por que eu estou aprendendo JSON, e me deram isso pra fazer, eu pesquisei em tudo quando é lugar pra ver exemplos e o único que deu certo foi um com tabela, mas quando eu tento reproduzir o mesmo com HTML não dá certo, desculpa a nubisse!!
Comment: imagina... Olha, primeiro entenda o seguinte. JSON é um formato. Ou seja, uma forma de armazenar dados. Poderia ser por exemplo o XML. Sabendo disso, vou tentar jogar um exemplo aqui de Json como resposta e você adapta o seu blz?
Comment: blz, vlw mesmo, pois estou perdidão heheh
Comment: O problema está na atribuição do valor a variável `postRow`. Tens aspas simples onde deverias ter aspas duplas, não tem o `;` no fim. Isso tudo gera erros e por isso não é renderizado nada.
Comment: vc diz ali nas tags de link? pq foi o único jeito que o dreamweaver não acusou erro
Comment: Coloquei uma resposta abaixo, focando numa outra forma de consumir o JSON, que pelo que vi é sua dificuldade. Acho que é mais fácil de entender assim...
Comment: na linha onde tens `var postRow = `. O seu problema não é só entender como o JSON funciona e sim programação em si.
Comment: @FilipeMoraes  Se vc se refere ao espaço, é que eu dei um enter ali, mas mesmo sem ele não da certo
Comment: Eu recentemente escolhi usar o VueJS e o AXIOS, pode dar uma olhada nesta resposta para ver como tudo fica simples https://pt.stackoverflow.com/a/308311/5704
Answer: Veja que é um exemplo bem simples e que pode ser utilizado de diversas formas...

var json = {
   person: [
   {
  "author": "Nobtaka Nukui",
  "title": "Want people to use your product? Use it yourself",
  "url": "http://www.medium.com",
  "category": "Product Design",
  "comments": 4,
  "created_at": 1460030400,
  "upvotes": 11
},
{
  "author": "Danil Ishutin",
  "title": "Font Size Idea: px at Root, rem for Components, em for Text Elements",
  "url": "http://www.css-tricks.com",
  "category": "ux_ui",
  "comments": 7,
  "created_at": 1459857600,
  "upvotes": 9
},
{
  "author": "Mikael Greif",
  "title": "What do you do with a failed project?",
  "url": "http://www.mika.el",
  "category": "discussion",
  "comments": 2,
  "created_at": 1460203200,
  "upvotes": 4
},
{
  "author": "Kenny Schrub",
  "title": "Some things can't be prototyped",
  "url": "http://www.mika.el",
  "category": "discussion",
  "comments": 25,
  "created_at": 1460203200,
  "isOwner": true,
  "upvotes": 4
},
{
  "author": "Jacky Mao",
  "title": "How to prototype without any tools",
  "url": "http://www.jackymao.wix",
  "category": "product_design",
  "comments": 0,
  "upvotes": 1
},
{
  "author": "Christopher Alesund",
  "title": "Case study: Redesigning the Folyo landing page",
  "url": "http://www.medium.com",
  "category": "case_study",
  "comments": 0,
  "created_at": 1460289600,
  "upvotes": 3
},
{
  "author": "Pasha Biceps",
  "title": "Don't let bad process or structure kill great interfaces",
  "url": "http://www.medium.com",
  "category": "product_design",
  "comments": 0,
  "created_at": 1460376000,
  "isOwner": true,
  "upvotes": 2
  }
 ]
};

//console.log(json);
for(var i=0;i< json.person.length; i++){
  var html = "
";
  html +=""+json.person[i].author+"	";
  html +=""+json.person[i].title+"	";
  html +=""+json.person[i].url+"	";
  html +=""+json.person[i].upvotes+"	";
  html +="
";
  $('table tbody').append(html);
}

      Author
      Title
      Url
      Upvotes

Comment: vlw vou tentar aqui
Comment: Se realmente ajudar, marca como resposta valeu? Abraços e boa sorte!
Comment: aliás fazendo isso não precisa do javascript?
Comment: Sim, precisa! Inclusive, é ele que ta pegando as informações do Json e jogando no HTML
Answer: Para filtrar os dados você pode usar search:
//Sintaxe:
var teste = 'exemplo'
teste.search('ex') //Retorna 0 que é a posição da primeira ocorrência do filtro
teste.search('Ex') //Retorna -1, ou seja, não foi encontrado
teste.search(/Ex/i) //Exemplo de busca com case-insensitive, retorna 0

//No JSON, para buscar os autores que tenham a letra y ou Y:
for(var i = 0; i < json.person.length; i++) {
    if(json.person[i].author.search(/y/i) != -1) {
        //Mostra os dados
    }
}

Para cadastrar use push:
//Sintaxe
var exemplo = [1, 2, 3]
exemplo.push(4)
console.log(exemplo) //Retorna [1, 2, 3, 4]

//Você pode usar push para adicionar objetos no JSON
json.person.push({
    author: 'nome exemplo',
    title: 'exemplo de titulp',
    url: 'https://google.com',
    category: 'minha categoria',
    comments: 0,
    created_at: 1460030400,
    upvotes: 0
})
//push() retorna o índice do cadastro, no caso 8

Leia mais sobre arrays
Comment: A resposta não ajuda a responder a pergunta. O mais indicado é colocar em um comentário, mesmo assim não sei em que ajudaria.
Comment: @rLinhares concordo com isso apesar de achar difícil a w3s mudar seus links, por isso editei a pergunta com um exemplo
Comment: vlw mano vou dar uma estudada
Comment: @FilipeMoraes Que resposta, minha ou do Guilherme?
Comment: @user4451 O seu foi um comentário, por tanto estou a falar do resposta do Guilherme.
Comment: @FilipeMoraes a pergunta principal é sobre o erro, mas ele também pede referencias sobre manipulação de JSON, porque isso não é uma resposta?
Comment: Utilize o comentário para isso. A resposta deve ser completa e não parcial.
Comment: @FilipeMoraes mesmo se outra resposta anterior ja sanou a outra metade? sendo desnecessário repetição do mesmo
Comment: Eu não sei se é uma regra aqui do stack, mas acho que não tem necessidade desta discussão, mesmo que ele não tenha colocado outra parte eu agradeço, pois pra quem está perdido toda ajuda é bem vinda!!
Comment: Embora este link possa responder à pergunta, é melhor incluir as partes essenciais da resposta aqui e fornecer o link para referência.  As respostas apenas por link podem ser invalidadas se a página com o link for alterada. - [Da Revisão](/review/low-quality-posts/156288)
Comment: É nisso vc tem razão
Comment: @GuilhermeCostamilam Eu tentei usar os dados que passou mas não consegui, fiz um update usando o código que postei, só que o problema que ele só é perfeito se o código estiver diretamente no HTML e não trazido do jason.
Comment: Se o erro acontece apenas quando o arquivo é externo ao html o erro esta em carregar o mesmo, de uma olhada nessa [pergunta](https://pt.stackoverflow.com/questions/268692/como-incluir-e-manipular-arquivo-json-local), se o problema persistir avise
Comment: @GuilhermeCostamilam Eu coloquei outro código lá no post principal que agora dá certo, só falta agora eu filtrar por categoria e pronto.
Comment: Crie outra pergunta, não use a mesma se esse problema foi resolvido
Comment: @GuilhermeCostamilam Sim, é que as vezes fico meio com receio de fazer isso, dai dizerem que estou sendo redundante e fecharem meu post

Exibir dados de um arquivo Json em HTML


Feedback on Admin set user as mod in rails

Question: i'm a beginner to Rails and is following Michael Hartl's book. In chapter 9, where he set up an Admin role, and admin can delete users. I want to extend this feature by allowing admin to set users to Mod as well.
The plan is this:
1.An logged in admin go to the users page, where he sees a list of users(users_url)
2.And next to their name, the admin have an option of 'Set Mod', when the admin clicks that, it sets the user's mod attribute to true.
$ rails g migration add_mod_to_users mod:boolean

then in the migrated file, set default to false, and
$ rake db:migrate

In the routes.rb
get 'setmod' => 'users#setmod'

and in users_controller.rb
def setmod
  if logged_in? && current_user.admin?
    @user = User.find(params[:id])
    @user.update_attribute(:mod, true)
    flash[:success] = "User ID #{@user.id} is now a mod!"
    redirect_to users_url
  else
    flash[:warning] = "You can't do that!"
    redirect_to users_url
  end
end

In the list of users view file:
<% if current_user.admin? && !current_user?(user) %>
    | <%= link_to "Set Mod", setmod_path(:id => user.id) %>

Is this the right approach to it? I'm a beginner so i'd be glad if i can get some feedback on this. Does my code have any vulnerable spots? What's a better way doing it?
Also, i tried to do some test on this
in test/controllers/users_controller_test.rb
  # This test passes
  test "should redirect setmod when not logged in" do
    get :setmod
    assert_redirected_to users_url
  end

  # This test failed
  test "should redirect setmod when logged in as a non-admin" do
    log_in_as(@other_user)
    assert_no_difference '@user.mod' do
      get :setmod, id: @user
    end
    assert flash.empty?
    assert_redirected_to users_url
  end

I know the second test's code is wrong, but i can't figure out the right way to do it.
Answer: You're not passing a user id into the setmod route.
Change to this:
get 'setmod/:id' => 'users#setmod'

Now, navigating to http://localhost:3000/setmod/1 will attempt to set the user (with id=1) to mod.
However, you can use Rails' built-in resources to handle this just fine.
routes.rb
resources :users

your view
link_to("Promote the user to MOD", user_path(@user, status: 1), method: :put)

Clicking that link will update the single attribute for a user shown on the page. You would simply authenticate the admin in the users_controller.rb update action.
Comment: right now the route is /setmod?=1, and i'm using the two methods(logged_in? && current_user.admin?) from the railstutorial book to limit people who have access to it, is this secure enough?
Comment: I honestly cannot say without seeing the source of those methods. I would recommend at least changing the `get 'setmod'` to a `post` or `put` request though
Comment: So there's GET, POST AND PUT, which one do you think i should use in this case? Thanks for helping me btw
Comment: You can use built-in rails resources to update a user. I'll edit my answer


Find the solution of SDE $dY_t=rdt+\alpha Y_tdB_t$

Question: Problem: find the explicit solution of the following SDE
$$dY_t=r dt+\alpha Y_t dB_t$$
with initial condition $Y_0=y_0$ and $B_t$ is a Brownian motion.
Hint: consider $Z_t=\exp(-\alpha B_t+\frac{1}{2}\alpha^2 t)Y_t$

I've tried to apply Ito's formula to the process given in hint:
$$dZ_t=f(t,Y_t)=\frac{1}{2}\alpha^2Z_tdt+\exp(-\alpha B_t+\frac{1}{2}\alpha^2t)dY_t$$
$$=\frac{1}{2}\alpha^2\exp(-\alpha B_t+\frac{1}{2}\alpha^2 t)Y_tdt+r\exp(-\alpha B_t+\frac{1}{2}\alpha^2t)dt+\exp(-\alpha B_t+\frac{1}{2}\alpha^2t)\alpha Y_t dB_t$$
I get stuck on that it doesn't seem we can get a equation without $Y_t$. Usually, we would have an Ito process which we can transform to the Integral form and then we can multiply the inverse of the hint to get the solution $Y_t$.
And the process in the hint is the inverse of the stochastic exponential with argument $\alpha$, I don't know if it can be used to solve the problem.
Does anyone have some hints or indicate what I've done mistakenly so far?
Comment: Does this answer your question? [Solving the SDE $dX_t=bdt+cX_t dW_t$](https://math.stackexchange.com/questions/755396/solving-the-sde-dx-t-bdtcx-t-dw-t)
Comment: @Snoop, i do think so, thank you for the link, but i also want to find the way solve this problem using the hint.
Comment: For the general case of linear SDE have a look here :  https://math.stackexchange.com/questions/1788853/solution-to-general-linear-sde
Answer: Consider $X_t=\alpha X_tdW_t$, $X_0=1$. Then, $X_t=e^{-(\alpha^2/2)t+\alpha W_t}$. The hint then suggests to consider $Z_t=X_t^{-1}Y_t$. Note that by Ito
$$d(X_t^{-1})=-X_t^{-2}dX_t+\alpha^2X_t^{-3}X_t^2dt=\alpha^2(X_t^{-1})dt-\alpha (X_t^{-1})dW_t$$
So
$$dZ_t=(X_t^{-1})dY_t+Y_td(X_t^{-1})-\alpha^2Z_tdt=r (X_t^{-1})dt$$
Therefore $Y_t=Z_tX_t=y_0X_t+r \int_0^tX_tX_s^{-1}ds$.
Comment: @Malik correct, got a typo in mine. You're welcome.
Comment: thanks, i solved it and get the solution $Y_t=\exp(\alpha B_t-\frac{1}{2}\alpha^2t)(y_0+\int_0^t \exp(-\alpha B_s +\frac{1}{2}\alpha^2s) ds$.


How to programmatically create new user with custom fields?

Question: I want to create user with some custom fields. I have created extra fields through config > people > site information > manage fields and fields like first name, last name, city etc. I want to create user with this custom fields.
How can I create user programmatically?
Answer: Using user_save Drupal function you can create new users like so:
$new_user = array(
  'name' => 'JohnDoe',
  'mail' => 'email@example.com',
  'pass' => 'password123',
  'status' => 1,
  'field_custom_first_name' => array(LANGUAGE_NONE => array(array('value' => 'John'))), // This becomes $account->field_custom_first_name[LANGUAGE_NONE][0]['value']
  'field_custom_last_name' => array(LANGUAGE_NONE => array(array('value' => 'Doe'))),
  'access' => REQUEST_TIME,
  'roles' => array(), // No other roles than Authenticated
  //'roles' => array('10' => '10', '11' => '11'), // If you want to specify additional roles, the numbers are role_id's
);
user_save(NULL, $new_user);

Comment: I'm not sure what `access` does, I've copied this from the user_save page's comments on d.o and modified them, so I'm not 100% on what `access` does. I'm gonna assume that it's the last access date, so if it's a new user, I'm guessing it shouldn't be set.
Comment: thanks its working good for me. and sorry for late replay.
Comment: @GandhiPranav Don't forget to accept the answers to your questions if they've helped you out; this lets future visitors know that a particular solution was the one that solved your specific problem, and it rewards the answerer for their efforts. You can accept an answer by clicking the checkmark underneath the vote indicator. Thanks :)
Comment: Access is just the last access field (like the "created" field
Comment: This works to create new users, but isn't there a "preferred" entity way like with nodes? Something involving entity_create_stub_entity('user') or entity_metadata_wrapper(..)?  I ask because I have been struggling doing it the entity way.. :)
Comment: @texas-bronius see here: https://devblog.more-onion.com/content/snippet-how-programmatically-create-user-profile2-using-entity-api (not sure if it works or not)


Angular 7 mat-checkbox not being checked with reactive forms

Question: I am using Angular7 mat-checkbox with reactive forms. Below is the code.
shared: FormGroup;
 constructor(private router: Router, fb: FormBuilder,private filterServices:FilterServices) {
        this.shared = fb.group({
            "byAll": false,
            "byFriends": false,
            "byPeers": false,
            "byExperts": false,
            "bySpecificFriends": false,
            "byNone":false,
            "permissionType":"share",
            "emails": []
        });
}

On nginit function i am getting data from db as shown below
  ngOnInit(){
       this.filterServices.getFilters(12).subscribe((res)=>{
        console.log(res);
        this.setFormvalues(res);
       })
    }
setFormvalues(response:any){
     response.forEach(element => {

             this.sharedEmails = [];
             this.sharedEmails = element['emails'].split(',');
             this.shared.value['byAll'] = element["byAll"]
             this.shared.value['byExperts'] = element['byExperts']
             this.shared.value['byFriends'] = element['byFriends']
             this.shared.value['byNone'] = element['byNone']
             this.shared.value['byPeers'] = element['byPeers']
             this.shared.value['bySpecificFriends'] = element['bySpecificFriends']
             console.log(this.shared)
       })
}

I am able to set the data to the properties in shared object, but checkboxes in html is not getting checked. Suppose shared['byAll'] was initially false (checkbox initially unchecked),but after getting data fro service calls now its value is true. But in html its not getting reflected i mean checkbox is not getting checked. Am i going wrong somewhere??
below is the html code.
<form [formGroup]="shared">

                            <mat-checkbox formControlName="byAll">All</mat-checkbox>

</form>

Comment: You are looping over the response and overriding Form values again and again. Also, I don't think setting value to the form this way would work, call `setValue()` over the formgroup directly (as the control name and data keys are same) or `setValue()` to the form controls individually
Answer: Try this
this.shared.value['byAll'].setValue(element["byAll"]);

Answer: I got the solution!
We can use patchValue if we are updating only few values,else if we want to update all the values in a form group then use setValue.
patch value format
this.shared.patchValue({
"key":"value"
})


Traffic on IP which is not being used?

Question: My server (Debian 7.4, x86_64, Proxmox) has 4 IPs. One for the VM Host (call it A), and three that I use for virtual machines (say B, C and D). Currently, only B and C are used, the D address is not assigned at all. The VM host does not even respond to pings or anything on D, so as far as I can see it doesn't even "know" about it. ifconfig -a and ip addr show only refers to A.
I have set the traffic limit at my server's ISP for D to 1MB. Since yesterday, I am suddenly receiving traffic warnings that D is using several megabytes of traffic per hour. It's not that it's much, but I am completely clueless what could even generate that traffic? It seems to be outgoing only. How does Proxmox (the VM software I use) assign IPs to OpenVZ containers? How can I check that D is not just randomly used as outgoing for perfectly normal traffic? But why would it do that, since there does not seem to be a way to respond to any packets? Or have I been hacked, and someone somehow figured out that D must belong to that server too and is using it for nefarious purposes? Any suggestions to track this down welcome. :-)
Answer: Use tcpdump. It will listen on an interface and show all of the traffic moving through that interface. There are a bunch of different options to tune what you capture and how to display it:
tcpdump -i [interface D] will show you traffic on D. If D doesn't have its own interface, then use tcpdump -i [interface] host [D IP address], this will show you all traffic on that shared interface bound for D's IP address.
Comment: Turns out, my provider has a bug in their interface and basically just the labelling was wrong. But using tcpdump is always a good idea in a situation like this, so marking you as correct :)

Traffic on IP which is not being used?


What can cause Drupal to crash Apache?

Question: In my local development environment, Drupal keeps crashing Apache when I try to load admin pages. The user pages all load fine, but any admin page causes apache to reset itself.
In the apache error log I get:

Parent: child process exited with status 255 -- Restarting.

The files were all copied from our test server, although I removed all the cached data inserts from the database while transferring it over.
We're running a separate admin theme (Garland for admin, custom theme for all other pages).  The custom themed pages work fine. I haven't found a way to determine if its the theme or the admin pages that are causing the problem.
I'm using Drupal 6 with WAMP, on Windows 7.
I'm looking for suggestions about what's causing the resets.
Comment: Disabling modules can be done quickly with drush, http://ninjagirl.com/posts/013/installing-drush-windows contains installation instructions for Windows.
Comment: You can rule out whether it's your admin theme by just setting the admin theme to be your default theme.
Comment: What PHP version? Make sure you're running the most recent one. Also, can you reproduce with just Drupal 6 core? If not, try to disable modules until you can point down which module it is.
Comment: Getting in to turn off modules is a challenge without the admin interface (doing it through phpMyAdmin is time consuming enough I haven't done it yet since it's a working database on the server). I'm running a PHP version to match my server: 5.3.4.
Comment: Thanks Jody. The problem seems to come forward with the theme, but when I disable the theme in drush the problem persists on the admin pages (even though the front end loads with Zen). Working on disabling modules now.
Comment: Having disabled all but the core-required modules a few more pages function, but not all.  For example I can now reach /admin but not /admin/build/modules.
Comment: You may have more luck on serverfault.
Comment: Is this a fresh install? Have you tried running a fresh install?
Comment: A fresh install works, but the database from the working version on the server does not.
Comment: Did you set enough memory for drupal? Wamp defaults to very little memory by default in the apache .conf file.
Answer: In your settings.php add this line ini_set('memory_limit', '128M'); and disable update module.
Answer: I had the same issue "Parent: child process exited with status 255 -- Restarting." on my setup with below configuration

Windows 7
Apache Server 2.2.25
PHP 5.2.17 / 5.3.27
MySQL Server 5.6

*Note that this is not a XAMPP or WAMPP setup. All components were individually installed.
This error occurs due to multiple reasons, the answer for some of which you can find directly via google but unfortunately mine was not one of them. After spending a lot of head scratching, I finally got it working. The issue was due to stack size allocated to Apache threads. This can be resolved by setting 'ThreadStackSize' to a higher value. Add the below line to your httpd.conf or better enable loading of httpd-mpm.conf and add it there.
<IfModule mpm_winnt_module>
    ThreadStackSize  8388608
</IfModule>

Comment: I'm recommending this answer because I had a similar issue over here http://drupal.stackexchange.com/questions/81322/module-heavy-site-quits-without-error-on-w7-dev-machine (I posted before I saw this) and this solution worked for me.
Answer: I had a similar problem. Everything was resolved with the installation of latest version of  xampp.
Comment: The question is about what can cause the problem.
Comment: My bad, I thought solution would be nobler than the cause itself.
Answer: The Update Manager is a module that can increase the required resources to run Drupal, as it gathers update information about the installed modules (whatever they are enabled, or not).
It runs for pages for which arg(0) returns 'admin', but it doesn't run for specific pages, as visible in update_init().
  if (arg(0) == 'admin' && user_access('administer site configuration')) {
    switch ($_GET['q']) {
      // These pages don't need additional nagging.
      case 'admin/appearance/update':
      case 'admin/appearance/install':
      case 'admin/modules/update':
      case 'admin/modules/install':
      case 'admin/reports/updates':
      case 'admin/reports/updates/update':
      case 'admin/reports/updates/install':
      case 'admin/reports/updates/settings':
      case 'admin/reports/status':
      case 'admin/update/ready':
        return;

        // If we are on the appearance or modules list, display a detailed report
        // of the update status.
      case 'admin/appearance':
      case 'admin/modules':
        $verbose = TRUE;
        break;

    }
  }

If you see the same issue for any admin page, then Update Manager is not the cause. If the issue appears for all the admin pages, except the ones listed after "// These pages don't need additional nagging." then chances are the Update Manager module is causing the issue.

What can cause Drupal to crash Apache?


Trigonometry express $4\cos x+3\sin x$ in the form $R \cos (x+a)$.

Question: I have been asked to express $4\cos x+3\sin x$ in the form $R \cos (x+a)$.
I know that the formula to express it in that form is $a \cos x+b\sin x=R \cos (x-a)$.
But as the question is asking me to express it in where it is $(x+a)$ instead of $(x-a)$ I am unsure of what to do.
Any help is much appreciated.
Comment: Use your formula, and get, say, $a=2.6$. Then you know that $R\cos(x-2.6)$ is what you're looking for. Rewrite to $R\cos(x+(-2.6))$, and you have it on the form you were asked for.
Answer: I have never seen this kind of question but here is my attempt for a solution.
Assume, a $\triangle ABC$ right angled at B, opposite angle $\angle CAB$ as $a$, and hypotenuse as AC.
Now, presume BC is 4 units and BA is 3. So, AC becomes 5 units.
That implies, $\cos a=\frac{4}{5}$, $\sin a=\frac{3}{5}$
Coming back to your original question.
$4\cos x+3\sin x=k$
Divide by 5 both sides,
$\frac{4}{5}\cos x+\frac{3}{5} \sin x=\frac{k}{5}$
which is the form of
$\cos a\times\cos x+\sin a\times\sin x=\frac{k}{5}$
$\implies \cos(a-x)=\cos(x-a)=\frac{k}{5}$
Or,
$k=5\cos(x-a)=5\cos(x+(-a))$
$a$ is approximately $0.64$


SQL Browser service doesn't work when Login account is anything but LocalSystem

Question: I have a named instance of SQL Server 2008 R2. When I attempt to connect to the named instance I get the following error (if the browser service is set to logon as anything other than Local System):

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)

When I change the account I use SQL Server Configuration Manager and have tried Local Service, Network Service, and a local account. I made sure the local account was a member of the "SQLServer2005SQLBrowserUser$MachineName" local group and has all the rights specified here.
How can I use a local account as the log on account for the SQL Browser service?
Answer: SQL Browser reads instance network configuration information from the registry; maybe the permissions there got messed up.  Verify that the account you're using has access to read info underneath the following key:
<code>HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQLServer\
</code>
Comment: For whatever reason, your method didn't work, but granting read on the parent (HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\ in your example) did work. Also, this key will be different for a named instance - replace MSSQL10_50.MSSQLSERVER with MSSQL10_50.INSTANCENAME)
Answer: The account running the SQL Browser service must have read permissions on the following key: HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\ (for a named instance, replace MSSQLSERVER with instance name). Thanks to squillman for putting me on the right track.


regular expression to extract a query string parameter value from a URL in PHP

Question: I need to extract an item id from a URL; the pattern is this
   &R=10031004&, I mean, I need to extract the string within &R= and the other &
This is what I have so far, but I keep getting errors.
preg_match('^[&R=]+ &$',
"http://www.lapdirecciondemario.com/items.php&R=10031004&", $matches);
$host = $matches[0];

echo $host;

Comment: Your pattern is missing the delimiters - it's an invalid pattern.
Answer: $url = 'http://www.lapdirecciondemario.com/items.php&R=10031004&';
preg_match('/(&|\?)R=([0-9]+)/i', $url, $matches);
echo $matches[2];

In contrast to the other answers, this will also match if the parameter R is preceded by a ? instead of a &. If you know more about the length of the number, you can replace the + after [0-9] with {min,max}.
This regular expression should be pretty robust and match all of these:

http://www.lapdirecciondemario.com/items.php&R=10031004
http://www.lapdirecciondemario.com/items.php?foo=bar&R=10031004
http://www.lapdirecciondemario.com/items.php?R=10031004
http://www.lapdirecciondemario.com/items.php?R=10031004&something=else
http://www.lapdirecciondemario.com/items.php&R=10031004#more-here
Answer: Use this:
preg_match('/&R\=(.*?)&/i', "http://www.lapdirecciondemario.com/items.php&R=10031004&", $matches);
echo $matches[1]; // will echo 10031004

Comment: @middus I answered the OP's question that ask to get the string between &R= and &, so there was no need to do a regex for other strings.
Comment: Yeah, I know. But the URL given by the OP is likely to be invalid.
Answer: preg_match('#R=([0-9]+)#is', "http://www.lapdirecciondemario.com/items.php&R=10031004&", $matches);
echo $matches[1]; # 10031004

Comment: @middus, it can be pretty much anything as long as `Delimiter must not be alphanumeric or backslash` is satisfied. Try `~` or even `*` for example.
Answer: well first of all maybe I can simplify your task,
is this the url from the script?
then you should check the contents of $_GET where you will find a variable R with contents 10031004...
$item_id = $_GET['R'];
echo $item_id;

Comment: I think he is scraping website :)
Answer: if (preg_match('/(?<=&R=).*?(?=&)/', "http://www.lapdirecciondemario.com/items.php&R=10031004&", $regs)) {
    $result = $regs[0];
}

Use this one.
Comment: why making simple things look complicated? :)
Comment: :) Why capture something not needed? :)
Answer: I might as well chuck another at you. This one will match any character between an R= preceeded by ? or & and ending with & or #.
preg_match('/[?&]R=([^&#]+)/', "http://www.lapdirecciondemario.com/items.php&R=10031004&", $matches);

Comment: If the id is supposed to be numeric, this does not add value.
Comment: Yes, but his question says that he has to 'extract the string within &R= and the other &', so my answer is more precise.
Comment: Your answer would match `http://www.lapdirecciondemario.com/items.php&R=1003/IamtheWalrus/1004&`, which is probably not what he wants or is it?
Comment: Your regex returns 1003. Mine returns '1003/IamtheWalrus/1004'. Mine is more correct, based on the wording of the question. On the other hand, that input is absurd and neither is likely to be useful to lapdirecciondemario.com's meaning of R.
Comment: There is no "more correct", just correct and not correct. If we assume the id to be numeric, this URL should not match. If we knew more about the id, we could specify `{min,max}` (see my answer) to further avoid false positives.
Answer: $url = "http://www.lapdirecciondemario.com/items.php&R=10031004&";
$urlQueryParts = array();
parse_str(parse_url($url, PHP_URL_QUERY), $urlQueryParts);
if(isset($urlQueryParts[ "R" ]))
    $urlQueryParts[ "R" ];

I couldn't test it but it should work.

parse_url
parse_str


How to add number to beginning of each line?

Question: This is what I normally use to add numbers to the beginning of each line:
awk '{ print FNR " " $0 }' file

However, what I need to do is start the number at 1000001.  Is there a way to start with a specific number like this instead of having to use line numbers?
Comment: Check out `man nl`. For example `nl -v 1000001 file`...
Comment: @twalberg: I think it should be `nl -ba ...`, since the OP wants to number **all** lines, which is not the default.
Comment: @user1934428 Fair enough. The main point, though, was to introduce a utility that the OP might not have been aware of...
Answer: there is a special command for this nl
nl -v1000001 file

Answer: You can just add 1000001 to FNR (or NR):
awk '{ print (1000001 + FNR), $0 }' file

Answer: $ seq 5 | awk -v n=1000000 '{print ++n, $0}'
1000001 1
1000002 2
1000003 3
1000004 4
1000005 5

$ seq 5 | awk -v n=30 '{print ++n, $0}'
31 1
32 2
33 3
34 4
35 5


Regex. Match words that contain special characters or 'http://'

Question: I want to match words that contain special characters or that begin with 'http://'
So this sentence

%he#llo, my website is: http://www.url.com/abcdef123

should turn into this

my website

So far, i have this
re.sub(r"^[^\w]", " ", "%he#llo, my website is: http://www.url.com/abcdef123")

This just removes the symbols, but it doesn't remove the words associated with the symbol (it also doesn't remove ':' and ','), nor does it remove the URL.
Comment: BTW, your question title says "words that begin with special characters" while the text of the question says "that contain special characters".  You might want to change the title so that it's consistent.
Answer: For the example string you give, the following regular expression works OK:
>>> a = '%he#llo, my website is: http://www.url.com/abcdef123'
>>> re.findall('(http://\S+|\S*[^\w\s]\S*)',a)
['%he#llo,', 'is:', 'http://www.url.com/abcdef123']

... or you can remove those words with re.sub
>>> re.sub('(http://\S+|\S*[^\w\s]\S*)','',a)
' my website  '

The | means alternation and will match the expression on either side within the group.  The part on the left matches http:// followed by one or more non-space characters.  The part on the right matches zero or more non-space characters, followed by anything that isn't a word or space character, followed by zero or more non-space characters -- that ensures that you have a string with at least one non-word character and no spaces.
Updated: Of course, as the other answers implicitly suggest, since the http:// prefix contains a non-word character (/) you don't need to have that as an alternative - you could simplify the regular expression to \S*[^\w\s]\S*.  However, perhaps the example above with alternation is still useful.
Comment: Works great! I've got another question though. What if I wanted to keep all words that end with (or just contain) punctuation marks?
Comment: Instead of `[^\w\s]` you could use `[^\w\s",]` to say that you want to keep words that have '"' or ',' in them.  e.g. `re.sub('(^|\s)(http://\S+|[^\w\s",]\S*)','\\1','%he#llo, my "so-called", well, website is: http://www.url.com/abcdef123'` will give you `' my "so-called", well, website is: '`
Comment: @user216171 You're welcome.  I notice now that I accidentally used a different (incorrect) regexp in that comment but it's too late to correct it now - anyway, I hope the idea is clear...
Answer: You can use look aheads:
>>> re.findall(r"(?:\s|^)(\w+)(?=\s|$)", "Start %he#llo, my website is: http://www.url.comabcdef123 End")
['Start', 'my', 'website', 'End']

Explanation:

(?:\s|^) means our word starts the regex or is preceeded by a space. (and the space does not belong to the word).
(\w+) matches a word (and is what we are interested in).
(?=\s|$) means our word is followed by space or end of the string. (and once again, the space does not belong to the word).
Comment: What if the word contains a number? e.g. web5site.  It seems that words containing numbers are still included.
Answer: Not using regexs, but maybe this can work? (I'm assuming ':' and '/' are special characters so it will remove the URL implicitly)
def good_word(word):
    import string
    for c in word:
        if not c in string.ascii_letters:
            return False
    return True

def clean_string(str):
    return ' '.join([w for w in input.split() if good_word(w)])

print clean_string("%he#llo, my website is: http://www.url.com/abcdef123")


Can I plug my guitar combo to my audio interface, then monitor the sound?

Question: My amp is a Marshall Valvestate 100 (combo with 1 valve) and I would like to record the guitar with my audio interface, though without using mic. My idea is to plug the guitar to Marshall, than disconnect the speaker (112) and plug a jack cable there (into the port where you normally plug Marshall speaker's jack), then plug the other tip of that cable into my audio interface's instrument line (Behringer UMC22) so I can monitor the sound on my computer speakers.
And I am wondering if this idea is going to ruin my amp or the audio interface?
Comment: Why don't you plug into the headphone jack? That will automatically mute the speaker, and the output level will more like what your audio interface is designed to handle. Since AFAIK the power amp is transistor not valve, you won't damage the amp with no speaker connected, but the signal level from the speaker output will be higher than you need, and possibly too high for your audio interface to handle without distortion.
Comment: FYI, one of the techniques for digital recording is to record the clean signal from the guitar and "reamp" the guitar after recording using either a direct to amp interface or a simulated amp in the DAW. Not only does this make editing easier, it can also help eliminate bad recordings that peak the inputs causing clipping that cannot be recovered.
Comment: That'd probably ruin the interfacer. Valve amps work at high voltages and the cables to the speaker are carrying hundreds of volts which would ruin your interfacer.
Comment: @alephzero - i tried pluging into the headphone jack but it doesnt produce any sound on my interface (when i plug headphones i can hear the guitar perfectly but audio interface doesnt get any signal, i tried monitoring the sound, but with every volume knobs on max i can barely hear anything at all)
Comment: so the chain is: amp {headphone out} to Behringer {mic/line in/Inst 2} {adjust gain until clip, then back off gain} to computer to DAW {adjust armed track-in to 0dB, then back off}?
Comment: @Yorik the chain is correct, i didnt even use DAW because i wanted to monitor first but i have no signal on the interface and no clip and this is weird
Comment: @Yorik you did you mean in your first comment that it won't ruin my interface?
Comment: I think, if you unplug the speaker from your amp and plug something else into it, you will ruin your amp: you need to match amp-to-speaker impedance. Running the amp-to-speaker-out into your behringer will probably damage your behringer also. The basic idea behind "reamping" with an actual amp is that you run the guitar to the interface, {record the dry sound or simply pass-through}, then pass the audio interface output into {possibly a line-in to hi-z out box and then into} the amp. The reason you would do this is so that you can completely alter the amp and pedal chain of your performance.
Comment: https://www.youtube.com/watch?v=Hm46WaRUkFw
Comment: Does your amplifier have a Line Out jack socket? This would be preferable over the Speaker Out or Headphones sockets. Connect Line Out (also known as Aux Out) from your amplifier to Line In (or Aux In) on your audio interface using a jack instrument cable.
Answer: The Valvestate 100 actually has a really useful feature: on the back panel it has a D.I. Jack. This is specified for:

connection to recording or P.A. equipment, featuring Marshall's acclaimed Speaker Emulation circuitry as featured on the JTM60

So this will not only give you a line out, but it will also deliver a tone that sounds like the amp itself, so when you hook it up to your audio interface you will be able to record that lovely Marshall tone.
Do not disconnect the speaker and try to connect the speaker output to your audio interface. You will destroy the audio interface!
Answer: You can not connect the head's speaker output to an interface without potentially damaging either the head or the interface.
If you want to get a signal out of your amp and into an audio interface without using a microphone, you have a few ways to do it.  The sound you get will be different than what you normally hear from the amp as the speaker helps create the tone that your amp produces.
You could use a D.I Box that is specifically designed to handle speaker output. You would plug the speaker out into the D.I., pass through to the speaker, and take the D.I. out of the box to your interface.  The tone from doing this us usually quite pinched sounding.
Many amp heads will have Effects Send/receive jacks. You can use the effects send jack to get output, usually from the pre-amp section of your amp.
If the amp has a D.I. or Line out, this is designed to send your amp's signal out to other equipment and is usually sending the signal that is after the Effects loop.
The headphone out will usually work, but the sound quality will likely be poor or noisy as the headphone amp is usually a separate amp circuit, and not really designed for audio output other than for headphones.


MySQL - SELECT duplicando?

Question: Alguém sabe me dizer por que está duplicando os SELECT?
CREATE TABLE tb_grupos(
  id_tbl_grupos int(3) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  id_grupo int(50) NOT NULL,
  hostname_grupo varchar(50) NOT NULL);

CREATE TABLE tb_hosts (
  id_tbl_host int(3) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  id_host int(50) NOT NULL,
  hostname varchar(50) NOT NULL,
  fk_hostname_grupo int(3) NOT NULL,
  FOREIGN KEY (fk_hostname_grupo) REFERENCES tb_grupos(id_tbl_grupos));

  CREATE TABLE tb_monitoramento (
  id_tbl_monitoramento int(3) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  problemas varchar(50) NOT NULL,
  tempo int(50) DEFAULT NULL,
  fk2_hostname_grupo int(3) NOT NULL,
  FOREIGN KEY (fk2_hostname_grupo) REFERENCES tb_grupos(id_tbl_grupos));
CREATE TABLE tb_eventos (
  id_tbl_eventos int(3) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  id_evento int(50) NOT NULL,
  eventos varchar(50) NOT NULL,
  tempo int(50) NOT NULL,
  trigger_or_network int(3) NOT NULL,
  ok_or_problema_or_desconhecido int(3) NOT NULL,
  fk3_hostname_grupo int(3) NOT NULL,
  FOREIGN KEY (fk3_hostname_grupo) REFERENCES tb_grupos(id_tbl_grupos));

  insert into tb_grupos values("0","15","HOUSE");
  insert into tb_hosts values("0","10087","HOUSE - MICRO", 1);
  insert into tb_grupos values("0","16","CLIENTE");
  insert into tb_hosts values("0","10088","CLIENTE - DIRETORIA", 1);

  insert into tb_monitoramento values("0","MEMÓRIA EM ALTO CONSUMO EM HOUSE - MICRO","158909809",1);
  insert into tb_monitoramento values("0","ERRO DE DISCO CLIENTE - DIRETORIA","158909856",1);

  SELECT
   tb_grupos.hostname_grupo,
   tb_monitoramento.problemas,
   tb_monitoramento.tempo
  FROM
   tb_grupos
  LEFT JOIN
   tb_monitoramento ON tb_grupos.id_tbl_grupos = tb_monitoramento.fk2_hostname_grupo
  WHERE
   tb_grupos.hostname_grupo = 'HOUSE'

Saída:
HOUSE   MEMÓRIA EM ALTO CONSUMO EM HOUSE - MICRO    158909809
HOUSE   ERRO DE DISCO CLIENTE - DIRETORIA   158909856

Comment: Poste a listagem de suas tabelas para facilitar a análise.
Comment: Aparentemente você está apontando para o mesmo id de grupo em seus inserts, ambos estão setados como 1.
Answer: Em sua tabela tb_monitoramento ambos os registros estão com o mesmo fk2_hostname_grupo.
Se você quer usar a query já pra agrupar, use group_concat, ou group_by.
Comment: Obrigado, vou passar no algoritmo para incrementar +1 no ultimo valor assim mantendo a tabela relacionada!

MySQL - SELECT duplicando?


Assigning value to pointer without allocating memory (C)?

Question: When I tried the following code:
int *no_alloc_i;
*no_alloc_i = 3;
printf("%d\n", *no_alloc_i);

my code crashed, as expected. I believe that is because I did not allocate memory dynamically to no_alloc_i (correct me if I am wrong), because doing so makes the main function return 0 and the code works as expected:
int *alloc_i = (int*)malloc(sizeof(int));
*alloc_i = 3;
printf("%d\n", *alloc_i);

Afterwards, I tried allocating memory to alloc_i, did not allocate memory to no_alloc_i and then assigned a value to no_alloc_i:
int *alloc_i = (int*)malloc(sizeof(int));
int *no_alloc_i;
*no_alloc_i = 3;
printf("%d\n", *no_alloc_i);

The problem is that the pointer no_alloc_i that I had not allocated memory to was capable of holding a value. I do not understand how allocating memory to another variable could influence the behavior of the first variable. Thank you in advance!
Comment: **It is wrong**, Doing what you expect makes it more difficult to make sure it is wrong, but it is wrong nevertheless. **UB** is always wrong (sometimes (very very seldom!) there may be excuses for it -- not in your case though)
Comment: **Undefined Behaviour** (or **UB**) is just that: undefined. It can crash, it can behave as you expect, it can fail to compile, it can give wrong answer, it can give correct answer, it can behave different on two successive *invocations*...
Comment: @pmg So it *could* be wrong but it just happens to be right?
Answer: Undefined behavior. It cannot (and shouldn't be attempted to) be predicted and relied upon*. The thing is, you just didn't assign any value to your pointer so it was uninitialized, i.e. holding a semi-random unpredictable value. If that value happens to be an address inside a memory region that's writable, using that spot in memory will "succeed" but corrupt something else because it's not your memory. If it's an address where no writable memory is allocated, you'll crash attempting to access the memory there.
It's important to realize that not every errornous behavior or action immediately results in an exception being thrown. It can for example also just cause subtle corruption of data or other issues that may or may not cause bigger trouble later.

Think of it like this:
You just wrote your shopping list on that random piece of paper you found. There is no way of saying whether that paper was actually the next empty page in your notebook anyway or it was yesterday's newspaper, your notes for today's speech, your roommate's rare author-signed copy of Goethe's "Werther" or incidentally not paper at all but your slumbering cat's belly. The outcomes can differ wildly - from everything working as expected to you getting scratched badly by a fairly furious feline, and the effects of your actions could even manifest themselves with a time delay, such as when your roommate returns from his Karate training and realizes that you blatantly vandalized his most precious piece of family heritage. Attempting to rationalize this and analyze under what conditions you can get away with it is like thinking the issue here was the wrong choice of pen, not compatible with the squishy nature of your cat's belly without applying enough force to wake her up, instead of realizing that none of this would have happened if you had stuck to using your notepad in the first place.

*: Of course, it's possible to understand what happens technically and why, and it can be quite educational. Once you understand the low-level details of it deeply enough, you can probably predict what will happen. But if you discover that a certain scenario seems to work "reliably" despite it being undefined behavior (even if you checked the generated machine code and can statically say for sure that it will work in that binary), it's still a bad idea to rely on this discovery, because one manifestation of undefined behavior can also be that it works on a specific platform or with a specific compiler only. Essentially, the compiler has to follow the specifications exactly in every scenario that is defined by them, but is allowed to do whatever it wants (or whatever was easy to do when writing the code, such as not caring about what happens in "impossible" situations) in case of things that involve "undefined behavior".
Comment: After you *released* the **UB** anything can happen. It may change the return value, it may keep `0` as the return value, it may return `0` on Wesdnesdays only... it may even return `π` or not return at all :-)
Comment: @BillTheKid not necessarily. You just wrote your shopping list on that random piece of paper you found. There is no way of saying whether that paper was actually the top of your notebook anyway or it was yesterday's newspaper, your roommate's rare author-signed copy of "Werther" or incidentally not paper at all but your cat's belly. The outcomes can differ wildly.
Comment: When I am assigning a value to a memory address that is not *mine*, shouldn't the return value of the main function be different than 0? (I check it using the ```echo %ERRORLEVEL%``` command).
Comment: Re "It cannot (and shouldn't be attempted to) be understood": That is false, absurdly so. When the C standard does not define the behavior of a program, its behavior nonetheless follows from the design of the compiler, the properties of the operating system, the hardware specification, and other things. It generally can be understood, and doing so is useful for improving speed and ability to diagnose bugs in programs. The knowledge is also useful to malicious actors for exploiting bugs, so understanding it also helps to counter and avoid those exploits.
Comment: @EricPostpischil OK maybe the wording isn't right. What I meant is that it shouldn't be predicted and relied upon. I edited the answer.


JQuery Dialog: Show Message in Dialog Box After Selecting Confirm Option

Question: I am using the JQuery dialog UI to have users confirm an action on the page.  If yes, an API call will be made and then window will redirect.  If no, the dialog closes.
Before the redirect, I'd like to show a "success" message within the actual dialog box, like "this action was performed".  Any ideas on how this can be accomplished?
Here's my code:
<code>$( "#dialog-confirm" ).dialog({
    resizable: false,
    height:140,
    modal: true,
    buttons:
    {
        "Yes": function()
        {

                    var request = '123';
            var url = '<?= $this->baseURL; ?>?rn=' + request;
                $.getJSON(url, function(data) {});
            }

            var msg = 'Action performed';

                    //?   How do I display this message in the modal dialog window???

                    $( this ).dialog( "close" );
            var url = '<?= $this->moduleURL; ?>/cancel';
            window.location.href = url;

        },

        "Nevermind": function() {
                $( this ).dialog( "close" );
        }
    }
});
</code>
Answer: this may be a way, you empty your dialog div und append new text and set a timout and after 3 seconds the diloge closes and the redirect happens
<code>$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons:
{
    "Yes": function()
    {

                var request = '123';
        var url = '<?= $this->baseURL; ?>?rn=' + request;
            $.getJSON(url, function(data) {});
        }

        var msg = 'Action performed';

        $( "#dialog-confirm" ).empty();

        $( "#dialog-confirm" ).text(msg);

 setTimeout(function() {
     $( this ).dialog( "close" );
       var url = '<?= $this->moduleURL; ?>/cancel';
        window.location.href = url;
}, 3000);

    },

    "Nevermind": function() {
            $( this ).dialog( "close" );
    }
}
});
</code>
Answer: Use the AJAX method, and set async to false. This will make sure the request has returned before proceeding with the redirect.
To set the dialog content, you could just use <code>.html()</code>.
<code>$("#dialog-confirm").dialog({
    resizable: false,
    height: 140,
    modal: true,
    buttons: {
        "Yes": function () {
            var request = '123';
            var url = '<?= $this->baseURL; ?>?rn=' + request;
            var msg = 'Action performed';
            $("#dialog-confirm").html(msg);

            $.ajax({
                dataType: "json",
                url: url,
                async: false,
                success: function (data) {
                    $("#dialog-confirm").dialog("close");
                    var url = '<?= $this->moduleURL; ?>/cancel';
                    window.location.href = url;
                }
            });
        },
        "Nevermind": function () {
            $(this).dialog("close");
        }
    }
});
</code>


Edit a form retrieved using FormBuilder::getForm()

Question: I found out how to get a node creation form, but I want to display and modify it (e.g. delete some fields I don't need).
This is my code.
public function buildForm(array $form, FormStateInterface $form_state) {
  $entity = \Drupal::entityManager()->getStorage('node')->create(array(
    'type' => node_type_load('friterie')->id(),
  ));
  // OPTIONAL - Set default values for node fields
  // $entity->set('field_machine_name', "value");
  $node_create_form = \Drupal::service('entity.form_builder')->getForm($entity);

  // I can display it with this method, but I don't know how to delete
  // some fields.
  $form['friterie'] = array(
    '#type' => 'markup',
    '#markup' => render($node_create_form),
    '#prefix' => '
',
    '#suffix' => '
'
  );
  return $form;
}

Answer: I see two approaches here:

You will have to use "hook_form_alter", or a more strict form alter (for example: hook_form_FORM_ID_alter()). You can remove any elements there (calling from you .module file).
When you get back your form object ($node_create_form) which will be rendered later on, you could make changes on that specific object witt it's public methods! Just dpm, or kint the object (with devel module enabled), and you will able the find the right method to alter the form elements you are about to render.

Side note: I highly discourage you from using "\Drupal::..." static service calls. FormBase classes are implementing the ContainerInjectionInterface, which means, in public static create function you can pass the services you need. Read more on this here!
Comment: It not satisfy me because it's a markup then in hook form alter i got a string ^^ and if i change markup into container i've this problem : http://drupal.stackexchange.com/questions/203674/include-node-creation-form-error-processform
Answer: You may just set the #access attribute of your fields in $node_create_form to false. I.e. if you have a field called title in your form, just set
$node_create_form['title']['#access'] = false;

This will hide the field (see From API Ref - access). Additionally, I'd suggest not to use the #markup. Instead of this, wrap your 'friterie' as a #type => 'container' and handover the result of getForm as sub-render array.
You don't need the alter-hooks if you're on that api-level. If you don't know what fields you have in your $node_create_form you may look at the rendered html (the field classes in there), or use the devel module and dpm().
But dpm() (as dpr() and kint()) may be very chatty and load your browser with tons of data. So you may just file_put_contents the array_keys of $node_create_form to some tmp-file.
Regards,
Rainer


Resizable Image

Question: I know how to use resizable images for normal shaped objects such as button backgrounds, but what about an image like a star?
Is this possible?  Let's take the image below for reference.
<code>UIImage *starImage = [[UIImage imageNamed:@"star"] resizableImageWithCapInsets:UIEdgeInsetsMake(1.0f, 1.0f, 1.0f, 1.0f)];
</code>
Comment: No, that will distort the star. Do you have a gradient or something inside the star that you are trying to preserve?
Comment: I do not at this point
Comment: `resizeableImageWithCapInsets` is for preserving portions of an image (such as gradients or text) while stretching other portions. If you don't need that functionality, consider stretching normally, as answered below.
Comment: Why use an image? Create a custom `UIView` with a `drawRect:` method that draws the star based on the view's current size.
Comment: @rmaddy I might add a gradient, drop shadow, etc.  I prefer to do these things in Photoshop unless I need to use draw a view
Comment: Scaling a bitmap image doesn't look as nice which is why I suggested a custom view. The custom view can render the picture to the exact size needed. This can include gradients and shadows. It all depends on how you need the end result to look.
Answer: If you want to resize an image like the star, you just set the frame to something bigger and make the image fill the image view.
Resizable images do not work for something like a star, but it has to be one that could be resizes vertically and/or horizontally.
This article gives a good intro to resizable images.

Resizable Image


Meaningless differentiability of implicit functions

Question: Studying calculus and came across this thing:

When differentiating implicitly, it is assumed that y represents a differentiable function of
  x. If this is not so, then the resulting calculations may be nonsense. For example, if we
  differentiate the equation
  $x^2 + y^2 + 1 = 0 $(13)
  we obtain $2x + 2y\frac{dy}{dx}= 0$ or $\frac{dy}{dx}=-\frac{x}{y}$
  However, this derivative is meaningless because there are no real values of x and y that
  satisfy (13) (why?); and hence (13) does not define any real functions implicitly

They explain why this derivative is meaningless, but I still don't understand it. In what cases derivative can be meaningless?
Answer: Since $x^2+y^2 \geq 0$, it follows that $x^2+y^2+1 \geq 1 >0$. Therefore, there are no values that can be plugged in to make it hold. Regarding implicit differentiation, the assumption when you have $F(x,y)=0$ is if $F_y(x,y)\neq 0$, then by the implicit function theorem, we can write $F(x,y(x))=0$. In other words, $y(x)$ is a curve defined implicitly. Then by taking $\frac{d}{dx}$ of both sides, it follows that $F_x(x,y(x)) + F_y(x,y(x))y'(x)=0$ and you can solve for $y'(x).$
Answer: The same way that solving certain equations can be meaningless. You can "solve" the equation $\sqrt{x}=-1$ by applying algebraic techniques, but then the value of $x$ found this way isn't actually a solution to the original equation.
You can also find the derivative of $f(x)=\ln(-x^2)$ (as a real valued function) but since the original function does not exist for any particular value of $x\in\mathbb{R}$, anything dependent on $f$, and so its derivative, is also meaningless for the context of the problem.
The point is that algorithms have assumptions. e.g. "Assume there is a solution to this equation," "Assume this function is defined on some interval," etc.  You can apply algorithms blindly, but you can't trust the results unless all assumptions of the algorithm are verified.


How to save a checkbox config_object in the schema files?

Question: We have a custom module with the following files. It is mainly used to store a list of content types that this configuration applies to. When saving the configuration, we get the following code.
How do we properly set the mymodule.schema.yml file to save the checkboxes?
Error Message. We also get the error message if we select Basic Page from the configuration.

The website encountered an unexpected error. Please try again
  later.InvalidArgumentException:
  The configuration property mymodule_enabled_content_types.article
  doesn't exist. in Drupal\Core\Config\Schema\ArrayElement->get()
  (line 76 of core\lib\Drupal\Core\Config\Schema\ArrayElement.php).
  Drupal\Core\Config\StorableConfigBase->castValue('mymodule_enabled_content_types.article
  ', 'article ') (Line: 211)

mymodule/config/schema/mymodule.schema.yml
mymodule.settings:
  type: config_object
  label: 'My Module settings'
  mapping:
    mymodule_enabled_content_types:
      type: string
      label: 'Enabled Content types'

mymodule/config/install/mymodule.settings.yml
mymodule_enabled_content_types: ''

mymoduleForm.php
...
public function buildForm(array $form, FormStateInterface $form_state) {
  $config->$this->config('mymodule.settings');
  // Get all Content Types.
  $types = \Drupal::entityTypeManager()
    ->getStorage('node_type')
    ->loadMultiple();

  foreach($types as $type) {
    $content_types[$type->id()] = $type->label();
  }
  $form['mymodule_enabled_content_types'] = [
    '#type' => 'checkboxes',
    '#title' => $this->t('Enabled Content Types'),
    '#description' => $this->t('Define what content types will be enabled.'),
    '#default_value' => $config->get('mymodule_custom_variable'),
    '#options' => $content_types,
  ];
}

public function submitForm(array &$form, FormStateInterface $form_state) {
    // Retrieve the configuration
    $this->configFactory->getEditable('mymodule.settings')
      ->set('mymodule_enabled_content_types', $form_state->getValue('mymodule_enabled_content_types'))
      ->save();

    parent::submitForm($form, $form_state);
  }
}
...

Answer: You are creating your checkbox options as an associative array of node type (bundle) IDs as keys and their labels as values.
When this form is submitted, checked checkboxes submit as key => key. So the stored information (I suppose 'rss_url' in your question is intended to being 'mymodule_enabled_content_types') is similar to:
mymodule_enabled_content_types:
  article: article
  page: page
  custom: custom

As the keys of the submitted values are unknown before submission, and the values clearly are strings, this is a sequence of strings (compare https://www.drupal.org/docs/8/api/configuration-api/configuration-schemametadata#properties). The correct schema definition is:
mymodule.settings:
  type: config_object
  label: 'My Module settings'
  mapping:
    mymodule_enabled_content_types:
      type: sequence
      label: 'Enabled Content types'
      sequence:
        type: string

After changing your schema definition and rebuilding your caches, your form submit handler should work just fine and the configuration being saved using its correct data types.
Comment: yes that was a typo that i fixed, good catch. When i used the `sequence` as you mentioned it worked.


issue to solve the geo tagging in android

Question: I am a new guy in Android. How to implement the Geo-tag for images? I have tried by myself but not getting expected result.
My code is like:
@Override
    protected Dialog onCreateDialog(int id) {
       jpgDialog = null;;
       switch(id){
        case ID_JPGDIALOG:
        Context mContext = this;
        jpgDialog = new Dialog(mContext);
        jpgDialog.setContentView(R.layout.jpgdialog);
        exifText = (TextView) jpgDialog.findViewById(R.id.text);
        geoText = (TextView)jpgDialog.findViewById(R.id.geotext);
        bmImage = (ImageView)jpgDialog.findViewById(R.id.image);
        bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 2;
        Button okDialogButton = (Button)jpgDialog.findViewById(R.id.okdialogbutton);
        okDialogButton.setOnClickListener(okDialogButtonOnClickListener);
        mapviewButton = (Button)jpgDialog.findViewById(R.id.mapviewbutton);
        mapviewButton.setOnClickListener(mapviewButtonOnClickListener);
        break;
        default:
        break;
        }
       return jpgDialog;
    }

Please help me how to proceed?
Comment: Have you looked at the GPS System service?
Answer: First you need to obtain the location information:

http://developer.android.com/guide/topics/location/obtaining-user-location.html

Then, if your images are JPEG files, you can embedded the coordinates in the EXIF data. Use Android's ExifInterface to inject or extract that information.

http://developer.android.com/reference/android/media/ExifInterface.html

Example:
ExifInterface exifInterface = new ExifInterface(fileName);
exifInterface.setAttribute(ExifInterface.TAG_GPS_LATITUDE, latitude);
exifInterface.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, longitude);            exifInterface.saveAttributes();


Finding the general term of this sequence

Question: I have been challenged to find the general term or the recurrence relation for this sequence
5,18,44,96,195....
The only hint I have is that this sequence is an applied Fibonacci sequence.
Can someone  please suggest ways to find the recurrence or the nth term.
I have looked at OEIS but found no note this for this particular integer sequence.
I have searched at numerous locations but have had no success.
Also ,I think the terms of this sequence can be determined in logarithmic time.
Any help will be highly appreciated.
Answer: A closed form of the sequence is
a(n) = (n*Luc(n+6) - 4*Fib(n))/5

where Luc(k) is the k-th Lucas number, and Fib(k) the k-th Fibonacci number. Since Luc(k) = Fib(k+1) + Fib(k-1), the formula can easily be rewritten to use only Fibonacci numbers.
Answer: Can you provide more members of the sequence?
Nvm, I got it.
a[n] = a[n-1] + a[n-2] + Fibonacci[n+5]

Answer: Searching for part of sequence 5,18,44 on OEIS, gives A037140. That sequence is of form:
a(n) = F(n+9)-(29+8*n)

Trying similar approach with parts of Fibonacci sequence on F(n+k)-your_sequence(n) gives:
F(n+10)-your_sequence(n) = 50, 71, 100, 137, 182

That sequence has nice progression: 29+21*n+8*n*(n-1)/2. This sequence has presentation:
a(n) = F(n+10)-(29+21*n+4*n*(n-1)), n=0, 1, ...


Insufficient Permission com Google calendar api v3 usando python

Question: Não estou conseguindo permissões para criar o evento.
Abaixo o código que estou usando:
import httplib2
import os
import json
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

import datetime

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/calendar'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Insert Event'

def get_credentials():
    "Gera as crendeciais"
    #home_dir = os.path.expanduser('~')
    credential_dir = os.path.join('credentials', '.credentials')
    if not os.path.exists(credential_dir):
    os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, 'calendar.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatability with Python 2.6
            credentials = tools.run(flow, store)
        print ('Storing credentials to ' + credential_path)
     return credentials

def main():

    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('calendar', 'v3', http=http)

    title = 'teste de insercao'
    day = '27'
    month = '07'
    year = '2015'
    hourstart = '20'
    minutestart = '00'
    hourfinal = '20'
    minutefinal = '30'

    event = {
      'summary': title,
      'start': {
        'dateTime': year + '-'+ month + '-'+ day + 'T' + hourstart + ':'+        minutestart +':00-03:00',
        'timeZone': 'America/Sao_Paulo',
       },
      'end': {
        'dateTime': year + '-'+ month + '-'+ day + 'T' + hourfinal + ':'+ minutefinal +':00-03:00',
        'timeZone': 'America/Sao_Paulo',
      },
      'recurrence': [
        'RRULE:FREQ=MONTHLY;COUNT=3'
      ],
      'attendees': [
        {'email': 'firstname.lastname@example.com'},
      ],
      'reminders': {
        'useDefault': False,
        'overrides': [
          {'method': 'email', 'minutes': 24 * 60},
          {'method': 'popup', 'minutes': 10},
        ],
      },
    }
    create_event = service.events().insert(calendarId='primary', body=event,   sendNotifications= False).execute()
    print ('foi')

if __name__ == '__main__':
    main()

Answer: Provavelmente já faz um tempo que você perguntou e talvez até tenha solucionado, mas eu passei por esse erro e achei a solução.
Se você observar na documentação você verá que tem uma linha lá no exemplo que eles disponibilizam que diz o seguinte:

Change the scope to 'https://www.googleapis.com/auth/calendar' and delete anystored credentials.

O escopo você alterou, mas o que falta é você ir no seu diretório home (do tipo: C:\Users\seunomedeuser>.credentials) e apagar a pasta .credentials, porque você mudou a permissão de acesso.
P.S.: Tem uma linha que abre o diretório que você a comentou, decomente-a!
Comment: faz tempo msm hahaha, mas era isso msm. Vlw :D


Lilypond: B-note stem up

Question: I want B note to have its stem going up most of the time so I don't need to use every time \stemUp and \stemNeutral commands.
Is that possible?
Thank you.
Answer: Use <code>\override Stem.neutral-direction = #UP</code> as given in the first snippet here: https://lilypond.org/doc/v2.23/Documentation/notation/inside-the-staff#stems
Comment: Is `#UP` different to `#up` in any way?  Capital letters looks/feels nicer for some reason, but it's not what they use in the documentation (in that snippet).
Comment: @ElementsinSpace They are both naught but syntax candy for `1`. You can see this by executing `#(display UP)` or `#(display up)`. Similarly `DOWN` stands for `-1`. `LEFT` and `RIGHT` are also syntax candy for `-1` and `1`. So you could also say `\override Stem.neutral-direction = #RIGHT` if you want :). This is a direction value (what in Lilypond code is called drul (down/right/up/left) value), the interpretation for which depends on the axis in question.
Comment: @ElementsinSpace Nah, I'm using uppercase versions because I'm used to it, and it is consistent with things like `X`. This way everything that is uppercase can be seen as a constant, everything else would be a function.
Comment: @ElementsinSpace Also if we talk about axes: `X` is syntax candy for `0` and `Y` is syntax candy for `1`. So we could in fact even write `\override Stem.neutral-direction = #(/ (- Y LEFT) 2)` or something, if you intend to annoy everyone trying to read your code :)
Comment: So, lowercase letters are being used in the snippet because it's *slightly* more "human friendly".
Whereas, you're using uppercase letters because it's *slightly* more explicit that these terms are just monikers for low level integers.
Right?
Comment: `#up` exists for historical reasons, I believe. Virtually everything in LilyPond uses the convention `#UP`.
Comment: @ABOUSAMRAJean *Except* for this snippet in the documentation, as it seems. But then this first appears in documentation with version 2.8, introduced by Graham Percival in February 2006. That's quite some time ago, I was 12 back then ...

Lilypond: B-note stem up


History of the method of adding and subtracting the same number

Question: We know that when a number is added and subtracted, the effect is null (same number of course).
I want to know the first occurrence of this documented method. Is it from Euclid's elements in Book $5$?

the relationships of equivalence and of excess are compatible with addition and subtraction in the sense that if equivalent magnitudes are added to (or taken from)
  each of two others, the resulting magnitudes will be in the same relation as the
  originals.

Source
Answer: Book V of Euclid's Elements deals not with number, but with ratio between magnitudes.
The interpretative issues are thorny; see :

Jacob Klein, Greek Mathematical Thought and the Origins of Algebra, German original ed 1936 (Dover reprint)
Wilbur R. Knorr, The Evolution of the Euclidean Elements, 1975
Ian Mueller, Philosophy of Mathematics and Deductive Structure in Euclid's Elements, 1981 (Dover reprint)
Ivor Grattan-Guinness, Numbers, Magnitudes, Ratios, and Proportions in Euclid's Elements, 1996 in Historia Mathematica.

Magnitudes for Euclid are not numbers; for ancient Greeks, numbers are (our) natural numbers.
Lenght and area are magnitudes. The discovery of the irrationality of $\sqrt 2$ forced ancient Greek mathematics to leave the Pythagorean "axiom" that every natural phenomenon can be described with (natural) numbers : the diagonal of the unit square cannot.


How to verify the set of two vectors is a basis for the plane?

Question: Verify that B={(3,2,0),(0,2,3)} is a basis for the plane 2x[1]-3x[2]+2x[3]=0 in R3.
How to solve out this question?
And I have a question about this question. I thought dim(Rn)=n.So in this question the basis should have 3 vectors rather than two. So my question is how two vectors can be a basis in R3?
Thank you very much!
Comment: UW represent!!!!
Answer: The plane is 2 dimensional sitting inside of $\mathbb{R}^3$ so you only need two vectors for a basis for the plane.  To prove it is a basis you must show that it is a spanning set and it is linearly independent.
To show it is linearly independent suppose:
$$a(3,2,0) + b(0,2,3) = (0,0,0)$$
Then comparing the entries we see that $3a + 0b = 0$ so $a = 0$ and similarly $0a + 3b = 0$ so $b=0.$  Thus the set is linearly independent.  Since the vectors lie in the plan (easy check) and they are linearly independent, and since the plane is 2-dimensional it follows that they are a basis.
Comment: I got that! Thank you very much~


Pyramid + MySQL

Question: I'm setting up pyramid app with MySQL DB and I'm facing problem with connection. I'm using python 3.7.2
Here is my sqlalchemy.url:
sqlalchemy.url = mysql://0.0.0.0:3309/pyramid_framework
when I try to init the database with alembic:
alembic -c development.ini revision --autogenerate -m "init"
This error is shown:
ModuleNotFoundError: No module named 'MySQLdb'
I've already tried add mysql-python to my setup.py but this not seem to work.
Has someone sucessfully combined Pyramid with MySQL?
Comment: You should read following thread
https://stackoverflow.com/questions/8773380/using-mysql-and-sqlalchemy-in-pyramid-framework
Comment: Found solution after several hours. You need to use ```mysql-connector-python``` beacause MySQLdb is not available for python 3+. So the connection string would look like this ```mysql+mysqlconnector://root:email@example.com:3309/pyramid_framework```
Answer: For me this solution worked fine, after some other tries:
Some environments might have conflicts if MariaDB is installed:
$ sudo apt install libmysqlclient-dev

Then, after activating the python virtualenv:
$ pip install mysqlclient

Pyramid + MySQL


How to correct for non-linearity of response in linear regression

Question: I want to train a linear regression model to predict a non-linear variable. This how the two independent variables correlated against the response (points are jittered):

And the residuals against the fitted values:

Most of the values for the response are zero. The effect is a very strong heteroscedasticity
<code>        studentized Breusch-Pagan test

data:  model
BP = 55483.84, df = 2, p-value < 2.2e-16
</code>
event though the the predictors are strongly correlated with the response
<code>Call:
lm(formula = response ~ predictor1 + predictor2, data = train_predictors)

Residuals:
    Min      1Q  Median      3Q     Max
-7.6996 -0.0268 -0.0238 -0.0182  4.8785

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept)  2.748e-02  2.825e-04   97.28   <2e-16 ***
predictor1   8.491e-05  6.574e-07  129.16   <2e-16 ***
predictor2  -3.934e-10  8.298e-12  -47.41   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.1561 on 498498 degrees of freedom
Multiple R-squared:  0.0365,    Adjusted R-squared:  0.0365
F-statistic:  9442 on 2 and 498498 DF,  p-value: < 2.2e-16
</code>
Should I consider more adopting non-linear models or could I first try correcting the non-linearity of the response?
Comment: In addition to @whuber's point, the marginal distribution of the response is not really of interest, but rather the conditional distribution / the distribution of the residuals. On another note, are all Y values integers / counts?
Comment: "Linearity" (or lack thereof) refers to the relationship between the predictors and the response, about which you have offered no direct relevant information. Could you please amend your post to provide that?
Comment: Some useful searches you can investigate include [multinomial logistic regression](http://stats.stackexchange.com/search?q=multinomial+logistic+regression) and [ordinal regression](http://stats.stackexchange.com/search?q=ordinal+regression).
Comment: Is the response a *count* or does it represent some categorical thing, or something else?
Answer: I don't know details of your model, but in my opinion you need to deal with the large amount of "zero responses". Look into compound models with a mass point at zero. Something like the "Tweedie model".


Platform independent xaringan presentation (Blackboard)

Question: I'm preparing some html slides for my students. I have used both slidy and ioslides before and basically I can upload those straight onto Blackboard within an iframe box without any problems.
I've just started playing with xaringan and it looks like I loose the fonts and styles and some of the images (for example knitr output) after uploading to Blackboard.
Here is an example of the "Ninja" template in R Studio:
a) this is how it should look like

b) this is how it looks like after uploading to Blackboard

Am I missing something?
Comment: See https://bookdown.org/yihui/rmarkdown/some-tips.html#disadvantages (and I recommend you to use a true web server, such as Netlify to host your slides).
Comment: Thanks, I'll have a look into this
Comment: @YihuiXie so I basically bundle the css, libraries and html (renamed to index.html) together in a folder and deploy on Netlify? I've included all images (R output etc.) in the folder, but they are not showing up yet.
Comment: R output fixed with `dev="svg"` setting in `knitr` chunk - just need to get external images to work now
Comment: you don't need to use `dev="svg"`, I have a little repo to demonstrate how to host xaringan on gh-pages if you are interested: [repo](https://github.com/tcgriffith/xaringan_gh) [webpage](https://tcgriffith.github.io/xaringan_gh/), netlify should be similar
Comment: @TCZhang cool, will have a look
Answer: Ok, here's what I came up with

css, styles and index.html (rename your Rmd slide to index.Rmd is the easiest) need to be hosted on true web server, i.e. Github or Netlify

if you use Github: enable github pages settings

the image output in the R chunk needs to be set to dev="svg"

I'm still having problems with including other images though.


Structure for Headless Drupal 8 and Angular

Question: I have been looking and can't find an answer to this relatively simple thing. In doing headless Drupal 8 with angular front-end, I was able to build an app in angular but it won't reach the Drupal endpoint as they are running on different ports (local development, :9000 and :80). I don't want to use CORS as that seems that it will introduce a host of security issues in production that I am not looking to deal with.
If I create the angular app with Drupal inside angular, will Drupal have access to LAMP - if its in the same location that has access to LAMP stack?
Answer: There are third-party JS modules that allow proxying of a subpath on your app domain to an entirely different domain. One such example is grunt-connect-proxy. This way, the browser will think it's hitting the same domain, when the proxy is actually forwarding it to the other domain. However, this will depend on your JS setup, which you didn't mention.
Alternatively, just enable CORS and work with it. It's as simple as adding the following to the remote domain's .htaccess (which in your case, Drupal's).
Header Set Access-Control-Allow-Origin "*"


(in)equivalence of the sine and cosine representations of Dirac comb

Question: Going through these lecture notes, I have seen two representations of the Dirac comb. The first one is obtained through the complex Fourier series of a periodic functions $f(x)= f(x+L)$ (see the case of $L=2\pi$ in page 27) and in reads as
\begin{equation}
 \frac{1}{L} + \frac{2}{L} \sum_{n=1}^\infty \cos (\frac{2n \pi (z-z')}{L} ) = \sum_{m=-\infty}^{\infty} \delta(z-z'-mL) \qquad\qquad (I)
\end{equation}
The second  representation comes from the sine representation of functions that satisfy Dirichlet boundary conditions (see page 32 of the notes) and reads as
\begin{equation}
\frac{2}{\ell} \sum_{n=1}^\infty \sin(\frac{n\pi z}{\ell}) \sin(\frac{n\pi z'}{\ell}) = \sum_{m=-\infty}^\infty \delta(z-z'-2m \ell). \qquad\qquad (II)
\end{equation}
I am trying to see the equivalence of the l.h.s of these relations, by starting from the l.h.s of the second one and setting $\ell=L/2$ and then using trigonometric formulae. Here is what I get:
\begin{align}
\sum_{m=-\infty}^\infty \delta(z-z'-m L) &\stackrel{(II)}{=}
\frac{4}{L} \sum_{n=1}^\infty \sin( \frac{2n\pi z}{L}) \sin(\frac{2n\pi z'}{L})\\ &= \frac{4}{L} \sum_{n=1}^\infty \frac{1}{2}
\left[ \cos (\frac{2n\pi (z-z')}{L}) - \cos (\frac{2n\pi (z+z')}{L}) \right]\\
&= \frac{2}{L} \sum_{n=1}^\infty \cos (\frac{2n\pi (z-z')}{L})
-\frac{2}{L} \sum_{n=1}^\infty \cos (\frac{2n\pi (z+z')}{L}) \\
&\stackrel{(I)}{=} \sum_{m=-\infty}^\infty \delta(z-z'-mL) - \sum_{m=-\infty}^\infty \delta(z+z'-mL)
\end{align}
which seems to be a contradiction. Am I doing something wrong here, or does this mean these two representations are not equivalent?
Answer: Although you've not said what you yourself mean by "equivalent" exactly, you are correct that, as tempered distributions for example, the two infinite sums are not equal.
In some ways, it's even worse than that: the second version, using $\sin(\pi nx)$'s, makes best sense as a functional on smooth functions (etc) vanishing at endpoints. A fundamental issue is that these functions with odd $n$ are being construed as $1$-periodic, even though they are only $2$-periodic, and the $1$-periodic extensions are not smooth (they have corners!).
Some troubles are already visible if we just look at the two families as orthogonal bases for $L^2[0,1]$. The $\sin(\pi n x)$ with $n$ odd are not finite sums of the others. And the expansion in terms of the $\sin(\pi nx)$'s of smooth $1$-periodic functions $f$ does not converge very well if $f(0)\not=0$. The expansion of $f(x)=1$ already has this problem.
The latter issues mean that conditions for convergence of those series in any strong sense is problemmatical. Taking duals, the characterizations of periodic distributions by such series expansions are not quite comparable. Perhaps amusingly, computing somewhat naively at the level of expansions of distributions easily overlooks that disconnect, leading to the seeming paradox of your computation. Your first expression is valid for the Dirac comb as a distribution, that is, a continuous functional on smooth functions. The second version (as your computation shows) cannot be that, although it will agree (for example) on smooth functions vanishing to infinite order at integers.
EDIT: in response to comments... Yes, indeed, in an $L^2$ sense the Dirichlet boundary conditions (can't really be on $L^2$, since pointwise values don't quite make sense... ominous) give the $\sin(n\pi x)$ expansion, and Neumann boundary conditions give the analogous cosine expansion. And both (as well as the "smoothly periodic") give orthogonal bases for $L^2$. Check.
But at the point that we are interested in smoothness properties of functions, and in how well their various expansions reflect this (meaning that the finite partial sums of the expansions converge to the function in a stronger topology reflecting derivatives...), the happy-naive boundary-value story is inadequate.
Again, observe that the periodicized versions of $\sin(\pi nx)$ and $\cos(\pi nx)$ are not smooth at the "joints" (EDIT-EDIT: for odd $n$). Bad omen.
Comment: I don't seem to understand your point regarding 1-periodic vs 2-periodic. What I understand is that $\sin (n\pi z/L) $  make a basis for an interval $L$ with Dirichlet boundaries, and in that interval they are normal to each other. They do look like the $\sin$ part of a Fourier series with period $2 L$, but maybe this is just incidental?
Comment: The issue is a bit tricky, and apparently I've failed to explain... :) I'll edit the answer, since it's likely that I've equally badly failed to communicate to others... Thanks for the prompt!
Comment: Also, for an interval $L$ with Neumann boundaries, the basis are $\cos(n \pi z /L) $ and this can be used to reproduce the first equality in my question. So I don't see how one of those two equalities could be more 'general' than the other.
Comment: Ok thank you :) and one more thing is that since these equalities involve infinite series, I was wondering if any of the steps I have taken are actually not allowed - causing the paradox
Comment: Well, the assertion that Dirac delta is "equal to" a certain expansion is only correct inside a certain topological vector space... which is not exactly the space of distributions. So, yeah, comparing the two expressions is itself not legit. To say exactly why not is far more complicated than the manipulation of the formulas, unfortunately. Right, "in some sense" both expressions are correct, but those senses do not admit the naive comparison that your computation embodies.
Comment: Thank you paul for the edits. However, I still don't fully understand parts of your answer. You said that ''...And the expansion in terms of the $\sin(\pi n x)$'s of smooth 1-periodic functions f does not converge very well if $f(0) \neq 0$. The expansion of $f(x)=1$ already has this problem.'' I agree, but so is the expansion in terms of $\cos(\pi n x)$' for functions with nonzero derivatives at the end points...
Comment: ...and the expression $(I)$ in the question can be derived from this latter expansion. So when you later say ''...Your first expression is valid for the Dirac comb as a distribution, that is, a continuous functional on smooth functions. The second version (as your computation shows) cannot be that, although it will agree (for example) on smooth functions vanishing to infinite order at integers", this is where I get confused why the $\cos$ expression is more general.
Comment: ''Perhaps amusingly, computing somewhat naively at the level of expansions of distributions easily overlooks that disconnect, leading to the seeming paradox of your computation.'' OK, but how (in which step) this overlooking is happening? Could it be fixed by any means?
Answer:
Yes, OP is correct: The Dirac comb/Shah function $$III_{2\ell}(z-z^{\prime})\tag{P}$$ in OP's eq. (II) [or equivalently, eq. (2.145) in the linked lectures by Kevin Cahill] should be$^1$ $$III_{2\ell}(z-z^{\prime})-III_{2\ell}(z+z^{\prime}),\tag{D}$$
where $z,z^{\prime}\in\mathbb{R}.$

The link considers a problem on an interval $I=[0,\ell]$ with vanishing Dirichlet boundary conditions. This is equivalent to an $\mathbb{Z}_2$-orbifold $\mathbb{S}^1/\mathbb{Z}_2$, where the circle
$\mathbb{S}^1\cong\mathbb{R}/\mathbb{Z}$ has circumference $2\ell$, and functions of the problem should obey $$-f(-z)~=~f(z)~=~f(z+2\ell), \qquad z~\in~\mathbb{R}.$$
See also the method of images.

--
$^1$ If we restrict to $ 0\leq z,z^{\prime}\leq \ell$, the second term only affects boundary points. E.g. OP's eq. (II) is clearly not satisfied at the point $z=0=z^{\prime}$. However since the Dirac comb is a distribution note that all evaluations should strictly speaking be done with the help of test functions.
Comment: It's actually these boundary points that are confusing. One thing is that the $\sin$ expression is obtained for an interval $[0,L]$ or maybe $(0,L)$, which in principal can only give a $\delta$ function in the same interval. So I don't fully understand how can it be extended to form a Dirac comb? For the $\cos$ expression, eq 2.113 in the notes is utilised to get the Dirac comb, but I don't think the same works for the $\sin$ series. Am I right?
Comment: On the other hand, these completeness / closures identities, with only one $\delta$ instead of a Dirac comb, are also familiar from electrostatics. See for example chapter 2 of Jackson. In my 1999 ed, there is a section on orthogonal functions and expansions where it is stated that $\sum_n U_n^*(\xi') U_n(\xi) = \delta (\xi' - \xi)$ and $U_n$'s form the orthonormal basis...
Comment: ...If one takes this, then both expressions $I$ and $II$ should be valid with only $m=0$, however for different boundary conditions.
Comment: Regarding the method of images: I am somewhat familiar with this from electrostatics and from diffusion problems. As far as I know, you can convert a solution obtained from the method of images to that obtained from eigenfunction decomposition, using something like Poisson summation formula. Doing this essentially looks like you take an arbitrary source, use the images to obtain the solution with required BCs, then if you use the Poisson summation it suddenly looks like you have decomposed the original source on a basis that satisfies the BCs...
Comment: ... While this effectively neglects those modes in the source term that do not satisfy the boundary conditions (because, for example, their projection on the basis that satisfies the BC is zero), the method of images doesn't seem to have this issue - and I suspect this point is also related to the question above.


Contador de rotações unity

Question: Estou estudando o jogo Flippy Knife, e utilizei o AddRelativeTorque para fazer o giro da faca e aplicar o 360 que sempre soma 1 ponto, porém ao tentar fazer a contagem da pontuação checando se a faca ja atingiu determinado angulo, simplesmente não adicionava pontuação alguma (tentei varios angulos para ver se funcionava, mas não dava certo)
O angulo começa zerado, fiz o contador rodar no update, o que notei foi que no inspector, ao rodar o jogo, o rotation.x não vai de 0 a 360 por algum motivo, ele funciona de uma forma diferente.
Codigo do torque: (funciona conforme eu arrasto o mouse)
void Launch()
{
    isInAir = true;
    knifeRb.isKinematic = false;
    knifeRb.AddForce((releasePosition - touchPosition) * launchForce, ForceMode.Impulse);
    knifeRb.AddRelativeTorque(torqueForce, ForceMode.Impulse);
}

Contador (coloquei ele no update para rodar):
void Contador()
{
    if (contAng.transform.rotation.eulerAngles.x == 359)
    {
        pontos++;
    }

}

Comment: Não entendi... ele só vai somar `pontos` se o ângulo for exatamente 359?
Answer: Acho que seria mais facil você fazer uma equação que calcule quantas vezes a faca girou ao invez de incrementar sempre que ela girar. pode fazer algo assim.
void Contador()
{
   points = (int) contAng.transform.rotation.eulerAngles.x/360
}

Pode deixar esse metodo no update caso queira criar feed backs cada vez que o valor do points mude ou pode chamar esse metodo no final pra saber quantas voltas deu.

Contador de rotações unity


Probability that a periodic event with a duration $d$ will happen in the next $l$ days

Question: I have a periodic event that has a duration in time $d$. This event always starts happening $p$ days (or whatever unit of time) after the start of the previous event, with $p>d$. Given a length of time $l$ days with $d < l < p$, and given that I don't know when the last time the event happened was (or even if it's happening at the moment), what's the probability that this event will be happening during the next $l$ days? Not necessarily start to finish, just that there'll be some part of this event happening then.
EDIT: By the way, I used "days" as a unit of time here but I want a solution to the continuous problem, i.e. the event can happen at any time during a day, it does not necessarily start at midnight, $d$, $l$, and $p$ are real numbers, etc.
Answer: I would consider two cases.
The first if $d+l \geq p$. Since the time windows of length $d$ and $l$ can't be arranged within the time window of length $p$ without overlapping.
The second case is where $d+l < p$. $\frac{d+l}{p}$ is the "percentage" (between $0$ and $1$) of time the time windows $d$ and $l$ together cover of $p$ without overlapping. Hence $1-\frac{d+l}{p}$ of the time window $p$ is left within which the time window $l$ can "move" without overlapping the time window $d$, i.e. the probability that the time window $l$ does not overlap the time window $d$ is exactly $1-\frac{d+l}{p}$, or in other words it is the probability that the event $d$ does not happen within the next time window $l$. This is the opposite of what you were asking, so your question is answered by $1-(1-\frac{d+l}{p}) = \frac{d+l}{p}$.
Comment: This really needs more explanation to qualify as an answer to the question
Comment: This is being automatically flagged as low quality, probably because it is so short.
At present it is more of a comment than an answer by our standards. Can you expand
on it? We can also turn it into a comment.
Comment: Ok, I'll improve it asap


How to use inline_entity_form in Drupal 8?

Question: I am building 2 custom Content entity types: one is a Node type representing a type of food, called "food". This food may have multiple varieties, which will differ with regards to specific details, so I wish to store information about the varieties in a separate database table, and to accomplish this I have defined a second entity type called "food_type" which serves to provide additional information related to the "food" node.
Within the Food form, I want to also fill out all the fields for the related food_type. I am trying to accomplish this using inline_entity_form.
Following the documentation, I have done the following things for food_type:

Added a dependency of inline_entity_form in food_type.info.yml (there are no other dependencies)
Created food_type/src/Controller/FoodTypeInlineEntityFormController.php, which contains the following code:
namespace Drupal\food_type\Controller;

/**
 * Controller routines for Food Type pages.
 */
class FoodTypeInlineEntityFormController extends EntityInlineEntityFormController {

 /**
   * Overrides EntityInlineEntityFormController::entityForm().
   */
  public function entityForm($entity_form, &$form_state) {

    return parent::entityForm($entity_form, $form_state);
  }
}

Added the following code to food_type_install() in food_type.install:
$entity_info['food_type']['inline entity form'] = array(
    'controller' => 'FoodTypeInlineEntityFormController',
);

Defined '\Drupal\food_type\Controller\FoodTypeInlineEntityFormController::entityForm' as the _controller default under entity.food_type.form in food_type.routing.yml

I cannot enable the food_type module. Attempting to do so yields the following error:

Fatal error: Class 'Drupal\food_type\Controller\EntityInlineEntityFormController' not found in {directory}\sites\all\modules\custom\food_type\src\Controller\FoodTypeInlineEntityFormController.php on line 9

I assume this is caused because I do not include a use statement in FoodTypeInlineEntityFormController.php for EntityInlineEntityFormController. From Googling, it seems that such a statement is not used in example code that uses this module at all, and it's supposed to simply work when the inline_entity_form module is enabled. However, I for sure have inline_entity_form enabled and am still getting this error.
I would like to try a use statement, but the EntityInlineEntityFormController class does not seem to exist at all in the module code, as far as I can tell from searching. I am using 8.x-1.0-alpha6.
I am very new to drupal development and believe I am probably doing something else wrong, but I am completely at a loss here as to how to proceed or troubleshoot. Can anyone please help me or point me in the right direction?
Thank you in advance.
Comment: It looks to me like the README did not get updated between the 7.x branch and the 8.x branch, so those instructions are probably totally wrong. I don't think the issue is you. I would suggest opening an issue in the issue queue.
Comment: I can try to write a full response later, traveling today. I recommend looking at the Drupal Commerce 2.x source. We implement IEF in two content entity base fields (product and orders)
Comment: Thank you both. I will look at the source for Drupal Commerce 2.x and will also open an issue.
Comment: @MattGlaman, I am wondering if your offer to write a full response is still on the table - I have been working through the Drupal Commerce code but am having difficulty understanding just how everything works together. This is probably because I am new to Drupal development, but the use of IEF is something I am struggling a lot with. Thank you very much for your initial response, if you don't have time I understand, but figured I would ask :)
Answer: In order to implement Inline Entity form in D8, all you need to do is set your entity reference field to use the IEF widget - simple or complex. That is all. No additional work.
Here is how we set it up in Drupal Commerce for products, programmatically.
$form_display = commerce_get_entity_display('commerce_product', $product_type->id(), 'form');
$form_display->setComponent('variations', [
  'type' => 'inline_entity_form_complex',
  'weight' => 10,
  'settings' => [
    'override_labels' => TRUE,
    'label_singular' => 'variation',
    'label_plural' => 'variations',
  ],
]);
$form_display->save();

This tells the variations field, which is a Product Variation entity reference, to use IEF as the way to manage field values.