405 (Method Not Allowed) on reactjs component

Question: I am trying to call an endpoint with post method.
The code is:
import React, { Component } from 'react';
import { Input} from 'antd';
import Form from '../../components/uielements/form';
import Button from '../../components/uielements/button';
import Notification from '../../components/notification';
import { adalApiFetch } from '../../adalConfig';

const FormItem = Form.Item;

class CreateSiteCollectionForm extends Component {
    constructor(props) {
        super(props);
        this.state = {Alias:'',DisplayName:'', Description:''};
        this.handleChangeAlias = this.handleChangeAlias.bind(this);
        this.handleChangeDisplayName = this.handleChangeDisplayName.bind(this);
        this.handleChangeDescription = this.handleChangeDescription.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    };

    handleChangeAlias(event){
        this.setState({Alias: event.target.value});
    }

    handleChangeDisplayName(event){
        this.setState({DisplayName: event.target.value});
    }

    handleChangeDescription(event){
        this.setState({Description: event.target.value});
    }

    handleSubmit(e){
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                let data = new FormData();
                //Append files to form data
                //data.append(

                const options = {
                  method: 'post',
                  body: JSON.stringify(
                    {
                        "Alias": this.state.Alias,
                        "DisplayName": this.state.DisplayName,
                        "Description": this.state.Description
                    }),
                  config: {
                    headers: {
                      'Content-Type': 'multipart/form-data'
                    }
                  }
                };

                adalApiFetch(fetch, "/SiteCollections/CreateModernSite", options)
                  .then(response =>{
                    if(response.status === 204){
                        Notification(
                            'success',
                            'Site collection created',
                            ''
                            );
                     }else{
                        throw "error";
                     }
                  })
                  .catch(error => {
                    Notification(
                        'error',
                        'Site collection not created',
                        error
                        );
                    console.error(error);
                });
            }
        });
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 6 },
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 14 },
        },
        };
        const tailFormItemLayout = {
        wrapperCol: {
            xs: {
            span: 24,
            offset: 0,
            },
            sm: {
            span: 14,
            offset: 6,
            },
        },
        };
        return (
            <Form onSubmit={this.handleSubmit}>
                <FormItem {...formItemLayout} label="Alias" hasFeedback>
                {getFieldDecorator('Alias', {
                    rules: [
                        {
                            required: true,
                            message: 'Please input your alias',
                        }
                    ]
                })(<Input name="alias" id="alias" onChange={this.handleChangeAlias} />)}
                </FormItem>
                <FormItem {...formItemLayout} label="Display Name" hasFeedback>
                {getFieldDecorator('displayname', {
                    rules: [
                        {
                            required: true,
                            message: 'Please input your display name',
                        }
                    ]
                })(<Input name="displayname" id="displayname" onChange={this.handleChangedisplayname} />)}
                </FormItem>
                <FormItem {...formItemLayout} label="Description" hasFeedback>
                {getFieldDecorator('description', {
                    rules: [
                        {
                            required: true,
                            message: 'Please input your description',
                        }
                    ],
                })(<Input name="description" id="description"  onChange={this.handleChangeDescription} />)}
                </FormItem>

                <FormItem {...tailFormItemLayout}>
                    <Button type="primary" htmlType="submit">
                        Create modern site
                    </Button>
                </FormItem>
            </Form>
        );
    }
}

const WrappedCreateSiteCollectionForm = Form.create()(CreateSiteCollectionForm);
export default WrappedCreateSiteCollectionForm;

and the webapi is this one:
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using TenantManagementWebApi.Entities;
using TenantManagementWebApi.Factories;
using Cosmonaut.Extensions;
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core.Sites;
using TenantManagementWebApi.Components;

namespace TenantManagementWebApi.Controllers
{
    [Authorize]
    public class SiteCollectionsController : ApiController
    {
        // GET: ModernTeamSite
        public async Task<List<TenantManagementWebApi.Entities.SiteCollection>> Get()
        {
            var tenant = await TenantHelper.GetTenantAsync();

            using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(tenant.TenantAdminUrl, tenant.ClientId, tenant.ClientSecret))
            {
                Tenant tenantOnline = new Tenant(cc);
                SPOSitePropertiesEnumerable siteProps = tenantOnline.GetSitePropertiesFromSharePoint("0", true);
                cc.Load(siteProps);
                cc.ExecuteQuery();
                List<TenantManagementWebApi.Entities.SiteCollection> sites = new List<TenantManagementWebApi.Entities.SiteCollection>();
                foreach (var site in siteProps)
                {

                    sites.Add(new TenantManagementWebApi.Entities.SiteCollection()
                    {
                        Url = site.Url,
                        Owner = site.Owner,
                        Template = site.Template,
                        Title = site.Title
                    });
                }

                return sites;
            };
        }

        [HttpPost]
        //[Route("api/SiteCollections/CreateModernSite")]
        public async Task<string>  CreateModernSite(string Alias, string DisplayName, string Description)
        {
            var tenant = await TenantHelper.GetTenantAsync();
            using (var context = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(tenant.TenantAdminUrl, tenant.ClientId, tenant.ClientSecret))
            {
                 var teamContext = await context.CreateSiteAsync(
                    new TeamSiteCollectionCreationInformation
                    {
                        Alias = Alias, // Mandatory
                        DisplayName = DisplayName, // Mandatory
                        Description = Description, // Optional
                        //Classification = Classification, // Optional
                        //IsPublic = IsPublic, // Optional, default true
                    }
                );
                teamContext.Load(teamContext.Web, w => w.Url);
                teamContext.ExecuteQueryRetry();
                return teamContext.Web.Url;
            }
        }
    }
}

Comment: Change 'Content-Type': 'multipart/form-data' to application/x-www-form-urlencoded
Comment: http post is already used, I also put post in the options header. maybe I am missing application./json
Comment: after changing application/json I still get method not allowed
Comment: I had the route uncommented, but that didnt make any difference.
Comment: https://www.screencast.com/t/yOQPGJGt4  and https://www.screencast.com/t/8364REsWIuxT
Comment: yes https://www.screencast.com/t/WAYBsqy09
Answer: Attribute routing is enabled, according to the screenshot posted in comments, as the WebApiConfig has the default configuration
public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Note the api prefix on the convention based route.
The request from client is being made to /SiteCollections/CreateModernSite which wont match the Web API as the API controller appears to not be using the attribute routing and the requested URL does not match the Web API convention based route.
Also on the client side a JSON body is constructed in options while the content type is set to 'multipart/form-data'
If the intention is to POST content in the body, then on the server side you would need to make a few changes to make the API accessible.
[Authorize]
[RoutePrefix("api/SiteCollections")]
public class SiteCollectionsController : ApiController {
    // GET api/SiteCollections
    [HttpGet]
    [Route("")]
    public async Task<IHttpActionResult> Get() {
        var tenant = await TenantHelper.GetTenantAsync();
        using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(tenant.TenantAdminUrl, tenant.ClientId, tenant.ClientSecret)) {
            var tenantOnline = new Tenant(cc);
            SPOSitePropertiesEnumerable siteProps = tenantOnline.GetSitePropertiesFromSharePoint("0", true);
            cc.Load(siteProps);
            cc.ExecuteQuery();
            var sites = siteProps.Select(site =>
                new TenantManagementWebApi.Entities.SiteCollection() {
                    Url = site.Url,
                    Owner = site.Owner,
                    Template = site.Template,
                    Title = site.Title
                })
                .ToList();
            return Ok(sites);
        }
    }

    // POST api/SiteCollections
    [HttpPost]
    [Route("")]
    public async Task<IHttpActionResult>  CreateModernSite([FromBody]NewSiteInformation model) {
        if(ModelState.IsValid) {
            var tenant = await TenantHelper.GetTenantAsync();
            using (var context = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(tenant.TenantAdminUrl, tenant.ClientId, tenant.ClientSecret)) {
                 var teamContext = await context.CreateSiteAsync(
                    new TeamSiteCollectionCreationInformation {
                        Alias = model.Alias, // Mandatory
                        DisplayName = model.DisplayName, // Mandatory
                        Description = model.Description, // Optional
                        //Classification = Classification, // Optional
                        //IsPublic = IsPublic, // Optional, default true
                    }
                );
                teamContext.Load(teamContext.Web, _ => _.Url);
                teamContext.ExecuteQueryRetry();
                //204 with location and content set to created URL
                return Created(teamContext.Web.Url, teamContext.Web.Url);
            }
        }
        return BadRequest(ModelState);
    }

    public class NewSiteInformation {
        [Required]
        public string Alias { get; set; }
        [Required]
        public string DisplayName { get; set; }
        public string Description { get; set; }
        //...
    }
}

Note the inclusion of a proper strongly typed object model for the POST action, model validation and the returning of the proper HTTP status code as expected by the client. (204)
On the client side, update the URL being called to match the API controller's route and update the options to send the correct content type.
//...

const options = {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(
    {
        Alias: this.state.Alias,
        DisplayName: this.state.DisplayName,
        Description: this.state.Description
    })
};

adalApiFetch(fetch, "api/SiteCollections", options)
  .then(response =>{
    if(response.status === 204){
        Notification(
            'success',
            'Site collection created',
            ''
            );
     }else{
        throw "error";
     }
  })
  .catch(error => {
    Notification(
        'error',
        'Site collection not created',
        error
        );
    console.error(error);
});

//...

Note how the headers are directly in the fetch options as apposed to config.headers in the original code.
Comment: thanks, very extensive explanation, I did all what you say but I still get: https://screencast.com/t/txuDXlEmtBL
Comment: @LuisValencia are you able to see the raw request to confirm what content type is being requested. I find it strange that it is not accepting JSON, which is the default for asp.net-web-api.
Comment: this is weird, if I do it with postman it works, for some reason, if I do it within the react app the content type is text/plain
Comment: @LuisValencia check update. I think it had to do with how you were setting the headers in the fetch options. I also had to update the format of the payload before being stringified.
Answer: Try moving your Post request parameters into a class like this
public class TeamSiteInformation
{
    public string Alias { get; set; }
    public string DisplayName  { get; set; }
    public string Description   { get; set; }
}

and modify your method CreateModernSite signature to
[HttpPost]
public void CreateModernSite([FromBody]TeamSiteInformation site_info)
{

and in Change 'Content-Type': 'multipart/form-data' to 'application/json' in your reactjs app


How do I set up PXE boot so that it failsover to another server when a MAC address is unrecognized?

Question: We want to automate our OS installations. We currently have Linux and Windows boxes. We already use Cobbler for Linux installs with preliminary plans to use Windows Deployment Services for Windows.
Unfortunately, we have both OSs on mixed in different subnets. Is there a way I could configure Cobbler to failover to the WDS server if it does not recognize the MAC address of the machine?
Comment: Would it be practical for you to set up a PXELinux server that would provide a menu for the user to select between getting sent to Cobbler or WDS?
Comment: We'd rather have it completely automated for obvious reasons but, if we cannot, I suppose that would be the best solution.
Answer: You may want to check out pxechain.
PXEChain allows you to chain load pxeboot environments.  I've seen this presented at some infrastructure conferences but never used it in production.
I don't know if you can set a timeout to go to the next one or not but maybe worth exploring.
http://www.vcritical.com/2011/06/peaceful-coexistence-wds-and-linux-pxe-servers/
http://blog.friocorte.com/2011/05/chain-loading-pxe-servers.html


elegant way to check if a string inputed by user is an integer in ruby?

Question: I'm trying to validate that the input a user gives my program via gets is an integer. is_a?(Integer) does not work, as far as i can tell, because gets gets a string from the user, so it will always return false even if the user enters an valid integer (in string form). One would think I could simply use to_i on the input and be done with it, but that raises another issue - "75akjfas".to_i results in 75. So if I relied on to_i to solve my problems, anything starting with numbers will work.
How do I cleanly validate that the value is an integer only, and not a combination of numbers and letters? Or do I need to resort to regex for this?
Comment: possible duplicate of [Does ruby 1.9.2 have an is_a? function?](http://stackoverflow.com/questions/4282273/does-ruby-1-9-2-have-an-is-a-function)
Answer: print "Enter an integer (or try to sneak by something other): "
puts Integer(gets) rescue puts "Hey, that's not an integer!"

Comment: I'd just add a quote [from the docs](http://ruby-doc.org/core/classes/Kernel.html#M001434): "strings should be strictly conformed to numeric representation. This behavior is different from that of String#to_i"
Answer: How about s.to_i.to_s == s? I'd prefer regex however.
Comment: i have no reason to not use regexp. i'm just hoping there's a nice helper function somewhere that i'm missing :).
Answer: Using regex you could do it like this:
class String
  def integer?
   !!(self =~ /^[-+]?[0-9]+$/)
  end
end

Answer: You could use Integer() but you need to be careful with hex, binary, or octal input. http://ruby-doc.org/core-2.3.1/Kernel.html#method-i-Integer
def valid_integer?(string)
  begin
    !!Integer(string)
  rescue ArgumentError
    false
  end
end

Answer: Check this code example for how to use the checked string input by the user
        puts "Enter a number: "
    user_input = gets.chomp
    check = (user_input.to_i.to_s == user_input)
while (!check ) do
 puts("Wrong Input, Pls, Enter a number: " )
 user_input = gets.chomp
  check = (user_input.to_i.to_s == user_input)
end

if user_input.to_i < 0
puts "Number is negative"
elsif user_input.to_i > 0
puts "Number is positve"
else
puts "Number is Zero"
end

Comment: thanks @J0e3gan i have removed the link and it does show the same thing just that you can be able to run it there... I noticed the link was private to me.
Comment: The link you have provided yields an application error.  Maybe that is just a passing circumstance, but consider whether it is a lasting one you need to correct.  Also, the connection between the link you have provided and the sample code in your answer is not very clear.  Are they the same?  Edit your answer to make it clear.
Answer: Ruby can do it without esoteric solutions:
Integer is a integer
1970.is_a?Integer
true

String is not a integer
"1970".is_a?Integer
false

String to integer is a integer
"1970".to_i.is_a?Integer
true

Comment: This seems not to be totally correct. @LyleDickie wrote this as a suggested edit:
Unfortunately the "String to integer is a integer" section is incorrect. If you run it in IRB it does return true. However, if the user were to enter "197e" it would also evaluate to true.

```
 "197e".to_i.is_a?Integer
true
```
Comment: "a".to_i is 0. Which is still an integer.


Nativescript error: tns run android - "Cannot find a compatible Android SDK"

Question: I followed the whole Getting Started Tutorial for Mac (https://docs.nativescript.org/tutorial/chapter-1).
Now I try to get the sample app running. IOS works fine!
But Android doesn't work: Not on USB-device, either on Genymotion.
Here the error after typing in:
"tns run android"
Executing before-prepare hook from /Users/Username/Documents/Development/sample-Groceries/hooks/before-prepare/nativescript-dev-typescript.js
Found peer TypeScript 1.8.10
Processing node_modules failed. Exception: Cannot find a compatible Android SDK for compilation. To be able to build for Android, install Android SDK 22 or later.

I have installed Android SDK 23, as it was written in the tutorial:
android update sdk --filter tools,platform-tools,android-23,build-tools-23.0.3,extra-android-m2repository,extra-google-m2repository,extra-android-support --all --no-ui

How can I fix it? I tried everything...
Thanks!
Answer: First question I have would be, have you run tns doctor?
Be sure you have your ANDROID_HOME set correctly, pointed to your actual sdk install location, without a trailing slash at the end. here is mine as an example:
ANDROID_HOME=/sdks/android-sdk-macosx

It's also good to have the tools in the path (example snippet):
PATH='/sdks/android-sdk-macosx/tools:/sdks/android-sdk-macosx/platform-tools:/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/bin:/Applications/Genymotion.app/Contents/MacOS'

Comment: tns doctor says everything is fine. I've now redone everything (with a patched version) and I have a new problem, but at the same point. I opened up an issue on Github, because I think it's a problem with the repo. You may answer there, if you have any suggestions. https://github.com/NativeScript/sample-Groceries/issues/151


Correct recursion for $|4-x_{n+1}|<q |4-x_n|^2$

Question: Concerning my question here, let $(x_n)_{n\in \mathbb N}$ be a sequence such that $$|4-x_{n+1}|<q |4-x_n|^2, \, q>0$$
I am looking for the correction recursion $$|4-x_{n+1}|<q^a|4-x_1|^b$$
(So I want to find $a$ and $b$). I tried the following but apparently it's not correct:
$|4-x_{n+1}|<q |4-x_n|^2<q\Big|q|4-x_{n-1}|^2\Big|^2=q^3|4-x_{n-1}|^4<...<q^{2^n-1}|4-x_1|^{2^n}$
Answer: To simplify a chain of equations/inequalities/recurrence relations, it is usually a good idea to perform a change of variable to make the core part of the relations depend on as few parameters as possible.
In this case, let $u_n = q(4 - x_n)$, one will find $x_n$ converges to a limit iff $u_n$ converges to some other limit. Furthermore, the inequalities are simplified:
$$|4 - x_{n+1}| < q|4 - x_n|^2\quad\iff\quad |u_{n+1}| < |u_n|^2$$
From this, we can deduce
$$|u_{n+1}|
< |u_{\color{red}{n}}|^{2^\color{red}{1}}
< |u_{\color{green}{n-1}}|^{2^\color{green}{2}}
< |u_{\color{blue}{n-2}}|^{2^\color{blue}{3}}
< \cdots
< |u_\color{magenta}{1}|^{2^\color{magenta}{N}}$$
It is clear the last term is $|u_1|$ raised to power $2^N$ for some integer $N$.
The problem is it may not be immediately obvious what $N$ should be. If that happens, a trick is look for invariant quantities in the intermediate terms.
Notice

$\color{red}{n + 1} = n+1$,
$\color{green}{n-1 + 2} = n+1$,
$\color{blue}{n-2 + 3} = n+1$

The sum of subscript of $u$ and the power of $2$ is an invariant and equals to $n+1$.
This means $\color{magenta}{N + 1} = n + 1 \implies N = n$. As a result,
$$\begin{align} |u_{n+1}| < |u_1|^{2^n}
\iff &
q|4-x_{n+1}| < |q(4-x_1)|^{2^n}\\
\iff &
|4-x_{n+1}| < q^{2^n-1} |4-x_1|^{2^n}\end{align}$$
What you have is correct.


XADES4J - How to change  to something other id

Question: When i signing XML document with Xades4J (Xades-BES), i'm getting signed document including my xml within something like:
<ds:Object Encoding="UTF-8" Id="xmldsig-1ddcf1ab-7648-4039-b166-69e14da39982-object0" MimeType="text/xml">
 ....
</ds:Object>
i must change Id="xmldsig-1ddcf1ab-7648-4039-b166-69e14da39982-object0" to Id="Dokument-0"
How can i do that ?
Thanks for all answers and sorry for my bad english.
Darek
Answer: Currently there's no way to change how the signed data object id's are generated, mostly because the lib ensures that unique id's are used, even if a document contains multiple signatures.


Song is described as C# is this C# major, minor or?

Question: I am learning to play "Every praise by Hezekiah Walker" and the gentleman in the video describes the song in C# with the chords  F, Eb, F#, is he referring to C# Major or Minor?
I understand C# is equivalent to Db. I used this site to verify which chords are in which key. This site lists the chords in C#/Db as D flat major scale notes: Db Eb F Gb Ab Bb C Db
I'm confused, what key (major, minor, or what other variant??) exactly is this song in if I were to follow the video description of "they key of C#"
Answer: TLDR: If someone doesn't specific, go based off of what the tonic chord is major or minor.

First of the person in the video should not have called the one chord Eb. There are concepts in music called enharmonic equivalence where the same notes can have multiple names. Because we are looking at a key with a lot of sharps either way, calling the chord Eb doesn't make sense so it should be D# instead. Same goes for F which is actually an E#. Other sites for this show song in Db which is fine, but has all the chords written out with that in mind so you see chords that would appear in that key and never one with a sharp name.
Chords can be major or minor and I highly dout that you are playing only major keys based on the other site's version of this song. The quality of the chords will help define what is more appropriate to call the key as just a simple test can be checking whether the tonic chord is major or minor. Most of the time this is as far as you have to look to determine if the key. Also typical if it's in a major key you'll typically leave out the "major" when saying the key as major keys are typically more prevalent then minor keys.
This song starts on a C# major chord and uses the typical major chord of vi-IV-V (A#m - F# - G#) so the key is easily seen as C# major. This piece does modulate up the circle of 5ths however which is why the other site puts this in the key of Db as you'll start to get into double sharp territory if you start on C#.
Comment: Often chords are printed for purpose of performance rather than theoretical analysis.  Almost any guitar player who sees a "E" will know how to play an E major chord.  A guitar player who sees "Fb" will be far less likely to recognize that it should be played just like an "E" chord.
Answer: In itself, "the key of C#" would normally be taken to mean C# major. But not every description is fully precise, or made by a fully informed musician!
In this case - well, you're learning the song.  Which chord DOES frequently appear - C# major or C# minor?
Don't confuse "chords using the notes of the scale of the key" with "chords that are allowed in a song in a certain key".   The scale is a framework, not a restriction.  Chromatic chords are allowed.


Concorrência Server ASP.NET

Question: Tenho uma aplicação Silverlight, que acessa um serviço em WCF. Nessa aplicação tenho um método SalvarNotaFiscal(). Esse método chama um método ValidarNotaFiscal que verifica se já existe uma nota fiscal com o número e série informados. Esse método SalvarNotaFiscal é bem grande, pois executa várias rotinas.
Ocorreu do cliente clicar várias vezes nesse botão, e foram lançadas 6 notas com o mesmo número no sistema; o cenário foi esse acredito, pois não teria outra forma de duplicar essas notas se existe a validação.
Acredito que o ASP.NET atende as requisições em paralelo, o que faz sentido para mim, pois pode haver vários usuários simultâneos e o servidor precisa atender todos ao mesmo tempo.
Quanto ao meu problema no Silverlight, já tentei desabilitar o botão quando é clicado e habilitar no retorno callback, mas não tem funcionado.
<code>public void Salvar()
{
  btnSalvar.IsEnabled = false;
  NotaFiscalClient objSvcNotaFiscal = new NotaFiscalClient();
  objSvcNotaFiscal.SalvarNotaFiscalAsync(this.objNotaFiscal);
  objSvcNotaFiscal.SalvarNotaFiscalCompleted += (s, e) =>
       btnSalvar.IsEnabled = true;
  };
}
</code>
Comment: Você pode fazer isso com TransactionScope http://pt.stackoverflow.com/questions/32299/controle-de-concorr%C3%AAncia-em-inser%C3%A7%C3%A3o-no-banco-de-dados
Comment: Da uma olhada, isso vai bloquear outra inserção ENQUANTO outra nao acaba. http://www.bufaloinfo.com.br/ExibeNoticias.aspx?entryid=7326980343120390112
Comment: Qual código dentro de SalvarNotaFiscalAsync() ? coloca aí
Comment: O código é gigantesco, chama vários métodos, integra com webservices, e não posso postar por regras de privacidade da empresa. Esse bloco acima ainda posso. A validação funciona normal em um cenário normal. O problema é usuário que fica clicando várias vezes no botão. Inclusive a tela é congelada, mas até ela congelar dá tempo pelo jeito de ser enviada várias requisições iguais.
Comment: Então, basta você colocar um semáforo que creio que resolva seu problema
Comment: O que seria isso na prática?
Comment: isso ai é minha pergunta. talvez convenha eu fechar o post
Answer: Sim, as requisições HTTP ocorrem em paralelo.
É possível bloquear que isso ocorra de diversos modos...
Primeiro comece bloqueando o usuário de apertar o botão várias vezes, antes que uma solicitação seja concluída... (basta colocar um LOCK simples no método Salvar que já deve resolver!)
Já em relação a múltiplos usuários gerando a nota com mesmo número, você terá que fazer o tratamento no back-end (WCF), o mais fácil é também através da instrução LOCK, porém somente se você tem um único servidor executando um único processo do WCF irá funcionar!
Caso o webservice esteja executando através de vários processos simultâneos, você pode usar uma Mutex para garantir o acesso único a um trecho do código (ou ao método inteiro, no seu caso)
Lembrando que tanto a instrulção LOCK, como a utilização da classe Mutex, você precisa criar uma lógica que só permita que uma nota por vez entre no processo de acordo com o número da nota e não generalizado, se não você terá uma fila de notas a processar, sendo uma por vez, causando lentidão aos usuários.
Caso o seu back-end (WCF) esteja distribuido (em vários servidores, balanceamento de carga, failover, etc) você não irá conseguir sucesso só com um LOCK/MUTEX, você irá precisar criar um sistema em que irá existir um servidor único de controle de locks e então efetuar o lock por lá, ou melhor, você pode fazer isso usando um banco de dados (SQL) ou até mesmo o Redis.
Numa solução melhor para este cenário seria implementar um sistema de mensageria (MSMQ ou Redis) onde apenas um host seria responsável por processar as notas, e os outros apenas executando as outras tarefas...

Concorrência Server ASP.NET


awk print matching line and line before the matched

Question: Following is what I am trying to do using awk. Get the line that matches the regex and the line immediately before the matched and print. I can get the line that matched the regex but not the line immediately before that:
awk '{if ($0!~/^CGCGGCTGCTGG/) print $0}'

Comment: Lets suppose lines 3 and 4 match the regex.  do you want 2,3,4 to show up?
Answer: In this case you could easily solve it with grep:
grep -B1 foo file

However, if you need to to use awk:
awk '/foo/{if (a && a !~ /foo/) print a; print} {a=$0}' file

Comment: Not all grep(1)'s have the "-B" option. It's non-standard.
Comment: How about awk '{if ($0~/>/) head=$0;getline} {if ($0~/^CGCGGCTGCTGG/) print head"\n"$0}'..is this correct??
Comment: @Sudeep: You can tell yourself whether it's correct by testing it... but it's longer and harder to understand than marco's suggestion, so why bother?
Comment: Thanks Jeromi, yes, I can test...I am, but getline was bit confusing, this is why I posted to see is someone sees the command and can raise the flag :)
Comment: @Sudeep: My point exactly. It's confusing, so if there's a perfectly good way without it, don't bother confusing yourself.
Answer: /abc/{if(a!="")print a;print;a="";next}
{a=$0}

Comment: your script will not properly handle a case like "bcd\nabc\nabcdef"
Comment: Corrected to account for that.
Answer: use more straightforward pattern search
gawk '{if (/^abc$/) {print x; print $0};x=$0}' file1 > file2
Answer: I created the following awk script. Prints the matching line as well as the previous 2 lines. You can make it more flexible from this idea.
search.awk
{
    a[0]=$0;
    for(i=0;i<2;i++)
    {
       getline;
       if(i==0){
            a[1]=$0;
       }
       if(i==1){
            if($0 ~ /message received/){
                print a[0];
                print a[1];
                print $0;
            }
       }
    }
}

Usage:
awk '{print $0}' LogFile.log | awk -f search.awk

Answer: Why not use grep -EB1 '^CGCGGCTGCTGG'
The awk to do the same thing is very long-winded, see Marco's answer.
Comment: Thanks Marco and Solmojo..grep works too, just waned to do in awk.
Comment: As a learning exercise, it's a good thing to do, however, the grep will also run faster, and on biometrics that's probably a useful feature.
Comment: If you only have to do that, sure. But if you need to do that as part of a longer awk script, then you need a more flexible approach.
Answer: Maybe slightly off-topic, but I used the answer from belisarius to create my own variation of the above solution, that searches for the Nth entry, and returns that and the previous line.
awk -v count=1 '/abc/{{i++};if(i==count){print a;print;exit}};{a=$0}' file


Probability of Losing a Dice Game

Question: Consider the following game.

A game involves rolling two six-sided dice, followed by rolling a
third six-sided die. To win the game, the number rolled on the third
die must lie between the two numbers rolled previously. For example,
if the first two dice show $1$ and $4$, the game can only be won by
rolling a  $2$ or $3$ with the third die.

I am trying to find the probability that a player has no chance of winning before rolling the third die.
My thought process was that this only occurs when the first two rolls are the same number or consecutive numbers. Both of these have probability $1/6$ and so the probability of losing before the third roll is $1/6+1/6=1/3$.
However, the solution states the probability is $4/9$. I do not understand how my logic is incorrect.
Comment: The probability of the first two rolls being consecutive numbers isn't $1/6$.  You could roll $12$, $23$, $34$, $45$, or $56$, in either order, for a total of $10$ possibilities, and a probability of $10/36=5/18$.  (Otherwise, your reasoning is correct.)
Comment: Right... 11 is the same as 11, we can't distinguish those (because they're identical).  Another way to see this: after the first roll, whatever it is, there's only one possibility for the second roll that makes the two rolls identical (probability is $1/6$).  There's either one possibility ($1/3$ of the time) or two ($2/3$ of the time) for the second roll that makes the two rolls consecutive (probability is $1/18 + 4/18 = 5/18$).
Comment: Silly question, but if we can roll $12, 23, 34, 45$ or $56$ in any order, why do we not have $12$ possibilities of rolling the same number (i.e. while $11$ is the same as $11$, can we not distinguish these)?
Comment: As in your comment, you can roll 12, 23, 34, 45, 56 or their reversed orders, which are just $10$ possibilities out of $36$.
Answer: Probability of having the same number is $\frac16$ however to have consecutive numbers the probability is $\frac5{18}$ which sums to $\frac49$
Comment: Why is the probability $5/18$ and not $5/36$? Have you assumed that the roll $1$ and $2$ is different from the roll $2$ and $1$?
Answer: Notice the probability of having consecutive numbers is actually $\dfrac{4}{9}$. In this case, the first two dice rolls are distinct, so we have $5 \cdot 2$ ways for the two dice out of $36$ total was. We get $5 \cdot 2$ because we have $(1, 2), (2, 3), \dots, (5, 6)$ and the same thing with the ordered pairs reversed. From $\dfrac{5}{18} + \dfrac{1}{6}$, the answer is $\dfrac{4}{9}$ as your solution states
Hope this helps your understanding!
Answer: Simple, you're being asked the probability of the second dice being equal in value to the first having having a difference in value of one. If the first die is 2,3,4 or 5, the the probability is clearly $3/6=1/2.$ However if the first result is 1 or 6, then the probability is $2/6=1/3$. And finally $2/3*1/2+1/3*1/3=4/9$.

Probability of Losing a Dice Game


scope of geocode Google Maps API

Question: The console.log is giving an undefined value of the coord. If we console.log coord inside the if function, it gives the value, but it seems like the values cannot be coming out from the geocode function.
Does anyone know what the scope of geocode is and how can I change to get the values out from the geocode function?
THANKS
<code>    var coord;

    function change_coord(location) {
    var geocoder = new google.maps.Geocoder();
      geocoder.geocode({'address': location}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
              //real_lat and real_lng are int values
              var real_lat = results[0].geometry.location.lat();
              var real_lng = results[0].geometry.location.lng();
              coord = {lat: real_lat, lng: real_lng};
          }
      });
  console.log(coord); //undefined
  }
</code>
Comment: I have not used GeoCoder but looks like you need to put console.log(coord) inside the if block because geocoder.geocode looks like some kind of async call to back end and it takes time to give result and before that returns you are printing coord
Answer: Try with console.log inside the geocoder callback function.
In your code console.log is executed before you have receive the geocode response.

scope of geocode Google Maps API


Dates return null and not null values mysql

Question: So i have a temporary table that I need to populate with the records that have to deal with enrollment history
I work with a dataset that looks like this:
sccphidsid    enroll_date disenroll_date    status
abc123x        2009-01-01  2010-31-12           0
abc123x        2011-01-01  null                 0
abc123x        2011-03-01  2012-01-01           0

So I need it to return all records with the same sccphidsid and return them including the null and not null values.
The conditions it has to meet are

Disenroll dates are not null
Disenroll dates are null and
records have multiple disenroll_dates

Current Solution:
select *, count(disenroll_date is null)
              from enrollment _test
              where Status = 0
              group by Sub_Client_Cd, Policy_Holder_ID, Suffix_ID
              having count(disenroll_date is null) > 1;

However this is returning too many records, is there a way to isolate this query down, maybe simpler, that can prevent this from returning too many records by constraints or parameters?
Thanks all
Comment: The conditions "Disenroll dates *are not null*" and "Disenroll dates *are null*" do not seem to be valid..
Comment: I was referring to disenroll date is null and a case where the disenroll_date is not null with a valid date...not "not null".
Answer: SELECT Sub_Client_Cd, Policy_Holder_ID, Suffix_ID,
       SUM(CASE WHEN disenroll_date IS NULL THEN 1 ELSE 0 END) AS NullDateCount,
       SUM(CASE WHEN disenroll_date IS NOT NULL THEN 1 ELSE 0 END) AS NotNullDateCount
    FROM enrollment_test
    WHERE Status = 0
    GROUP BY Sub_Client_Cd, Policy_Holder_ID, Suffix_ID
    HAVING COUNT(*) > 1;

Answer: Actually this took care of it... Thanks anyways.
 select *, count(disenroll_date is null) from enrollment_test
 where  Status = 0
 and disenroll_date is null
 group by Sub_Client_Cd, Policy_Holder_ID, Suffix_ID
 having count(disenroll_date is null) > 1;


Are there any connection limits on Windows 7 IIS v7.5?

Question: My current development machine is Windows XP, and I use a modified tcpip.sys to allow me to exceed the 10 connection limit built in to IIS. I know that Vista's IIS has the same limit.
Can anyone confirm whether this connection limit is present in Windows 7 IIS as well?
Comment: Are your eferring to the 10 authenticated connection limit in XP, or the 10 half-open connections limit?  It seems that those answering your question are assuming the latter.. which doesn't make a lot of sense regarding IIS on desktop OS's.
Comment: I am referring to the 10 half-open connection limit.
Comment: This question is badly-formed. The (outbound) half-open connection limit from Windows XP SP2 has nothing to do with the (inbound) IIS number-of-requests limit. The accepted answer covers both possibilities, but the question is like asking "what orange is the best pear?"
Comment: @TristanK I framed the question as best as I could with my limited understanding. The issue I was trying to deal with was the IIS connection limit exceeded errors (actually EventID 4226) that you can get when hosting IIS on Windows XP. The reason I assumed half-open connections were the issue was that this is what was patched by the TCPIP.SYS patcher I used (http://www.lvllord.de/?lang=en&url=4226patch/faq), which resolved the issue.
Answer: From the base OS perspective, the limit has gone.
With Vista pre-sp2 it depended on the version. See https://stackoverflow.com/questions/413110/which-is-the-maximum-number-of-windows-concurrent-tcp-ip-connections/929973#929973
Since Vista SP2 the limitation have been removed from TCPIP.SYS, and has been configurable through a registry key. Windows7 should follow that same behavior (source and for 7, and here), but of course we will not know for 7 definitely until RTM since appart from technial there may be license restrictions.
However, IIS introduces its own limitations, depending on the version of the OS. For Windows 7 this limit is between 3 (Home Premium) and 10 (Business, Enterprise & Ultimate) simultaneous connections . Depending on your scenario, it might help to lower the connection timeout to free up slots sooner.
Comment: This answer describes *TCP* connections, but does not discuss IIS itself. IIS has a 10-connection limit in any non-server OS. Easily confirmed by testing.
Comment: Thanks, but interested in Windows 7, not Vista.
Comment: Sorry, I'll update.
Comment: You are right, I included the info in the answer. For Windows 7, it is not always 10. For "Home Premium" edition the limit is 3.
Answer: The connection limit in IIS is NOT THE SAME as the 10 half-port open limit. This is a limit built into IIS and has nothing to do with TCP/IP.  Pay for server or run Apache.
Comment: No need to pay for a server, as I was having no issue with connection limit - only half-open connection limit, which is a solved problem.
Answer: There is a special version of TCP-Z, a tool for "patching" tcpip.sys, for Windows 7 - an indication that this setting still exists in Microsoft new operating system.
Disclaimer: it is not advised to change operating system drivers.
Comment: You're confusing the "10 connection limit" of Desktop OS's with the "10 half-open connection limit" that was imposed as a security restriction.  I'm not sure which the question asker was referring to.  The "10 connection limit" is imposed on authenticated connections to prevent Desktop IIS from being used as a server.
Comment: The question itself is a little confusing. The asked writes "IIS connection limit" (?) and "patching tcpip.sys", so I deduced he was referring to this limit.
Comment: I am referring to the 10 half-open connection limit. The same limit that was fixed by this Win XP patch: http://www.lvllord.de/?url=tools.
Comment: You deduced correctly. thanks for the link splattne, sounds like the limit is still there :(
Comment: I confirmed with this tool that on Windows 7 the limit is still 10.
Comment: Clarification - the tool shows what the limit WOULD be if it is turned on by the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\EnableConnectionRateLimiting=1
Answer: Edit: I stand corrected, there is a 10 concurrent connection HTTP limit, confirmed by testing.
Comment: What is the basis for your statement that there is no concurrent connection limit in Windows 7 IIS? Is it an assumption based on your knowledge of Vista, or have you confirmed it to be the case?
Comment: My original screenshot was against IIS7 server, not IIS 7.5 client due to a typo in hostname. Apologies.
Answer: Pleae see this link, and how to get more concurrent connections in IIS.
http://community.psion.com/knowledge/w/knowledgebase/1227.a-r-c-increase-iis-connection-limits.aspx
Regards
Comment: Welcome to Server Fault! Generally we like answers on the site to be able to stand on their own - Links are great, but if that link ever breaks the answer should have enough information to still be helpful. Please consider editing your answer to include more detail. See the [FAQ](http://www.serverfault.com/faq) for more info.
Comment: -1: The information in the linked article is incorrect.


Whats the difference between *(a+b) and (*a+b)

Question: A friend helped me with this code and I don't understand how it works. in the 5th line is (*pp-97)*4 basically the size of the char 110 so (110-97)*4 or the scanned value of pp? Thanks
char *pp =(char*)malloc(110);
printf("Enter text: ");
scanf("%s", pp);
*pp = *(pp + n);
int f = (*pp - 97)*4;

Comment: Does this look like Java to you?
Comment: Why did this get downvoted?
Comment: I'm totally confused. What do you want by this code? 97 is the ascii of 'a'
Comment: @ luchian I thought someone would know as its not that different from java
Comment: @ halelfits a small chunk of a larger program I just tried to understand this part
Comment: @jeniffer_214 I keep seeing you asking these questions in the comments. Do you have any idea what that f is used for? You seem to be asking us to make sense of it. But how can we make sense of it when we don't have the context of this code? We told you what this snipet does technically...
Answer: Note that *pp is equivalent to pp[0], and generally *(pp + n) is equivalent to pp[n], so
*pp = *(pp + n);

could also be written pp[0] = pp[n];, that copies the char at offset n to the first char at offset 0.
int f = (*pp - 97)*4;

and this could be written
int f = (pp[0] - 97)*4;

so 97 (the ASCII value of 'a') is subtracted from the first char in the block pp points to, and that difference is multiplied with 4.
Comment: so is the 97 subtracting from the ASCII value as well i.e. a-b (97-98)
Comment: I'm not entirely sure I understand your question, the idea is to get the offset of that `char` from `'a'` to get the appropriate index into the Morse-code array.
Comment: int f = (pp[0] -97)*4; lets say pp is 'abc' (97-97)*4
Comment: No, `pp` is a pointer to `char`, so it's not `'abc'`. It could point to `"abc"`, though. Then for `n == 0`, it would produce `int f = (97 - 7)*4;`. Each Morse code is aligned at a multiple of 4 from the start of the array, the first being the Morse code for 'a'. So if the `char` is e.g. `'d'`, the difference is `'d' - 'a' = 3`, and the offset into the Morse-code array is `4*3 = 12` because there are 3 Morse-codes (for 'a', 'b' and 'c') of four symbols (filled up with spaces if the actual code is shorter) before the code for `'d'`.
Answer: This is a pretty weird snippet.
This line basically declares a string of size 110:
char *pp =(char*)malloc(110);

These two lines grab input from users:
printf("Enter text: ");
scanf("%s", pp);

Now this is where things start to get weird.
*pp = *(pp + n);

The line above changes the first character of this string to the nth char in the string.
int f = (*pp - 97)*4;

Now in terms of this line. Here you are derefrencing the pointer pp. When you derefrence this pointer it will be first char that pp is pointing too. The value of this char will be converted to an integer (its ASCII representation) and then subtract 97 (which is the ASCII value of a) and then multiplied by 4.
Comment: "The line above moves the pointer by n" no it doesn't. It assigns the char at `pp+n` to the first char that `pp` points to. The pointer is not moved.
Comment: Wrong, the `*pp = *(pp + n);` expression doesn't change the pointer. It only copies the character at index `n` to index 0, i.e. it overwrites the first character with the last of the string.
Comment: @LuchianGrigore You're right. I saw plus beside a pointer and did not stop to think. Please see my edits
Comment: @tristopia You're right. Please see my edits.
Answer: char *pp = malloc(110);
printf("Enter text: ");
scanf("%s", pp);
pp[0] = pp[n];
int f = (pp[0] - 'a')*4;

In C, array operator is the same thing than pointer dereferencing. By using the right notation, the code gets less confusing (imo).
*(p + i) is a synonym of p[i]  therefore *pp is same as *(pp + 0) which is the same as pp[0]


(Minimum) Sample size in a clinical study, rule-of-thumb

Question: I was asked this question and I am not sure about my answer that is why I am asking it here. An institute wants to conduct a clinical study. This study has most likely three treatment arms. The design is not yet set up, nor is any information given about the efficacy, endpoints, estimates, methods and so. The (randomized) study basically checks if the weight has decreased. In most simple case this would be a simple mean comparison, but of course also Kaplan-Meier-Estimates and other statistics (ratios and so) can come into play. The study itself is a simple one. So we are not talking about a new drug or whatever. It is from sports life science, basically how can get people to live healthier and it checks if a certain training schedule reduces the weight. The other arm next to placebo is schedule plus addition nutrition consulting.
The problem now is that of course the costs should be estimated, but especially the budget is limited and the question arised how many subjects are needed. Because each subject needs to be assigend to an educated trainer and each subject therefore crucially increases the costs. Of course my first answer was it depends on the design, the estimates and so. But I had to give a specific number. My answer was it should be not less than 30-40 subjects per treatment arm. My thoughts were that if it is more or less some simple mean comparison from my personal point of view it should be sufficient. If I think about weight and comparing weights between groups, what personally is sufficient for me? If I only have 10 subjects to compare this is not enough. 20 already would make T test and so stable, from my point of view. I thought if there are 30-40 subjects per treatment group, this should be sufficient. But later on I thought about Kaplan-Meier plots and estimates (log rank test, Cox-regression, odds ratios to come into play?), especially I do not have any information about the event rate. So I don't know what exactly they will specify - this is also more or less a question to me - and I thought that 30-40 is maybe not sufficient if we talk about comparing weights.
So is there somehow a rule-of-thumb? The problem is really to give a number. With Survival analysis I am not that much used to (those studies I had this never was a problem), so I cannot estimate how many subjects or events are needed to get these plots and estimates working ? So what is the minimum sample size for a clinical study? Also how many events do I need?
Answer: If you want to study change in weight, then a Kaplan-Meier curve is irrelevant. That just studies the time till an event occurs. Since you don't have a discrete event, this methodology does not apply.
Before you start investing time and effort into this project make sure you actually can do an experiment on humans. Depending on your jurisdiction the bar can be quite high. See, e.g. https://en.m.wikipedia.org/wiki/Institutional_review_board
To answer your question: you need to perform a power analysis: https://en.m.wikipedia.org/wiki/Power_(statistics) .
Comment: Thanks for your answer. Your comment regarding Kaplan-Meier and change in weight is correct, however I was not 100% precisely here. The main point is indeed the weight situation, however this also focusses on dependent factor, like time until a surgery is needed or time until another specific happening occurs. So it could arise that Kaplan-Meier and other survival analysis methodologies and not only a simple weight change check will come up. Yes, I am aware of the ethical point of a clinical study and informed consent and committee.


str_replace in Javascript

Question: I want to do str_replace in javascript but without using an inbuilt function.
I want Scratch Code for this.
Please Someone can have the code for this?
I WANT JAVASCRIPT INBUILt FUNCTION STR_REPLACE DITTO without USING STR_REPLACE.
function Replace(string, charToChange, charToReplace){
var replaced = "";
for(var i=0; i < string.length; i++){
    if(string[i] == charToChange){
        replaced = charToReplace;
    }
}
return replaced;
}

Comment: smells like homework. what have you tried?
Comment: Use `"I am joking".split("I am").join("We are");`
Comment: @LGSon,
I can't use any inbuilt Methods....
Comment: Then you simply write your own parser
Comment: @NinaScholz Can't agree more....:)
Comment: wait sending Code
Answer: JS has a function for replace. go through this link:
https://www.w3schools.com/jsref/jsref_replace.asp
Comment: thanks for reply,
But i want WITHOUT USING STR_REPLACE method
Answer: Try the below example
enter code here
    function myFunction()
           {
              var str1 = 'This is a test string.';
            // Let's replace the word This with 'that'
             str1 = str1.split('This').join('that');
        }

Note : The string inside the split function is case sensitive.
Hope this will help you...
Answer: You can try below code

var string = "abc Code Snippet abc pqr abc";
var result = string.split(' ');
var i =0;
result.forEach(function(element){
if(result[i] == "abc"){
result[i] = "change";
}
i++;
});
var a = result.join(" ");
alert(a);
Answer: Please note the following is entirely under the assumption that you can't use built in functions which is stated by OP in comments
function Replace(s, strOld, strNew){
    //find returns the starting index of the string you are looking for
    // do some exception handling or return -1 if not there
    var loc = find(s, strOld); //you should implement find
    //assuming you can't use the slice function
    retStr = "";
    for(var i = 0; i < loc; i++){
        retStr += s[i]; //builds new string with chars up to loc
    }
    retStr += strNew; //put the new string in
    for(var i = loc + strOld.length; i < s.length; i++){
        retStr += s[i]; //puts remaining chars from original string
    }
    return retStr;

}

Do something like this. I left the find function up to you but the rest is a pretty simple algorithm. Find should check s by character for matches with strOld that happen in a row.
Note: I changed the variable names from your original function. string to s because it's bad form to name a variable after a type. I changed the other two because they are misleading, since you are trying to replace a string not a char.
I'd also recommend you use === instead of == for equality until you understand what the difference is. See here for more

str_replace in Javascript


MySQL: Select records that don't have transitive child records

Question: I will illustrate my question as I understand it's very confusing.
Say you have three tables (data is not consistent it's only for illustrative purposes):
Category
+----+----------+
| id | name     |
+----+----------+
| 1  | History  |
| 2  | Sci-fi   |
| 3  | Mystery  |
+----+----------+

Book
+----+-----------------------------+
| id | category_id | name          |
+----+-------------+---------------+
| 1  | 5           | Mowgli        |
| 2  | 7           | Don Quixote   |
| 3  | 11          | Ulysses       |
+----+-------------+---------------+

Tags
+----+---------+-------------+
| id | book_id | name        |
+----+---------+-------------+
| 1  | 452     | Bestseller  |
| 2  | 42      | Novel       |
| 3  | 921     | Novelty     |
+----+---------+-------------+

I need to select all unassigned tags for each book.
Below is the query that simply shows all tags per category, per book, where I need (I'm repeating myself here) to select only those tags that are assigned to any other book but not the current one.
Or in other words to only select tags that haven't yet been assigned to the book.
SELECT c.id category_id, b.name, t.book_id, t.id tag_id
FROM tags t
LEFT JOIN book b ON b.id=t.book_id
LEFT JOIN category c ON c.id=b.category_id

Comment: Show the results you want.  What does `category` have to do with the question?
Comment: I feel like with your setup of tags you should probably just have the tags be their own table, so that the list of tags remains fixed, while creating a new table that links the two things.
Comment: All comments and answers are the point. I didn't fully understand the problem when I asked the question hence some of the things I asked didn't quite connect. Thank you everyone to their input
Answer: The idea is to use cross join to generate all combinations of books and tags.  Then use left join or some other method to filter out the ones that already exist:
select b.*, t.name
from (select distinct name from tags) t cross join
     books b left join
     tags tt
     on tt.book_id = b.id and tt.name = t.name
where tt.book_id is null

Comment: Thank you very much for your answer!


Geodesic Uniqueness in the Hyperbolic Plane

Question: I am studying Hyperbolic Geometry. At this part, I have proved that semicircles and straight lines orthogonals to the real axis are geodesics in the hyperbolic plane. But how I proof that this geodesics are uniques? That it does not exist others geometric places between two different points that minimizes the hyperbolic length?
I have seen a topic related to this, but I do not know nothing about Riemannian Geometry. If someone could indicate to me some references to this proof(or the idea behind) I will be very grateful!
Answer: There is a general fact in Riemannian geometry which follows from "standard" existence and uniqueness theorems in the study of ODEs.  Mainly, given any point $p$ in a Riemannian manifold $M$ and given any $v\in T_pM$, there is a unique geodesic defined for some open neighborhood of time around 0 starting at $p$ in the direction of $v$.
Assuming this, it's not too hard to show that you've found all the geodesics.  You just need to verify that for any point $p$ in the hyperbolic plane and tangent vector,  either the vector points up/down (so a vertical line geodesic has $v$ as tangent vector), or some semicircle through $p$ hitting the $x$-axis perpendicularly does.
Finally, to show there is a unique geodesic between any two points, one argues as follows:
Given $p$ and $q$, if $q$ and $p$ have the same $x$ coordinate, a vertical line passes through them.  Further, no semicircle hitting the $x$-axis perpendicularly can go through both $p$ and $q$ since the semicircle is the graph of a function, so passes the vertical line test.
Next, given $p$ and $q$ with different $x$ coordinates, it's clear that a vertical line can't connect them, so we need only find all semicircles passing through both perpendicular to the $x$-axis.  Algebraically, proceed by noting the equation of such a circle is $(x-a)^2 + y^2 = r^2$ for some $a$ and $r$.  Plugging in $(x,y) = (p_1,p_2)$ and $(x,y) = (q_1,q_2)$ respectively and setting the two equal to each other (since they both equal $r^2$), one gets $$(p_1-a)^2 + p_2^2 = (q_1-a)^2 + q_2^2.$$
By simplifying this, one sees the $a^2$ cancels out and so one gets an equation linear in $a$, so $a$ is uniquely determined.  (The assumption that $p_1\neq q_1$ means that the equation has the linear piece).  Knowing $a$ easily implies that $r$ is uniquely determined (keeping in mind that $r \geq 0$).  This shows that there is a unique semicircle perpendicular to the $x$-axis going through $p$ and $q$.
Comment: I think I followed your argument in the first two paragraphs. But where I use the fact that the metric of this space is the hyperbolic one? I can proceed like that in the Euclidian plane and obtain the same results, but semicircles are not geodesic in this space.
Comment: ignore the previous post, now I understood all, thank you. I've already proved that this curves are geodesics, so if I can construct, for a given point p and tangent vector v, a vertical line or semicircle orthogonal to the real axis, the theorem that you told me guarantee that, necessarily, those are the unique geodesics. And I already have calculate the radius and center of the semicircle and, in fact, they are unique. Thank you a lot! p.s. You can give me some references to this theorem that you told me? Thank you in advance!
Comment: I don't have any references currently available, but if I remember to, I can look it up at school on Monday.
Answer: You can argue "geometrically" as follows: For two points $p$, $q$ on the imaginary axis it is pretty obvious that the segment $[p,q]$ is the unique shortest curve connecting $p$ and $q$. Now if $p$, $q\in H$ are arbitrary there is a Moebius transformation $T: H\to H$ sending $p$ and $q$ to two points $p'$, $q'$ on the imaginary axis. Since $T$ is a hyperbolic isometry it follows that $p$ and $q$ have a unique shortest connection, and since $T$ (now considered as a map $\bar {\mathbb C}\to \bar {\mathbb C}$) maps circles to circles and preserves angles between curves it follows that this shortest connection lies on a circle intersecting the real axis orthogonally.
Comment: Why it is pretty obvious that in case of $p,q$ are in the same imaginary axis ? Can you give a proof that image of the geodesic joining $p,q$ entirely lies in positive imaginary axis?


Find the fraction where the decimal expansion is infinite?

Question: Find the fraction with integers for the numerator and denominator, where the decimal expansion is $0.11235.....$
The numerator and denominator must be less than $100$.
Find the fraction.
I believe I can use generating functions here to get $1+x+2x^2+3x^3+5x^4+.....$, but I do not know how to apply it.
Comment: Good rational approximations can be found using partial fractions.
Comment: Is the fractional term supposed to be the simple stringing together of the Fibonacci numbers, i.e., `0.112358132134...`?
Comment: What's the next digit, $8$?
Comment: @CameronBuie It was not given.
Comment: @barakmanos: Not sure. It was not given.
Comment: Ah! Never mind. I missed the condition that the numerator and denominator must be less than $100.$
Answer: Like you hint, we can observe that the value
$$0.11235955056\ldots = \sum_{k = 1}^{\infty} 10^{-k} F_k,$$
where $F_k$ is the $k$th Fibonacci number (with the convention that $F_0 = 0$, $F_1 = 1$),
is simply the value of the series
$$F(x) := \sum_{k = 1}^{\infty} F_k x^k = x + x^2 + 2x^3 + 3x^4 + 5x^5 + 8x^6 + 13x^7 + \cdots$$
at $x = \frac{1}{10}$.
Hint Using the defining recurrence relation
$$F_{k + 2} = F_{k + 1} + F_k$$
(and the above convention) gives that $F(x)$ satisfies
$$F(x) = x + x F(x) + x^2 F(x).$$

Rearranging gives that on the open interval of convergence of the series, which turns out to be $(-1/\phi, 1/\phi)$---where $\phi$ is the Golden Ratio, and which in particular contains the value $\frac{1}{10}$ of interest)---we have $$F(x) = \frac{x}{1 - x - x^2}.$$ Thus, the series has value $$F\left(\tfrac{1}{10}\right) = \frac{\left(\frac{1}{10}\right)}{1 - \left(\frac{1}{10}\right) - \left(\frac{1}{10}\right)^2} = \color{#bf0000}{\boxed{\frac{10}{89}}} .$$ Since this is a rational number, its decimal expansion repeats: $$0.\overline{1123595505617977528089887640449438202247191}.$$
Comment: @FlybyNight yes, that behavior is obvious and expected -- 1, 1, 2, 3, 5, 8, 13 and then the 8 and 13 overlap to give a 9 in the decimal expansion in place of the 8.
Answer: Continued fractions:
\begin{align}
\frac{11235}{100000}&=\frac{2247}{20000}\\
&=\cfrac{1}{8+\cfrac{2024}{2247}}\\
&=\cfrac{1}{8+\cfrac{1}{1+\cfrac{223}{2024}}}\\
&=\cfrac{1}{8+\cfrac{1}{1+\cfrac{1}{9+\cfrac{1}{13+\cfrac{2}{17}}}}}\\
&=\cfrac{1}{8+\cfrac{1}{1+\cfrac{1}{9+\cfrac{1}{13+\cfrac{1}{8+\cfrac{1}{2}}}}}}\\
&=[0;8,1,9,13,2]
\end{align}
The first convergent is $1/8$; the second convergent is
$$
\cfrac{1}{8+1}=\frac{1}{9};
$$
the third convergent is
$$
\cfrac{1}{8+\cfrac{1}{1+\cfrac{1}{9}}}=\cfrac{1}{8+\cfrac{9}{10}}=\frac{10}{89};
$$
The fourth convergent can be computed to $131/1166$ (see this continued fraction calculator)
Answer: An exhaustive search (by computer) of all fractions with numerator and denominator $< 100$ shows there is only one whose decimal representation starts 0.11235:
$$
\frac{10}{89}
$$
The decimal expansion continues $\ldots 955056179775\ldots$ (I haven't bothered finding aprogram that can calculate enough that we can see the period), that's completely impossible to guess- I would call the question poorly worded.
Comment: To save anyone from having to reach for a calculator, the first many digits of the expansion goes $0.1123595505617977\dots$.  The question of if there is a better method than brute force remains.  We could clearly see that for it to work for some $\frac{p}{q}$, we would need $8.5p < q<9p$ and so $p\leq 11$, reducing cases to test to less than 18
Comment: @Henrik: I am guessing that the decimal representation would represent Fibonacci numbers, but I'm not sure..
Comment: The period is $44$ since $m = 44$ is the smallest positive integer such that $10^m \equiv 1 \pmod{89}$. [WolframAlpha](http://www.wolframalpha.com/input/?i=10%2F89) gives the decimal expansion to enough digits.
Comment: @MathisLife: I would be surprised if the decimal representation of the Fibonacci numbers were rational.
Answer: These are fractions $f$ with $11235/100000\le f<11236/100000.$ A direct, if slow, method for counting these would be
$$
\sum_{d=1}^{100}\left\lfloor\frac{100000d}{11235}\right\rfloor-\left\lfloor\frac{100000d}{11236}\right\rfloor
$$
or
<code>sum(d=1,100,100000*d\11235-100000*d\11236)
</code>


How should I dampen timpani?

Question: I've been working on my timpani playing, and the music has it written in that I should dampen certain notes at various parts of the song. But having I'm having trouble figure out the best technique for doing so. When I put my hand flat on the timpani head it makes a buzzing sound and the sound continue for a while afterwards. If I press harder, the resonance stops slightly more quickly, but the notes goes sharp because of the added tension on the head.
How can I learn to dampen timpani quickly, but with minimal 'ring over', sharpness of note, and buzzing sound from my hand touching the drum?
Answer: I discussed this topic with my teacher a few weeks ago because I also had problems with dampening the timpani. I never managed to do it without adding any noise from touching the head. He gave me three tips that solved most of my problems:

Although it is desirable to have the muting as silent and perfect as possible, not everything you hear is heard by the audience. A small remaining buzz sound will never be avoidable.
A good technique is to touch the head at the edge and then quickly move your hand or finger to the center of the timpani. This way, all kinds of oscillating modes of the head are dampened.
Practicing helps. Use some time in your practice routine for the topic exclusively to find out what works best for you.
Comment: @NReilingh: no, I really meant the different vibration modes of the head, see http://music.nebrwesleyan.edu/wtt/?page_id=183
Answer: Dampening timpani is not a complete art in itself, but it does take some practice to do well. The easiest technique is to use the pads of your fingers and palm to stop the vibration as you said, but things get slightly more complex than that. I find small quick circles with the hand on the drum head can make for a faster dampening and usually doesn't make too much extra noise. If you really need the sound stop stop quickly, you can use your entire forearm in addition to your palm.Also take note where you are placing your hand on the timpani (edge, center, middle, etc.) as each will give you a slightly different effect. I'd probably go for the area between the edge and the center for quickest stop of sound and least buzz, but you should still experiment on your own to see what works best.
Things get slightly more interesting when you have to continue playing while dampening or have to dampen multiple drums at once. You can usually use fingers 2, 3, and 4 for the dampen and regrasp the stick for another note very quickly. If you have to dampen three or more drums, try using both hands and your elbow for the last drum. I've even heard tell of some professionals using their legs and knees when 5 drums had to be dampened at once.
If you want to get really good results, you can buy woolen gloves, cut out the thumb and first, and wear them the entire time when you play. I've occasionally seen players have a good-sized piece of felt nearby to throw over the drum to mute it, but this usually isn't necessary. :D
Disclaimer: self answer!

How should I dampen timpani?


Failure to bundle ec2 - how to get more information?

Question: I'm trying to create a ec2 bundle.
I'm running the command:
ec2-bundle-vol -r $arch -d /mnt -p $prefix -u $AWS_USER_ID -k ~/.ec2/pk-*.pem -c ~/.ec2/cert-*.pem -s 10240 -e /mnt,/vol/mysql_data  --debug

It ends with error "execution failed" (how informative!)
ERROR: execution failed: "
rsync -rlpgoD -t -r -S -l --exclude /sys --exclude /proc --exclude /dev/pts --exclude /dev --exclude /media --exclude /mnt --exclude /proc --exclude /sys --exclude /etc/udev/rules.d/70-persistent-net.rules
--exclude /etc/udev/rules.d/z25_persistent-net.rules --exclude /mnt --exclude /vol/mysql_data --exclude /mnt/img-mnt -X /* /mnt/img-mnt 2>&1 > /dev/null"

with debug flag it shows also:
#<RuntimeError: execution failed: "rsync -rlpgoD -t -r -S -l --exclude /sys --exclude /proc --exclude /dev/pts --exclude /dev --exclude /media --exclude /mnt --exclude /proc --exclude /sys --exclude /etc/udev/rules.d/70-persistent-net.rules --exclude /etc/udev/rules.d/z25_persistent-net.rules --exclude /mnt --exclude  /vol/mysql_data  --exclude /mnt/img-mnt -X /* /mnt/img-mnt 2>&1 > /dev/null">
/usr/local/lib/site_ruby/1.8/ec2/platform/linux/image.rb:244:in `execute'
/usr/local/lib/site_ruby/1.8/ec2/platform/linux/image.rb:156:in `copy_rec'
/usr/local/lib/site_ruby/1.8/ec2/platform/linux/image.rb:84:in `make'
/usr/lib/site_ruby/ec2/amitools/bundlevol.rb:151:in `bundle_vol'
/usr/lib/site_ruby/ec2/amitools/bundlevol.rb:193:in `main'
/usr/local/lib/site_ruby/1.8/ec2/amitools/tool_base.rb:201:in `run'
/usr/lib/site_ruby/ec2/amitools/bundlevol.rb:201

Which tells me the error starts somewhere at VolBundler run() method (guessing, I don't know ruby).
Anyone has any idea what the error is?  or how can I get more information?
Comment: I am getting the same error. When I checked the size of image created in /tmp folder it is 10GB. So it is exceeding the max size of the image
Answer: Make sure that you do not exceed 10 GB Limit for an AWS bundle. Exclude all extra directories.
Also if you are doing bundling from within a running instance, make sure that you got all unnecessary services (like sendmail) stopped.


FloatingActionButton does not show up on app

Question: I want to create a simple layout in Android like that of Gmail Inbox. A list of items and a FloatingActionButton to add a new item. In the design tab of Android Studio, the button shows up. However, when I launch the app in emulator, the button does not show up. I am using a recyclerview for displaying items. The items get displayed correctly.
Fragment code
    <FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/question_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/floatingActionButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon_add"
        android:layout_gravity="end|bottom"
        android:layout_margin="16dp"/>

</FrameLayout>

Activity layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:layout_width="wrap_content"
    xmlns:tools="http://schemas.android.com/tools">

    <android.support.design.widget.AppBarLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.TabLayout
            android:id="@+id/dashboard_tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill">
        </android.support.design.widget.TabLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Dependencies
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
    applicationId "com.tl.dialog"
    minSdkVersion 19
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}

 dependencies {
        implementation fileTree(include: ['*.jar'], dir: 'libs')
        implementation 'com.android.support.constraint:constraint-layout:1.0.2'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.1'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
        implementation 'com.android.support:recyclerview-v7:26.1.0'
        implementation 'com.android.support:cardview-v7:26.1.0'
        implementation 'com.android.support:appcompat-v7:26.1.0'
        implementation 'com.android.support:support-v4:26.1.0'
        implementation 'com.android.support:design:26.1.0'

        compileOnly 'org.projectlombok:lombok:1.16.20'
        annotationProcessor 'org.projectlombok:lombok:1.16.20'
    }

Comment: You could use [LayoutInspector](https://developer.android.com/studio/debug/layout-inspector.html) at runtime to check if the FAB is part of the emulator/ device screen
Comment: "Shows" like in the picture or also "shows" in the View hierarchy list on the left side? The FrameLayout may have been merged with the ViewPager tab, but let's concentrate on the missing FAB. If it's in the list but not on the screen then may be below the lower screen edge.
Comment: Good, there's finally enough code so I can reproduce the error. Which gives me the opportunity to make sure I really have a solution before posting an answer. Interesting problem. I'll get back to you as soon as I find out anything useful.
Comment: Thanks. Didn't know about this feature. I am not able to see the FAB in layout inspector. Actually, the inspector only shows recyclerview inside the ViewPager. It does not mention the framelayout as well. Something terrible going on here?
Comment: "Shows" as in view hierarchy. Both Framelayout and FAB missing in view hierarchy as well as sceen.
Comment: That's bad. In this case you should post enough code to reproduce your error (so we can easily set up a small sample).
Comment: Only code remaining is the recyclerview adapter. Rest everything I have shared. I know the reference to the files are correct because if i make any changes in the recycler view design, they get reflected.
Comment: "Rest everything I have shared" - well, you did not post any Java (or Kotlin) code.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/168252/discussion-between-adi-and-0x0nosugar).
Answer: You return the RecyclerView from onCreateView() not the root View. (I suppose this happened because in some earlier version you only had a RecyclerView inside the Fragment)
So all you have to change is the last line of onCreateView(), instead of return recycler; it should be
return mView;

Comment: Brilliant. Not sure how long would it have took for me to figure out. Inheritance can be a tough nut sometimes. Any suggestions around best practices on how to avoid such problems in future?
Comment: Mainly one suggestion: use your own coding conventions, like "always name the inflated View the same, e.g. 'root'." This way, your last statement will of course be "return root;" And maybe (may not apply here) run tests more often so harmful changes will surface earlier
Comment: BTW I found out what was wrong when I used the problem Fragment standalone in an otherwise empty Activity and got an Exception because the Fragment's View already seemed to have a parent. Suddenly the last line in onCreateView() was a very important line to look at, and then everything made sense.


incrementing a void pointer

Question:
Possible Duplicate:
void * arithmetic

Hi guys I have a small question regarding pointer increment in C. First let say that I know that ptr++, where ptris a pointer will increment as much as the sizeof(*ptr). Also I know that when doing *ptr, the compiler knows it has to grab sizeof(*ptr) bytes from memory.
The second part helps me understand why the following does not even compile:
int main(){
 int a = 3;
 void* b = &a;
 printf("%d\n", *b);
 return 0;
}

Because the compiler does not know the size of a variable of type void. However, I'm a little bit confused about the following code:
int main(){
 int a = 3;
 void* b = &a;
 printf("%p\n", b);
 b++;
 printf("%p\n", b);
}

So, my two questions are:

How is the compiler able to know how much it should increment b?
Why does it increment only one byte (at least in my machine is one byte)?
Comment: http://stackoverflow.com/questions/3922958/void-arithmetic
Comment: What's with all the trailing whitespace on the `printf` line of the 1st snippet? Ugh!
Answer: 1) it doesn't, 2) that's undefined behaviour. void is an incomplete type, so it doesn't have a well-defined size, so you cannot do pointer arithmetic with its pointers.
Typically you will want char pointers for byte-wise memory fiddling.
If you compile with all compiler warnings enabled, you will spot such problematic code.
Comment: Well, you don't necessarily need _all_ the warnings, but you should definitely try a few of them on for size.
Comment: @ChrisLutz: In GCC, I'd recommend `-W -Wall -Wextra -pedantic` (hence "all"), which gives you a *very* good basis. The compiler offers some more esoteric and subjective warnings (like `-Weffc++` for C++ for checking conformity to Scott Meyers's C++ book!) which I'm happy to skip ;-) Basically any warning that lets you know about blatant misuse of the language should be enabled...
Comment: gcc provides arithmetic on void pointers as an extension though. It treats the size as 1 when doing arithmetic. http://gcc.gnu.org/onlinedocs/gcc-4.6.1/gcc/Pointer-Arith.html
Comment: @KerrekSB - I use `-Wall -Wextra -Werror` and a few others as well, but one of those (I think it's `-Wall`) turns on a warning for `if(x = something)`, which I don't like (I think the double parenthesized version it recommends to silence the warning is ugly). I wish you could disable warnings as easily as you could enable them.
Comment: @ChrisLutz: Really? I get: `warning: suggest parentheses around assignment used as truth value [-Wparentheses]` This is on GCC 4.6.2.
Comment: @KerrekSB - That's the warning I don't like. I just find the extra parentheses to be a bit too Lispy.
Comment: @ChrisLutz: Ah, I understand. In your case you want `-Wno-parentheses` then :-)

incrementing a void pointer