How can i on button press execute a command in the command prompt and get back the output in ActionScript?

Question: I have a GUI using Flex. I have a condition like i need to execute some command line arguments in the local machine and get the results back or output back to a textbox area. How can i do a button on submit, execute command in the local machine and return the output?
Command to execute example:

    echo logfile.log | grep username

Code:

button1.onRelease = function ()
{
    // in this computer, it will now run a command, please wait.
}

My reference from the answer: https://gist.github.com/993905
Comment: I would like to do the same for AS2, AS3 too.
Comment: Laura please see my answer. This just isn't possible with AS2 or even AS3 from within the browser. You need native extensions and the flash player specifically avoids this to avoid security issues. You need a modified flash player projector or, in the best case, Adobe AIR 2.0 or greater which would require the use of Actionscript 3.
Comment: button1.onRelease is AS2 why are you tagging it for AS3?
Answer: You're not going to be able to do this using actionscript 2 and you're not going to be able to do this using actionscript 3 in the flash web player. There are certain tools you can use to create projectors using actionscript 2 and 3 to add this kind of extended capability but you cannot simply do it from the web, as of course this would be an extreme security risk.
However, you can do this with Adobe AIR 2.0 or greater. You use the NativeProcess class and detect the operating system, launch the terminal or cmd.exe and then you can run commands against it. Below is some code from a project I developed to run commands against the OS using AIR just as you're trying to do:
private var os:String;
private var consoleExecutable:File;
private var consoleNativeProcess:NativeProcess;

private function usbMounted(e:StorageVolumeChangeEvent):void
{
    //status.appendText('Device: ' + e.storageVolume.name + ' mounted to drive: ' + e.storageVolume.drive + '\n');

    os = Capabilities.os.substr(0, 3).toLowerCase();

    switch (os)
    {
        case "win":
            //Windows OS
            var rootDirs:Array = File.getRootDirectories();

            var i:int = 0;
            for (i; i < rootDirs.length; ++i) {
                consoleExecutable = rootDirs[i] as File;
                consoleExecutable  = consoleExecutable.resolvePath("Windows");
                if (consoleExecutable.exists == true) {
                    consoleExecutable = consoleExecutable.resolvePath("System32");
                    consoleExecutable = consoleExecutable.resolvePath("cmd.exe");
                    i = rootDirs.length;
                }
            }

        break;

        case "lin":
            //Linux OS

        break;

        case "mac":
            //Mac OS

        break;

        case "iph":
            //Iphone OS

        break;
    }

    var consoleNativeProcessStartupNfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
    consoleNativeProcessStartupNfo.executable = consoleExecutable;
    var startupArgs:Vector.<String> = new Vector.<String>();

    startupArgs.push('/C fsutil fsinfo volumeinfo ' + e.storageVolume.drive + ':');

    consoleNativeProcessStartupNfo.arguments = startupArgs;
    consoleNativeProcess = new NativeProcess();
    consoleNativeProcess.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, consoleOutput);
    consoleNativeProcess.start(consoleNativeProcessStartupNfo);
    consoleNativeProcess.closeInput();
}

private function consoleOutput(e:ProgressEvent):void
{
    var consoleOuput:String = consoleNativeProcess.standardOutput.readUTFBytes(consoleNativeProcess.standardOutput.bytesAvailable);

    switch (os)
    {
        case "win":
            //Windows OS

        break;

        case "lin":
            //Linux OS

        break;

        case "mac":
            //Mac OS

        break;

        case "iph":
            //Iphone OS

        break;
    }

    consoleNativeProcess.exit();
}

So the code should be pretty straight forward. It might not all be there as I've just copied the portion of the code dealing with the native process startup, output and termination. I then deleted parts of the code that were sensitive. Basically you're just getting the OS info, navigating to the path of the executable, check to see if it exists and if so, start it up, run a command against it and wait for output. I put in a switch statement to check the OS when handling the output as well, since it's safe to assume what you do next with the output will also be OS dependent (or at least in my case it was). If you need more help understanding all this I suggest googling for a tutorial on the Adobe AIR Native Process API or just post some more questions here. :)
Comment: Also note as one example of how this code isn't quite complete, the code starts off with me receiving a StorageVolumeChangeEvent because in this application I am acting whenever a new USB key is mounted. The part of the code that listens for these events, as well as import statements are missing.


If two biased coins show the same side, what is the probability that the two coins were taken from the same box?

Question: Two identical boxes contain biased coins. Each coin in box $1$ shows head with probability $1/4$, and tails with probability $3/4$, while each coin in box $2$ shows heads with probability $1/3$, and tails with probability $2/3$. Twice we choose one box at random and take a coin from that box. Each of the two coins is then tossed once. If the two coins show the same side, what is the probability that the two coins were taken from the same box?
Currently, I have the following.
Let
$A = \{\text{Box 1 is chosen}\}$, $B = \{\text{Box 2 is chosen}\}$, $C = \{\text{A coin shows heads}\}$, $D = \{\text{A coins shows tails}\}$, $E = \{\text{Both coins show the same side}\}$, $F = \{\text{Both coins are taken from the same box}\}$
Then we must determine the following.
$$P(F|E) = \frac{P(E|F)P(F)}{P(E)}$$
Did I solve the following correctly?
$P(F) = 1/2$
$P(C)=P(C|A)P(A)+P(C|B)P(B) = 1/8 + 1/6 = 7/24$
$P(D)=P(D|A)P(A)+P(D|B)P(B) = 3/8 + 1/3 = 17/24$
$P(E)=P(C)P(C) + P(D)P(D) = \frac{7}{24}\frac{7}{24}+\frac{17}{24}\frac{17}{24}=169/288$
I am having trouble solving the following.
$P(E|F)=P(C|A)P(C|A)+P(D|A)P(D|A)+P(C|B)P(C|B)+P(D|B)P(D|B)=1/16+9/16+1/9+4/9=85/72$
What am I doing wrong?
Answer: This is how I would have done the question, to find $P(F|E)$ rather than $P(E|F)$:
The probability both coins come from the same box and both show the same side $P(E,F)$ is $$\left(\frac14\right)^2\left(\frac12\right)^2  +\left(\frac34\right)^2\left(\frac12\right)^2   + \left(\frac13\right)^2 \left(\frac12\right)^2 +\left(\frac23\right)^2\left(\frac12\right)^2  = \frac{85}{288}.$$
The probability both coins come from the different boxes and both show the same side $P(E,F^C)$ is $$2\left(\left(\frac14\right)\left(\frac12\right)\left(\frac13\right)\left(\frac12\right)+ \left(\frac34\right)\left(\frac12\right)\left(\frac23\right)\left(\frac12\right)\right) = \frac{84}{288}.$$
So you are correct when you say $P(E)=\frac{169}{288}$ as it is the sum of those two terms.
Given both coins show the same side, the probability both coins come from the same box $P(F|E)$ is $$\frac{\frac{85}{288}}{\frac{85}{288}+\frac{84}{288}}=\frac{85}{85+84}=\frac{85}{169}.$$
If you really wanted to calculate $P(E|F)$ then, using $P(F) = \frac12$, it would be ${\frac{85}{288}}/{\frac12} = \frac{85}{144}$ which as leonboy points out is half of your result.
Comment: Where it says "Given both coins show heads", you mean "Given both coins show the same side"?
Comment: @joriki: Yes, thank you - I started off in one direction and then changed the numbers
Answer: The first term in your computation of $P(E|F)$ corresponds to the events "both heads, both from box 1". The probability of that event is
$ P( A_1  C_1  A_2  C_2 | F) = P(C_1 C_2 | A_1 A_2 F) P(A_1 A_2 | F) = P(C|A) P(C|A) \frac{1}{2}$
The same goes for the other terms


Finding $\lim_{ n \to \infty }(1-\tan^2\frac{x}{2})(1-\tan^2\frac{x}{4})(1-\tan^2\frac{x}{8})...(1-\tan^2\frac{x}{2^m})=?$

Question: Find the limit :
$$\lim_{ n \to \infty }(1-\tan^2\frac{x}{2})(1-\tan^2\frac{x}{4})(1-\tan^2\frac{x}{8})...(1-\tan^2\frac{x}{2^n})=?$$
My try :
$$1-\tan^2 y = \frac{2\tan y }{\tan(2y)}$$
$$\lim_{ n \to \infty }\left( \frac{2\tan\frac{x}{2} }{\tan(x)}\right)( \frac{2\tan\frac{x}{4} }{\tan(\frac{x}{2})})( \frac{2\tan\frac{x}{8} }{\tan(\frac{x}{4})})...( \frac{2\tan\frac{x}{2^n} }{\tan(\frac{x}{2^{n-1}})})=?$$
Now?
Answer: Note that the numbers in the deonominator and numerator cancel, leaving only $$\lim_{n \to \infty} 2^{n} \frac{\tan \frac{x}{2^n}}{\tan x}$$
In your original equation. However, as $\lim\limits_{n \to \infty} \frac{x}{2^n}=0$, we have that $$\lim_{n \to \infty} 2^n \tan \frac{x}{2^n}=\lim_{n \to \infty}x \times \dfrac{ \tan \frac{x}{2^n}}{\frac{x}{2^n}} =x$$
Using the fact that $\lim\limits_{a \to 0}\frac{\tan a}{a}=1$. So the limit becomes $$\lim_{n \to \infty} 2^n \times {\tan \frac{x}{2^n}} \times \frac{1}{\tan x}= \frac{x}{\tan x}=x \cot x$$
The answer is $x \cot x$.


Função js funciona apenas uma vez

Question: Tenho uma página que pesquisa os dados do cliente pelo código e exibe numa tabela. O problema é que eu sempre preciso atualizar a página para conseguir fazer uma nova pesquisa, o botão só funciona uma vez. O que devo fazer? Segue meu código:
PHP:
$funcao = post('funcao');

if($funcao == 'pesquisa') {
  $codcliente = post('codcliente');

  $codempresa = '';
  $codveiculo = '';

?>

                Codigo Cliente
                Cliente
                Veículo - Tabela Cliente
                Veículo - Tabela Evento
                Novo Veículo

<?

$sql = "select cli.codempresa,
               cli.codcliente,
               cli.nome cliente,
               ve.codveiculo codveiculo_cliente,
               ve.nome veiculo_cliente,
               veic.codveiculo codveiculo_evento,
               veic.nome veiculo_evento
        from cliente cli
        inner join evento ev on ev.codcliente = cli.codcliente
        inner join veiculo ve on ve.codveiculo = cli.codveiculo
        inner join veiculo veic on veic.codveiculo = ev.codveiculo
        where cli.codcliente=$codcliente;";
$rst = my_query($connR, $sql);

if(!empty($rst)) {
    $codempresa = $rst[0]['codempresa'];

    $sqlve = "select ev.codempresaveiculo, ev.codempresa, ev.codveiculo, ve.nome
          from empresaveiculo ev
          inner join empresa emp on emp.codempresa = ev.codempresa
          inner join veiculo ve on ve.codveiculo = ev.codveiculo
          where ev.codempresa=$codempresa
          and ev.indcadastromanual=1
          order by ve.nome;";
    $rstve = my_query($connR, $sqlve);
    $selectveiculo = getOptionSelect($rstve, 'codveiculo','nome');
    $codveiculo = $rstve[0]['codveiculo'];
    $codveiculo = explode('|',$codveiculo);
    $codveiculo = $codveiculo[0];
    $nomeveiculo = $rstve[0]['nome'];
    $nomeveiculo = explode('|',$nomeveiculo);
    $nomeveiculo = $nomeveiculo[0];

} else {
    echo "";
}

foreach ($rst as $row) {
?>

        <?=$row['codcliente']?>
        <?=$row['cliente']?>
        <?=$row['veiculo_cliente']?>
        <?=$row['veiculo_evento']?>

            <select class="form-control" name="codveiculo" id="codveiculo" data-target="" style="width: 250px;"><?=$selectveiculo?></select>

    <?
}
?>

<?
exit;
}

HTML

            <form class="form-inline" method="post" name="formpesq" action="/trocarveiculo.php" id="formpesq" style="margin-bottom: 0.25em; padding-top: 0.25em;">
                <input type="hidden" name="funcao" id="funcao" value="pesquisa" />

                    Código do cliente
                    <input type="text" class="form-control" name="codcliente" placeholder="123456" id="codcliente" style="width: 250px;" onkeypress='return SomenteNumero(event)' />
                    <button type="button" id="botao" name="botao" onclick="javascript:pesquisar();" class="btn btn-default">Buscar</button>

            </form>

JS:

Comment: É por causa disso: `event.preventDefault();`
Comment: Então, tirei o `prevent` e mesmo assim não rolou ainda ;(
Comment: Dá algum erro no console ?
Comment: Não, inclusive a requisição manda o segundo código que eu tento pesquisar, mas a tabela não muda.
Answer: Basicamente sua

 é removida com o $("#tabela").replaceWith(). Então depois da primeira requisição não existe mais nenhum elemento com id tabela. Mude para $("#tabela").html() talvez resolva seu  problema.
Comment: Deu certo, era o que eu precisava ! Muito obrigada !!!

Função js funciona apenas uma vez


Server 2019 Domain Controller SMBclient cannot map NetApp Drives

Question: I am supporting Windows again after many years. This client I'm assigned to has Domain Controllers running 2008r2 and 2012r2 and they want Azure AD Connect Password Hash Sync. The minimum requirement for this is a functional level of 2016.
I installed a new Server 2019 instance, migrated the FSMO roles, and ensured all DCs are replicating to each other. I created a new domain user and ran the logon script that maps a few network drives from an old NetApp FAS2552 running Ontapp 184.108.40.206. This was successful.
After applying patches and rebooting, the new DC will no longer connect the drives. I believe it has something to do with KDC changes made in November 2022, but I'm not sure.
I added another Server 2019 instance to the network, logged in locally, and connected the NetApp drives successfully. Then I installed Windows Security Updates, and after a reboot the drives failed the same way as they do on the new DC.
After digging around, I found a couple of things:
This article
And a random bit about some Registry changes:

reg add HKLM\system\currentcontrolset\services\kdc /v KrbtgtFullPacSignature /t REG_DWORD /d 0 /f
reg add HKLM\system\currentcontrolset\services\kdc /v ApplyDefaultDomainPolicy /t REG_DWORD /d 0 /f
reg add HKLM\system\currentcontrolset\services\netlogon\parameters /v RequireSignorSeal /t REG_DWORD /d 0 /f

These changes worked on the test instance and the NetApp drives connected again. So long as the %logonserver% is one of the old Domain Controllers.
These changes do not work on the new domain controller, and when any client uses it as their %logonserver%, the drives fail to connect.
I'm ready to uninstall Windows Security updates to see if the NetApp drives connect again. Then inform the client their environment cannot be patched until they upgrade their NetApp OS to support AES KDC auth.
Any help is much appreciated.
Answer: If it's about 2022 November patch, you may check whether NetApp support AES encryption type.
New flag introduced in 2022,Nov.
J AES256-CTS-HMAC-SHA1-96-SK
Comment: Thanks for your reply. I stated that my only option was to ask the client to upgrade Ontapp to 8.3 or higher to support AES auth. I'm looking for a solution for Server 2019 Domain Controllers because the solution I shared works on Server 2019.


Opening multiple windows with one click in javascript function

Question: I use the toggleDays class to expand and collapse my requests. Each request (obj) has multiple entries of Days that are links to open new tabs. For example; Request-1 can have Day-1, Day-2. Request-2 can have Day-1, Day-2 and Day-3.
My issue is when if I click on Day-1 of Request-2, it opens a new tab for Day-1 of Request-1 as well as the correct tab of Request-2. How can I make sure that I'm only opening the Day for a particular request I clicked and not all. Below is my code. Any help would be appreciated!
Thanks in advance!
May
    function GetSpecificRequest(requestId, that) {
    var parms = "{'requestId' :'" + requestId + "'}";

    jQuery.ajax({
        type: "POST",
        url: "DisplayRequests.aspx/GetSpecificRequest",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: parms,
        success: function (response) {

            if (response.d != '') {
                var obj = JSON.parse(response.d);

                $.each(obj, function (index, item) {

                    that.next('.toggleDays')
                        .append('

Day:  ' + '' + item.RQST_ID_CNTR + '
</div')
                        .append('

Print Date:  ' + $.datepicker.formatDate("mm/dd/yy", (new Date(parseInt(item.RQST_CYCL_DT.substr(6))))) + '
</div')
                        .append('

Status:  ' + item.RQST_STAT_CD + '
</div')
                        .append('

Copies Matched:  ' + item.RQST_NBR_MTCH + '
</div')
                        .append('
</div');
                });

                $('.dayRequest').bind('click', function () {
                    var day = $(this)[0].innerHTML;
                    window.open("DisplaySearchCriteria.aspx?RequestID=" + requestId + "&RequestCtr=" + day);
                });
            }
            return false;
        },
        error: function (httpRequest, textStatus, errorThrown) {
            LogAjaxErrorToServer(httpRequest, textStatus, errorThrown, parms, "GetSpecificRequest");
        }
    });
}

Answer: You keep binding to the click event of all .dayRequests for each obj. You can add an ID to your link and bind to that. i.e.
.append('

Day:  ' + '' + item.RQST_ID_CNTR + '
</div')

 $('#' + requestId).bind('click', function () {
     var day = $(this)[0].innerHTML;

Or add the requestId as a data attribute to your links and bind to click outside your ajax call.
.append('

Day:  ' + '' + item.RQST_ID_CNTR + '
</div')

on your document.ready:
$(document).bind("click", ".dayRequest", function()
{
    //take attributeid here
});

Comment: Thanks for your reply artm..that does stop the code from running multiple times. But the new issue is I can't get the value of the DAY anymore since innerHTML returns everything associated with the '#'. Any suggestions?


row,column detection in OpenCV (OCR preprocessing)

Question: first my final goal is to process the following image with tesseract:
http://ubuntuone.com/72m0ujsL9RhgfMIlugRDWP
(I wiped out the second and the third column...)
However tesseract has problems with the dotted background. So my idea is to pre-process the image with OpenCV. The best would be if I could somehow detect each line, because I need to remove the dotted background by applying a different threshold than to even lines. Is there any solution to solve my problem? So far I have found Hough Transformation and maybe segmentation, but the results weren't very good (maybe because of wrong parameter)... But I'm not sure, if these are possible approaches and what I invest my time best on.
Column detection would be fine, too, because the second column contains numbers and the third characters, only. Passing this "knowledge" to tesseract could improve its detection rate even more.
I would be really thankful if somebody could give me some hints how to solve this issue and which OpenCV functions are used best, with which paremeters. Some snippets that give me a fair idea about the different steps would be helpful, too.
Thank in advance!!!
Kind regards.
Comment: Did you find a solution for this? If so please share as i also have a similar issue. Also the image link is no longer available. Could you update that too? Thansk
Answer: I would suggest you use something like erosion, as the dots seem to be rather small as compared to the width of the letters.
OR I would Canny edge detection with proper thresholds so that I would discard the rather short and thin edges of the dots.
Hope this helps, have fun!
Comment: Hi, thanks for your reply. I already tried erosion, however this kind of "destroyed" the characters and so the ocr. As already said I would prefer an approach segmenting (line+row=>cell) the image properly, because this would help to define the expected content for tesseract.


nrfutil changes python version mid-script

Question: I'm using nrfutil in a shell script. It's failing with this error:
<code>Traceback (most recent call last):
  File "/usr/local/bin/nrfutil", line 6, in <module>
    from nordicsemi.__main__ import cli
  File "/Library/Python/2.7/site-packages/nordicsemi/__main__.py", line 57, in <module>
    from nordicsemi.zigbee.prod_config import ProductionConfig, ProductionConfigWrongException, ProductionConfigTooLargeException
  File "/Library/Python/2.7/site-packages/nordicsemi/zigbee/prod_config.py", line 41, in <module>
    import yaml
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/yaml/__init__.py", line 374
    class YAMLObject(metaclass=YAMLObjectMetaclass):
</code>
It's starting in python 2.7, then it looks like its running "import yaml" from a 3.6 library.
Why would it do this? How do I prevent it?
Thanks
Comment: I would think that you should be running python 3 at this point. If you are still running 2.7 I would-suggest a fresh python 3 install.
Answer: I had an old version of nrfutil. I upgraded, all is good


How to map 2 different methods from the same class to GET request in spring boot?

Question: I created a REST API in java with spring boot , but when I try to run it I get some error that it has already mapped one method from one of the controller classes to the get method and it can't map another one even though they have different names. Ex: /drugs/filtered/{amount} and /drugs/report
Here is the code
    @RestController
    @AllArgsConstructor
    public class DrugController {
           private DrugService service;
           private DrugConverter drugConverter;

    @RequestMapping(name = "/drugs", method = RequestMethod.POST)
    public DrugDTO handleAddDrug(@RequestBody DrugDTO dto) {
        Drug addedDrug = service.addDrug(
                dto.getId(),
                dto.getName(),
                dto.getRecommendedAmount());
        return drugConverter.convertModelToDto(addedDrug);
    }

    @RequestMapping(name = "/drugs", method = RequestMethod.PUT)
    public DrugDTO handleUpdateDrug(@RequestBody DrugDTO dto) {
        Drug updated = service.updateDrug(
                dto.getId(),
                dto.getName(),
                dto.getRecommendedAmount());
        return drugConverter.convertModelToDto(updated);
    }

    @RequestMapping(name = "/drugs/{id}", method = RequestMethod.DELETE)
    public DrugDTO handleDeleteDrug(@PathVariable Integer id) {
        Drug deletedDrug = service.deleteDrug(id);
        return drugConverter.convertModelToDto(deletedDrug);
    }

    @GetMapping(name = "/drugs/{id}")
    public DrugDTO handleGetDrug(@PathVariable Integer id) {
        Drug drug = service.getDrug(id);
        return drugConverter.convertModelToDto(drug);
    }

    @GetMapping(name = "/drugs")
    public DrugsDTO handleGetAllDrugs() {
        Collection<Drug> drugs = service.getAllDrugs();
        return new DrugsDTO(drugs.stream().map(drugConverter::convertModelToDto).collect(Collectors.toSet()));
    }

    @GetMapping(name = "/drugs/filtered/{amount}")
    public DrugsDTO handleGetDrugsWithDoseBiggerThan(@PathVariable Integer amount) {
        Collection<Drug> drugs = service.getDrugsWithDoseBiggerThan(amount);
        return new DrugsDTO(drugs.stream().map(drugConverter::convertModelToDto).collect(Collectors.toSet()));
    }

    @GetMapping(name = "/drugs/report")
    public DrugsDTO handleGetDrugsWithDosesOf() {
        Collection<Drug> drugs = service.getDrugsWithDosesOf();
        return new DrugsDTO(drugs.stream().map(drugConverter::convertModelToDto).collect(Collectors.toSet()));

    }
}

And this is the error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'drugController' method  BloodManagement.ServerSide.Controller.DrugController#handleGetDrug(Integer) to {GET []}: There is already 'drugController' bean method BloodManagement.ServerSide.Controller.DrugController#handleGetAllDrugs() mapped.
Answer: Try changing the parameter name to value on all your mapping.
i.e.:
@GetMapping(name = "/drugs")

becomes
@GetMapping(value = "/drugs")


How to deal with array pointers in ruby Fiddle

Question: I am trying to switch from Ruby FFI to Fiddle, which is now part of Ruby std lib.
It is pretty undocumented though, and I am having a hard time in figuring out how to deal with arrays and pointers. In particular, how can I write a Fiddle interface to a C function like this:
void my_func(double *, size_t len)

Mapping it into Ruby is pretty easy:
module Test
  extend Fiddle::Importer
  dlload './lib/libTest.dylib'
  extern 'void my_func(double *, size_t)'
end

But then how can I build a pointer to an array, to be passed as a first argument?
Thanks!
Answer: you mean build an c array and this array`s pointer in ruby?
you can try like this:
free = Fiddle::Function.new(Fiddle::RUBY_FREE, [TYPE_VOIDP], TYPE_VOID)
p = Pointer.malloc(SIZEOF_DOUBLE*len, free)

and call like this:
my_func(p,len)

ruby GC will call the free function when this memory block will not be used.


Meaning of the Rank of a Map of Free Modules?

Question: I am reading the section on differentials in Eisenbud's book (Commutative Algebra), and I'm just wondering what he means in sentences like this one:
"Suppose that $J:R^t \rightarrow R^r$  is a map of free modules over a ring $R$ whose rank is less than or equal to $c$, as for the Jacobian matrix of an ideal of codimension $c$..." (Chapter 16.7, Page 407)
I'm not sure what "rank" stands for in this generality (where the image need not be free). Vanishing of minors?
Comment: You might check out section 1.4 of Bruns and Herzog's "Cohen Macaulay Rings", starting at page 20.  Definition 1.4.2 and Proposition 1.4.3 might be helpful.
Answer: Presumably it means the largest $k$ such that the induced map $\Lambda^k(J) : \Lambda^k(R^t) \to \Lambda^k(R^r)$ on exterior powers doesn't vanish. (This is a coordinate-free restatement of a condition on vanishing of minors.) At least, that would be my guess. Does the rest of the statement make sense with this interpretation?
Comment: I would have to brush up on my exterior powers (and I will!) to see if your interpretation fits as well, but I do think mbrown's lines up pretty nicely with what Eisenbud is doing. The $R$s that Eisenbud actually deals with wind up being domains, so it seems reasonable that he could mean the rank of the map induced by localization at 0 (he does mention vanishing of minors though).
Comment: @Cass: if $R$ is a domain, the two conditions should be equivalent.


$\frac{P(x)}{x^2+3}$ is $2x+5$, find the remainder of $\frac{[P(x)]^2}{x^2+3}$

Question: The remainder of $\frac{P(x)}{x^2+3}$ is $2x+5$
$$$$
Find the remainder of
$$\frac{[P(x)]^2}{x^2+3}$$
The approach I have attempted for this exercise is to write $P(x)=(x^2+3)Q_1(x)+2x+5 ...(1)$ and also
$$[P(x)]^2=(x^2+3)Q_2(x)+ax+b...(2)$$
Now, in (1):
$$[P(x)]^2=(x^2+3)^2Q_1^2(x)+4x^2+25+4x(x^2+3)Q_1(x)+20x+10(x^2+3)Q_1(x)$$
For the remainder the only terms I need to consider are lineal and independent, given that the degree of $x^2+3$ is $2$, but I have had struggles, because $Q_1(x), Q_2(x)$ degrees are unknown, and that's where I get stuck. Any other way to approach this exercise or hint to continue with what I am doing?
Comment: $\bmod x^2+3\!:\ P\equiv 2x\!+\!5\Rightarrow P^2\equiv (2x\!+\!5)^2.\,$ Expand that using $\,x^2\equiv -3\,$ to get the sought remainder.
Comment: Thank you so much, by doing this, I actually got the correct answer!
Answer: Your expression for $[P(x)]^2$ can be rewritten
$$Q_3(x)(x^2+3) + 4x^2+20x+25.$$
It doesn't matter what the degree of $Q_3$ is.  All you have to do is divide $4x^2+20x+25$ by $x^2+3.$


Commerce - how do I set a discount to a specific user's next order only?

Question: I'm making an e-commerce site for a friend.
The point of his shop is to sell honey in jars. When people return the jars, they get a 2 euro discount on their next order.
I've tried several things so far but if I give the user a discount, it continues to give the discount. I only want it the discount for the next order. Same goes for other ways I've tried it. I'm not quite sure how to set these specific conditions.
Answer: Generic solution
I think you need to write some custom code to get a solution that will work automatically. This could be handled by a custom Rules condition - meaning hook_rules_condition_info() implementation. After you add the code below, make sure to add this condition through Rules interface as well. Here's example code that would go in YOUR_MODULE.rules.inc:
function YOUR_MODULE_rules_condition_info() {
  return array(
    'YOUR_MODULE_rules_condition_check_next_order_discount' => array(
      'label' => t('Sample condition'),
      'parameter' => array(
        'order' => array(
          'label' => t('Order')
          'type' => 'commerce_order',
        ),
      ),
      'group' => t('Custom'),
    ),
  );
}

function YOUR_MODULE_rules_condition_check_next_order_discount($order) {
  // Perform any checks you want here, load the owner, see previous orders, etc.
  $customer = user_load($order->uid);
  if ($whatever) {
    return TRUE;
  }

  // I recommend doing this the other way around: by default visitors shouldn't be
  // able to have the rights for this discount, but they can get it IF they fulfill
  // your rules above.
  return FALSE;
}

Note: the YOUR_MODULE.rules.inc file would be loaded automatically, and you don't have to include it in the .info file of your module.
One-off solution
In case I misunderstood your question, here's how to configure the discount to have this work only once:

"Apply to" fieldset, add "User" and there select the target user.
Set the value of "Maximum usage per customer" field to 1.

Hope this helps.
Comment: It would actually not be a set rule because there are also other items than honey (for example, candles and such) which would not give a discount. So basically, I want to manually give the discount to a specific account every time I receive the jars back from them so I'm sure no discount is given for no reason.
Comment: Okay, then the one-off solution should work for you I think.
Comment: Wouldn't that just allow me to do it once? Instead of every time I receive the jars from the clients?
Comment: Yep; to do this in a better way, you need to describe your workflow in full: is the discount always the same for all clients, can they accumulate them (e.g. someone has the right for 3 discounts), can they return to you multiple times (e.g. can they accumulate the number of orders they can get the discount on), and so on. On one hand, this sounds as an on/off flag, but at the same time it might be more complex than that (e.g. integer field where you store the number of times the user can use a discount). Hope this makes sense.
Answer: I would take a different approach here, but just note that nothing that I know of would support this out of the box without additional code. The big issue is that your discount is a flat amount off of an order as opposed to an amount off of the unit price of a product, but the Commerce Discount module's order level discounts don't have the necessary conditions to set the price accordingly.
Basically, I'd add a field to the user that represents how many jars they've returned. Presumably, they might return multiple and get even more off of their next order. This field would need to be hidden from their edit form, though it's reasonable for it to appear when they view their own user profile so they know how much to expect off of their next order.
You then need to create new inline condition code in a custom module that can read this field and apply a discount if the value of the field is > 0. This is actually pretty straightforward and could be done without using Commerce Discount / inline conditions, but the problem is you really need Commerce Discount to get the $ off the order total correct.
Then for actually applying the discount to the order, you can do one of two things: you can define a new offer type that knows how to look at the user's profile to determine how large the discount should be or you can is the $ off offer type but alter the line item after the fact to be the correct amount (presumably on pre-save).
Completing the process, you need a custom rule to fire when the order is first paid in full (this is the name of the relevant event) to set the user's jar count back to 0. Not sure how you process refunds, but you'll most likely just need to reset the jar count manually in the event of a refund.
Answer: I agree with Ryan's suggestion above, however if you don't want to write custom code, I recently provided a patch for Discount Extra that allows you to use a rules component as a discount condition. You could then just write the component to check that the user has returned jars > 0 in the profile field Ryan mentioned.
The above assumes that the discount is a maximum of 2 Euro per order and not based on the number of jars they have returned. If you want it to be based on a discount for the number of jars returned (e.g 2 jars is 4 Euro discount), then you will need some custom code to look at the jar count and apply the discount accordingly.


Concavity of negative binomial GLM

Question: I need to estimate the log-likelihood of the negative binomial regression. I mean full log-likelihood, including the dispersion parameter.
The problem is: when I start LBFGS, BFGS, or gradient descent procedures, they estimate the dispersion parameter all differently depending on the starting point. I use this for the derivatives: https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/NCSS/Negative_Binomial_Regression.pdf
Is the negative binomial regression log-likelihood actually concave?
PS. I know that glm.nb in R estimates the dispersion in steps - first it estimates the linear coefficients with the Newton method, then it estimates the dispersion, then it comes back to linear coefficients, and so forth. This seems to give the same result not depending on the starting point. But I do not understand why it is done this way.
PPS. Links are welcome.
Answer: It is relatively simple to write the log-density of the negative binomial distribution in terms of its mean, and then use this to get a log-likelihood expression for the negative binomial GLM.  For all values $y=0,1,2,...$ the log-density of the negative binomial distribution is:
$$\log f(y|r,\theta) = \log {y+r-1 \choose y} + r \log (1-\theta) + y \log (\theta).$$
If we let $\mu \equiv \mathbb{E}(Y)$ denote the mean of the distribution then we have the relationships:
$$\mu = r \cdot \frac{\theta}{1-\theta}
\quad \quad \quad \theta = \frac{\mu}{r+\mu}.$$
Thus, we can re-parameterise the log-density in terms of its mean parameter to obtain the log-likelihood for a single data point:
$$\ell_y(r,\mu) \equiv \log f(y|r,\mu) = \log {y+r-1 \choose y} + r \log (r) + y \log (\mu) - (r+y) \log (r+\mu).$$
The derivatives with respect to $\mu$ are:
$$\begin{aligned}
\frac{d\ell_y}{d \mu} (r,\mu)
&= \frac{y}{\mu} - \frac{r+y}{r+\mu}, \\[6pt]
\frac{d^2 \ell_y}{d \mu^2}  (r,\mu)
&= -\frac{y}{\mu^2} + \frac{r+y}{(r+\mu)^2}. \\[6pt]
\end{aligned}$$
Letting $\hat{\mu}$ be a critical point of the log-density, we obtain:
$$\frac{d^2 \ell_y}{d \mu^2}  (r,\hat{\mu})
= -\frac{y}{\hat{\mu}} \Bigg[ \frac{1}{\hat{\mu}} + \frac{1}{r+\hat{\mu}} \Bigg] <0.$$
This shows that all the log-likelihood for a single data point has a single maximising value for its mean parameter, and so it is quasi-concave with respect to the mean parameter.  (The log-likelihood function is not concave in $\mu$, but it is quasi-concave in $\mu$ for all $r$.)  Unfortunately, this simple result gets more muddied when we transition to the log-likelihood for multiple data points in the negative binomial GLM.

Negative binomial GLM: In the negative binomial GLM we have data $Y_i \sim \text{NegBin}(r, \mu_i)$ where the value $\mu_i$ is determined from a corresponding explanatory variable $\mathbf{x}_i$ using a link function.  Written in general terms, using the mean vector $\boldsymbol{\mu}$ the log-likelihood of the data $\mathbf{y}=(y_1,...,y_n)$ is:
$$\ell_\mathbf{y} (r, \boldsymbol{\mu}) = \sum_i \log {y_i+r-1 \choose y_i} + n r \log (r) + \sum_i y_i \log (\mu_i) - \sum_i (r+y_i) \log (r+\mu_i).$$
In the standard negative binomial GLM we use the link function $\log \mu_i(\boldsymbol{\beta}) = \sum_k \beta_k \cdot x_{i,k}$, which gives the likelihood function:
$$\begin{aligned}
\ell_\mathbf{y} (r, \boldsymbol{\beta})
&= \sum_i \log {y_i+r-1 \choose y_i} + n r \log (r) \\
&\quad + \sum_i y_i \sum_k \beta_k \cdot x_{i,k} - \sum_i (r+y_i) \log (r+\mu_i(\boldsymbol{\beta})).
\end{aligned}$$
The derivatives of this function with respect to the model coefficients are:
$$\begin{aligned}
\frac{\partial \ell_\mathbf{y}}{\partial \beta_k} (r, \boldsymbol{\beta})
&= \sum_i y_i \cdot x_{i,k} - \sum_i (r+y_i) \cdot x_{i,k} \cdot \frac{\mu_i(\boldsymbol{\beta})}{r+\mu_i(\boldsymbol{\beta})}, \\[6pt]
\frac{\partial^2 \ell_\mathbf{y}}{\partial \beta_k \partial \beta_l} (r, \boldsymbol{\beta})
&= - \sum_i (r+y_i) \cdot \frac{\mu_i(\boldsymbol{\beta})}{r+\mu_i(\boldsymbol{\beta})} \Bigg( 1- \frac{1}{r+\mu_i(\boldsymbol{\beta})} \Bigg) \cdot x_{i,k} \cdot x_{i,l}. \\[6pt]
\end{aligned}$$
As you can see, these derivatives are more complicated than in the case of a single data point.  This is owing to the fact that we now have $n$ data points, and we are looking at derivatives with respect to the model coefficients, rather than the mean value.
Comment: True, but even for many points, the log-likelihood is still concave. Which can be seen from writing neg.bin regression in the exponential form if the parameter $r$ is preset (I use the NB2 parameterization with variance $\mu + \alpha \mu^2$). However, if the $r$ is also estimated, then the function still has one maximum, but it is not concave anymore. So it breaks all 2nd order methods if they accidentally fall into the wrong region. It is a shame such a basic fact is not explained anywhere, and all the books talk about the optimization with Newton method, overlooking this basic fact.
Comment: The first part of your solution only certifies that $\hat\mu$ is a local maximizer. It does not show that the log-likelihood is concave. For it to be concave, you would need the second derivative to be nonpositive everywhere, yes? Also, you claim this verifies quasi-concavity. How?
Comment: @WazyMaze: Quasi-concavity and global maximisation would follow in this case as a result of the ["only critical point in town test"](https://mathworld.wolfram.com/OnlyCriticalPointinTownTest.html).
Comment: Ah, that's a neat result! I think your answer (while very helpful, and correct) should more clearly state the log likelihood is not globally concave, though. One can cook up values of $r$ and $y$ over which the second derivative is positive for large $\mu$. Of course, for "off the shelf" maximum likelihood, this is superfluous, but better to be precise.
Answer: The answer is: NO, negative binomial regression is NOT CONCAVE when estimated with dispersion.
I do not know how to show this mathematically (since negative binomial WITH dispersion parameter does not belong to the exponential family), but I simply found a line in my parameter space, which is not concave. Here it is:

Target is the log-likelihood of the negative binomial model with 28 parameters, and $x$ ranges from 0 to 1 along the x-axis. I do not provide the numbers, but you can easily see from the picture, that the log-likelihood is not concave along the x-axis (concavity changes into convexity around 0.01).
In practice it means that during Newton method optimization, some of the Hessians become indefinite, which breaks the method (it tries to find the dispersion at infinity as seen from the picture). This is why glm.nb uses coordinate descent.

Concavity of negative binomial GLM


WordPress not recognizing theme in /themes/ folder

Question: Having a really baffling issue with permissions, WordPress and theme files.
I have a fresh install of WordPress and tried uploading the theme I made for my client. It uploaded fine but it doesn't show up in the Manage Themes menu. I checked everything was uploaded and it was. Checked permissions (even set them to 777 at one point) and they were fine. But the theme doesn't show up.
Here are the different scenarios I've tried:

Using the Install Themes menu and uploading a .zip (failed)
Duplicate twentyten folder and contents (worked)
Duplicate twentyten folder and used my theme files (failed)
Duplicate twentyten folder and used my theme files and their style.css (failed)
Uploaded my theme WITHOUT style.css (gave missing style.css error)
Uploaded my theme WITHOUT style.css and put in twentyten/created one from scratch (both failed)

I'm on my clients MediaTemple hosting and I've never encountered this error. Their support has yet to get back to us.
Does anyone have a similar problem? Solution? It's possible I can give you FTP access if needed.
CSS Head (changed values but format and everything is still the same):
/*
Theme Name: Example Theme
Theme URI: http://example.com/
Description: WordPress theme
Author: Company
Version: 1.0
*/

Edit: Trying to access the folder through my browser results in a 403 error (works fine on twentyten). style.css can be viewed from the browser.
Comment: Can you show your style.css's head?
Comment: Added to original question. Formatting wasn't working as a comment.
Comment: Strange. The only idea that comes to mind is style.css getting screwed up by either FTP transmission (Line endings, stuff like that) or style.css getting a [BOM](http://en.wikipedia.org/wiki/Byte_order_mark) by your editor, and that BOM messing up the parsing.
Comment: Well I thought that it could be from FTP transfer as well. So rather than uploading the file, I created one (through Transmit.app) and then copy and pasted my stylesheet in there. Same effect.
Comment: happy to investigate for you if you want... inbox me
Answer: If you are using a MULTI-SITE installation of Wordpress, you have to first go into Network Admin, select Themes from the left menu and enable the themes you like to use before they can appear on the "Manage Themes" page in the Site Admin section.
Answer: Perhaps you are missing a required template file?

At the very minimum, a WordPress Theme
  consists of two files:
style.css
index.php

http://codex.wordpress.org/Theme_Development
Comment: Im using bedrock and the index.php was in the `resources` directory
Answer: On Ubuntu 14.04 you can install the wordpress package simply using sudo apt install wordpress but then you have to set a link to the themes directory.
E.g. for your "newTheme":
ln -s /usr/share/wordpress/wp-content/themes/newTheme /var/lib/wordpress/wp-content/themes
Comment: WHY??!? WHY, UBUNTU?!? Do you have to ubuntuize _everything_? This answer deserves to be higher - Ubuntu installs a complete Wordpress in `/usr/share/wordpress`, but sets WP_CONTENT_DIR in the default config to point to `/var/lib/wordpress/wp-content`, which has symlinks to `/var/lib/wordpress/wp-content/[symlink]`, a _special copy_ of `wp-content` ... just like NOBODY EVER would expect. Thank you for unblocking me after hours of troubleshooting.
Comment: @Matt If you want the WordPress package provided by Debian and all other Debian-based distro means you probably want to have something as: *one* installation of WordPress for thousand of websites; upgrades handled by your package manager (for every website, instead of manually for each website); stability in mind; and files placed in the right standard way of your distribution.
The way it's packaged allows it. So, if you do not understand the Filesystem Hierarchy, it's your problem.
http://tldp.org/LDP/Linux-Filesystem-Hierarchy/html/Linux-Filesystem-Hierarchy.html
Answer: I bet you have some special characters in your templates. This once drove me nuts to find.
Check your Template files and/or rename them until the theme shows up. I used a german "ö" in a templates name.
Comment: Seeing as the OP is from Scottsdale, Arizona, it's kind of unlikely... But very good point, applies to all non-ASCII characters. Maybe this is it.
Comment: I did have an ampersand in the CSS Theme name, but that didn't seem to be the issue as I removed it trying to see if that was the problem.
Comment: +1 This could be another reason why the theme is not registering in the theme list. then you need at least the index.php, style.css files
Answer: I had a very similar problem. Spent a few hours before I found that somehow when I moved  my local site (probably using All-in-one Wp Migration plugin), a .htaccess file was created in the /wp-content folder.  I don't remember what was inside this file but I think it didn't matter.
After removing this file everything was ok.
Answer: Is the theme folder name different than everything else? Is the Theme Name in style.css different than everything else?
Comment: I have the directory as "exampletheme" and the Theme Name in style.css as "Example Theme". All my @subpackage values in the .php files are "exampletheme".

Edit: Changing any of those to be all the same has no effect.
Answer: I am guessing BOMs are the problem. They messed up my validation of a page once, as I tried to remove the BOM. Try using an editor and remove the BOMs. For Notepad++, the text editor I use, I just set the encoding to UTF-8 without BOM and saved. That solved my problem. Of course, your text editor may be different.
Answer: As I discovered at the end of tortuous troubleshooting, an old wp-config.php may cause newly installed themes to be undetected and invisible in /wp-admin/themes.php - I am not sure that you have the exact same problem but it looks very similar to mine and you might want to try your configuration with a wp-config.php newly generated by Wordpress.
Answer:
Make a backup of your styles.css
Copy the styles.css file from twentyforteen to your theme folder.
Only change the template name at the top of the file
Re-load the themes page in WordPress admin; once you've seen it working,
Further-modify the new styles.css file as needed.
Answer: The problem could have been, that you uploaded it in .zip
Answer: Your php setting might disable the scandir. It may cause the wordpress cannot scan the theme folder
Solution:
find php.ini. You may run php --ini to get the php.ini file location.
Open php.ini,Search for disable_functions, then you may removescandir parameter.
Save and restart your php services.


Let $f \in C^{\infty}(\mathbb{R}^n)$ be such that $\underline{0}$ is a local minimum point for every algebraic curve, is it $0$ a local minimum point?

Question: Let $f \in C^{\infty}(\mathbb{R}^n)$ be a real function such that $\underline{0}$ is a local minimum point for $f$ on every algebraic curve, i.e. for every algebraic curve $C$ there exists an $\epsilon > 0$ such that if $x \in B_{\epsilon}(\underline{0}) \cap C$ then $f(0) \leq f(x)$
Where  $B_{\epsilon}(0) := \{ x \in \mathbb{R}^n \; : \; ||x|| < \epsilon \}$ and $C$ is the set of points that belongs to the algebraic curve
(Observe that $\epsilon$ depends on $C$).
Is it true that $\underline{0}$ is necessarily local minimum point for $f$?
Answer: Probably we can give an explicit example, but being lazy we can use Whitney extension theorem to only have to talk about some of the values at some points or sets of points, and the rest gets filled up by Whitney.
Consider the sequence of points $p_n=(1/n, e^{-n!})$ and circles $c_n=\{\|x-p_n\|=e^{-n!}\}$. The $e^{-n!}$ is there to decrease faster than any power. By Lojasiewicz's inequality, an algebraic curve is not going to intersect infinitely many of the $p_n$ or of the $c_n$.
Let's define a function $f$ such that $f(p_n)=-1/n$, the Taylor series of $f$ is zero at every point of $c_n$, and $f(0)=0$. Whitney gives us some smooth function on all of $\mathbb{R}^n$ that takes these values. In the exterior of the union of all $c_n$ and the origin, we can replace $f$ by $f^2$, just to make it non-negative there.
You can see now that on an algebraic curve passing through the origin, there will be a neighborhood of the origin not intersecting the $c_n$. Therefore, $f\geq0$ on that neighborhood. So, $f(0)$ is a local minimum. However, in every neighborhood of the origin we will have points $p_n$ at which $f$ is taking negative values.
Answer: To get you started: Let $g$ be smooth and nonnegative with $g^{(k)}(0)=0$ for all $k=0,1,2,\dots$. For example, take
$$g(t) = \begin{cases} e^{-1/t^2}, & t\ne 0 \\ 0, & t=0\end{cases}.$$
Write points in $\Bbb R^n$ as $(x,y)\in\Bbb R^{n-1}\times\Bbb R$, and set $$f(x,y) = \big(y-g(\|x\|)\big)(\big((y-2g(\|x\|)\big).$$
Then $f$ is negative on $R=\{g(\|x\|)<y<2g(\|x\|)\}$ but nonnegative elsewhere. Any algebraic curve passing through the origin will be in contained in the complement of $R$ and you can check that $f$ has a local minimum at $0$ when restricted to such a curve. But $f$ itself has a saddle point at $0$, since $f<0$ on $R$.


Derivation of Fibonacci sequence by difference equation/Z transform

Question: I'm trying to derive the Fibonacci sequence. I have the following problem:
$$N(t) = N(t-1)+ N(t-2)  \quad \quad \quad \quad (I)$$
With initial conditions $N(1) = 2$ and $N(2) = 3$. Using:
$$N(t+2) = N(t+1)+ N(t) $$
We get $N(0) = 1$, $N(-1)=1$ and $N(-2)=0$. Taking the Z transform on (I) we have:
$$ N_Z(z) = z^{-1}N_Z(z)+N(-1) + z^{-2}N_Z(z) + z^{-1}N(-1)+N(-2)$$
$$\therefore N_Z(z) = \frac{z^{-1}+1}{1-z^{-1}-z^{-2}} $$
This give me the wrong formula. I should get the binet formula when I take the inverse Z transform. Z trasform of N(t) should look like:
$$\therefore N_Z(z) = \frac{z^{-1}}{1-z^{-1}-z^{-2}} $$
Thanks!
Comment: Im not familiar with z-transform, but maybe it's because it's not an actual Fibonacci sequence?
Comment: The fibonacci sequence isnt $N(t) = N(t-1)+N(t-2)$?
Comment: $N(1)=1$, $N(2)=1$ would be Fibonacci, this one is "shifted" Fibonacci.
Comment: Thanks, your answer clarified my problem!
Comment: https://math.stackexchange.com/questions/279868/causal-inverse-z-transform-of-fibonacci
Answer: Let $x_n=N(n)$. Then:
$$
\forall z\in\Omega\subset\mathbb{C}\\
\sum\limits_{n=-2}^\infty (x_{n+2}-x_{n+1}-x_n)z^{-(n+2)}=0\\
\iff \sum\limits_{n=-2}^\infty x_{n+2}z^{-(n+2)}-z^{-1}\sum\limits_{n=-2}^\infty x_{n+1}z^{-(n+1)}-z^{-2}\sum\limits_{n=-2}^\infty x_nz^{-n}=0 \\
\iff -x_{-1}z^{-1}+\sum\limits_{n=-3}^\infty x_{n+2}z^{-(n+2)}-z^{-1}\sum\limits_{n=-2}^\infty x_{n+1}z^{-(n+1)}-z^{-2}\sum\limits_{n=-2}^\infty x_nz^{-n}=0 \\
\iff (1-z^{-1}-z^{-2})\sum\limits_{n=-1}^\infty x_nz^{-n}=z^{-1} \\
\iff \sum\limits_{n=-1}^\infty x_nz^{-n}=\frac{z^{-1}}{1-z^{-1}-z^{-2}}
$$.


Spring Batch ResultSet got closed by other before all data being fetched

Question: I am trying to setup the DB2 source as the persistence for the Batch meta data.  I am getting this stacktrace:
Caused by: org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [SELECT JOB_EXECUTION_ID, START_TIME, END_TIME, STATUS, EXIT_CODE, EXIT_MESSAGE, CREATE_TIME, LAST_UPDATED, VERSION, JOB_CONFIGURATION_LOCATION from rhall.BATCH_JOB_EXECUTION where JOB_INSTANCE_ID = ? order by JOB_EXECUTION_ID desc]; SQL state [null]; error code [-4470]; [jcc][t4][10120][10898][3.57.82] Invalid operation: result set is closed. ERRORCODE=-4470, SQLSTATE=null; nested exception is com.ibm.db2.jcc.am.SqlException: [jcc][t4][10120][10898][3.57.82] Invalid operation: result set is closed. ERRORCODE=-4470, SQLSTATE=null
   at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:84)
   at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
   at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
   at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:645)
   at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:680)
   at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:712)
   at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:722)
   at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:777)
   at org.springframework.batch.core.repository.dao.JdbcJobExecutionDao.findJobExecutions(JdbcJobExecutionDao.java:131)
   at org.springframework.batch.core.repository.support.SimpleJobRepository.getStepExecutionCount(SimpleJobRepository.java:253)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
   at java.lang.reflect.Method.invoke(Method.java:611)
   at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
   at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
   at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
   at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
   at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
   at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
   at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
   at $Proxy32.getStepExecutionCount(Unknown Source)
   at org.springframework.batch.core.job.flow.JobFlowExecutor.isStepRestart(JobFlowExecutor.java:82)
   at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:63)
   at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:67)
   at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:169) ... 22 more
Caused by: com.ibm.db2.jcc.am.SqlException: [jcc][t4][10120][10898][3.57.82] Invalid operation: result set is closed. ERRORCODE=-4470, SQLSTATE=null
   at com.ibm.db2.jcc.am.bd.a(bd.java:660)
   at com.ibm.db2.jcc.am.bd.a(bd.java:60)
   at com.ibm.db2.jcc.am.bd.a(bd.java:103)
   at com.ibm.db2.jcc.am.zl.Db(zl.java:4219)
   at com.ibm.db2.jcc.am.zl.q(zl.java:4180)
   at com.ibm.db2.jcc.am.zl.c(zl.java:1009)
   at com.ibm.db2.jcc.am.zl.getTimestamp(zl.java:985)
   at com.ibm.ws.rsadapter.jdbc.WSJdbcResultSet.getTimestamp(WSJdbcResultSet.java:2607)
   at org.springframework.batch.core.repository.dao.JdbcJobExecutionDao$JobExecutionRowMapper.mapRow(JdbcJobExecutionDao.java:425)
   at org.springframework.batch.core.repository.dao.JdbcJobExecutionDao$JobExecutionRowMapper.mapRow(JdbcJobExecutionDao.java:396)
   at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:93)
   at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60)
   at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:693)
   at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:629)
  ... 45 more

I trace the code, and found the problem around this method: JdbcJobExecutionDao.mapRow(ResultSet rs, int rowNum)
(I am  using Spring-batch version 3.0.6)  List paste the method here for your
 convenience,
public JobExecution mapRow(ResultSet rs, int rowNum)
 throws SQLException {
 Long id = rs.getLong(1);
 String jobConfigurationLocation = rs.getString(10);
 JobExecution jobExecution;
 if (jobParameters == null) {
    jobParameters = getJobParameters(id);
 }
 if (jobInstance == null) {
    jobExecution = new JobExecution(id, jobParameters, jobConfigurationLocation);
 } else {
    jobExecution = new JobExecution(jobInstance, id, jobParameters, jobConfigurationLocation);
 }
 jobExecution.setStartTime(rs.getTimestamp(2));
 jobExecution.setEndTime(rs.getTimestamp(3));
 jobExecution.setStatus(BatchStatus.valueOf(rs.getString(4)));
 jobExecution.setExitStatus(new ExitStatus(rs.getString(5), rs.getString(6)));
 jobExecution.setCreateTime(rs.getTimestamp(7));
 jobExecution.setLastUpdated(rs.getTimestamp(8));
 jobExecution.setVersion(rs.getInt(9));
 return jobExecution;
}

As I trace it, I notice that the problem is in the getJobParameters(id) method.  This method performs another query to the JOB_EXECUTION_PARAMS table for paramaters for the given job id.  But within this method, the getConnection method returns the same connection as in the current context.  After the query, the finally block closes the resultSet.  So when the control gets back to the mapRow method, it failed at this line:
jobExecution.setStartTime(rs.getTimestamp(2));

It is because the rs has already been closed by the getJobParameters(id) method.
Wondering if I did wrong?  Please point me out.
Many thanks.
Comment: I have the same issue and started a bounty...

SQL state [55032]; error code [-1224]; [jcc][t4][2055][14191][4.19.26] The database manager is not able to accept new requests, has terminated all requests in progress,
or has terminated this particular request due to unexpected error conditions detected at the target system. ERRORCODE=-1224, SQLSTATE=55032
Comment: do you have some code in your job (service or DAO) marked with @Transactional?
Answer: removing @Transactional from my method that uses the Batch Infrastructure classes, ie, JobExplorer, solves this issues around the closed ResultSet.


Default Tableview - deleting sections

Question: My application contains a table view with rows and sections.
When I delete the last item of a section, I delete the section. It works fine.
But, when i move the last row of a section into another section, I get an error.
Here is my code in both cases :
<code>[categoryArray removeObjectAtIndex:indexPath.section];
[tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationTop];
</code>
Here is the error that occurs in moveRowAtIndexPath:fromIndexPath:toIndexPath:
<code>2009-03-11 17:56:09.524 Test[5140:20b] 1
2009-03-11 17:56:09.525 Test[5140:20b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]: index (5) beyond bounds (5)'
</code>
Any help would be great !
Answer: Well, in fact, my code isn't trying to access to an element. I think the error come from a UITableView method (that I don't know because we only have access to header files of the sdk).
The problem occurs at this point :
<code>[tableView deleteSections:[NSIndexSet indexSetWithIndex:fromIndexPath.section] withRowAnimation:UITableViewRowAnimationTop];
</code>
Comment: How did you resolve this issue? I seem to be getting a similar one
Answer: It looks like you are trying to access the sixth element of a five-element array. Are you using the array size as the index without subtracting 1?
Answer: I had this issue and I just solved it. In my case, I was using Core Data, and I had to wrap the deletion logic in
<code>    [tableView beginUpdates];
    ...
    [tableView endUpdates];
</code>
I had to wrap everything; from before I deleted the data/section until after I had saved the context. Hope it helps.

Default Tableview - deleting sections


Single page template from multiple markdown files

Question: How can I construct a template in Gatsby that can pull content from multiple markdown files.
The use case is a webpage that contains multiple content sections where each section's content will exist in its own markdown file.
Mainly, I'm looking for a link to a tutorial.
For example:
Say I have content in the following three files; hero.md, feature-one.md, and feature-two.md
I want to plug the content from those three markdown files into my homepage as follows.
home.js template pseudo code

{{ hero content }}

Features

<card>{{feature-one content}}</card>
<card>{{feature-two content}}</card>

Answer: Here is a link to the tutorial on the Gatsby Docs - Adding Markdown Pages
Basically, you use the plugin gatsby-source-filesystem to give path to the *.md files. Then use graphQL query in a template to get data.
import React from "react"
import { graphql } from "gatsby"

import Hero...

const MarkdownTemplate = ({ data }) => {
  const { markdownRemark } = data.markdownRemark
  const { frontmatter, heroContent } = markdownRemark
  return (
    <React.Fragment>
      <Hero heroContent={heroContent} />

{frontmatter.featureOne}

{frontmatter.featureTwo}

    </React.Fragment>
  );
};

export const pageQuery = graphql`
  query($path: String!) {
    markdownRemark(frontmatter: { path: { eq: $path } }) {
      heroContent
      frontmatter {
        featureOne
        featureOne
        path
      }
    }
  }
`;
export default MarkdownTemplate;


How to use segues from view controller that has a XIB for it's design?

Question: I'm implementing a navigation hierarchy in a storyboard. For part of my navigation, I am drilling down through a tree of data, so I have a couple view controllers in a row with the exact same look but different data management so they need separate controllers. To avoid duplication I did the layout for those views in a XIB, made a VC class for the XIB to handle setting up the views, and then I extend that class for each VC in the storyboard to handle the UITableViewDataSource stuff.
Now the navigation is working fine, but I want to have a button on the XIB views that triggers an unwind segue back to the beginning. I have the segues set up with identifiers in the storyboard from my VCs with a XIB layout to the home screen, but no matter what I do, when I call performSegueWithIdentifier I always get the has no segue with identifier error.
I think what's going on is that everything extra added to the view controller in the storyboard is removed when the XIB is loaded. I found that that was happening with my navigation item in these views and I had to create the navigation item in code since there's no way to add one in a XIB. I suspect something related is happening with the segues, but I can't figure out a workaround. Is it just not possible to have a VC in a storyboard with its layout in a XIB and then perform a segue from it? Is there a programmatic way to do an unwind segue without setting it up in the storyboard?
Answer: Unwinding is only available if you are using storyboard. So in your case you have to use UINavigationController.popViewControllerAnimated or UIViewController.dismissViewControllerAnimated:completion:.
Comment: I know segues are only available in a storyboard, and I _am_ using a storyboard. The issue is that if the view controller in the storyboard has its root view defined by a XIB, the segues don't actually get hooked up. I believe this is just a bug in Interface Builder.


Matlab: How to Exclude Zero from Domain?

Question: I want to plot the wireframe surface of $f(x,y)=\frac{x^2-y^2}{x^2+y^2}$ in Matlab. The code I typed is as follows.

x=-0.1:.001:0.1;
  y=-0.1:.001:0.1;
  [X,Y]= meshgrid(x,y);
  Z=((X.^2)-(Y.^2))/((X.^2)+(Y.^2));
  mesh(Z)

However, an empty graph appears, and a line says:

Warning: Matrix is singular to working precision.

I know this happens because the graph is not defined at $x=0$, $y=0$. Is there any way that I can change the domain of $x$ and $y$ so that it excludes $0$?
I did plot the solid surface with the following code, which works.

clear
  syms x y
  ezsurf(((x.^2)-(y.^2))/((x.^2)+(y.^2)))

Thank you for your time.
Comment: You want the divide to be elementwise. i.e. ./. The effect of this will be one element equal to inf corresponding to the (0,0) element.
Answer: <code>x=-0.1:.001:0.1;
y=-0.1:.001:0.1;

% Add these lines
x = x(x~=0);
y = y(y~=0);

[X,Y]= meshgrid(x,y);
Z=((X.^2)-(Y.^2))/((X.^2)+(Y.^2));
mesh(Z)
</code>
Comment: @euler It's because of the /.
Comment: Ah yes, add a `/.` Missed that!
Comment: Hi, I tried your code, and it still produces an empty graph and the same line: 'Warning: Matrix is singular to working precision.'


What is the best way to store and search through class objects (in PHP)?

Question: I've around 80 instances of this class called Items and would like to efficiently search the objects by their ID or NAME.
<code><?php
class Item
{
    public $id;
    public $name;

   //methods
}
?>
</code>
I'm using PHP5.
Comment: I would think that a simple foreach loop would be about as efficient as you should care to get.  Anything else would probably cause unnecessary overhead or wouldn't be worth your time.  I'm assuming you're asking this in context of a problem you're trying to solve.  Are the classes you're working with extremely large?
Comment: yeah a foreach loop would work fine. Item class is around 70 lines of code, fairly small.
Answer: Assuming no duplicate names or IDs:
<code>$ids = array();
$names = array();
foreach ($items as $item) {
  $ids[$item->id] = $item;
  $names[$item->name] = $item;
}
</code>
If you have duplicates (of names; I imagine there are no duplicate IDs by definition) then you need to work out how to handle that. You could store all the duplicates under one key (so the value becomes an array of matches).
Or do you mean a more sophisticated search? If so, a simple variant might be to break up the item name into words and/or phrases and then index them accordingly into an array.
Comment: is $items an array that contains references to objects? I wanted a simple search and the code you provided would do the job. Thanks
Answer: I would think about making an ItemIndex class;
this would allow you to maintain an arbitrary number of
independent indexes, overloading the comparison and
search functions as appropriate.
Answer: If you have 80 instances, it really doesn't matter which option you use. Even if your search is N squared, I don't think it's worth it to invest time into a performance optimization here. Do the simplest thing and then profile; if it's horrible, only then consider increasing the complexity of the implementation to make it faster.


Derivative of a minor

Question: From matrix $Y_{T \times I}$ I can can calculate the covariance as follows:
$$
S=\frac{1}{I}{Y^tY}
$$
and a singular entry of the inverse like so (as explained in this post):
$$
s_{i,j}^{-1} = \frac{(-1)^{i+j}M_{j,i}}{\det(S)}
$$
where $M_{j,i}$ is a minor taken from  $S^T$. What would $\frac{\delta(s_{i,j}^{-1})}{\delta{y_{t,i}}}$ be?
Answer: Let $S = \alpha Y^TY$
Then
$$\eqalign{
 \alpha S^{-1}Y^T &= (Y^TY)^{-1}Y^T = Y^+ \cr
 \alpha YS^{-1} &= Y(Y^TY)^{-1} = (Y^+)^T \cr
}$$ where $Y^+$ is the pseudoinverse of $Y$.
Taking the requested differential
$$\eqalign{
 dS^{-1}
  &= -S^{-1}\,dS\,S^{-1} \cr
  &= -S^{-1}\,\alpha(dY^T\,Y+Y^T\,dY)\,S^{-1} \cr
  &= -S^{-1}\,dY^T\,\alpha YS^{-1} - \alpha S^{-1}Y^T\,dY\,S^{-1} \cr
  &= -S^{-1}\,dY^T\,(Y^+)^T - Y^+\,dY\,S^{-1} \cr\cr
 dS^{-1}_{ij}
  &= -S^{-1}_{im}\,dY^T_{mn}\,(Y^+)^T_{nj} - Y^+_{im}\,dY_{mn}\,S^{-1}_{nj} \cr
  &= -S^{-1}_{im}\,dY_{nm}\,Y^+_{jn} - Y^+_{im}\,dY_{mn}\,S^{-1}_{nj} \cr
}$$
And applying the basic gradient for these situations:
$$\frac{\partial Y_{ij}}{\partial Y_{kl}} = \delta_{ik}\delta_{jl}$$
Yields
$$\eqalign{
\frac{\partial S^{-1}_{ij}}{\partial Y_{kl}}
  &= -S^{-1}_{im}\,\delta_{nk}\delta_{ml}\,Y^+_{jn} - Y^+_{im}\,\delta_{mk}\delta_{nl}\,S^{-1}_{nj} \cr
  &= -S^{-1}_{il}Y^+_{jk} - Y^+_{ik}S^{-1}_{lj} \cr
}$$
I know that you were hoping for something in terms of the minors, but nothing like that occurs to me.
Comment: Nice, how did you set the indexes in $dS^{-1}_{ij}$ before applying the gradient? Also, $\frac{\partial Y_{ij}}{\partial Y_{kl}} = \delta_{ik}\delta_{jl}$ only works when all elements of Y are independent right?
Comment: The leftmost index on each term is $i$, the rightmost is $j$, and all the ones in-between are dummies. If there is some constraint, that makes the elements of $Y$ interdependent, then by all means apply it.

Derivative of a minor


How to create silence in MP3

Question: I need MP3 file consiting of literally 2 (two) complete frames @ 44100/16 bit/stereo, without any metadata. The issue here is that I need to be able to create it myself as cutting 2 frames from larger file will cause artifacts in my decoder processing.
I tried the following

windows sound recorder - can record only up to 24 kHz, I need 44100, my decoder can not handle it;
VLC seems not understanding such small files - I tried to feed 0.02 second WAV file to it, and it refuses to convert (generates output file of size of 0);
there's an application called FFMPEG, I have it on PC, but can not make it working, too complicated for me. Not sure if it can take fractional input for -t key though.

I am sure those who deal with electronic music can help me. Thank you in advance.
Update: my question really seems to be offtopic here, and DSP (digital signal processing) is not about music, but about technology, however I was hoping that musicians use technology and must know how analog and digital works relating to making a sound.
I found out that I, most probably, need more than 2 frames to fill 2048 bytes of decoder's buffer for decoder to start processing. The main issue I am solving that decoder does not have option to reset (zero) its intermediate buffers, and the only way to reset them is to push several frames of silence through them.
Thus it is just down to the understanding MP3 format, and I even will not need frames, I will need algorithm how to construct data within the frame so that they would decode to all zeros (silence).
Comment: maybe a different stack for what you are looking for? https://stackoverflow.com/questions/39734057/how-to-insert-silence-into-an-audio-file-with-programming
Comment: @AlphonsoBalvenie thank you, I saw this question, but for specific reason decided to post question here to get more options from music technologists. I not only needed to insert silence, I must have understood how to create it myself. I know how to do it now without any utility.
Comment: There used to be a program called MP3DirectCut that allowed you to do some operations directly on mp3 files without re-encoding. ... seems to be still around https://en.wikipedia.org/wiki/Mp3DirectCut
Answer: This question may not be on topic here, but in Audacity if you create a new (empty) project and then go to Generate > Silence... you can generate whatever length of silence you want in units of seconds, samples, frames and more.
Then go to File > Export audio, and choose MP3.
Comment: Sound file creating using the above method still has some background noise. I want to create an absolute silent mp3.
Answer: Just to be sure others will be able to find solution to this question. Silent MP3 frame consists of the header, side info and data comprised of just one type of byte. Here're two headers - first to be used for the first frame, and second for all subsequent frames:
Header (including side info) of the first frame
FF FB 90 64-00 0F F0 00-00 69 00 00-00 08 00 00
0D 20 00 00-01 00 00 01-A4 00 00 00-20 00 00 34
80 00 00 04

Header (including side info) of following frames
FF FB 90 64-40 8F F0 00-00 69 00 00-00 08 00 00
0D 20 00 00-01 00 00 01-A4 00 00 00-20 00 00 34
80 00 00 04

Size of data following the header and side info is 381 bytes, and consists of 381 copies of byte 'U' (0x55). It decodes to all zeros using respective Huffman table. Thus in total frame size is 417 bytes. Each frame (to my understanding) will decode into 1152 16-bit stereo samples, performing at 44100 Hz (thus lasts for ~26.122 ms).
Comment: The 0x55 are there because hardware prefers to have a number such as 0x55 or 0xAA rather than 0x00. The code you show result in a size of 0 bytes for the data, which means _no data_ (or more precisely, all zeroes, which is the default).
Comment: For some reason *audacity* does not show second frame: If only the first frame is used, it is shown with correct duration. If two frames are used, the same duration (~26.122 ms) is used, and if N frames are used (N>2), total duration is 26.122*(N-1). What may be the cause of this? Where can one find the description of this headers byte-by-byte?
Comment: There're a number of websites showing this information, but the best explanation I found is this one http://www.mp3-tech.org/programmer/docs/mp3_theory.pdf. I suspect it uses N-1 frames dropping last frame, thinking that 26 ms is not actually much audible and does not affect quality of listening. Why? this is good question to the developers of the Audacity. Could be feature or bug :)
Answer: To complement and answer your question about why 1 frame of data doesn't work, I wanted to add that the MP3 format (and most certainly many others) require training the compressor. For that reason a library such as LAME will add some silence at the beginning.
Similarly, to get the last bit of data, it adds yet more silence at the end of the stream. This is usually the job of the Flush() function. In some situations, when you can't call the Flush() function, you have to provide the silence yourself. (i.e. when creating a live feed or running with multiple threads.)
Also for those interested in doing a silencing of an existing frame, you can do so by setting all the side info values to zero like so:
FF FB 90 64-00 00 00 00-00 00 00 00-00 00 00 00
00 00 00 00-00 00 00 00-00 00 00 00-00 00 00 00
00 00 00 00

WARNING: The size of the side info varies depending on the version (MPEG-1 or not) and whether you have single channel or not.
This is how the Info or Xing tag are defined and if a player doesn't recognize the tag, it will just add an extra ~26ms of silence.
You can actually void the Info or Xing by replacing these character by U or some other value. These would appear right after the header and side info bytes:
FF FB 90 64-00 00 00 00-00 00 00 00-00 00 00 00
00 00 00 00-00 00 00 00-00 00 00 00-00 00 00 00
00 00 00 00-55 55 55 55

Info would be 49 6E 66 6F and Xing would be 58 69 6E 67. This method allows you to edit an MP3 file in place without having to move all the content which can be huge or while streaming.
Answer: Learned that when concatenating silent wav file with other music wav files, the channels, sample rate, etc. have to be compatible.  A simple way to do this with ffmpeg is to simply copy an existing music wav file and turn the volume to 0.  Command line example of a 4 second silent file is as follows:
ffmpeg -i existing_music_file.wav -t 4 -filter:a "volume=0.0001" silent.wav

How to create silence in MP3


Java build system with automatic dependency resolution

Question: I am trying to get up to speed with Java after spending my last couple of years with Python and Perl. And boy is this hard! First of all, there's no easy to use build system that can do only what you want it to do without adding tons of boilerplate. Then, how to add dependencies to your project, how do you run junit tests from the build systems (say ant for example)? How can I make the build system download the dependencies on the fly (or can't I?)
Can I find some docs around that can get me up to speed with this without reading a couple of books ? I am trying to be "agile", but the comeback is hard.
Please feel free to close it if it is too subjective. Thanks!
Comment: So, let me get this straight... you're complaining that Java isn't python or perl? Some languages and platforms have a steep learning curve. How about you ask a specific question or show us a specific problem you've bumped into instead of stating the obvious that Java is not as simple as a dynamic agile scripting language?
Comment: As other have mentioned, you should look into Maven. It handles dependencies (including test-time only ones) and integrates well with just about all the Java IDEs. Really all you need is a proper directory structure and a proper `pom.xml`.
Comment: @Lior Cohen: no specific question, just wondering if anyone battled with this before and what was the approach here. And yes, it's hard coming from dynamic languages, but one step at a time should do it.
Comment: Just wondering though how Scala (SBT) and even Clojure (Leinigen) made it and it's so hard to do it for Java
Answer: This question is close to textbook trolling... anyway.
There are a lot of build systems that resolve dependencies for you out there (maven, ant, buildr, etc).
I'd say go with buildr since you are familiar with scripting languages.
NOTE
Though many people pointed out maven, considering your background (perl, python, etc) that will make you hate java even more (it's a sea of <XML> out there dude!). Please consider buildr if you feel frustrated enough
Answer: You don't mention which build systems you've tried (other than ant). I feel either Maven or Gradle would meet your needs (although I think Maven might fail your "tons of boilerplate" test; it certainly fails mine).
Answer: There are an awful lot of questions here. "Maven" is the Java build system that automatically downloads dependencies; it is based on Ant, which does everything else you ask about (running tests, etc).
If you want to use Maven, get started by using Maven's quickstart docs and examples.


Find the set of real numbers where $f(x)$ is continuous.

Question: The function is defined  as

$f(x) = x+\sqrt{2}$ if $x$ is rational
$f(x) = x-3$ if $x$ is irrational

The question:
Find the set of real numbers at which $f$ is continuous.
Note : It presumably wants me to justify it with an epsilon-delta proof.
Any advice would be appreciated, I can't quite see how to proceed.
EDIT: For anyone looking for help on similar problems, try here -->
Proving Discontinuity using Epsilon Delta for Function
I eventually found it after further hunting, and it provides a greater degree of mathematical instruction than the answers given here.
Comment: Draw the graphs of $y=x+\sqrt2$ and $y=x-3$. Is there *any* value of $x$ at which they are close to each other? Take $\epsilon=1$, say, at any $x$; is there any $\delta$ small enough to 'work'?
Comment: They, uh... don't look too close to each other. Those graphs are parallel. Am I missing something here?
Comment: They are indeed parallel, at a vertical distance of $3+\sqrt2$. So if you take $\epsilon=1$ and $a\in\Bbb R$, is there any $\delta$ that guarantees that $|f(x)-f(a)|<1$ whenever $|x-a|<\delta$?
Answer: With sequences the problem is easy to solve: let $x_0 \in \mathbb R$.
Take a sequence $(a_n) $ in $\mathbb Q$ with $a_n \to x_0$. Then
$f(a_n)=a_n + \sqrt{2} \to x_0+\sqrt{2}$.
Next, take a sequence $(b_n) $ in $\mathbb R \setminus\mathbb Q$ with $b_n \to x_0$. Then
$f(b_n)=b_n -3\to x_0-3$.
Now suppose that $f$ is continuous in $x_0$. Then we would have
$\lim_{n \to \infty}f(a_n)=\lim_{n \to \infty}f(b_n)$, hence $x_0+\sqrt{2}=x_0-3$, a contradiction.
Comment: Okay, thanks for the input! So you think this is a trick question, and I need to justify that the set of real numbers at which f is continuous is empty?
Comment: ???? I have showed that there is no $x_0$ such that $f$ is  continuous in $x_0$. What is your problem ?
Comment: @Jo: No, it is not a trick question. You have to *prove* that for each $a\in\Bbb R$, $f$ is not continuous at $a$.
Comment: I understand that. I mentioned a 'trick', in that the question leads that there is such a set of x values at which f(x) is continuous.
Comment: Look, I appreciate help but please don't get so hung up on a turn of phrase and throw yourself into a lecture. It's not constructive, just condescending.
Comment: In my book, a question stated in such a way as to misdirect (as this one does) is a trick question. There's nothing wrong with that, nor do I think it is an improper question. It's just deliberately misleading, and I spent a while confused because the function appeared discontinuous yet demanded of me the points of continuity.


Filling asp controls using Client Side C#

Question: It's been a long time since I've used classic asp.net and asp: controls.
I have this textbox;
<asp:TextBox ID="txtTitle" runat="server" CssClass="fieldLge" Text='<%= this.Title %>'/>

In my cs I have;
 public string Title { get; set; }

The property is being set from a presenter.
However when I see my field on screen I see "<%= this.Title %>" as it's text and not the value of the property.
I know this is a mind numbingly silly question to ask but I can't figure it out.  Love MVC!
Answer: Using MVP with Webforms you would normally set properties on controls directly from the property in the view interface.
change:
public string Title { get; set; }

to:
public string Title
{
    get { return txtTitle.Text }
    set { txtTitle.Text = value }
}

Comment: +1.  Boy it has been a long time.  I remeber doing this now.  Thanks a bunch @rabs.  Will mark as correct in 6 minutes


How to collect payments for the missed periods with the hard decline status?

Question: Scenario: A user's credit card expires and he misses to pay his recurring monthly fee. Two months later he updates his credit card and because the license never expired the system picks it up and continues to successfully charge his card on file for consequent periods, but unfortunately not for the previous.
And it's not clear how to charge for the missed payments with the "Payment failed (hard decline)" status. Any suggestions?
Edit: I had to delete my own answer:

It was not obvious for me that I needed to use Commerce Dunning module
  to re-charge for the missed payments.

after trying the Commerce Dunning module, because unfortunately for hard declines it only sends notifications without attempting to re-charge for the missed period even if a customer updated his credit card. Per description on https://www.drupal.org/project/commerce_dunning:

If it was a hard decline that led to the failure, the customer needs
  to update their credit card, so notifications regarding that are also
  scheduled.

So unfortunately it is still not clear how to collect payments for the missed period.
Comment: After 6 month I am hitting the same issue. Unfortunately, no acceptable answer is given and it is not clear how to collect charges for the missed periods.
Answer: If a customer has a hard decline, they'll need to log in and create a new stored payment option. They can create new stored payments via their account dashboard:

If memory serves, it should then be used by default.
Comment: Nick, thank you for your response, however as I stated above `even if a customer updated his credit card` the order for the missed period is never processed. Future periods are ok, but what about the missed ones?


Error 500 on create table using Google API PHP client 1.0 fusion tables insert method

Question: This code should add a new table on an authenticated client:
$client = new Google_Client();

$client->setClientId($config['client_id']);
$client->setClientSecret($config['client_secret']);
$client->setRedirectUri($config['redirect_uri']);
$client->setScopes(
    array(
        'https://www.googleapis.com/auth/plus.login',
        'https://www.googleapis.com/auth/fusiontables'
    )
);
$client->setAccessToken($_SESSION['access_token']);

$fusionTablesService = new Google_Service_Fusiontables($client);

$table = new Google_Service_Fusiontables_Table();
$table->setName('testTable');

$column = new Google_Service_Fusiontables_Column();
$column->setName('testColumn');
$column->setType('STRING');

$table->setColumns(array($column));

$fusionTablesService->table->insert($table);

But it doesn't. I just get a 500 error:
Fatal error: Uncaught exception 'Google_Service_Exception'

with message

'Error calling POST https://www.googleapis.com/fusiontables/v1/tables:
(500) Backend Error'

in

/vendor/google/apiclient/src/Google/Http/REST.php on line 79

which I can trace back to the last line: $fusionTablesService->table->insert($table);
I've been researching and trying for 6 hours, but the docs just suck.
Does anybody know what's happening?
Answer: It seems that all I had to do was to set isExportable to true ($table->setIsExportable('true');). Here's the code working:
$client = new Google_Client();

$client->setClientId($config['client_id']);
$client->setClientSecret($config['client_secret']);
$client->setRedirectUri($config['redirect_uri']);
$client->setScopes(
    array(
        'https://www.googleapis.com/auth/plus.login',
        'https://www.googleapis.com/auth/fusiontables'
    )
);
$client->setAccessToken($_SESSION['access_token']);

$fusionTablesService = new Google_Service_Fusiontables($client);

$table = new Google_Service_Fusiontables_Table();

$table->setName('testTable');

//missing line that was causing the trouble
$table->setIsExportable('true');

$column = new Google_Service_Fusiontables_Column();
$column->setName('testColumn');
$column->setType('STRING');

$table->setColumns(array($column));

$fusionTablesService->table->insert($table);


How do I get a field label by the field name?

Question: How do I get a field label by the field name in Drupal 7?
Answer: The label is set per instance (not per field) so you would use the field_info_instance() function with some appropriate arguments:
$entity_type = 'node';
$bundle_name = 'article';
$field_name = 'field_some_field';

$info = field_info_instance($entity_type, $field_name, $bundle_name);

$label = $info['label'];

There's a bunch of other useful functions in the Field Info API documentation that might be helpful in case you haven't seen it already.
Comment: That works for english.  Doesn't seem to work when trying to get the translated version of a title.
Comment: Oops, sorry about that
Answer: The easiest way to print the field label of a node is:
<?php print $content['field_your_field_name']['#title']; ?>

(I've discovered it after a lot of print_r arrays and objects of Drupal! If it's so easy, why isn't explained anywhere, or why is so hidden that I've not found the trick? And passed a long time from the question to this answer...)


Busca contando resultado

Question: Faço uma busca por um determinado termo e mostro o resultado, o que está correto, agora preciso mostrar a quantidade de cada produto por categoria, por exemplo, pesquisa pelo termo "cadeira".

COZINHA (10)
DORMITÓRIO (05)

A minha busca pelo termo ficou assim:
mysql_select_db($database_conexao, $conexao);
$query_rsBusca = "SELECT marca.descricao AS marca,
                         produtos.id_produto,
                         produtos.id_departamento,
                         produtos.id_subdepartamento,
                         produtos.id_marca,
                         produtos.descricao AS prodDesc,
                         produtos.codigo_msb
                    FROM produtos INNER JOIN marca ON (produtos.id_marca = marca.id_marca)
                   WHERE (produtos.descricao LIKE '%".$pesquisa."%')  OR
                         (produtos.resumo LIKE '%".$pesquisa."%')     OR
                         (produtos.codigo_msb LIKE '%".$pesquisa."%') OR
                         (produtos.detalhes LIKE '%".$pesquisa."%')   OR
                         (marca.descricao LIKE '%".$pesquisa."%') $ordena ";
// echo $query_rsBusca;
$rsBusca = mysql_query($query_rsBusca, $conexao) or die(mysql_error());
$row_rsBusca = mysql_fetch_assoc($rsBusca);
$totalRows_rsBusca = mysql_num_rows($rsBusca);

Em seguida fiz um novo conjunto de registro para mostrar as categorias e seus valores, ficou assim:
mysql_select_db($database_conexao, $conexao);
$query_rsSoma = "SELECT
                      departamento.descricao AS descricao,
                      COUNT(*) AS Registros
                    FROM
                      departamento
                      INNER JOIN produtos ON (produtos.id_departamento = departamento.id_departamento)
                      INNER JOIN marca ON (produtos.id_marca = marca.id_marca)
                    WHERE
                      (produtos.descricao LIKE '%".$pesquisa."%')  OR
                      (produtos.resumo LIKE '%".$pesquisa."%')     OR
                      (produtos.codigo_msb LIKE '%".$pesquisa."%') OR
                      (produtos.detalhes LIKE '%".$pesquisa."%')   OR
                      (marca.descricao LIKE '%".$pesquisa."%'))
                    GROUP BY
                      departamento.id_departamento";
$rsSoma = mysql_query($query_rsSoma, $conexao) or die(mysql_error());
$row_rsSoma = mysql_fetch_assoc($rsSoma);
$totalRows_rsSoma = mysql_num_rows($rsSoma);

Mas ao executar a query, meu servidor acusa o seguinte erro:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

near ') GROUP BY departamento.id_departamento' at line 13.
Answer: Consegui resolver o meu problema, estava sobrando um ")" no final do comando, vejam como ficou a Query completa corrigida.
mysql_select_db($database_conexao, $conexao);
$query_rsBusca = "SELECT marca.descricao AS marca,
                         produtos.id_produto,
                         produtos.id_departamento,
                         produtos.id_subdepartamento,
                         produtos.id_marca,
                         produtos.descricao AS prodDesc,
                         produtos.codigo_msb
                    FROM produtos INNER JOIN marca ON (produtos.id_marca = marca.id_marca)
                   WHERE (produtos.descricao LIKE '%".$pesquisa."%')  OR
                         (produtos.resumo LIKE '%".$pesquisa."%')     OR
                         (produtos.codigo_msb LIKE '%".$pesquisa."%') OR
                         (produtos.detalhes LIKE '%".$pesquisa."%')   OR
                         (marca.descricao LIKE '%".$pesquisa."%') $ordena ";
// echo $query_rsBusca;
$rsBusca = mysql_query($query_rsBusca, $conexao) or die(mysql_error());
$row_rsBusca = mysql_fetch_assoc($rsBusca);
$totalRows_rsBusca = mysql_num_rows($rsBusca);

mysql_select_db($database_conexao, $conexao);
$query_rsSoma = "SELECT
                      departamento.descricao AS descricao,
                      COUNT(*) AS Registros
                    FROM
                      departamento
                      INNER JOIN produtos ON (produtos.id_departamento = departamento.id_departamento)
                      INNER JOIN marca ON (produtos.id_marca = marca.id_marca)
                    WHERE
                      (produtos.descricao LIKE '%".$pesquisa."%')  OR
                      (produtos.resumo LIKE '%".$pesquisa."%')     OR
                      (produtos.codigo_msb LIKE '%".$pesquisa."%') OR
                      (produtos.detalhes LIKE '%".$pesquisa."%')   OR
                      /* AQUI TINHA UM ')' A MAIS */
                      (marca.descricao LIKE '%".$pesquisa."%')
                    GROUP BY
                      departamento.id_departamento";
$rsSoma = mysql_query($query_rsSoma, $conexao) or die(mysql_error());
$row_rsSoma = mysql_fetch_assoc($rsSoma);
$totalRows_rsSoma = mysql_num_rows($rsSoma);

Obrigado a ajuda e as dicas.

Busca contando resultado


Consuming QnA and LUIS in a v4 bot

Question: Documentation tells me I need CognitiveServices package to obtain support for consuming LUIS and QnA services. However, v4 uses the Core framework and https://www.nuget.org/packages/Microsoft.Bot.Builder.CognitiveServices/ gives a warning that it requires 4.6

warn : Package 'Microsoft.Bot.Builder.CognitiveServices 1.1.7' was
  restored using '.NETFramework,Version=v4.6.1' instead of the project
  target framework '.NETCoreApp,Version=v2.0'. This package may not be
  fully compatible with your project.

Are there dotnet core versions of the CognitiveServices packages, or it is LUIS and QnA support now somewhere else?
My interest in the CognitiveServices package is entirely driven by the need to consume LUIS and QnA services from a v4 bot.
Answer: Which Cognitive Service would you like to use? The package you mentioned was done for v3 bots.
For example, some of the Cognitive Services are included in the Bot Builder SDK librairies:

LUIS: https://github.com/Microsoft/botbuilder-dotnet/tree/master/libraries/Microsoft.Bot.Builder.AI.LUIS
QnA Maker: https://github.com/Microsoft/botbuilder-dotnet/tree/master/libraries/Microsoft.Bot.Builder.AI.QnA

These librairies are used to consume the services.
Otherwise, there are also other official NuGet packages, have a look to Microsoft.Azure.CognitiveServices... packages, targeting .Net Standard or .Net Framework:

Microsoft.Azure.CognitiveServices.ContentModerator
Microsoft.Azure.CognitiveServices.Vision.ComputerVision
Microsoft.Azure.CognitiveServices.Language.TextAnalytics
etc.
Comment: Your first para is right on point. My interest in CogServices is entirely driven by the need to consume LUIS and QnA services. I will put this plus supporting info into the question.
Comment: It would appear that the key is to read _all_ of the error message. I originally _tried_ to add the packages you list and they threw errors so I moved on looking for another answer without reading the details. The trick is to edit the csproj and bump all the versions to suit (4.2.2 at time of comment). It may help others if you fold this into your answer.
Comment: Or doing a Nuget package upgrade of your project?
Comment: It doesn't seem like there's an easy single command Nuget package upgrade. See https://stackoverflow.com/questions/41080749/how-do-i-update-all-nuget-packages-at-once-with-the-dotnet-cli
Comment: Was talking about doing it in an IDE like Visual Studi

Consuming QnA and LUIS in a v4 bot


Routing to production and testing Drupal installations on shared hosting account

Question: I am having issues with routing users to different domains on a shared hosting account.  Each of these domains are separate Drupal installations with separate databases.  site is intended to be the production environment, and site1-test is where we do our development and testing of content and modules prior to upload to the main site.  Also, if it has any impact on this issue, clean_urls are enabled.
Here is my file structure
+ public_html
   + site1
   + site1-test

site1 should route to www.site1.com (or site1.com)
site1-test should route to www.site1.com/site1-test (or site1.com/site1-test)
To me, this should be fairly straightforward updating of the .htaccess files.
Here is what I have done so far:
public_html/.htaccess
Options +FollowSymLinks
RewriteEngine on
#========================================================================
# FIRST Handle the http requests first before removing the additional url junk
#========================================================================
#rule for site1.com to link to site1 directory
RewriteCond %{HTTP_HOST} ^(www.)?site1.com$
RewriteCond %{REQUEST_URI} !^/site1/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /site1/$1
#rule for site1.com/site1-test to link to site1-test directory
RewriteCond %{HTTP_HOST} ^(www.)?site1.com/site1-test$
RewriteCond %{REQUEST_URI} !^/site1-test/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ /site1-test/$1
#rule for site1.com to link to site1folder directory

#==========================================================
# SECOND Remove the additional url junk once the new url is loaded
#==========================================================
#rule for site1 url rewrite to remove /site1/index.php from the URL
RewriteCond %{HTTP_HOST} ^(www.)?site1.com$
RewriteRule ^(/)?$ site1/index.php
#rule for site1-test url rewrite to remove /site1-test/index.php from the URL
RewriteCond %{HTTP_HOST} ^(www.)?site1-test$
RewriteRule ^(/)?$ site1-test/index.php

public_html/site1/.htaccess and public_html/site1-test/.htaccess
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  #RewriteRule ^ index.php [L]
  RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

  # no changes within <IfModule mod_headers.c> ...

public_html/site1/sites/default/settings.php
...
$base_url = 'http://www.site1.com';
...

public_html/site1-test/sites/default/settings.php
...
$base_url = 'http://www.site1.com/site1-test';
...

public_html/site1-test/sites/default/settings.php
So, there are multiple issues that I have.  With the code listed above, all themes and login information is completely broken when visiting www.site1.com.  However, visiting www.site1.com/site1-test works fine, although there are some issues with the Testing module (cannot run tests from the web interface, though I think this issue is linked to something being wrong in my htaccess file).
If I comment out the base_url for site1.com (i.e., //$base_url = 'http://www.site1.com';) then site1.com works, however all links show up as http://www.site1.com/site1, and all navigation after leaving the front page also shows that subdirectory.
Unfortunately I don't have access to the domain registration, but I do not believe that any redirects currently exist there, simply that the domain points to the site1 subdirectory.
Answer: Most shared hosting plans have a feature called subdomains or addon domains (these features exists in cpanel plans for sure. I m attaching a screenshot from a godaddy hosting plan). You may use this feature to effectively create a new apache virtual host so you dont have to mess with the .htaccess file to do the routing depending on the domain name
Also note that most shared hosting providers do not support overriding many features using the .htaccess file so many on of the options in your .htaccess file may be ignored depending on the apache configuration file (which you usually do not control)
Also note that .htaccess is an Apache concept. If your hosting provider uses another http server (e.g. nginx or IIS) the .htaccess file will be totaly ignored.
Last if you really want to do this with .htaccess (i dont recomend this) make sure you dont miss the query option in any of your cases. Notice the last part here index.php?q=$1  the ?q=$1 part is very important