How to reload page after ajax form submit

Question: I'm using FAPI #ajax to make the form more user friendly (it reloads in-place on validation). Works like a charm. However I would like to reload the page after form is submitted. How to that?
Obviously if I call for example drupal_goto(current_path()) inside submit handler it won't do anything since this function is called via AJAX call. The actual page that user is on is not reloaded.
Is there some neat Drupal AJAX API trick that will allow whole page reload after AJAX form submit?
Comment: If you want to reload anyway, why to bother with AJAX?
Comment: Validation reloads page too. I want to reload only after successful submit. Not on every submit.
Answer: For the purpose of the question, an easy-ish way to do a redirect after ajax is with ctools and ctools_ajax_command_redirect
// In your ajax form submit callback
ctools_include('ajax');
ctools_add_js('ajax-responder');
// Path to redirect to
$path = 'node/12';
$commands[] = ctools_ajax_command_redirect($path);
// you can also use ctools_ajax_command_reload() –  xurshid29
print ajax_render($commands);
drupal_exit();

Note, it depends on ctools, which is a popular contrib module.
Comment: you can also use [ctools_ajax_command_reload](http://drupalcontrib.org/api/drupal/contributions!ctools!includes!ajax.inc/function/ctools_ajax_command_reload/7)
Comment: Ah yes, in this case `ctools_ajax_command_reload` is probably a better fit, thanks.
Comment: The ctools solution didn't work for me, besides I think that adding a ctools dependency for such a small thing is just overkill. See my answer for alternative solution.
Comment: @DavidThomas Can you asnwer this? https://drupal.stackexchange.com/questions/238447/attach-or-embed-node-add-form-to-a-view
Answer: Another simple solution could be using a custom ajax command in your module JS file :
(function($) {
    // Custom AJAX commands
    if(typeof Drupal.ajax != "undefined") { // Ensure follwing code will not generate errors in administration pages
        Drupal.ajax.prototype.commands.reloadPage = function(ajax, rsp, status) {
            location.reload();
        };
    }
})(jQuery);

Then call it when returning your array of commands in your ajax callback function :
$commands = array();
...
$commands[] = array('command' => 'reloadPage');
...
return array('#type' => 'ajax', '#commands' => $commands);

Comment: Can answer this? https://drupal.stackexchange.com/questions/238447/attach-or-embed-node-add-form-to-a-view
Answer: If you want to avoid the ctools dependency but want to avoid the pitfalls of inline js-ing...
In your submit handler
if (current_path() == 'system/ajax') {
  // This was an ajax submission.

  // Cause Drupal to rebuild the form
  $form_state['rebuild'] = TRUE;
  // Special flag, call it what you want.
  $form_state['ready_to_go'] = TRUE;
}

Then in your build form function do something like
if (!empty($form_state['ready_to_go'])) {

  // Add js to autosubmit, stored in an external js file.
  $form['#attached']['js'][] = drupal_get_path('module', 'mymod')
    . '/my-bit-of-js.js';

}

Then your my-bit-of-js.js file finds the form and submits it immediately.
What this will do
Your form is ajax enabled. Validation errors are returned, as you wish. Once there are no validation errors, the form is submitted, but is actually returned rebuilt identical, except for the inclusion of your auto-submit-my-form js, which submits the form through a non-ajax submission, and from there you can issue whatever redirect you want.
While you could have your js do the redirect (as in your inline example), the benefit of doing the full non-ajax submission is that you can use PHP to determine where to redirect to, since the external js file is not going to be based on any of your form values, which the redirect might need to be. I know in this specific case you just want to reload. So just treat all this as a helpfully intended jus' sayin' :-)
Aside: Multi-step form ajax except last page
I came upon this when I had a multi-page form that I wanted to be ajax until the final page (because I wanted a redirect on final submission). The way I'd done this was that I'd built the last page of the form without the #ajax on the submit elements. This resulted in quirky behaviour though because Drupal could no longer call the ajax callback that would return the last page of the form because it looks to the rebuilt form to find the callback(!). The solution I found was to hide ('#type' => 'hidden') the "next" button and leave it's #ajax stuff in place, but then provide a different submit button without the #ajax stuff (which needed a different #name).
Answer: Instead of messing with ctools i've just set a flag in submit handler to let the ajax callback know that the form was submitted correctly and the page can be reloaded. Then inside the callback function I just returned some JavaScript instead of a form.
function my_module_ajax_callback($form, $form_state) {
  if ($form_state['my_flag']) {
    $ret =  '';
  }
  return $form;
}

Works perfectly.
Comment: Whilst this may work you are injecting inline javascript into the DOM. It is generally thought of as bad practise because it will be hard to modify later.

If you must inject javascript I would suggest you use the #attached key in the form item.
Comment: Yes I know. I don't like this solution either, but it works. In this particular case it made much more sense that adding ctools dependency just for such a small thing.


Positive divisors of prime factorization of n

Question:
Let $n=p_1^{k_1}p_2^{k_2}...p_r^{k_r}$ be the prime factorisation of $n>1$. Show that the positive divisors of n are the integers $d=p_1^{a_1}p_2^{a_2}...p_r^{a_r}$ for $i=1,2,...,r$, with $0\le a_i\le k_i$.

Attempt: We know the positive divisors of n that are powers of $p_1$ are $1, p_1, p_1^2, p_1^3, ..., p_1^{k_1}$, and for $p_2$ are $1, p_2, p_2^2, p_2^3, ..., p_2^{k_2}$ and so on up to $p_r$. Could $d(n)$, the number of divisors function be used somehow? Not really sure how to approach this.
Comment: It's easily checked that each of these is a divisor.  You must show that they are the only divisors.  Use the fact that $p|ab\implies p| a or p|b$
Answer: You could also take this approach. Also remember the definition of a prime ($p|ab \implies p|a \mbox{ or } p|b$)

First, show that any integer of the form $$d=p_1^{a_1}p_2^{a_2}...p_r^{a_r}$$ for $i=1,2,...,r$, with $0\le a_i\le k_i$ does divide $n$ (this is clear and direct..)
Second you can show that any integer not of that form does not divide $n$.  To do this, there are 2 cases: $$d \mbox{ has a prime factor } q\neq p_i \mbox{ for any }i$$ or $$ d=p_1^{a_1}p_2^{a_2}...p_r^{a_r} \mbox{ where for some } i \mbox{, } a_i>k_i$$


Campos de texto (textarea, text, etc) não mostram o ponteiro do mouse e nem o texto digitado

Question: Boa noite, pessoal!
Estou desenvolvendo um ambiente para criação de questionários e, no momento de coletar dados sobre as perguntas, tenho um formulário para cada tipo de pergunta, que é selecionado por um "dropdown-menu". Acontece que os campos de texto destes formulários estão "errados" de alguma forma. O ponteiro do mouse não aparece depois da seleção do campo (clique no campo de texto). O texto digitado também não aparece.
Este problema só ocorre nos campos que estão dentro do esquema de abas, o campo de ler o título do questionário está sem problemas, portanto, imagino que possa ser alguma coisa relacionada a estas abas e/ou a seleção "dropdown-menu".
Segue o projeto no codepen:
https://codepen.io/AmygdalaClicker/pen/ZavgBq
Provavelmente tem muita coisa incompleta e, se tratando da parte de controle, talvez até coisas erradas, portanto, peço que ignorem por enquanto. Gostaria somente de resolver o problema dos campos de texto.
Desde já, obrigado!
Answer: O problema está no color:#fff; da classe:
.tab-content{
    background-color: #B0C4DE;
    color:#fff;
    padding:5px
}

Como está com estilo de cor de texto branca (#fff), o texto fica ilegível nos textarea e nos input por terem fundo branco. Aplique uma cor a esses elementos adicionando o código ao CSS:
textarea, input{
  color: #000; /* neste caso, cor preta */
}

Comment: Muito obrigado pela resposta!

Só ocorreu um outro problema. Realmente o erro parece ser este, adicionei o código ao CSS no codepen e os campos ficaram normais agora. Entretanto, adicionei o código ao meu projeto aqui e a alteração não teve efeito. Sabe o que pode ter ocorrido?

Grato!
Comment: Consegui aqui, mano. Foi só limpar o cache do navegador. De qualquer forma, muito obrigado! Estava a um tempo neste problema.
Comment: @AcreanoDingo-Dingo É isso mesmo. O navegador é chato com arquivos css que guarda no cache. As vezes tenho esse problema tb.


Block updating .NET Framework

Question: For compatibility reasons I want to keep the current .NET Framework version (which is 4.7, the latest version) and stop automatic/silent updates in the future from Windows Update or WSUS only for .NET Framework version while allowing all other system/security updates on a Windows Server 2008 or 2012.
I have found answers for how to prevent updating to a certain .NET Framework version or how to hide the update from the list of updates in Windows Update after the update is already available, but this is not what I want.
What I'm interested is preventing updating from a .NET Framework version when we don't know if, when and to what version an upgrade will be available. E.g. the latest .NET Framework available is version 4.7. Future versions could be 4.7.1, 4.7.2, 4.8 or 4.9 but we don't know yet. How can one prevent these future updates from being installed by Windows Update or WSUS on a Windows Server 2008/2012?
Comment: Only one hour passed since I have asked my question and already have a negative vote which means that my question "does not show any research effort; it is unclear or not useful" :D
Following quote from my question shows (some) research effort: "I have found answers for how to prevent updating to a certain .NET Framework version or how to hide the update from the list of updates in Windows Update after the update is already available, but this is not what I want."
Comment: This quote shows the usefulness: "For compatibility reasons I want to keep the current .NET Framework version (which is 4.7, the latest version) and stop automatic/silent updates in the future from Windows Update or WSUS only for .NET Framework version while allowing all other system/security updates on a Windows Server 2008 or 2012".
If there is something unclear please ask for clarification in a comment.
Comment: I suspect the downvotes are because what you are trying to do would negatively impact any other code which needs to run on a computer you did this to. If your code needs 4.7 and my code needs some hypothetical 4.8, then you blocking updates would prevent my code from ever running. That's unacceptable developer behavior. Thankfully it's unnecessary; see my answer below.
Comment: @Necoras: That is why we would only run code that needs 4.7 on that specific computer. For code that would need some hypothetical 4.8 we would setup a new machine just for that. And it is necessary, see my comment on your answer.
Answer: I think this is a very sensible question, and I'm a bit surprised that the whole internet seems to be trusting Microsoft not to break their stuff (at least in the context of automatic web server .NET Runtime updates).
Yes, what you are asking is not recommended by Microsoft.

Important We strongly recommend that you do not block the installation
  of .NET Framework 4.7.2. However, you may have a business reason to
  temporarily block the installation. For example, you may require more
  time to test line-of-business applications in your environment. In
  such a case, you can modify the registry to temporarily block this
  installation.

And yes, Microsoft .NET Framework Windows Updates are intended to be fully backwards compatible.
But for a critical application on a Production server, there is a definite risk to automatically rolling out version upgrades to the underlying code without first testing them in a Staging environment.  Although rare, there are known instances of existing applications being broken by Microsoft's in-place Windows Updates.  (This is also a risk for updates generally, including security updates.)
To answer your question:
No, there does not appear to be any server-level setting that allows you to block future, unannounced .NET Framework updates generally for computers that directly connect to Windows Update.
As an alternative, the following three workarounds could help you to prevent an untested .NET Runtime update:

If your organization uses an update management solution, such as Microsoft WSUS or System Center Configuration Manager, those tools can be used to selectively approve or defer your updates individually.
You could always stay one version behind.  (Ex: Don't update to .NET 4.7.2 until you can confirm the next "BlockNetFramework48" setting name.)
(Less reliable) Recent .NET Framework version updates have been rolled out as Recommended updates.  If you disable Recommended updates that might partially mitigate the risk that a future .NET Framework version update would be rolled out automatically without testing.
Answer: You shouldn't need to. You can install and run multiple versions of the .Net Framework concurrently. Your application can then target a specific version. So long as that version is available, it doesn't matter what newer versions are also available.
Comment: You can install and run multiple .NET Framework versions only if those versions are say 3.5 and 4.6.2, but not if those versions are 4.0 and 4.7 or any other 4.x version in between. All 4.x versions are installed in the same folder, on top of the previous version so only the newest installed version is available.

Block updating .NET Framework


Erro ao realizar consulta com cáusula GroupBy do Linq no C#

Question: Preciso selecionar os Grupos anteriormente cadastrados, trazendo dados não repetidos. Porém, um erro é retornado quando realizo a consulta na tabela Ponto de Atendimento, onde o campo Grupo no qual é aplicado o GroupBy contém valor nulo. Como adequar o código para que ele não retorne erro se o campo Grupo estiver vazio?
OrigemDados = new OrigemDados(
    pontoAtendimentoService
        .RecuperarTodos(httpContextAccessor.HttpContext.User)
        .Select(pontoAtendimento => new { pontoAtendimento.Id, pontoAtendimento.Grupo })
        .GroupBy(p => p.Grupo)
        .Select(grp => grp.First())
        .ToList()
        .AsQueryable(),
    pontoAtendimento => pontoAtendimento
        .GetType()
        .GetProperty("Grupo")
        .GetValue(pontoAtendimento)
        .ToString(),
    mapeapeamento);

Answer: Resposta ao problema apresentado:
Incluir uma condição para que não considere quando o campo Grupo contiver valor nulo.
.Where(p => p.Grupo != null)
OrigemDados = new OrigemDados(
    pontoAtendimentoService
        .RecuperarTodos(httpContextAccessor.HttpContext.User)
        .Select(pontoAtendimento => new { pontoAtendimento.Id, pontoAtendimento.Grupo })
        .Where(p => p.Grupo != null)
        .GroupBy(p => p.Grupo)
        .Select(grp => grp.First())
        .ToList()
        .AsQueryable(),
    pontoAtendimento => pontoAtendimento
        .GetType()
        .GetProperty("Grupo")
        .GetValue(pontoAtendimento)
        .ToString(),
    mapeapeamento);


Finding commerce custom fields inside a rules loop

Question: I have a few custom fields added to line items (so buyers can add specific information for each item they add to their cart.)
I need access to those custom fields using rules. However, I can't seem to get at them inside of a loop.
In order to get access them in the first place, I used "Entity has field", and they show up just fine to use in actions, until I get inside a loop. line-items:... doesn't include those custom fields.
What am I missing?
Comment: Have you tried https://drupal.org/project/rules_conditional
Answer: The trick for this is to use a component.
Create a new component, and check for the fields using "entity has field". Then, in the original rule, loop over the line items, and put the component inside that loop.
The kicker is that it is impossible (possibly? not I couldn't find a way) to get other product-level fields into this component.


On Progress Event of SpriteSheet Animation Using createjs?

Question: I am using "onAnimationEnd" event but want to do some work when animation is progress. So I want to know current animated frame number via any progress or any event ?
Thanks for your help.
Answer: You can use the tick-event (http://www.createjs.com/Docs/EaselJS/classes/BitmapAnimation.html#event_tick) and the use the properties currentAnimation, currentAnimationFrame and/or currentFrame (http://www.createjs.com/Docs/EaselJS/classes/BitmapAnimation.html#property_currentAnimation)
Update:
Sprite now dispatches a change event whenever the displayed frame changes.
(by gskinner via comments)
Comment: As a note for anyone finding this answer in the future, `Sprite` now dispatches a `change` event whenever the displayed frame changes. http://www.createjs.com/Docs/EaselJS/classes/Sprite.html#event_change


How to make Powershell's Import-Csv correctly import blank spaces

Question: I have a CSV file where some of the cells have a blank space in them, and others are just empty. If I run
" " -eq ""

It returns False so Powershell itself understands the difference between a blank space and an empty string. But, I have a CSV file with the following content:
Header0,Header1,Header2,Header3
FillerData, ,,FillerData

When I import this and compare it I get the following:
PS C:\> $MyCSV = Import-Csv -Path "C:\MyCSV.csv"
PS C:\> $MyCSV.Header1 -eq " "
False

PS C:\> $MyCSV.Header1 -eq ""
True

PS C:\> $MyCSV.Header2 -eq " "
False

PS C:\> $MyCSV.Header2 -eq ""
True

So, Import-Csv defaults to treating CSV entries with a blank space as equal to an empty string, when they're not equal. I really need to import the blank spaces for my use case. Is there any way to make Import-Csv correctly import the blank spaces instead of treating them as empty strings?
Comment: Can you include some lines (including headers) of your csv as plain text here?
Comment: I added an example with some filler data to show the difference between a blank space and an empty string.
Comment: If you control the generation process for the csv, wrap meaningful spaces in quotes - see the output from ConvertTo-Csv for example: ```(new-object pscustomobject -property ([ordered] @{"Header0"="FillerData";"Header1"=" ";"Header2"=$null;"Header3"="FillerData"})) | convertto-csv``` gives ```"Header0","Header1","Header2","Header3"
"FillerData"," ",,"FillerData"``` - note the ```" "``` for Header1's value.
Comment: Of course, I think >95% of my questions have an accepted answer. However, I first need to verify that it actually works. Right now, trying this I get an issue that adding quotation marks makes Import-Csv import them literally.
Answer: If I were a bit better at regex this could be improved but here is working solution, so basically Import-Csv will remove empty spaces by default unless you specify you need a literal blank space. A way to do this is to add opening and closing " on each cell but since your CSV doesn't have that, one way to add those " is this:
$csv = Get-Content ./test.csv

$newCsv = $csv | ForEach-Object {
    $_ -replace '(^|$)','$0"' -replace ',','","'
} | ConvertFrom-Csv

# As you can see, this results in 1 instead of 0
PS /> $newCsv.Header1.Length
1

Edit:
Actually, the foreach-object shouldn't be needed. This works fine too:
$newCsv = $csv -replace '(^|$|[\r\n])','$0"' -replace ',','","' | ConvertFrom-Csv

Edit 2:
Adding mklement0's examples from his comments below.

With ForEach-Object for lower memory consumption however less efficient:

[^,]+ matches any nonempty run of characters other than , i.e. any nonempty field.

$newCsv = $csv | ForEach-Object {
    $_ -replace '[^,]+', '"$&"'
} | ConvertFrom-Csv

Without ForEach-Object (most efficient solution):

$csv = (Get-Content -Raw ./test.csv) -replace  '[^,\r\n]+', '"$&"' | ConvertFrom-Csv

Comment: Ah, so encircling the CSV content with quotation marks would solve that, interesting. I'll have a fiddle with both the CSV files and regex to see where this leads me. I'm doing a lot of importing with CSV files in loops so it might be better for me to just use your example and write the quotation marks to file before I use it in the script. I'll get back to you on this!
Comment: Great approach; you can simplify to a single `-replace` operation as follows: `-replace '[^,]+', '"$&"'`, but note that - as with your approach - this relies on fields having no _embedded_ `,` chars. (which would require such fields to be double-quoted already, which appears not to be the case here).
Comment: `$&` is just an alias of `$0` - you can use them interchangeably. `[^,]+` simply matches any nonempty run of characters other than `,`, i.e. any nonempty field. `ForEach-Object` is worth using with direct `Get-Content` input if the file is too large to fit into memory.as a whole; otherwise, the most efficient solution is: `(Get-Content -Raw ./test.csv) -replace  '[^,\r\n]+', '"$&"' | ConvertFrom-Csv`
Comment: You've come with the right explanation and the fundamentals of the approach, so I think it makes sense to improve your answer rather than my posting another. Feel free to use information from my previous comments to update your answer.
Comment: Oh my, of course! Thank you :) Yes, with those two solutions this works! Thank you so much!
Comment: @mklement0 oh my, that's incredible, can you please explain how this works? `-replace '[^,]+', '"$&"'` i'm really really interested. never seen `$&` being used before.
Comment: Okay, been trying to verify this and now have a clearer understanding of where it fails! All of these assume that the CSV file does not have quotation marks around any of the cells. I cannot control if the CSV file will have quotation marks or not, so if the CSV file already has quotation marks, each entry gets two literal double quotation marks added to the end, probably because the regex adds the quotation marks even if they're already there. I'm currently trying to add some checks to the -replace, will get back to you shortly.
Comment: One solution (found here: https://superuser.com/questions/130592/how-do-you-force-excel-to-quote-all-columns-of-a-csv-file) would be to import all CSV files, then export them back with Export-Csv as Powershell seems to always correctly add quotation marks to all cells, but having to do Import, export back, then re-importing just to ensure double quotation marks seems super-hacky.
Comment: @TanakaSaito I mean, you can always add a condition to your script checking if `'","'` is present then skip this method and use the normal `Import-Csv`
Comment: No problem, glad to help :) @TanakaSaito


Expo: Invariant Violation: ListView has been removed - but I don't use ListView

Question: I inherited a React Native / Expo app. I upgraded the expo version. Now I get the message that ListView has been removed. I have searched
grep -Ri listview * the entire codebase and ListView is not used anywhere in our codes - why am I getting this messages? If a dependency uses it somehow, how do I find out which one?
The emulator stack trace seems to not contain any of our modules, just a bunch of  and loadModuleImplementation
Answer: It seems that ListView was used by some of our dependencies. There were a few mentions of it in node_modules. I think I got them all by updating every single dependency we had to the latest version.
You could update one dependency at a time, one version at a time for a minimal fix, but that would probably take very, very long as constantly running npm install / expo install is very slow.


Prevent IP conflict from untrusted network machines

Question: I maintain a small LAN (192.168.1.0/24) on which we have several untrusted machines, where the users of those machines have administrative rights or are able to connect their own machines to the network.
The server is also on that network (192.168.1.200) and I need to prevent an IP conflict from taking down network services when the user sets his machine's IP the same as the server (possibly maliciously).
I've though about breaking the netowrk into two (something like 192.168.1.0/25 and 192.168.1.128/25).
What's the best way to keep services up?
Comment: You take away the user's admin/root privileges to set a static IP.  Barring that, you explain to the all of 15 people in your office not to set a static IP to 192.168.1.200.  If they do it at that point, it's a disciplinary issue.  This isn't that hard.
Comment: @PolHallen - then you give them a metaphorical smackdown every time they do it
Comment: TheCleaner: any person with a mobile can set static IP address of its smartphone.
Comment: Only if you allow them to connect to WiFi. Don't do that, either. If this happens frequently, try communicating with the users. Most places have a AUP (Acceptable Use Policy) that explains what they are, and are not, allowed to do with devices on the network.
Answer: Move your servers to a separate VLAN - this will mitigate although there is nothing preventing the user from setting his IP to that of the gateway. Or better, move the problem user to his own VLAN.
This can also be solved by using dynamic arp inspection on a good enough managed switch.
This can also be solved by treating it as a disciplinary problem that needs to be addressed at that layer.
Failing that, a Nailbat may be the last resort.
Answer: The technical solution to this sort of problem is 802.1x, but that's probably overkill for this situation.
Make your users trust DHCP and/or don't allow them to modify their IP settings.
Answer: If he knows the IP, and has rights to change the IP address of a machine, there is not much you can do. You could look at playing around with IP Source guard with DHCP Snooping to force the user to use DHCP.
Comment: No, don't do that.
Comment: Maybe I can work on static arp tables?


Find an efficient way to integrate different language libraries into one project using Python as the "glue"

Question: I am about to get involved in a NLP-related project and I need to use various libraries. Some are in java, others in C/C++ (for tasks that require more speed) and finally some are in Python. I was thinking of using Python as the "glue" and create wrapper-classes for every task that I want to do that relies on a different language. In order to do that, the wrapper class, for example, would execute the java program and communicate with it using pipes.
My questions are:

Do you think that would work for cpu-demanding and highly repetitive tasks? Or would the overhead added by the pipe-communication be too heavy?
Is there any other (preferably simple) architecture that you would suggest?
Comment: I think it could be simpler to use Java as the glue and use Jython instead of CPython.
Answer: I would simply advise not doing this.
Don't implement stuff in C/C++ "for speed".  The performance benefit is not likely to be as great as you expect; e.g. compared with implementing in Java using "best practice" design and performance techniques.
Don't try and glue lots of languages together.  You are setting yourself up for lots of portability issues, difficulties in debugging, and reliability issues; e.g. due to C / C++ bugs crashing the JVM.  In addition, there are performance overheads in bridging between languages, and there can be unexpected bottlenecks.  (For instance, you may find that your C/C++ has to be run single-threaded due to threading issues, and that you therefore can't get the benefit of Java multi-threading on a typically multi-core system.)
Instead, I advise you to look for libraries that allow you to implement the entire application in one language.  If that is not possible, design it so that the different language components are different executables / processes, communicating via some kind of RPC, messaging, or whatever.
Comment: In an ideal world, one language would solve all problems. But in NLP, lots of problems don't even admit a perfect solution so you have to select the libraries that give the best approximation.
Answer: Whether or not you'd have problems communicating over pipes / sockets has nothing to do with how CPU intensive the tasks are, but how frequently you'd need to send information between the processes and how much data they need to send. Setting up threads to do your communication will have little processing overhead.
You can probably automatically wrap the C/C++ code with Python (SWIG, ctypesgen, Boost.Python), so the only glue you'll have to write yourself would then be talking to Java.
You could also do it the other way -- run the Python code in the JVM with Jython so the Python and Java code are together, then talk to the C/C++ from there.
Answer: You should take a look at Apache UIMA. It is designed exactly for this. From the project website:

The Frameworks run the components, and are available for both Java and C++. The Java Framework supports running both Java and non-Java components (using the C++ framework). The C++ framework, besides supporting annotators written in C/C++, also supports Perl, Python, and TCL annotators.

UIMA can manage pipes and annotators and is built to scale.
Answer: I would look at Jepp or JPype instead of using IPC for this. I would avoid Jython since loading the C/C++ libraries into Java would probably be harder than into CPython.
Answer:
1) Do you think that would work for cpu-demanding and highly repetitive tasks? Or would the overhead added by the pipe-communication be too heavy?

Depends on your task. If this is a typical NLP app where you have a large model loaded in memory and you only communicate relatively small pieces of data (strings in, label sequences/parse trees out), it may work. Pipe communication is hard to get right, though, since there's a lot of buffering and synchronization issues you have to tackle. Python is a very good glue language, but it doesn't solve everything.

2) Is there any other (preferably simple) architecture that you would suggest?

Make your NLP components services and connect to them via REST interfaces. There are off-the-shelf tools that do this, e.g. CLAM. Pyro and SPIRO make communication between Java and Python even more direct and might be easier to use than HTTP/REST (but YMMV).
The parts that are written in C/C++ can also be integrated with CPython using Cython. Don't start implementing things in C or C++ because you think they'll be faster, though; you can also implement them in Python first, then see if you can get the desired performance with NumPy and/or Cython.


Informação contida em duas páginas Scrapy

Question: Não sou um programador de python, mas estou tentando trabalhar com a aplicação Scrapy.

O exemplo acima é o que preciso, isto roda em extensão do chrome.
Para explicar, eu preciso do post e todas informações disponíveis.
No caso do Post, nas categorias tem informação algumas(Short Desc, e outros) e informação no Post(Long Desc). São informações diferentes do mesmo Post.
A minha dúvida esta no processo, no primeiro loop tenho Posts que precisa de informações de um Segundo Request, que após o parse extract teria as informações.
Ficando assim
 Post.short_desc = ['xxxx'] ¹ loop

 Post.long_desc = ['xxx'] return ² loop

Como faço isto?
Agora que complica um pouco.
Pois dentro do Segundo Loop, preciso adicionar as Categorias,Tags na fila para ser processado.
Fila.lista -> Add -> Url

Como faço isto?
Eu não sei como realizar isto, se puderem me ajudar. Obrigado
Answer: A maneira tradicional de extrair dados de múltiplas páginas e usar o mecanismo de passar dados entre uma requisição e outra usando o dicionário meta.
Funciona assim: no callback que está extraindo o conteúdo da primeira página você monta um dict com os dados iniciais:
def parse_pagina_de_listagem(self, response):
    inicial = dict(
        short_desc=response.css('...').extract(),
        ...
    )
    # pega url da pagina com restante dos dados
    url = response.css('...').extract_first()

    # monta uma requisicao passando os dados com o parametro meta
    request = scrapy.Request(request.urljoin(url), callback=self.parse_restante)
    request.meta['item'] = inicial

O Scrapy vai enviar a requisição assincronamente, e irá passar adiante o valor na resposta.
Dessa forma, você pode receber o item inicial no callback parse_restante, e também agendar as requisições para outras páginas a seguir dentro dele:
def parse_restante(self, response):
    # recupera item do meta
    inicial = response.meta['item']

    # faz o restante da extracao do post
    yield dict(
        inicial,
        long_desc=response.css('...').extract_first(),
        ...
    )

    # segue para outras paginas, se necessario
    for link in response.css('...').extract():
        yield scrapy.Request(response.urljoin(link),
                             callback=self.parse_pagina_de_listagem)

Leia mais:

Tutorial de Scrapy que explica como seguir páginas
Documentação do Scrapy (em inglês), explica como usar o dicionário meta
Comment: Obrigado Elias. Você entendeu perfeitamente o que falei. Realmente vi poucos tutoriais, executei alguns e outros, mas todos eram sem seguir. Acredito que agora consigo progredir e por em pratica testes e funções. vlw
Comment: @Luiz Legal! Qualquer coisa, segue perguntando aqui. :)
Comment: Vlw jovem, graças a sua resposta consegui resolver um erro que tava me fudendo aqui


How can i refer one property file from another property file in spring cloud config

Question: I have to implement spring cloud config for an existing project where i have an use case to handle
Here Some property files are referred by other property files like
logging.propFile=classpath:/cfg/xyz.properties and these property files are used in multiple places like
Properties property = new Properties();
property.load(new FileInputStream(propsPath));
logger = somefactory.createfactory(property.get("logging.propFile")); and this factory creation is defined in a different jar.
If i move all property files in git repo files i mentioned will not be available in class path and if i go for code change a lot of code change is involved.What is the best way to handle this situation.
Is there any way to refer one property file to another in spring cloud config .
Answer: Spring Cloud Config server allows for reading static files through HTTP. So you can put your references properties file into the configuration git repository and reference them through http://<configserver_url>/*/*/<branch_name>/xyz.properties. This only works when your code can handle URLs, so the FileInputStream in your example would not do it.
See https://cloud.spring.io/spring-cloud-config/multi/multi__serving_alternative_formats.html and https://cloud.spring.io/spring-cloud-config/multi/multi__serving_plain_text.html.
Also note the resolvePlaceholders query parameter that defaults to true.
We are using this for keeping our logback.xml configuration in the config server by setting logging.config: http://<configserver_url/*/*/master/logback.xml?resolvePlaceholders=false


Estimating and comparing treatment effects with participants that have repeated measurments

Question: Suppose we run an experiment with 50 participants. We take repeated measurements from each participant: each undergoes three different treatments during which we measure their reactions (our continuous target variable). A toy example of such dataset could be generated as follows:
# Example Data
treat_1 = rnorm(50,10,2)
treat_2 = rnorm(50,20,2)
treat_3 = rnorm(50,20,2)

df = data.frame(participant_id = rep(1:50,3),
                treat_type = c(rep("1",50), rep("2",50), rep("3",50)),
                y = c(treat_1,treat_2,treat_3))

I am seeing people saying that when repeated measurements are involved we cannot simply run a linear regression and we need more sophisticated approaches such as mixed models and etc. But personally I don't understand what can go wrong with the following approach:
fit = lm(y ~ -1 + treat_type, data = df)

The only issue I can see, is that we are not accounting for heteroscedasticity (which is not the case in this example).
My question is if the approach I just showed is OK for estimating the treatment effects on the target variable considering that our dataset includes repeated measurements (three observation per each participant)? If not can someone please explain the reasons?
As a side question, why bother using t-test or ANOVA (which are common for comparing groups) that do not even provide any distributional information on the effects and just give p-values on whether there is a significant difference among the groups when we can fit a model that does give such information?
Answer: That is a perfectly fine way to estimate the treatment effect. You can increase your precision by including a fixed effect for participant, i.e.,
fit = lm(y ~ -1 + treat_type + factor(participant_id), data = df)

This will not change the estimate if all participants have an equal number of observations for each treatment, but it will reduce the residual variance and increase precision (same reason we use a paired-samples t-test instead of an independent samples t-test when we have two treatment levels). This is equivalent to a repeated measures ANOVA.
You can also include participant ID as a random effect, e.g.,
fit = lme4::lmer(y ~ treat_type + (1|participant_id), data = df)

This should yield the same estimate as the fixed effect approach but the precision might be a little different.
Note that you should account for possible heteroscedasticity by using a robust standard error, which is easier with a fixed effects model. Some might note that observations from the same participant are correlated with each other and so you should use a cluster-robust standard error. This is not necessary as explained by Abadie et al. (2022). The usual robust standard error is sufficient.
I would recommend using estimatr::lm_robust() to do this, e.g.,
fit = estimatr::lm_robust(y ~ treat_type, data = df,
                          fixed_effects = ~participant_id)

This automatically incorporates the fixed effects and produces robust (non-clustered) standard errors.
Comment: The *precision* is the key point. You can estimate the effect size fine, but if you want to know whether it's significant, you're better off accounting for differences between participants.
Comment: Thanks. Do you think three observations per participant is enough for estimating the participant effect? I am concerned about including participant id, which will be one-hot-encoded, because the ratio of predictors to observations will be roughly 1/3 and that increases the risk of overfitting.
Comment: @pixy there are no problems with that. A paired samples t-test (2-observations per participant) is exactly equivalent to regression including participant fixed effects. If you're okay with a paired t-test, you're okay with the fixed effects method. You're in an even better case here since you have 3 observations per participant. If you use `estimatr::lm_robust()` you can include fixed effects in an efficient way and estimate robust standard errors automatically, so I would recommend doing so rather than using `lm()`.
Comment: I am not sure if they are exactly equivalent. In the paired t-test, participants effect is differenced out, and is not estimated whatsoever. So the test is equivalent to regression with only one covariate. But in regression with participant fixed effect, for each participant there is a parameter to estimate. So the latter is much more paramterised compared to the former. Ain't that true? But I also get your point that including participant id leads to explaining more variance and thus more precision.
Comment: @pixy It might seem that way, but numerically they are identical (the estimate and its standard error). If you don't believe me, try it out for yourself on simulated data. In a paired samples t-test, your df is cut in half because you are using difference scores instead of the original observations. In a fixed effects model, your df is cut in half because you estimate a fixed effect for each individual. But that leaves the same df for both methods.


Closed form of the integral

Question: $$I=\int_{-1}^1 \frac{\sin\left(\frac{\sinh x}{x}\right)\cdot\log\left(\frac{1+x}{1+x^2}\right)}{x} \space\text{d}x$$
According to Wolfram Alpha, the integral comes out to $$I=2.1607...$$
I don't have a clue on how to solve this because of how the $x$ value is deeply nested here. An answer I am looking for does the following:
a) Showing each step. All of your steps also much use only the real plane. I.E. Real Analysis
b) You don't have to state theorems in your work, but if what you did is not obvious, just explain.
Thanks for any help.
EDIT: this integral has a specific application. That application is that I am just beginning to work on nested integral arguments. The further I get in my study, I consistently give myself challenge problems. Strangely, after a while of trying to crack this, I got nowhere! I just wanted to see how to do this and where my mistake lay. (On original trial of the problem, I tried to substitute $x^2$ with $-u^2$ and ignored the fact that $x \not\to -u$)
Comment: Why do you think the integral has a closed form? Where does it come from? ...
Comment: @0.5772156649... Wolfram Alpha is able to compute the integral with an approximation method. If I had to, I'd bet this integral has no "closed form".
Comment: He edited the question to add context
Comment: What are the limits of integration to get 2.1607? Your image didn't link correctly. Is it $(-1, 1)$?
Comment: Of course, I forgot! Hold on
Comment: @BenLongo Better? Thanks for pointing that one out
Comment: Yeah, don't forget that $dx$ ;).
Comment: @BenLongo Dude, thanks for these comments
Comment: Might I ask why down vote?
Comment: There might be some problems at $x=0$.
Comment: @BenLongo The function has a removable singularity at $0$.
Comment: The Gamma function is an integral whose argument is in a closed form: $$\Gamma (t) = \int_0^{\infty} x^{t-1} e^{-x} \, dx.$$
Comment: @MarkFantini Oh crap you're right. I guess I'll have to base my reason on intuition.
Comment: This question should not have been closed.
Answer: I will give some of my own estimates.. Note that
$$
\begin{align*}
\int_{-1}^1 \frac{1}{x} \sin\left(\frac{\sinh x}{x}\right) \log\left(\frac{1+x}{1+x^2}\right) \mathrm{d}x
& = \int_{-1}^1 \frac{1}{x} \sin\left(\frac{\sinh x}{x}\right) \Bigl[ \log\left( 1 + x\right) -  \log\left(1 + x^2\right) \Big] \mathrm{d}x \\
& = \int_{-1}^1 \frac{1}{x} \sin\left(\frac{\sinh x}{x}\right) \log(1+x) \mathrm{d}x
\end{align*}
$$
Due to the symmetry of the last integral. For example split it at $x=0$ and use the substitution $x \mapsto -x$ on the integral over $[-1,0]$. Again we can map the integral onto $[0,1]$. Introducing the function
$$
f(x) = \frac{1}{x} \sin\left(\frac{\sinh x}{x}\right) \log(1 + x)
$$
The integral can then be written as
$$
\begin{align*}
\int_{-1}^{1} f(x) \,\mathrm{d}x
& = \int_{0}^{1} f(x) + f(-x)\,\mathrm{d}x \\
& = \int_0^1 \frac{1}{x} \sin\left(\frac{\sinh x}{x}\right) \log\left(\frac{1+x}{1-x}\right)\,\mathrm{d}x
\end{align*}
$$
The reason for these algebraic manipulations is that the taylor expansion of the last expression converges much faster. It only contains $\sin x$ and $\log(1 \pm x)$ which are both very well known. We have
$$
\log \frac{1+x}{1-x} = 2\sum_{k=0}^\infty \frac{x^{1+2k}}{1+2k}\\
\frac{\sinh x}{x} = \sum_{j=0}^\infty \frac{x^{2j}}{(1+2j)!}
$$
Combining these and finding the taylor expansion (allowed since $|x|\leq 1$ we get
$$
f(x) \sim 2 \sin(1) + \frac{x^2}{3} \bigl(2 \sin(1) + \cos(1)\bigr)+ \frac{x^4}{180} \bigl(67 \sin(1) + 23 \cos(1)\bigr)
$$
Integrating from $0$ to $1$ we get
$$
\int_{0}^{1} f(x) \,\mathrm{d}x = \frac{689}{300} \sin(1)+\frac{41}{300}\cos(1) \approx 2.006419677
$$
Which is - if I dare so myself - a darn good estimate. Seeing from the taylor expansion that the answer will always be on the form $a \sin 1 + b \cos 1$, one can improve these constants somewhat. For example
$$
\frac{268}{125} \sin 1 + \frac{33}{50} \cos 1
$$
Which is good for 9 decimals give or take.

Closed form of the integral


Given two int arrays, return an array of length 2 containing as much will fit from the first and second array

Question: I'm trying to solve the exercise bellow. I don't get any compiler errors.
When I run it though, in the main method only the first Make2 gets called and the program stops working with this error:
The program '[4864] Make2Two.vshost.exe' has exited with code -1073741510 (0xc000013a).
Could someone help me with that?
And is there any better way to solve the problem? I think I put too much unnecessary code.
Thanks a lot.
Problem:  Given 2 int arrays, a and b, return a new array length 2 containing,
as much as will fit, the elements from a followed by the elements from b. The arrays may be any length, including 0, but there will be 2 or more elements available between the 2 arrays.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Make2Two
{
    class Program
    {
        static void Main(string[] args)
        {
            Make2(new int[] { 4 }, new int[] { 4, 2, 3 }); //output 44
            Make2(new int[] { 2, 3 }, new int[] { 2, 3, 6 }); //the others are not running
            Make2(new int[] { 2, 5 }, new int[] { 7, 6, 5 });
        }
        public static int[] Make2(int[] a, int[] b)
        {
            int[] result = new int[2];
            if (a.Length >= 2)
            {
                for (int i = 0; i < 2; i++)
                {
                    result[i] = a[i];
                    Console.Write(result[i]);
                }
                Console.WriteLine();
                Console.ReadLine();
            }
            if (a.Length < 2)
            {
                for (int i = 0; i < 2; i++)
                {
                    result[0] = a[0];
                    if (i == 0)
                    {
                        for (int j = 1; j < 2; j++)
                        {
                            result[j] = b[j - 1];
                            for (int k = 0; k < result.Length; k++)
                            {
                                Console.Write(result[k]);
                            }
                        }
                        Console.WriteLine();
                        Console.ReadLine();
                    }
                }
            }
            return a;
        }
    }
}

Answer: How about this?
int[] a = new int[5];
int[] b = new int[5];

var result = a.Concat (b).Take (2).ToArray();

PS: Would recommend reading about LINQ (https://msdn.microsoft.com/en-us/library/bb397897.aspx)
Comment: @xanatos read the excercise. There are garanteed to be 2 elements : 'The arrays may be any length, including 0, but there will be 2 or more elements available between the 2 arrays'
Comment: Haha, A bit late to post, but yeah this is way I'd go with it.
Answer: I do think you are overcomplicating it a little...
And your code is wrong:
result[0] = a[0];

How can you be sure that a has at least one element? You should check it!
Let's try in another way: three indexes: i (index of result), ai (index of a), bi (index of b). We always increment i. We increment ai or bi when we respectively take an element from a or from b.
public static int[] Make2(int[] a, int[] b)
{
    int[] result = new int[2];

    for (int i = 0, ai = 0, bi = 0; i < result.Length; i++)
    {
        if (ai < a.Length)
        {
            result[i] = a[ai];
            ai++;
        }
        else if (bi < b.Length)
        {
            result[i] = b[bi];
            bi++;
        }
        else
        {
            break;
        }

        Console.Write(result[i]);
    }

    Console.WriteLine();

    return result;
}

Another possible solution. Here we have two for cycles, one for a and one for b. The index i for result is shared.
public static int[] Make2(int[] a, int[] b)
{
    int[] result = new int[2];

    int i = 0;

    for (int ai = 0; i < result.Length && ai < a.Length; i++, ai++)
    {
        result[i] = a[ai];
        Console.Write(result[i]);
    }

    for (int bi = 0; i < result.Length && bi < b.Length; i++, bi++)
    {
        result[i] = b[bi];
        Console.Write(result[i]);
    }

    Console.WriteLine();

    return result;
}

Addendum: if you want to check that your algorithm works, you should check corner cases like:
Make2(new int[] { }, new int[] { 1, 2 }); // output 12
Make2(new int[] { 4, 5 }, new int[] { }); // output 45
Make2(new int[] { 1 }, new int[] { 5 }); // output 15

Note that in general, functions that do calculations and functions that write should be separate, so you should remove all the Console.Write from Make2 and put them in a separate method, that should be called by the Main method.
Answer: public int[] make2(int[] a, int[] b) {
  int[] arr=new int[2];

  if(a.length>=2){
    arr[0]=a[0];
    arr[1]=a[1];
    return arr;
  }
  if(a.length==1){
    arr[0]=a[0];
    arr[1]=b[0];
    return arr;

  }
  if(a.length==0){
    arr[0]=b[0];
    arr[1]=b[1];
    return arr;
  }
  return arr;

}

Comment: add more details
Answer: public int[] make2(int[] a, int[] b) {
  int[] array = new int[2];

  int counter = 0;

 for(int i=0;i<a.length;i++)
 {
   if(counter < 2)
     array[counter++] = a[i];
 }
 for(int i=0;i<b.length;i++)
 {
   if(counter < 2)
     array[counter++] = b[i];
 }
  return array;
}

Run separate for loops to check the elements in each array.
Comment: Take an additional counter variable and run up to the length of new array.
Answer: public int[] plusTwo(int[] a, int[] b)
{
    int res[]=new int[4];

    for(int i=0; i<2; i++)
    {
        res[i]=a[i];
        res[i+2]=b[i];
    }

    return res;
}

Comment: Given 2 int arrays, each length 2, return a new array length 4 containing all their elements.

plusTwo([1, 2], [3, 4]) → [1, 2, 3, 4]
plusTwo([4, 4], [2, 2]) → [4, 4, 2, 2]
plusTwo([9, 2], [3, 4]) → [9, 2, 3, 4]
Comment: please edit your answer and add there your description from comment.
Comment: Code without explanation is not recommended. Please provide how/why this resolves the problem.


Link same domain to AWS and DigitalOcean

Question: I want to link the same domain name to AWS and DigitalOcean.
Currently, www.domain.com is linked via Route53 to an S3 Bucket and I want api.domain.com to be linked to a droplet in DigitalOcean.
The problem is that DigitalOcean asks me to update the DNS records in my registrar panel. But I've just done it with AWS DNS servers.
So how can I do ? Am I missing something ?
Thanks.
Answer: You cannot have both Route53 and DO as authoritative resolvers for your domain.
All you need to do, though is just create an A record for api.domain.com in R53, pointing to the IP address of your DO instance.
Answer: Since api.domain.com is a subdomain and therefore different to domain.com you just need to have a separate A record for each pointing where you want. Don't think of this as pointing the same domain to two places because its not.


How to find the number of clicks on a flash banner?

Question: There is a flash banner in a Drupal website. I want to know number of clicks on that flash banner.
My Question: Is there such option in Drupal (in Joomla there is one).
Answer: I would recommend using Google analytics and attach a click event to the banner. using a module would introduce unnecessary overheads
Answer: You can follow WestieUK by installing the Google Analytics-module on your website or you can install the Click-module (Drupal < 6 only) so the admin can see exactly on which links, images,... are clicked by the users.
Or you can use the Advertisement module, which will allow you to place a banner on your site and the module tracks down the traffic it's generating. And Flash is a supported format!
Comment: Did you manage to get the analytics behind the banner?


windows 2003 server security audit -logging computer IP

Question: We have a network with 1 primary domain controller and 3 additional domain controllers.
We're trying to identify a user who attempted to use someone else's credentials to access some resources in our organization. At this point we want to see from what computers there were failed logon attempts with that respective user.
We enabled on the PDC success & failure audits for Account logon event & logon event and I made some tests from my computer.
The failed attempt is indeed logged in Event Viewer but the client IP is totally wrong (it's not logging  my IP it's logging one of the additional domain controllers). What do I need to do to track the REAL ip?
I assume the workstation connects to the first available domain controller, and that DC authenticates to the PDC. But how do I solve this?
Thank you!
EDIT
As stated in the comments, I looked on the ADC that was reported by the PDC but there were no failed log on attempts. The security policy settings seem to apply to all DC's from the domain so it should have logged it...
On a related note
I made some tests with an XP workstation: I enabled object access auditing, added the users to track, also enabled log on auditing; but it logs ONLY the username, not the ip (or at least the name) of the workstation - not even in the logon security report!!!.
I gotta say I'm really disappointed with these features from a product that sells itself as enterprise level. Either that, or I'm doing something wrong and I could use some pointers.
Comment: Have you tried looking at the DC it gave you the IP address for and tracing from there?
Comment: Yep. I tried there but there were no failed logons. The DCs do inherit the audit settings from the PDC, don't they?
Answer: The DC that processes the request will have an event in its event log with the clients IP.
Is this 2003 or NT4?
Also have a read of this document, it was a huge help in us tracking down which client was causing a similar issue.
Technet: Maintaining and Monitoring Account Lockout
Cheers...Gary


New billing fields not showing on User page (Poor Guys Swiss Knife plugin for WooCommerce)

Question: Using Poor Guys Swiss Knife plugin for WooCommerce, I created 3 new Billing fields: birthday (date), newsletter (select: yes/no) and terms & conditions (select: yes/no). I successfully registered as a new customer on the site and filled these new fields.
However when checking the account thus created in the dashboard, I see all the regular fields except the 3 ones I created with the Poor Guys Swiss Knife plugin. Why is that ?
Answer: Clearly plugin is not sending fields data to user account.
You can achieve same results using woocommerce custom fields in your functions.php file.
// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
     $fields['shipping']['shipping_phone'] = array(
        'label'     => __('Phone', 'woocommerce'),
    'placeholder'   => _x('Phone', 'placeholder', 'woocommerce'),
    'required'  => false,
    'class'     => array('form-row-wide'),
    'clear'     => true
     );

     return $fields;
}

To make it required use this code:
/**
 * Process the checkout
 */
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');

function my_custom_checkout_field_process() {
    // Check if set, if its not set add an error.
    if ( ! $_POST['my_field_name'] )
        wc_add_notice( __( 'Please enter something into this new shiny field.' ), 'error' );
}

you can find more on this website:
http://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/
Comment: Thanks, but although the field does appear during checkout process, it still doesn't show up on the dashboard Users page.
Answer: Here is a solution that I came up with and it has been working fine for me, hope it helps you as well.
I created a few new fields for the billing form using that plugin but let's just use one as an example:
-Resale License # ( billing_resale_license_ )
Now, the plugin ( or the code from the first answer ) will add the field to the form for you, in my case, I end up with:
<input type="text" class="input-text " name="billing_resale_license_" id="billing_resale_license_" placeholder="" value="" display="text">

Now, we need to save the value of that field to the user_meta table, like so:
add_action( 'woocommerce_checkout_process', 'ws_billing_fields_save', 10, 1 );

function ws_billing_fields_save( $user_id ){
    if ( isset( $_POST['billing_resale_license_'] ) ) {
        update_user_meta($user_id, 'billing_resale_license_', $_POST['billing_resale_license_']);
    }
}

Now that data is stored in user_meta, we need to hook in to the profile area to display it and allow it to be edited by the user or admins.
add_action( 'show_user_profile', 'ws_update_user_profile' );
add_action( 'edit_user_profile', 'ws_update_user_profile' );

function ws_update_user_profile( $user ){ ?>

Additional Fields

        Resale #
        <input type="text" name="billing_resale_license_" value="<?php echo esc_attr(get_the_author_meta( 'billing_resale_license_', $user->ID )); ?>" class="regular-text" />

add_action( 'personal_options_update', 'save_extra_fields' );
add_action( 'edit_user_profile_update', 'save_extra_fields' );

function save_extra_fields( $user_id ){
    update_user_meta( $user_id,'billing_resale_license_', sanitize_text_field( $_POST['billing_resale_license_'] ) );
}

I chose to break my additional fields into their own table just above the default Woocommerce fields as I have many of them and they are more specific to the user rather than the order processing itself, so I keep them organized in their own table titled "Additional Fields".
Answer: I think the billing fields are visible on the order only, not the user. User fields are available through the register_form and user_register hooks.


Change UIImageView Center - iPhone

Question: I am trying to make a little ball that rolls around based on the accelerometer values in the iPhone.
This code will not build:
<code>-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
 if(difficulty == @"Easy")
 {
  CGFloat newX = (CGFloat)(ball.frame.origin.x + (CGFloat)acceleration.x);
  CGFloat newY = (CGFloat)(ball.frame.origin.y + (CGFloat)acceleration.y);
  ball.frame.origin.x = newX;
  ball.frame.origin.y = newY;
 }
}
</code>
It gives me an lvalue required as left operand of assignment error.
I've tried 100 different things and I fail every time...This is just the latest failure.
Anyone have any insight?
Answer: You have to set the center in it's entirety:
<code>-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
 if(difficulty == @"easy")
 {
  CFPoint center = ball.center;
  CGFloat center.x = (CGFloat)(ball.x + (CGFloat)acceleration.x);
  CGFloat center.y = (CGFloat)(ball.y + (CGFloat)acceleration.y);
  ball.center = center;
}
}
</code>

Change UIImageView Center - iPhone


When will SoftLayer_Product_Package::getLocations() be disabled?

Question: SoftLayer support asked me to ask this question here at stack overflow,
so I am asking here and hopefully someone internal can answer...
According to January 11, 2016 note from here:
  https://softlayer.github.io/release_notes/
SoftLayer_Product_Package::getLocations() is deprecated.
When will it be disabled?  January 18th?
Answer: There is not currently a date when SoftLayer_Product_Package::getLocations method will be disabled. So as the release notes, we recommend to use SoftLayer_Product_Package::getRegions, since it contains the correct data.


Define available default colors for Color Field programatically

Question: I use the Color Field as a field in a custom module from where I create the content type programatically.
By default the available colors are defined at this hook:
color_field_field_settings_form
in the color_field module.
I need to modify the list of available colors and I wanted to do at the field creation time.
At my _slider_installed_instances function I have:
EDIT: Added the settings section with no results.
<code>        'slider_background' => array(
                'field_name' => 'slider_background',
                'type' => 'color_field_rgb',
                'label' => $t('Slider background color'),
                'widget' => array(
                        'type' => 'color_field_default_widget',
                ),
                'settings' => array(
                        'default_colors' => array(
                                'default_value' => '#AC725E,#D06B64',
                        ),
                ),
                'display' => array(
                        'default' => array(
                                'label' => $t('Slider background color'),
                                'type' => 'text'
                        )
                ),

        ),
</code>
and I wonder how to define the settings for default colors so the list will be the one defined by me at my module.
I'll appreciate any hint.
Thanks in advance.
Answer: Finally to achieve I move to implement in my custom module the hook hook_field_info_alter and update at this hook the $info[field]['settings']['default_colors'] list of hex color values.
I couldn't find the solution I was looking for.
Answer: You are using the following code:
<code>'settings' => array(
  'default_colors' => array(
    'default_value' => '#AC725E,#D06B64',
  ),
),
</code>
The correct structure for the settings array is the following one, in your case.
<code>'settings' => array(
  'default_colors' => '#AC725E,#D06B64',
),
</code>
Comment: @ShawnConn how does this not answer the question?  It points out before/after of what the code should be.  Is it *incorrect*?  If so, that that needs to be pointed out in a comment and/or downvote (incorrect answers are still answers, but what the voting system is for).
Comment: I added the part of the code that should be changed, but it was obvious what this answer suggested.
Comment: I am far from that code now (job change), so I can't check if it works, but it looks like it will work. Thanks. I will notice for the next. If I have the chance to recover the code I will come back to confirm it. btw, who is @ShawnConn?


How to perform segue from UITableView to UIView?

Question: I have my TableViewController setup as different Static cells, with 18 different buttons all setup in storyboards. Each button should segue to my View but bringing down some set of information with it. So far,I have given each button a different tag &  I have it so that for each box, it assigns a value to a variable, I have tested this to be working with my console:
- (IBAction)startClicked:(id)sender {

    if ([sender tag] == 0) {
        _selectionName = @"Box A";

    }
    else if ([sender tag] == 1){
        _selectionName = @"Box B";

    }
    else if ([sender tag] == 2) {
        _selectionName = @"Box C";

    }
}

But now, my question is: How to I add a segue to from my TableViewController to my  view AND bring  _selectionName's value as well?
Please be as detailed as possible, sample code would be great. Cheers
Answer: You don't segue from a UITableView to a UIView.
Segues are from one view CONTROLLER to another.
If you're using static cells, you should be able to control-drag from the buttons to the destination storyboard scene(s). Name each segue with a unique name, and then implement a prepareForSegue method. In that method, check the segue name, and use it to set up the desired properties in your destination view controller.
Alternately, you could use an IBAction like you are doing, and then in that IBAction set up your _selectionName as you have it in your post, then, use the method performSegueWithIdentifier:sender:  to invoke your segue. Again, use the prepareForSegue method to pass your _selectionName value to a property of your destination view controller.


How do I force unique values within a multi-value set?

Question: When programming my own field and autocomplete widget, how can I ensure that each delta has a unique value?
I would like to handle the case as much silently as possible, so to not bother user with validation errors. Most gladly I would just prohibit the autocomplete test from returning the duplicate matches but as far as I can see, the autocomplete function does not accept any context, just the search string.
Should I then keep the already selected values in a session variable - would it be the Drupal way?
Answer: It might be easier to filter the autocomplete results using JS. You could either extend the prototype being used by Drupal or use some sort of trigger for when the results are being displayed.
I don't think that server-side solutions such as session variables and so on are practical as there's no guarantee that the results of previous calls were actually used by the user. Similarly, hacking the autocomplete feature to perhaps send existing values along with current user input is inherently impractical.
Comment: Thank @coleopterist, you are apparently right. I just bumped into this post http://sachachua.com/blog/2011/08/drupal-overriding-drupal-autocompletion-to-pass-more-parameters/ and I'm digesting the code.


O que é uma função reentrante?

Question: Para que ela serve? Quando ela é reentrante? Qual é a diferença para uma função recursiva? E para a função thread safe?
Answer: A função reentrante é aquela que pode ser chamada de forma segura várias vezes concorrentemente sem causar efeitos indesejáveis. Ela precisa ser independente, e não ser afetada mesmo que haja interrupção na execução.
Uma função recursiva pode ser reentrante, mas nem sempre. Não há necessidade de função reentrante ser recursiva.
Certamente uma função reentrante é thread safe, mas não são sinônimos, porque uma função thread safe ainda pode ter efeitos colaterais.
Uma função reentrante é pura, em certa medida. Então além dela não poder modificar estado externo a ela, a não ser que tenha alguma proteção adequada para garantir a atomicidade da operação de forma isolada, ela também não pode se modificar, e só pode chamar outras funções reentrantes. Então ela pode ser menos pura, desde que dê certas garantias.
Apenas proteger um objeto com mutex em estado global ou algo do tipo, pode não ser suficiente. Se uma interrupção no processo para executar alguma outra coisa afetar o funcionamento do que estava fazendo então não há reentrância. A garantia de sincronização pode ser feita na função reentrante ou de forma global pela aplicação.
A forma mais fácil que garantir reentrância é ela ser totalmente pura, ainda que não precise, caso contrário terá que fazer uma análise profunda para garantir que nada será afetado em ambiente concorrente.
Exemplo de reentrância simples:
<code>void swap(int* x, int* y) {
    int tmp = *x;
    *x = *y;
    *y = tmp; //Hardware interrompe e chama a isr()
}
void isr() {
    int x = 1, y = 2;
    swap(&x, &y);
}
</code>
Coloquei no GitHub para referência futura.
Note que nada será afetado, a nova chamada é completamente independente e não afeta o resultado do que estava fazendo, os parâmetros de uma chamada não se confundem com os da segunda chamada.
Código puramente funcional é sempre reentrante, mas em código imperativo, ainda mais orientado a objeto, quase sempre não é, e necessita análise se precisa garantir a reentrância.
Comment: Não, seria *reentrant*, até porque não é o mesmo que idempotente que é um requisito para ser reentrante.
Comment: Então "reentrante" seria o que, em inglês, chamam de *idempotent*? Ver também: https://pt.stackoverflow.com/q/226232
Comment: Entendi. E idempotência também não implica nada a respeito de concorrência.
Comment: Certamente, grosso modo a reentrância é um *superset* de idempotente.

O que é uma função reentrante?


Why is this allowed? ("Fourier's Trick"; finding the coefficients in a Fourier Series)

Question: In my textbook (Introduction to Electrodynamics, D. Griffiths), we derive the equation for some strange potential function. Eventually, we get to this (for $n \in \mathbb{Z}^+$):
$$ V_0(y) = \sum_{n=0}^{\infty} C_n\sin{\frac{n\pi}{a}y} \tag{3.31}$$
Here's where things go awry for me.

... how do we actually determine the coefficients $C_n$, buried as they are in that infinite sum? The device for accomplishing this is so lovely it deserves a name—I call it Fourier's trick, though it seems Euler had used essentially the same idea somewhat earlier. Here's how it goes: Multiply Eq. 3.31 by $\sin{n'\pi y/a}$ (where $n'$ is a positive integer), and integrate from 0 to a:
$$ \displaystyle \sum_{n=0}^{\infty} C_n \int_0^a\sin{\frac{n\pi}{a}y} \sin{\frac{n'\pi}{a}y} dy ~~~=~~~ \int_0^a V_0(y)\sin{\frac{n'\pi}{a}y} dy$$

The answer understandably comes out to something very nice and convenient. But... why is this something you can do? There's no obvious reason for why that doesn't intrinsically change the problem (in the same way that I can say "Multiply both sides by $0$. You've successfully reduced the problem to zero. Well done!)
(While typing out the above, I suspect that it has something to do with the inner product of a function and an orthonormal basis? The infinite $\sin$ functions create an orthonormal basis, and taking that integral over all possible values effectively extracts the coefficients for each basis function. When it is suggested that we multiply by $\sin{\frac{n'\pi}{a}y}$ and integrate, this isn't changing the basis at all, it's just (sneakily) extracting the coefficients, which only exist when $n = n'$ (because the $\sin$ functions are all orthogonal). It's like taking the coefficients of a basis with itself... right?
I think this may be one of those cases where, in the process of asking the question, I figure out the answer—but this is all fairly new to me, and I'd like to ask it anyway for confirmation and, possibly, a clearer explanation).
Comment: Multiplying both sides of an equation by $0$ is perfectly valid, but the resulting equation $0 = 0$ isn't helpful.  With Fourier's trick, we multiply both sides by something non-zero, then integrate both sides, and obtain a result which is helpful.
Comment: What do you mean when you say we're multiplying "a lot" of the terms by zero?  All the terms are getting multiplied by the same thing.  Then, we integrate, and it turns out that all but one of the integrals on the left are equal to $0$.
Comment: @AmagicalFishy you are not multiplying by zero , the function which you are multiplying when integrated makes all but one term zero.
Comment: I know what the function does—but I still don't understand why this is considered "not multiplying by zero". It just seems like a neat way of *selectively* multiplying by zero.
Comment: I know you can do whatever you want to both sides of an equation, but you're still multiplying a lot of the terms by zero here (which is why so many of them drop out). There are a *lot* of $C_n$ terms there (infinite); the part about orthogonal basis was meant to explain why you're not losing any information when you multiply those terms by zero.

Is it an accurate explanation?
Comment: Fourier used the integral 'orthogonality' conditions to isolate the coefficients, without much regard to whether or not one may interchange integration and summation. This gave a formula for coefficients, and he then studied how the resulting series related to the original function $V_{0}$. This was all so new and controversial at the time that his work was denied publication by Lagrange and others for about 20 years. The explanation of why this works for general cases drove Mathematics into a new age of rigorous formulation, including integral, topology, analysis, linear space, etc..
Comment: By the way, you forgot the 'y' variable in your expressions. Is that part of the confusion?
Comment: @T.A.E. Oops. That wasn't a part of my confusion, but it's a stupid mistake, haha. Thank you.
Answer: It might help to break this up into smaller steps.
\begin{align*}
&V_0(y) = \sum_{n=1}^{\infty} C_n \sin \left(\frac{n \pi y}{a} \right) \\
\implies & V_0(y) \sin \left(\frac{n' \pi y}{a} \right) =
\sum_{n=1}^{\infty} C_n \sin \left(\frac{n \pi y}{a} \right)\sin \left(\frac{n' \pi y}{a} \right) \\
\implies & \int_0^a V_0(y) \sin \left(\frac{n' \pi y}{a} \right) \, dy =
\sum_{n=1}^{\infty} C_n \int_0^a  \sin \left(\frac{n \pi y}{a} \right)\sin \left(\frac{n' \pi y}{a} \right) \, dy = \frac{a}{2} C_{n'}.
\end{align*}
We now solve for $C_{n'}$ to obtain
\begin{equation*}
C_{n'} = \frac{2}{a} \int_0^a V_0(y) \sin \left(\frac{n' \pi y}{a} \right) \, dy.
\end{equation*}
Answer: Your suspicion about inner product is entirely correct. The trigonometic polynomials $\{\sin(nx), \cos(mx)\}$ (possibly translated and scaled) are known to form an  orthogonal system with respect to the scalar product given by $\langle f, g\rangle:=\int fg$, and if you choose the function space correctly (usually one uses a space called $L^2$) and use properly chosen norming factors then one can show they actally form a complete orthonormal system $e_k$, which simply means you can express any function in that space as
$$ f = \sum_k\langle f, e_k \rangle e_k$$
(where convergence is to be understood in that space wrt the norm derived from the scalar product). The coefficients in that sum are what you are looking at. You may know that kind of representation from the finite dimensional case.
I deliberately did not specify the constants which make the orthogonal system orthonormal, nor an interval as domain of definition -- by translation and scaling you can do something like that on any bounded interval in $\mathbb{R}$ There is also a complex version of this, in which case one would use the scalar product $\int f\bar{g}$, and $\{e^{ikx}\}$ as orthogonal system.
If you want to look up the details, then most introductions to real analysis will have a section on that topic. Rudin's books, for example do explain this.
Comment: Awesome! I will do that (look up the details, that is). Thanks very much.


Is there still a reason why binding to port < 1024 is only authorized for root on Unix systems?

Question: On Unix systems, binding to tcp port < 1024 from a process without root privileged is denied.
What was the initial reason and is it still valid ?
For example http server don't need root privileged to serve html page.
What process/protocol a Unix's user need to be sure that it runs with root privileged ?
Thanks
Comment: Actually, httpd does start as root, specifically to bind to port 80 (and maybe chrooting).
Comment: What Franck was referring to is that the http server doesn't need to be root to perform its basic function(serving web pages), but it does need to be root to bind to tcp/80.
Comment: Is there a way to simply set permissions on who is allowed to bind to what port?  I'd love to have a file that simply says that port 80 is owned by the apache user.  This is the sort of area where plan9 has unix beat all around the block...
Answer: That port range is not supposed to be programmer defined.
It is reserved by IANA,

The Well Known Ports are those from 0 through 1023.
DCCP Well Known ports SHOULD NOT be used without IANA registration.
  The registration procedure is defined in [RFC4340], Section 19.9.

For differing opinions check,

From a linuxquestions thread (read at the link for more context)

The port 1024 limit actually bites itself in the tail. It forces a daemon practice that might open security holes which make the limit ineffective as a security measure.

The SANS Top-20 Vulnerabilities notes

Several of the core system services provide remote interfaces to client components through Remote Procedure Calls (RPC). They are mostly exposed through named pipe endpoints accessible through the Common Internet File System (CIFS) protocol, well known TCP/UDP ports and in certain cases ephemeral TCP/UDP ports. Historically, there have been many vulnerabilities in services that can be exploited by anonymous users. When exploited, these vulnerabilities afford the attacker the same privileges that the service had on the host.

These days, protocols like BitTorrent and Skype have moved over through ephemeral ports into the unreserved space and do not bother for root access. The target is not just bypassing this old reserved-port security; Today's protocols want to bypass even the network perimeter (Skype is a good example for that). Things will go further as network bandwidth and availability increase when every computer user will probably run a web server off themselves -- and maybe, unknowingly, be part of a botnet.

We need the security desired by these old methods
but it will need to be done with newer ways now.
Answer: Well, the original thinking as I recall from the days of BSD Unix was that ports < 1024 were expected to be reserved for "well known services", and the assumption was still that servers would be relatively rare, and that folks with root privileges would be presumed to be "trusted" in some way.  So you had to be privileged to bind a socket to listen on a port that would represent a network service that other users would access.
Ports 1024-4999 were intended to be used as "ephemeral" ports that would represent the client's side of a TCP connection.  Ports 5000+ were intended for non-root servers.
Obviously all of those assumptions went out the window pretty quickly.  Check the IANA TCP port number reservation list to see just how high things have gotten.
One solution to this problem was the RPC portmapper idea.  Instead of reserving a TCP port for each service, the service would start up on a random port and tell the portmapper daemon where it was listening.  Clients would ask portmapper "where is service X" listening and proceed from there.  I can't recall what security mechanisms were in place to protect well-known RPC services from impersonation.
I'm not sure there's a Good Reason these days for all of this, but like most of the *nix world things tend to accumulate vs. getting completely reinvented.
Anyone read Vernor Vinge?  I remember him writing in one of his novels about a computer system in the far future that incorporated layers and layers of code from the ancient past, with the time still being represented by the number of seconds since some ancient date (1/1/1970 to be exact).  He's probably not far off.
Comment: "A Deepness in the Sky"
Comment: Actually, which ports are ephemeral ports is implementation-specific. 1025-5000 (not 1024-4999) is Windows-specific. The IANA recommends 49152 to 65535, but only BSD listened to them.
Comment: Thanks.  I couldn't remember which range was which, and I saw an apparently incorrect reference when searching via Google.  Serves me right.
Answer: In the old days regular users used to login to Unix machines. So you wouldn't want an average user setting up a fake ftp service or something.
These days, the typical usage is that only the admin and a few other trusted people have logins to a server, so if the model was redone today, the < 1024 restriction might not be present.
Comment: Only if the "old days" are now. I use two of three *nix boxes I don't have root on every week.
Comment: I wouldn't classify you as a "regular user" if you are reading serverfault :-).
Answer: This is a historical convention.
A long time ago, the number of systems was much smaller. There was also no DNS, FTP sites asked for your anonymous password to be your email address, and there was no spam.
It was essentially an implied "gentlemen's agreement". Systems were well administered, if someone messed this up, you knew who to talk to, or if they were petulant, getting kicked off the network pretty much meant staying offline.
Today, with TCP/IP on everything, this is provides no security anymore.
Answer: It makes sense for services which accept system-passwords to be running on privileged ports; this means that users with shell accounts cannot set up "fake" services on the same port to capture peoples' login details, or deny access by setting up nonfunctional services on the same ports.
If you had a multiuser box, and an unprivileged user was able to set up a rogue ssh daemon, they may be able to capture the passwords of other users and gain access to their accounts (of course they'd have to do it while the legitimate ssh daemon was down, perhaps for maintenance or during system startup or shutdown)
Things which don't accept system-passwords don't matter so much, although there are major security problems with sharing things such as web servers between users on a multiuser box (as shared-hosting providers have discovered)


How to serve 100Gb of random information?

Question: My ISP charges me if my server downloads more then uploads. Now I have 2 linux machines. How to make one of them send 100Gb of random information to another and don't create large file on disk?
Comment: That is one not-so-smart billing scheme...
Comment: Got it. I need to use netcat: ` | nc -l 1234` and at another host `nc  1234 > /dev/null`. Now all that remains is to figure out how to write 100G to input pipe.
Comment: cat /dev/zero ou cat /dev/urandom. It won't be limited to 100G so you should watch out.
Comment: urandom causes additional load, so i'll use zero. Also i figured out that i can pipe it to `head -c ` to limit file size
Answer: So the final solution is:
Sending machine
 cat /dev/zero | head -c <bytes> | nc -l <port>

Receiving machine
nc <sending ip> <port> > /dev/null

Answer: How about this to generate 100GB of random data?
cat /dev/urandom | head -c 100000000000


Explicit value for the identity column in table error?

Question: I get the below error message, I have debugged both identity inserts and they execute with no problems. Has anyone had trouble with this error before and does anyone know how to fix this?

Msg 8101, Level 16, State 1, Line 1
  An explicit value for the identity column in table 'c365online_script1.dbo.tProperty' can only be specified when a column list is used and IDENTITY_INSERT is ON.

Code:
declare @Source_Database_Name varchar(255) = 'Production2';
declare @Destination_Database_Name varchar(255) = 'c365online_script1';

declare @Company_Id int = 1 --declare a companyid

CREATE TABLE #CompanyID (ID bigint)

INSERT INTO #CompanyID(ID)
    VALUES('15')

-- Copy over company records from tCompanytable

--FIRST CURSOR LOOP THROUGH THIS TABLE
CREATE TABLE #TableList (
    processorder int,
    tablename NVARCHAR(100)
    )
INSERT INTO #TableList (processorder, tablename )
VALUES
(1, 'tProperty');

DECLARE @Counter INT = 0  -- counting variable

----------- Cursor specific code starts here ------------
-- company cursor
declare copyCompanyDataCursor CURSOR fast_forward FOR
SELECT ID from #CompanyID;

open copyCompanyDataCursor
fetch next from copyCompanyDataCursor into @Company_Id;

WHILE @@FETCH_STATUS = 0
    BEGIN
        declare @processorder int;
        declare @tablename varchar(500);
        -- table cursor

        declare copyTableDataCursor CURSOR fast_forward FOR
        SELECT processorder,tablename from #TableList order by processorder;

        open copyTableDataCursor
        fetch next from copyTableDataCursor into @processorder, @tablename;

        while @@FETCH_STATUS = 0
        BEGIN
            SET IDENTITY_INSERT [c365online_script1].[dbo].[tCompany] ON

            -- Does the table have a companyID column? if statement checking for company id
            IF EXISTS(SELECT * FROM Production2.INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME='CompanyID' and TABLE_NAME=@tablename)
            BEGIN
                if @Counter <= 0 -- make sure loop executes only once.
                BEGIN
                declare @debug varchar(max)
                SET @debug = 'INSERT INTO ' + @Destination_Database_Name + '.dbo.' + @tablename + ' SELECT * FROM ' + @Source_Database_Name + '.dbo.' + @tablename + ' WHERE ' + @Source_Database_Name + '.dbo.' + @tablename + '.CompanyID = ' + CAST(@Company_Id as varchar(10))
                print @debug
                set @Counter = 1
                EXEC(@debug)
                --EXEC('INSERT INTO ' + @Destination_Database_Name + '.dbo.' + @tablename + ' SELECT * FROM ' + @Source_Database_Name + '.dbo.' + @tablename + ' WHERE ' + @Source_Database_Name + '.dbo.' + @tablename + '.CompanyID = ' + @Company_Id )
                END
            END
            ELSE
            BEGIN
                    Print 'No'
            END
            -- if yes then copy data based on companyID in cursor
            -- if no check if this is the first time through company loop and copy all data
            -- if @firstloop company exists look at information schema

                    --EXEC('INSERT INTO ' + @Destination_Database_Name + '.dbo.' + @tablename + ' SELECT * FROM ' + @Source_Database_Name + '.dbo.' + @tablename )
                    -- company logic

            SET IDENTITY_INSERT [c365online_script1].[dbo].[tCompany] OFF

            FETCH NEXT FROM copyTableDataCursor into @processorder,@tablename;
        END

        close copyTableDataCursor;

        Deallocate copyTableDataCursor;

--INSERT INTO c365online_script1.dbo.tCompany
--SELECT *
--FROM production2.tCompany
--WHERE ISNULL(CompanyID, 0) = 0  -- copy all data where id is equal to zero
--@Destination_Database_Name

--
        --EXEC(INSERT  + @Destination_Database_Name + '.dbo.' + @tablename + ' SELECT * FROM ' + @Source_Database_Name + '.dbo.' + @tablename + ' WHERE ' + @Source_Database_Name + '.dbo.' + @tablename + '.CompanyID = ' + @Company_Id + ')')
        --SET @firstLoop = false;
        FETCH NEXT FROM copyCompanyDataCursor into @Company_Id;
    END

CLOSE copyCompanyDataCursor;
DEALLOCATE copyCompanyDataCursor;

--Cleanup
DROP TABLE #CompanyID
DROP TABLE #TableList

Comment: When inserting literal values into a table with a `bigint` column - please do **NOT** use string quotes! This is totally useless and just causes unnecessary conversions - use this code instead: `INSERT INTO #CompanyID(ID) VALUES(15)` (instead of `... VALUES('15')`)
Answer: Well, the error says it all:

An explicit value for the identity column in table 'c365online_script1.dbo.tProperty' can only be specified when a column list is used and IDENTITY_INSERT is ON.

So your INSERT statement MUST use a column list!
Use
INSERT INTO dbo.Table(col1, col2, ...., colN) VALUES(Val1, val2, ...., ValN)

and not just
INSERT INTO dbo.Table   VALUES(Val1, val2, ...., ValN)
                     ^^^^  no column list defined!!

then it'll work!
Comment: Hi but for the insert statement I am using a column list "INSERT INTO #TableList(processorder, tablename )VALUES
(1, 'tProperty');"
Comment: @user1259076: yes, for your last statement that's true, but **NOT** for the statement that you dynamically construct inside your two nested cursors ....
Comment: Ok im not too sure how that statement would go together


Correlation plot with one categorical variable and rest continuous

Question: In my dataset, I have one binary variable (Active/Inactive) and rest of the variables are continuous. I have converted a categorical variable into binomial (0,1) and then ran a correlogram plot in R among each variable. Am I right in calculating a correlation value between categorical and continuous variables by simply using corr_val <- cor(dataset) and corrplot(corr_val,type = "lower",order="hclust").
Answer: As long as the categorical variable has been converted to binary form beforehand, than using the R cor with the Pearson default command will work, and the correlation will be a point-biserial correlation. Note that when transforming your categorical variable to a binary one you should use logical points (as it seems you have via active/inactive).
Answer: In this way you lose the information related to the categorical variable.
You can try using the featurePlot() function from the caret package to display a scatterplot matrix.
library(caret)
featurePlot(x = dataset[, continuous variables], y = dataset[, categorical variable], plot = "pairs")


Getting started with guava

Question: How can I use Guava for my web application? I want to use it e.g. for testing instead of JUnit. Is that possible? What other uses can I have from Guava if I'm building webapps with JSP and servlets?
Comment: You mean Google Guava? There is a wiki has whole lot of info http://code.google.com/p/guava-libraries/w/list
Comment: Related: http://stackoverflow.com/questions/3924479/are-there-any-guava-overviews?rq=1
Answer: Please read https://github.com/google/guava/wiki
Guava is not a replacement of JUnit.
Comment: Guava is sort of *extension for the JDK.* It can't replace a specialized library like JUnit or servlet-api, but it can help with a lot of things. Whatever you do, it's quite probable you find something useful there.
Comment: @maaartinus You should transform your comment in a response

Getting started with guava


Inequalities for integrals

Question: In my notes it was said $$\begin{eqnarray*} n!\int_x^\infty \frac{e^{-y}}{y^{n+1}} \, dy &<& \frac{n!}{x^{n+1}}\int_x^\infty e^{-y} \, dy \\
&=& \frac{n!e^{-x}}{x^{n+1}}\end{eqnarray*}$$
How did they get from the first line to the second line? Can I just pull out the $y^{n+1}$ term and change it to $x^{n+1}$?
Also is it the case that $$n!\int_x^\infty \frac{e^{-y}}{y^{n+1}}dy  <n!\int_x^\infty e^{-y} dy$$
?
Comment: For a fixed constant x, we have y>x so 1/y < 1/x. Raise both sides to (n+1)th power, multiply by $e^{-y}$ and integrate with respect to y. The inequality follows.
Comment: You can change $y$ to $x$ if you put in the correct inequality. Then note that $x$ is a constant, so can be taken outside the integral sign. This is the opposite way round from your question - you can't take $y$ outside the integral sign.
Comment: Thanks for your help, understood it better!
Answer: For your first question:
They are using the fact that if $f(x)< g(x)$ on $(a,\infty)$, then $\int_a^\infty f(x)\,dx<\int_a^\infty g(x)\, dx$. This is a standard comparison test for improper integrals.
Here, we have $y^{n+1}>x^{n+1}$ for $y$ in the interval $(x,\infty)$ (note, then, that $y> x$); so for $y$ in the interval  $(x,\infty)$, we have ${e^{-y}\over y^{n+1}} <{e^{-y}\over x^{n+1}}$. Thus $\int_x^\infty {e^{-y}\over y^{n+1}} \,dy<\int_x^\infty {e^{-y}\over x^{n+1}}\, dy$.
Finally, since the integration is with respect to $y$, the term $1\over x^{n+1}$ is a constant as far as the integration is concerned and can be factored out of the integral sign.

Though it would lead to the correct result, you shouldn't think of pulling $y^{n+1}$ out first, since you are integrating with respect to $y$. You can change it to $x^{n+1}$ first, introducing an inequality, and then pull it out.
Comment: Thanks @DavidMitra , may I ask is my 2nd inequality valid? (2nd part of the question).
Comment: @Jonathan It's certainly true for $x\ge 1$, since then for $y>x$, you'd have ${e^{-y}\over y^{n+1}}<e^{-y}$. For $x<1$, it's not necessarily true, I think. Here is a [Worlfram computation](http://www.wolframalpha.com/input/?i=%28integrate+e^%28-y%29%2F+y%2C+y%3D.1..infty+%29-%28integrate+e^%28-y%29+%2C+y%3D.1..infty+%29) with $n=1$, $x=.1$.

Inequalities for integrals


Copy a range of cells to a new sheet

Question: I am trying to copy a range of data (that is constantly being updated) to the next empty row in a different sheet for permanent storage.
My code will work, but it will only copy the first row, I need it to copy a range of 9 rows.
Thanks in advance!
Sub Export()

Dim Timestamp As Date
Dim lastrow As Integer
Dim raw_data As Variant

'Records all data to DBO

Timestamp = Now
raw_data = Sheets("Data").Range("A2:M10").Value
        lastrow = Sheets("DBO").Range("B60000").End(xlUp).Row
        Sheets("DBO").Range("A" & lastrow + 1) = Timestamp
        Sheets("DBO").Range("B" & lastrow + 1, "N" & lastrow + 1).Value = raw_data
        Workbooks("Board.xlsm").Save

End Sub

Comment: change `"N" & lastrow + 1` to `"N" & lastrow + 9`
Comment: As simple as that... Thanks for the help!
Answer: raw_data = Sheets("Data").Range("A2:M10").Value

With Sheets("DBO").Range("B60000").End(xlUp).Offset(1,0).EntireRow

    .Cells(1).Value = Timestamp

    'If you set the destination range using the upper bounds of
    '   raw_data then you don't have to edit this line if you
    '   change your input range from A2:M10 to something a different size
    .Cells(2).Resize(UBound(raw_data,1),UBound(raw_data,2)) = raw_data

End With

Workbooks("Board.xlsm").Save

Copy a range of cells to a new sheet


Can nameserver issues affect SEO?

Question: take a look at the DNS errors on this site. Might it affect how google indexes the site? The site is not even returned in searches http://www.intodns.com/legacytrustuk.org
Answer: Ok, so here is what intoDNS is complaining about. I'll first give you all the commands I executed and then explain them step by step.
lukas$ whois legacytrustuk.org | grep "Name Server:[A-Za-z0-9]"
Name Server:NS0.TELIVO.COM
Name Server:NS1.TELIVO.COM

lukas$ host -t ns legacytrustuk.org
legacytrustuk.org name server ns0.lcn.com.
legacytrustuk.org name server ns1.lcn.com.

lukas$ dig @ns0.lcn.com legacytrustuk.org NS | grep -v '^;'
legacytrustuk.org.      600     IN      NS      ns0.lcn.com.
legacytrustuk.org.      600     IN      NS      ns1.lcn.com.

lukas$ host -t ns org | head -1
org name server B0.ORG.AFILIAS-NST.org.

lukas$ dig @B0.ORG.AFILIAS-NST.org legacytrustuk.org NS | grep -v '^;'
legacytrustuk.org.      86400   IN      NS      ns0.telivo.com.
legacytrustuk.org.      86400   IN      NS      ns1.telivo.com.

lukas$ dig @NS0.TELIVO.COM legacytrustuk.org NS | grep -v '^;'
legacytrustuk.org.      600     IN      NS      ns0.lcn.com.
legacytrustuk.org.      600     IN      NS      ns1.lcn.com.

So the first thing I did was ask the Whois Server what he thinks the DNS Servers for legacytrustuk.org are. He returns the telivo.com ones.
However in the second command I ask my providers Nameservers what they think are the authoritative nameservers for legacytrustuk.org and they return the lcn.com ones
In the third command I ask your lcn.com nameserver to return the list of nameservers that he thinks are authoritative for legacytrustuk.org and he answers with the two that are present in the zone, ns0.lcn.com and ns1.lcn.com.
In the fourth command I just get some authoritative nameserver for the TLD .org and then in the fifth command query that nameserver and ask him what he thinks are the nameservers for legacytrustuk.org. He returns the telivo.com ones from the Whois info.
In the last command I ask the telivo.com nameserver what he thinks is the auth NS for legacytrustuk.org and he returns the lcn.com ones. Which by the way is the reason why your Domain can be resolved at all.
So it's exactly as intoDNS explains. The parent Nameservers (those responsible for the TLD .org) think that ns0.telivo.com and ns1.telivo.com are authoritative for legacytrustuk.org. However when you ask them they tell you something different. And there's the missmatch. So technically it works but formally - as far as the registar information goes - the setup is broken.
To fix this just update the Domain Registration Information. Remove the ns0.telivo.com and ns1.telivo.com nameservers from the registar info and add the two ns0.lcn.com and ns1.lcn.com servers.
Answer: (Reposting my answer to your SO question.)
To index a site, Google has to be able to reach it. The absense of A records for your nameservers could make that an intermittent problem.
But one of the biggest problems surely is:

WWW A Record   ERROR: I could not get any A records for www.legacytrustuk.org!

...which is going to make it hard for Google or anyone else to actually visit the site. But I was able to ping it and get name resolution (18.104.22.168), so clearly something somewhere is working for you.
At the end of the day, you want to clean up the errors regardless of SEO.

Can nameserver issues affect SEO?