text:
Q: Is $L(\ell_2,\ell_2)$ dense in $L(\ell_2,c_0)$? Let $\ell_2:=\{ x:\mathbb{N} \to \mathbb{R}: \sum_{j=1}^\infty x_j^2<\infty\}$ and
$c_0:=\{ x:\mathbb{N} \to \mathbb{R}: \lim_{j\to\infty}x_j=0,\, \sup_{j\in\mathbb{N}}|x_j|<\infty\}$ denote the usual Banach sequence spaces.
Given Banach spaces $A,B$, let $L(A,B)$ denote the Banach space of bounded, linear operators from $A$ to $B$.
Question: is $L(\ell_2,\ell_2)\subseteq L(\ell_2,c_0)$ dense?

A: Choose finite sets $A_n\subset{\bf N}$ with $\max(A_n)<\min(A_{n+1})$, and then define $T:c_{00}\to c_0$ by $T(e_n)=\chi_{A_n}$.
It is easy to check that $T$ extends to a norm 1 linear map $\ell^2\to c_0$. On the other hand, I think that if you take $|A_n|\to\infty$ fast enough, then for each norm 1 $R:\ell^2\to\ell^2$ you can find $\xi\in c_{00}$ such that $\xi$ has 2-norm equal to 1 but $R\xi-T\xi$ has $c_0$-norm at least 1/3. Now use Riesz's lemma to conclude that the answer to your question is negative.
(I am writing in a hurry on an iThing, so apologies for lack of detail and pretty formatting. When I have breathing space at a keyboard I will try to elaborate.)

Added later:
As Mikael has pointed out in comments, one does not need any assumption on the growth rate of $|A_n|$, merely that $\sup_n |A_n|=+\infty$. Moreover, one doesn't need Riesz's lemma.
To give a little more detail: suppose $R: c_{00}\to \ell^2$ is any linear map such that $\Vert R - T \Vert_{2\to \infty} = \varepsilon < 1$. Then for every $k\in A_n$ we have $|(R e_n)_k| \geq 1-\varepsilon$, and thus
$$ \Vert R e_n \Vert_2 \geq (1-\varepsilon) |A_n|^{1/2} $$
Provided that $\sup_n |A_n|=+\infty$ this shows that $R$ cannot extend to any continuous linear map $\ell^2\to\ell^2$.
Remark you can all skip:
The reason I originally thought we might want growth conditions on the sequence $(|A_n|)_{n\geq 1}$ is because I was misremembering something I'd worked out years ago. Namely, if $1\leq p < \infty$ and we let $B$ be the subalgebra of $L(c_0,c_0)$ consisting of all operators that moreover map the dense subspace $\ell^p\subset c_0$ to itself, then $B$ is not dense in $L(c_0,c_0)$. (This rediscovery is what prompted me to ask this old MO question.) Explicit operators in $L(c_0,c_0)$ which can't be approximated by elements of $B$ can be provided by spreading shifts of the kind used in my answer here, but the proof they are not in the closure of $B$ seems to require more work. However, I'm not sure if this question is genuinely related to the one you asked, or whether they are just different questions involving some of the same symbols.


text:
Q: Can CircuitBraker design pattern be used with SOAP based web services in java I am new to the Spring cloud environment and i am trying out on implementing the circuit breaker pattern using SOAP based web service...
i implemented circuit breaker with REST and did upload in pivotal cloud foundry.
is that possible to implement it with in SOAP based web services.?

A: If you're using Hystrix implementation, you can directly add @HystrixCommand annotation on the method you want to monitor (the method that will receive the SOAP request object for example).
In the example provided by Spring : @HystrixCommand(fallbackMethod = "reliable")
https://spring.io/guides/gs/circuit-breaker/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python http download using requests.get always missing a chunk I am trying to define a function that resumes download if the connection is broken. However, the following does not work as expected.
In line 8, I have to manually deduce one chunk-size in order for it to work, otherwise, the final file will be missing exactly one chunk-size for each time I resume it.
if os.path.exists(fileName):
    header = requests.head(url)
    fileLength = int(header.headers['Content-Length'])
    if fileLength == os.path.getsize(fileName):
        return True
    else:
        with open(fileName, 'ab') as f:
            position = f.tell()-1024
            pos_header = {}
            print(position)
            pos_header['Range'] = f'bytes={position}-'

        with requests.get(url, headers = pos_header, stream = True) as r:
            with open(fileName, 'ab') as f:
                    #some validation should be here

                for chunk in r.iter_content(chunk_size=1024):
                    if chunk:
                        f.write(r.content)
                        f.flush()
                        print(os.path.getsize(fileName))

else:
    with requests.get(url, allow_redirects=True, stream = True) as r:
        with open(fileName, 'wb') as f:
            iter = 0
            for chunk in r.iter_content(chunk_size = 1024):
                if chunk:
                    f.write(chunk)
                    f.flush()
                    iter += 1
                if iter > 2000:
                    break

Interestingly, the part missing is the in-between two parts of the downloads. Is there a more elegant way of resolving this than what I did?

A: You have a bug in the code that downloads the 'rest' of the file if it's the second attempt. The bug is in the following line:
f.write(r.content)

It should be
f.write(chunk)

Basically, you're iterating over chunks but writing the entire content, and that messes things up.


text:
Q: Removing a /.br/ from a String in Java I have a Java app that reads data from an Oracle database and then moves it to a MySQL database for research purposes. The data comes from an application where end users can basically enter free text. It appears that when the text is entered they are hitting returns that is causing a /.br/ to appear in the text. MySQL doesn't like the /.br/. I have tried several ways to remove the /.br/ with no luck
clinDisp = clinDisp.replaceAll("<.br */>", "");

clinDisp = clinDisp.replace("/.br/", "");

clinDisp = clinDisp.replace("<.br>", "");

No matter what I try the .br is always there and the insert for this row breaks. Also, if it matters I don't care if the line feed is lost, just something that will allow the String to insert.


text:
Q: Repeating a function in Python How do I repeat a function in python. Such as Repeat... Unil in other languages. Thanks, this is the code I'm trying to repeat:
import random

line = random.choice(keywords)
print('Keyword:')
print (line)

line = random.choice(definitions)
print ('A:')
print (line)

line = random.choice(definitions)
print ('B:')
print(line)

line = random.choice(definitions)
print ('C:')
print(line)

#randomly selects a keyword and definition from the file

A = []
ans = input('Is it A, B or C?')
print()

if ans == 'A' :
    print ('Correct')
else:
    print ('Incorrect')

#asks the user for an answer, then tells them if their correct or not

Any help would be much appreciated!

A: To loop for infinity (or until a certain condition is met):
while True:
    # Insert code here
    if conditition_to_break:
        break

This will call your code in an endless loop until condition_to_break is True and then breaks out of the loop.
You can read more on while loops here.
If you want to repeat something n times try using a for loop (read more here).
for x in range(3):
    # This code will execute 3 times
    print("Executed {0} times".format(x+1))

A: Did you mean like while or for?
If you meant do while then it's a bit tricky in python, since python does not
have a built-in function for it, but your can do this:
while(True):
   your_code_here()
   if(your_exit_term): break

I know it's ugly, but I'm not familiar with any other way.


text:
Q: Exception when analyzing code When analyzing some code using PVS-Studio 6.18.23098 I got the following stack trace in the PVS-Studio window:
Exception message:   0
 Sequence contains no elements  0
 Stack:    at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Utils.VariableValueInfo.VariableValueInfoWalker.GetJoinVariableValueInfo(SyntaxNode environmentNode, SyntaxNode node, VariableValueInfo prewVariableValueInfo, IEnumerable`1 lastVariableValueInfo, TypeRelationship typeRelationship) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Utils\VariableValueInfo.cs:line 1002  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Utils.VariableValueInfo.VariableValueInfoWalker.VisitConditionalExpression(ConditionalExpressionSyntax node) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Utils\VariableValueInfo.cs:line 660  0
    at Microsoft.CodeAnalysis.CSharp.CSharpSyntaxWalker.Visit(SyntaxNode node)  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Utils.VariableValueInfo.VariableValueInfoWalker.VisitAssignmentExpression(AssignmentExpressionSyntax node) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Utils\VariableValueInfo.cs:line 553  0
    at Microsoft.CodeAnalysis.CSharp.CSharpSyntaxWalker.DefaultVisit(SyntaxNode node)  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Utils.VariableValueInfo.VariableValueInfoWalker.VisitExpressionStatement(ExpressionStatementSyntax node) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Utils\VariableValueInfo.cs:line 745  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Utils.VariableValueInfo.VariableValueInfoWalker.<>c__DisplayClass30_0.<VisitBlock>b__0() in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Utils\VariableValueInfo.cs:line 731  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Utils.VariableValueInfo.VariableValueInfoWalker.CommonFunctionForBlock(Ramification branch, Action action) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Utils\VariableValueInfo.cs:line 946  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Utils.VariableValueInfo.ParseFunction(SemanticModelAdapter model, SyntaxNode mainBlock) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Utils\VariableValueInfo.cs:line 433  0
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.SemanticModelAdapter.GetVariableValueInfo(SyntaxNode node, Boolean includeLastAssignment) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\SemanticModelAdapter.cs:line 814  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Utils.SyntaxNodeUtils.IsImmutableStateMethod(SemanticModelAdapter model, InvocationExpressionSyntax invocationExpression) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Utils\SyntaxNodeUtils.cs:line 300  0
    at ProgramVerificationSystems.PVSStudio.Core.VirtualValues.VirtualValuesUtils.ResetChangedVariables(SemanticModelAdapter model, InvocationExpressionSyntax invocation, VirtualValuesContainer container) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\VirtualValues\VirtualValuesUtils.cs:line 122  0
    at ProgramVerificationSystems.PVSStudio.Core.VirtualValues.VirtualValuesUtils.ResetChangedVariables(SemanticModelAdapter model, ExpressionSyntax expression, VirtualValuesContainer container) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\VirtualValues\VirtualValuesUtils.cs:line 112  0
    at ProgramVerificationSystems.PVSStudio.Core.VirtualValues.VirtualValuesProcessor.AfterProcessInvocation(InvocationExpressionSyntax invocation) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\VirtualValues\VirtualValuesProcessor.cs:line 1352  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.CommonVisit(Type typeRuleBase, SyntaxNode node, Action`2 actionVisitRule, Action callBaseVisit, Func`1 virtualProcessorBeforeAction, Action`1 virtualProcessorAfterAction, VisibleVariablesContainer visibleDeclarations) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 270  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.VisitInvocationExpression(InvocationExpressionSyntax node) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 1022  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.<>c__DisplayClass38_0.<Visit>b__1() in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 302  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.CommonVisit(Type typeRuleBase, SyntaxNode node, Action`2 actionVisitRule, Action callBaseVisit, Func`1 virtualProcessorBeforeAction, Action`1 virtualProcessorAfterAction, VisibleVariablesContainer visibleDeclarations) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 263  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.Visit(SyntaxNode node) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 303  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.<>c__DisplayClass37_0.<DefaultVisit>b__1() in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 295  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.DefaultVisit(SyntaxNode node) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 296  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.<>c__DisplayClass110_0.<VisitExpressionStatement>b__1() in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 819  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.VisitExpressionStatement(ExpressionStatementSyntax node) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 822  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.<>c__DisplayClass62_0.<VisitBlock>b__1() in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 468  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.VisitBlock(BlockSyntax node) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 476  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.<>c__DisplayClass149_0.<VisitMethodDeclaration>b__2() in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 1110  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.VisitMethodDeclaration(MethodDeclarationSyntax node) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 1112  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.<>c__DisplayClass73_0.<VisitClassDeclaration>b__4() in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 568  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.VisitClassDeclaration(ClassDeclarationSyntax node) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 570  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.<>c__DisplayClass153_0.<VisitNamespaceDeclaration>b__1() in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 1135  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 1136  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.<>c__DisplayClass75_0.<VisitCompilationUnit>b__1() in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 581  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.VisitCompilationUnit(CompilationUnitSyntax node) in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 582  0
    at ProgramVerificationSystems.PVSStudio.Analyzer.Core.Walkers.CSharpRulesWalker.WalkFullTree() in D:\JenkinsProjects\Workspace\proj_PVS-Studio_Setup\WorkDir\PVS-Studio\PVS-Studio\Analyzer\Core\Walkers\CSharpRulesWalker.cs:line 76  0

I tried to reduce the code as much as possible, to get a minimal example.
This is the smallest example I could make, that provoked the stack trace to appear.
class Class
{
    void MethodB(double value)
    {
        var a = 0;
        var b = 0;

        var (_, _) = (0 < 0) ? (a, b) : (b, a);
    }

    void MethodA(IInterface obj)
    {
        MethodB(obj.Property);
    }
}

interface IInterface
{
    double Property { get; }
}

Is this a known bug?

A: Please, don't use stackoverflow as a bugtracker. It goes against the spirit of stackoverflow. Please, write to our support about similar problems.
I gave the description of this problem to colleagues. Thanks for the information.


text:
Q: does airflow dag bash operator have command length limitation ? if so , what can we do to extend it? In our dag we have a task like the below:
task1 = BashOperator(
    task_id='xxyz',
    bash_command='echo $y |base64 -d > task.py; command1 ; command 2; \
        ....\
        ...\
    command N; ',
)

as so many commands there, so when we add one more command N+1 to this task's BashOperator, then Airflow can not run this code but still run the old code end with "command N;". I think we reach the length #limitation of the bash_command.
Is there a way to extend this limitation? thanks.
I have try to reduce the length of the bash_command then it is working, but if the bash_command is too long then it will not pickup the code change of the related task.

A: Can you try including all your commands in a shell script and execute it?
task2 = BashOperator(
    task_id="bash_example",
    # This works (has a space after)
    bash_command="/home/batcher/test.sh ",
    dag=dag,
)


text:
Q: Превращение одного тега в другой <!DOCTYPE html>

    <title>HJ3</title>

press Ctrl+E for edit text

press Ctrl+S for save text

    Lorem ipsum dolor sit amet, consectetur adipisicing elit.
    Quo debitis illum dolore ratione dignissimos exercitationem iste
    rerum quia laudantium placeat ex voluptate eius, dolorem possimus
    eaque sit tempore commodi sunt.

Ошибка: Uncaught TypeError: Cannot read properties of undefined (reading 'replaceparent'
 Сама программа отлично работает до момента использование клавиш "ctrl + S", если же использовать эту комбинацию сразу то мне любезно удалит текст.

A: Для textarea используйте value, а вы используете el1.innerHTML.
И getElementsByTagName заменил на querySelector
Вот рабочий код:

document.addEventListener("keydown", function(e) {
  if (e.ctrlKey && e.keyCode === 69) {
    e.preventDefault();
  }
}, false)
document.addEventListener("keydown", function(e) {
  if (e.ctrlKey && e.keyCode === 83) {
    e.preventDefault();
  }
}, false)

document.body.onkeydown = (e) => {
  if (e.ctrlKey && e.keyCode === 69) {
    let el1 = document.getElementById('t1');
    let el2 = document.createElement('textarea');
    el2.value = el1.innerHTML;
    el1.parentNode.replaceChild(el2, el1);
  }
  if (e.ctrlKey && e.keyCode === 83) {

    let el1 = document.querySelector('textarea');
    let el2 = document.createElement('span');

    el2.innerHTML = el1.value;

    el1.parentNode.replaceChild(el2, el1);
  }
}

press Ctrl+E for edit text

press Ctrl+S for save text

Lorem ipsum dolor sit amet, consectetur adipisicing elit.
    Quo debitis illum dolore ratione dignissimos exercitationem iste
    rerum quia laudantium placeat ex voluptate eius, dolorem possimus
    eaque sit tempore commodi sunt.

P.S:: Ваш вариант сейчас не предусматривает, если сперва нажмут Ctrl+S, если будете использовать учтите это.


text:
Q: How to make the back button act as the home button in Android I have a very simple application.  The app asks a question and depending on what the user clicks a different text is shown.  Now, when the home button is pressed the phone goes to the home screen and the app pauses.
But when I press the back button the dialog goes away but the white background (Default in an app made by eclipse) is still there.  Then I have to press the back button once more to get to the home screen.
My question, is there a way to make the back button act as the home button to return to the home screen?  If there is, what is it.
I have tried using onStop and onResume and onPause but the same thing happens.
Thanks,
dhoehna.

A: Sounds like android SDK. So, I'm going to assume you are doing Android development.
You'll have to override the method called OnBackPressed(). Then you can override the back button to do what you want it to do.


text:
Q: Standardising Results Between Experimental Groups I have data on five experiments, which vary slightly, and I would like to find a way of standardizing results between experiments to develop a "standard result." This will be a value I can multiply each result by to make them comparable.
The way I have gone about this is there are individuals in more than one experimental group (assuming being in more than one group doesn't affect results).
I am assuming the results of individuals in more than one experiment are only different because of the slight differences between experiments and so by calculating a conversion factor for each experiment that makes the average of the individuals results in more than one experiment the same that can translate results into a standard result.
The problem I am experiencing is at the end of the process most of my conversion factors are less than 1. However, I was expecting to get roughly an even number of values greater than 1 and less than 1 as I am sort of averaging out the results.
My procedure and MSQL code is below:

*

*Get data by experiment and by individual and exclude all individual's data that is only in 1 experiment.

    SELECT ExperimentID,
       IndividualID,
    INTO Z1_IndivByExperiment
    FROM Results
    GROUP BY ExperimentID,
         IndividualID

    SELECT IndividualID,
       COUNT(ExperimentID) AS ExperimentCount
    INTO Z2_MultiExperIndiv
    FROM Z1_IndivByExperiment
    GROUP BY IndividualID
    HAVING COUNT(ExperimentID) > 1
    ORDER BY ExperimentCount DESC

*Create two tables:
i)  Summaries results by individual (an individual can have multiple results per experiment) and experiment.
ii) Summaries results by individual

    SELECT ExperimentID,
       IndividualID,
       SUM(Results.Result) AS Result_sum,
       SUM(Results.ResultsCount) AS ResultCount_sum
    INTO Z3_MultiExperIndiv_Results
    FROM Results INNER JOIN
         Z2_MultiExperIndiv ON Results.IndividualID =
    Z2_MultiExperIndiv.IndividualID
    GROUP BY ExperimentID,
         IndividualID

    SELECT 'Standard' AS Experiment
       IndividualID,
       SUM(Result_sum) AS ResultIndiv_sum,
       SUM(ResultCount_sum) AS ResultCountIndiv_sum
    into Z4_MultiExperIndiv_Stand
    FROM Z3_MultiExperIndiv_Results
    GROUP BY IndividualID

*Link the two tables created in step 2 by individual summing results from table 1 and table 2 by experiment. I am hoping this provides two sets of results for individuals on the experiment in question and results for individuals who were part of the experiment in question from other experiments were.

    SELECT Z4_MultiExperIndiv_Stand.ExperimentID AS ExperimentID1,
       Z3_MultiExperIndiv_Results.ExperimentID AS ExperimentID2,
           SUM(Z4_MultiExperIndiv_Stand.ResultIndiv_sum -
    Z3_MultiExperIndiv_Results.Result_sum) AS Results1,
       SUM(Z4_MultiExperIndiv_Stand.ResultCountIndiv_sum -
    Z3_MultiExperIndiv_Results.ResultCount_sum) AS ResultCount1,
           SUM(Z3_MultiExperIndiv_Results.Result_sum) AS Results 2,
       SUM(Z3_MultiExperIndiv_Results.ResultCount_sum) AS ResultCount2
    into Z5_StandardConversion_data
    FROM Z3_MultiExperIndiv_Results INNER JOIN
         Z4_MultiExperIndiv_Stand ON Z3_MultiExperIndiv_Results.IndividualID =
    Z4_MultiExperIndiv_Stand.IndividualID
    GROUP BY Z4_MultiExperIndiv_Stand.IndividualId,
         Z3_MultiExperIndiv_Results.IndividualId

*Then I divide results for each set of results by number of results and divide one by the other to get my conversion to standard number for each experiment.

    SELECT ExperimentID1,
       ExperimentID2,
       Results1,
       ResultCount1,
       Results2,
       ResultCount2,
       Results1 / ResultCount1 AS Result1_avg,
       Results2 / ResultCount2 AS Result2_avg,
    (ResultCount2 * Results1) / (ResultCount1 * Results2) AS Conversion
    FROM Z5_StandardConversion_data

Sample input data:

Sample Output:


text:
Q: FullCalendar tooltip bug when dragging event in Resource timeline I'm using JavaScript FullCalendar library to build my calendar. Now updating my codes to work with FullCalendar V4. When Dragging event in resource timeline view, the tooltip does not work as expected (duplicate tooltips show when dragging). This issue only happens in resource timeline view, not in dayGrid view. I've attached two codepen codes. Daygrid view works fine, but Resource timeline view does not.
https://codepen.io/nmwangxin/pen/WNeRQaX
https://codepen.io/nmwangxin/pen/qBWROKz
eventRender: function(info) {
      var tooltip = new Tooltip(info.el, {
        title: 'test',
        placement: 'top',
        trigger: 'hover',
        container: 'body'
      });
    },

A: When dragging the event it gets re-rendered each time, so basically you are recreating a new tooltip each time thus creating multiple instances which in turn loose their reference to the element that gets destroyed hence it's odd placement.
I would suggest to hook into "eventMouseEnter" and "eventMouseLeave" callbacks and create and destroy a single tooltip object there.
Here is an example:
var tooltip = null;
eventMouseEnter: function(info) {
  tooltip = new Tooltip(info.el, {
    title: info.event.title,
    placement: 'top',
    trigger: 'hover',
    container: 'body'
  });
},
eventMouseLeave:  function(info) {
  if (tooltip) {
    tooltip.dispose();
  }
}

https://codepen.io/alex-hazanov/pen/rNBjPyL

A: Or use bootstrap's tooltip like this :
eventMouseEnter: function (info) {
    $(info.el).tooltip({
          title: info.event.title + '<br />' + info.event._instance.range.start,
          html: true,
          placement: 'top',
          trigger: 'hover',
          container: 'body',
    });
}


text:
Q: Probability of event happening when data is aggregated with many independent events over the course of time Let's say you have $X$ coins, each with a differing probability of landing heads (e.g. coin 1 has 10% chance of landing heads, coin 2 has 20% chance of landing heads, etc.).
Now, let's say that you flip coin $i$ coin $Y_i$ times (each coin has a differing amount of flips). We know how many times each coin was flipped.
Now let's say you do this every day for a really long time and record that info.
Example, with 2 coins, on day 1: 50 flips total, 30 heads total, coin1 was flipped 20 times and coin2 flipped 30 times. Day 2: 80 flips, 66 heads total, coin1 60 flips, coin2 20 flips.
What we know: total flips, total heads, how many times each coin was flipped.
Given that, is there a way to determine an approximate probability that the given coin will flip heads?  In the above example, coin1 has a 100% probability of heads and coin2 has a 33% probability.

A: Sorry for the delay, I was going to code this up as an example, but basically my method was going to agree with @Aniko's comment about using a linear regression.
So basically you can run a multiple linear regression where the outcome variable is number of heads and the predictors (or covariates) to the model is the number of tosses of each coin.  Doing it so lets you model the scenario with as many coins as you want.  Now, more formally, we want to model the following:
$$N_i=Y_{1i}p_1+Y_{2i}p_2+...Y_{Xi}p_X$$
where $N_i$ is the total number of heads on day $i$, $Y_{ji}$ is the $j^{th}$ coin thrown on day $i$, $X$ is the total number of coins, and $p_j$ is the probability of heads associated with the $j^{th}$ coin. So, we would like to be able to obtain estimates of the $p_j$'s.
One way (which is the way we shall illustrate) is to fit the above regression model using least squares.  Then, the least square estimators will give the estimated probability of head for each coin (note we exclude the intercept).
To see this method in action, we will simulate data in R for 5,000 consecutive days with four coins each being flipped a random amount of times each day.  Here is the R code for achieving this:
#The probabilities of heads for the 4 coins
p1 = 1
p2 = .3
p3 = .6
p4 = .45

#The number of days to flip the coins
days = 5000

#Variable for tracking number fo flips of each coin
coin1.flips = rep(NA,days)
coin2.flips = rep(NA,days)
coin3.flips = rep(NA,days)
coin4.flips = rep(NA,days)

#Variable for tracking total number of heads
heads = rep(NA,days)

#Variable for tracking total number of flips
flips = rep(NA,days)

for(i in 1:days){

    #Sample a random number of flips for each coin
    coin1.flips[i] = sample(10:100,1)
    coin2.flips[i] = sample(10:100,1)
    coin3.flips[i] = sample(10:100,1)
    coin4.flips[i] = sample(10:100,1)

    #Flip the coins
    coin1 = rbinom(coin1.flips[i],1,p1)
    coin2 = rbinom(coin2.flips[i],1,p2)
    coin3 = rbinom(coin3.flips[i],1,p3)
    coin4 = rbinom(coin4.flips[i],1,p4)

    #Calculate total number of heads and flips
    heads[i] = sum(coin1)+sum(coin2)+sum(coin3)+sum(coin4)
    flips[i] = coin1.flips[i] + coin2.flips[i] + coin3.flips[i] + coin4.flips[i]

}

#Fit the least sqaures model
model = lm(heads~coin1.flips+coin2.flips+coin3.flips+coin4.flips-1)

model

So we set the initial probabilities for the 4 coins to be $p_1 =1$, $p_2=0.3$, $p_3=0.6$, and $p_4=0.45$
Running the code we obtain the following estimates for the four probabilities:
> model

Call:
lm(formula = heads ~ coin1.flips + coin2.flips + coin3.flips +
    coin4.flips - 1)

Coefficients:
coin1.flips  coin2.flips  coin3.flips  coin4.flips
     1.0025       0.3022       0.6001       0.4459

And so we see that the coefficients (which are the estimated probabilities) are  extremely close to the true solutions.

A: Starting with the case of two coins, we know that $$E\{T_k \}=m_k\theta_A+n_k\theta_B.$$
If $k=2$, we can solve
$$t_1 = m_1\hat{\theta}_A +n_1\hat{\theta}_B$$
$$t_2 = m_2\hat{\theta}_A +n_2\hat{\theta}_B,$$
which is uniquely solvable if and only if $m_1n_2-m_2n_1 \neq 0$.
This yields Method of Moments (MoM) estimators.  I don't see any guarantees that $\mathbf{\hat{\theta}}$ is in the unit square here. If you have fewer sets of tosses than coins, the system is underdetermined and infinitely many solutions exist.  If you have more than two sets of tosses, the system is overdetermined, and a least squares solution can be derived using a generalized inverse.
For more than two coins, again you can get MoM estimators by equating the expected number of heads to their expectation.  If you have as many sets of tosses as coins, a unique estimator will exist if the sample size matrix $\mathbf{N}$ is nonsingular.  If there are more sets of tosses than coins, a least squares solution of the overdetermined system could be used.


text:
Q: JMSSerializerBundle doctrine entitie update I have a problem with deserialized Doctrine entities. Serialized objects don't have all fields of the entity and when I update them so that fields are set to null.
I think the same issue is here but there is no solution related to using of JMSSerializer + Doctirne.
Regards

A: Did you add to your annotations the @Expose? Sth like that
use JMS\SerializerBundle\Annotation\Expose;
use JMS\SerializerBundle\Annotation\Accessor;
use JMS\SerializerBundle\Annotation\ExclusionPolicy;
use JMS\SerializerBundle\Annotation\Type;

class MyEntity {
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     * @Expose
     * @Type("integer")
     */
    private $id;
}


text:
Q: Sending bytes in a string to Redis in order to using it as parameter for Celery's task I want to send bytes in a string to Celery's task using Redis as broker, but I'm receiving error shown below:
[2017-06-17 21:27:13,826] ERROR in app: Exception on /endpoint_method [POST]
Traceback (most recent call last):
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/developer/my_project/application.py", line 23, in endpoint_method
    task = my_task.execute.delay(request.data)
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/celery/app/task.py", line 412, in delay
    return self.apply_async(args, kwargs)
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/celery/app/task.py", line 535, in apply_async
    **options
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/celery/app/base.py", line 737, in send_task
    amqp.send_task_message(P, name, message, **options)
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/celery/app/amqp.py", line 558, in send_task_message
    **properties
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/kombu/messaging.py", line 169, in publish
    compression, headers)
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/kombu/messaging.py", line 252, in _prepare
    body) = dumps(body, serializer=serializer)
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/kombu/serialization.py", line 221, in dumps
    payload = encoder(data)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 35, in __exit__
    self.gen.throw(type, value, traceback)
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/kombu/serialization.py", line 54, in _reraise_errors
    reraise(wrapper, wrapper(exc), sys.exc_info()[2])
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/kombu/serialization.py", line 50, in _reraise_errors
    yield
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/kombu/serialization.py", line 221, in dumps
    payload = encoder(data)
  File "/Users/developer/my_project/venv/lib/python2.7/site-packages/kombu/utils/json.py", line 72, in dumps
    **dict(default_kwargs, **kwargs))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 250, in dumps
    sort_keys=sort_keys, **kw).encode(obj)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
EncodeError: 'utf8' codec can't decode byte 0x80 in position 5: invalid start byte

Shortened (mostly it's up to 1 mln characters string) example data which I want to send to:
'RIFF$\x80\r\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x02\x00D\xac\x00\x00\x10\xb1\x02\x00\x04\x00\x10\x00data\x00\x80\r\x00z\xefz\xef\xd5\xec\xd5\xec\xc1\xee\xc1\xee\xe6\xf3\xe6\xf3\xb4\xfa\xb4\xfa\x92\x03\x92\x03\xab\x0e\xab\x0e\xf9\x18\xf9\x18D\x1eD\x1ev\x1dv\x1d@\x19@\x19\x86\x13\x86\x13w\nw\n\xf0\xfd\xf0\xfd\xf9\xf2\xf9\xf2\xd0\xed\xd0\xedK\xedK\xed{\xed{\xed%\xee%\xeeP\xf3P\xf3\xeb\xfc\xeb\xfc!\x05!\x05\xa4\x08\xa4\x08\xe5\t\xe5\t\x84\x0b\x84\x0bF\x0bF\x0b\xfb\x04\xfb\x040\xfa0\xfa\x86\xf1\x86\xf1T\xeeT'

Part of the code responsible for calling Celery's task:
task = my_task.execute.delay(request.data)

This is how tasks/my_task.py file looks like:
from __future__ import absolute_import, unicode_literals
from my_module.celery import app

@app.task
def execute(request_data):
    return <some operations on request_data>

and celery.py:
from __future__ import absolute_import, unicode_literals
from celery import Celery

app = Celery(
    'my_module',
    broker='redis://127.0.0.1:6379/1',
    backend='redis://127.0.0.1:6379/2',
    include=[
        'my_module.tasks.my_task'
    ]
)

app.conf.update(
    result_expires=3600,
)

if __name__ == '__main__':
    app.start()

Maybe is there some clever way to encode that string before sending it to Redis and decode it in while running the task?

A: Finally, I came up with a solution using binascii methods binascii.b2a_base64(data) and binascii.a2b_base64(string). This is what I had to change to make this working:
task = my_task.execute.delay(binascii.b2a_base64(request.data))

and in tasks/my_task.py I had to convert data back to be able to make proper operations on it:
binascii.a2b_base64(request_data)


text:
Q: XCode: Still Able To Access Deleted .plist Files...Why? I noticed something odd today. I have an application that writes/read data to a .plist file, and when I deleted that file and left all my code in my implementation file the same, I ran the application in the simulator and it was still able to read/write data to this deleted file.
However, if I try to read data from this deleted file in another view controller, they cannot find it. Very very strange.
Is this a known issue in Xcode, or is there something I am probably doing wrong?
If I need to provide some sample code I will, just let me know.

A: The simulator loves to do this kind of thing, Try clicking "Reset Content and Settings" in the simulator, and cleaning targets in Xcode command-shift-K. Now if that doesn't completely do it you may have to restart Xcode. Another thing I've noticed when working with a .plist is that sometimes if the .plist is deleted and the code is intact, when you execute a write command it has created to the .plist file to write to.
EDIT:


text:
Q: Передача файла из input с помощью AJAX в IE Цель - передать файл ajax-запросом на Web-API с помощью javascript/jquery в браузере IE 8-9.
К странице подключен FileAPI, происходит эмуляция FormData() для браузеров, которые их не поддерживают, а чтобы все это работало на html5 - еще подключается html5shiv.
Работающий код для Google Chrome и IE>10 следующий:

function upload_scan(address, id) {
    var input = document.getElementById(address);
    var file = FileAPI.getFiles(input);
    var temp = new FormData();
    temp.append('picture', file[0]);
    if (id == undefined) id = '';
    else id = '/' + id;
    $.ajax({
      url: string_connection + 'uploadfile' + id,
      type: "POST",
      data: temp,
      processData: false,
      contentType: false,
      success: function(data) {
        //Код при выполнении
      },
      error: function(x, y, z) {
        alert('Не получилось загрузить скан\n' + x + '\n' + y + '\n' + z);
      }
    });
<pre>
<form name="scan" enctype="multipart/form-data" method="post" action="">
  <input type="file" id="scan_file" class="btn" accept="image/*">
  <input id="button_for_scan" type="button" value="Загрузить" onclick="upload_scan('scan_file');">
</form>
</pre>

Проблема заключается в том, что метод FileAPI.getFiles() в браузерах IE 8-9 берет не файл, а пустой blob. Есть предложение, как это все реализовать правильно?

A: *

*клонируете файловый <input>

*отсоединяете старый <input> (который с файлом)

*присоединяете новый <input> на место старого

*присоединяете старый <input> к вспомогательной форме

*настраиваете для вспомогательной формы target, чтобы он указывал на скрытый <iframe>

*сабмитите форму

Вот тут можно увидеть готовую реализацию: https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.iframe-transport.js#L53


text:
Q: Using stdout from piped command in nc connection and commands in parentheses I want to know how I can use stdout  from piped command and then use it in nc connection:
<COMMAND> | \
grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' | \
(echo "exit" | nc <IP-HERE> 23 -w 5 \
if [ "$?" -eq "0" ]; then
(
<SomeCommandsHERE>
) | nc <IP-HERE> 23 1>>$file 2>&1 )

Questions:
1) How can I use result of grep command for my nc command in this thread?
2) Can I say the result of grep that is an ip only be used in whole following statement like what I did here?
(echo "exit" | nc <IP-HERE> 23 -w 5 \
    if [ "$?" -eq "0" ]; then
    (
    <SomeCommandsHERE>
    ) | nc <IP-HERE> 23 1>>$file 2>&1 )

UPDATE
What I tried so far:
<COMMAND> | \
grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' | \
while read ip; do
    ( echo "exit" | nc "$ip" 23 -w 5
    [[ "$?" -eq "0" ]]
        (
            echo "hello"
        ) | nc "$ip" 23 1>>$file 2>&1
    ); done

Is this correct? How can I change the if statement if it is not corrrect?

A: If you pass the output of the <COMMAND> to a loop, you could evaluate it one line at a time:
<COMMAND> | while read text; do
  ipaddr=`echo $text | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])'`
  if [ $? -eq 0 ]; then
    (echo "exit" | nc $ipaddr 23 -w 5
      if [ $? -eq 0 ]; then
       (
         <SomeCommandsHERE>
       ) | nc $ipaddr 23 1>>$file 2>&1
      fi
    )
  fi
done


text:
Q: Asymptotics of product of Euler's totient function (A001088)? Conjecture:
\begin{align}
\lim_{n\to \infty } \, \frac{\left(\prod _{k=1}^n \phi (k)\right){}^{1/n}}{n}\sim 0.2059\text{...}
\end{align}
The numerical result from 100000 terms is:

My questions are:
1) exists this limit ?
2) if yes, what is closed form of this constant ?
I am sure that this limit is NOT equal to 6/Pi^2 * exp(-1) = 0.2236438825...

A: Yes, the limit exists, and is equal to $\exp(-1 + \sum_{p} \frac{1}{p}\log(1-\frac{1}{p}))$ (as Lucia said), where $p$ runs over primes. Hint: Reduce the problem to computing $\lim_{N\to \infty} \frac{1}{N} \sum_{n \le N} \log \frac{\phi(n)}{n}$. The arithmetic function $\log\frac{\phi(N)}{N}$ is strongly additive and (under favorable conditions which hold here) the mean value of a strongly additive function $g$ is given by $\sum_{p} g(p)/p$.

A: We may just write down $\varphi(k)=k\cdot \prod_{p|k} (1-1/p)$, $p$ runs over the primes which divide $k$, then
$$
\frac{\left(\prod_{k\leqslant n}\varphi(k)\right)^{1/n}}{n}=\frac{\sqrt[n]{n!}}n\prod_{p} (1-1/p)^{\frac{[n/p]}{n}}.
$$
First multiple tends to $1/e$ by weak version of Stirling's formula, and in the product we may replace each exponent $\frac{[n/p]}n$ to $1/p$ for $p\leqslant n$ with multiplicative error between 1 and
$$
\prod_{p\leqslant n} (1-1/p)^{1/n}\geqslant \prod_{2\leqslant k\leqslant n}(1-1/k)^{1/n}=n^{-1/n}\rightarrow 1.
$$
Hence the limit exists and equals $e^{-1}\prod_p (1-1/p)^{1/p}$ as Lucia and
so-called friend Don have already said.


text:
Q: How to use gettext? I am trying to understand how to use gettext. The following work flow does not retrieve the French text correctly. How can I get it to work?
$ cat po/fr/hello.po
msgid "Hello World\n"
msgstr "Bonjour le monde\n"
$ msgfmt -o po/fr/hello.mo po/fr/hello.po
$ cp po/fr/hello.mo fr/LC_MESSAGES/hello.mo
$ cat hello.c
#include <stdio.h>
#include <stdlib.h>

#include <libintl.h>
#include <locale.h>

#define _(STRING) gettext(STRING)

int main() {
  /* Setting the i18n environment */
  setlocale (LC_ALL, "");
  bindtextdomain ("hello", "/usr/share/locale/");
  textdomain ("hello");

  /* Example of i18n usage */
  printf(_("Hello World\n"));

  return EXIT_SUCCESS;
}
$ gcc -o hello.exe hello.c
$ LANG=fr_FR ./hello.exe
Hello World


text:
Q: numpy fastest way to transform an array's elements to their frequency As the title said, I am looking for a way to transform an array so it will be the array of frequency of its proper elements.
I found np.count and np.histogram but it's not what I am looking for
Something like:
From:
array_ = np.array([0,0,0,1,0,0,2,0,0,1,2,0])

To:
array_ = np.array([8,8,8,2,8,8,2,8,8,2,2,8])

Thanks in advance!

A: If the values in your array are nonnegative integers which aren't too large, you can use np.bincount.  Using your original array as an index into the bincount result gives your desired output.
>>> array_ = np.array([0,0,0,1,0,0,2,0,0,1,2,0])
>>> np.bincount(array_)
array([8, 2, 2])
>>> np.bincount(array_)[array_]
array([8, 8, 8, 2, 8, 8, 2, 8, 8, 2, 2, 8])

Bear in mind that the result of np.bincount has size max(array_) + 1, so if your array has large values this approach is inefficient: you end up creating a very large intermediate result.
An alternative approach that should be efficient even with large or negative inputs is to use np.unique with the return_inverse and return_counts arguments, as follows:
>>> array_ = np.array([0,0,0,1,0,0,2,0,0,1,2,0])
>>> _, inv, counts = np.unique(array_, return_inverse=True, return_counts=True)
>>> counts[inv]
array([8, 8, 8, 2, 8, 8, 2, 8, 8, 2, 2, 8])

Note that the return_counts argument is new in NumPy 1.9.0, so you'll need an up-to-date version of NumPy. If you don't have NumPy 1.9.0, all is not lost!  You can still use the return_inverse argument of np.unique, which gives you back an array of small integers in the same arrangement as your original one.  That new array is now in perfect shape for bincount to work on it efficiently:
>>> array_ = np.array([0,0,0,1,0,0,2,0,0,1,2,0])
>>> _, inverse = np.unique(array_, return_inverse=True)
>>> np.bincount(inverse)[inverse]
array([8, 8, 8, 2, 8, 8, 2, 8, 8, 2, 2, 8])

Another example, with larger array_ contents:
>>> array_ = np.array([0, 71, 598, 71, 0, 0, 243])
>>> _, inverse = np.unique(array_, return_inverse=True)
>>> inverse
array([0, 1, 3, 1, 0, 0, 2])
>>> np.bincount(inverse)[inverse]
array([3, 2, 1, 2, 3, 3, 1])

All of these solutions work in pure NumPy, so they should be significantly more efficient than a solution that goes via a Python Counter or dict.  As always, though, if efficiency is a concern then you should profile to find out what's most suitable.  Note in particular that np.unique is doing a sort under the hood, so its theoretical complexity is higher than that of the pure np.bincount solution.  Whether that makes a difference in practice is impossible to say without timing.
So let's do some timing, using IPython's timeit (this is on Python 3.4).  First we'll define functions for the operations we need:
In [1]: import numpy as np; from collections import Counter

In [2]: def freq_bincount(array):
   ...:     return np.bincount(array)[array]
   ...:

In [3]: def freq_unique(array):
   ...:     _, inverse, counts = np.unique(array, return_inverse=True, return_counts=True)
   ...:     return counts[inverse]
   ...:

In [4]: def freq_counter(array):
   ...:     c = Counter(array)
   ...:     return np.array(list(map(c.get, array)))
   ...:

Now we create a test array:
In [5]: test_array = np.random.randint(100, size=10**6)

And then we do some timings. Here are the results on my machine:
In [6]: %timeit freq_bincount(test_array)
100 loops, best of 3: 2.69 ms per loop

In [7]: %timeit freq_unique(test_array)
10 loops, best of 3: 166 ms per loop

In [8]: %timeit freq_counter(test_array)
1 loops, best of 3: 317 ms per loop

There's an order-of-magnitude difference between the np.bincount approach and the np.unique approach. The Counter approach from @Kasramvd's solution is somewhat slower than the np.unique approach, but that could change on a different machine or with different versions of Python and NumPy: you should test with data that are appropriate for your use-case.

A: As a fast approach you can use colections.Counter which is the more pythonic way for getting the frequency of an iterable items :
>>> import numpy as np
>>> array_ = np.array([0,0,0,1,0,0,2,0,0,1,2,0])
>>> from collections import Counter
>>> c=Counter(array_)
>>> np.array(map(c.get,array_))
array([8, 8, 8, 2, 8, 8, 2, 8, 8, 2, 2, 8])


text:
Q: How to connect C harp project to run it in Apche server? Can anyone tell the procedure how can I run C sharp project in Apache server?
To solve the problem how can I run C sharp project in Apache server?


text:
Q: Setting BiqQuery environment variable Error I was following Google's BigQuery get started page on how to set the credentials, but something is still incorrect. These are the steps I followed:

*

*Set up a free Service Account and created my key. Saved it to a folder.

*Set the environment variable in Anaconda Prompt as set GOOGLE_APPLICATION_CREDENTIALS=C:\Users\$Name\OneDrive\Templates\api\BigQuery\creds.json.

*In Python:
from google.cloud import bigquery
client = bigquery.Client()
This resulted in the following error. How do I fix it?
Traceback (most recent call last):
File "<ipython-input-2-490cf645c3eb>", line 1, in <module>
client = bigquery.Client()

  File "C:\Users\$Name\Anaconda3\lib\site-packages\google\cloud\bigquery\client.py", line 179, in __init__
    project=project, credentials=credentials, _http=_http

  File "C:\Users\$Name\Anaconda3\lib\site-packages\google\cloud\client.py", line 226, in __init__
    _ClientProjectMixin.__init__(self, project=project)

  File "C:\Users\$Name\Anaconda3\lib\site-packages\google\cloud\client.py", line 178, in __init__
    project = self._determine_default(project)

  File "C:\Users\$Name\Anaconda3\lib\site-packages\google\cloud\client.py", line 193, in _determine_default
    return _determine_default_project(project)

  File "C:\Users\$Name\Anaconda3\lib\site-packages\google\cloud\_helpers.py", line 186, in _determine_default_project
    _, project = google.auth.default()

  File "C:\Users\$Name\Anaconda3\lib\site-packages\google\auth\_default.py", line 338, in default
    raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)

DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started

A: Were you running the python in the same shell as where you set the environment variable? you may need to export GOOGLE_APPLICATION_CREDENTIALS if you are running in a different shell/tab.


text:
Q: In R how to control the cycling direction of values when copying in an array? I would like to copy some values across rows but the default seems to be cycling over columns, is there an elegant way to achieve what I want ?
The following code I have is:
> w = array(NA,dim=c(4,2))
> w
     [,1] [,2]
[1,]   NA   NA
[2,]   NA   NA
[3,]   NA   NA
[4,]   NA   NA
> w[2:4,] = c(2,3)
> w
     [,1] [,2]
[1,]   NA   NA
[2,]    2    3
[3,]    3    2
[4,]    2    3

But I would like the values to be cycled over rows to obtain:
     [,1] [,2]
[1,]   NA   NA
[2,]    2    3
[3,]    2    3
[4,]    2    3

A: You can write a new transposed assignment function:
`t<-` <- function(x, value)
{
    t(matrix(value, nrow=ncol(x), ncol=nrow(x)))
}

Result:
> w = array(NA,dim=c(4,2))
> t(w[2:4,]) = c(2,3)
> w
     [,1] [,2]
[1,]   NA   NA
[2,]    2    3
[3,]    2    3
[4,]    2    3

A: Create the matrix row-wise, then assign it:
w[2:4, ] <- matrix(c(2,3), nrow=3, ncol=2, byrow=TRUE)

A: Another elegant way :-)
 w[2:4,] <- rep(c(2,3),each=length(2:4))
     [,1] [,2]
[1,]   NA   NA
[2,]    2    3
[3,]    2    3
[4,]    2    3

A: w[2:4, ] <- matrix(c(2,3),nrow=1)[ rep(1,3), ]


text:
Q: xml.haml template dynamic constant assignment I am trying to produce a xml.haml template but I am receiving a "dynamic constant assignment" error at the %Worksheet{ss:Name="Sheet1"}. I have tried many variations but all error.
!!! XML
%Workbook{xmlns="urn:schemas-microsoft-com:office:spreadsheet", xmlns:o="urn:schemas-microsoft-com:office:office", xmlns:x="urn:schemas-microsoft-com:office:excel", xmlns:ss="urn:schemas-microsoft-com:office:spreadshet", xmlns:html="http://www.w3.org/TR/REC-html40"}
%Worksheet{ss:Name="Sheet1"}
  %Table
    %Row
      %Cell
        %Data{ss:Type="String"}ID
      %Cell
        %Data{ss:Type="String"}Name
      %Cell
        %Data{ss:Type="String"}Release Date
      %Cell
        %Data{ss:Type="String"}Price
  - @addresses.each do |address|
    %Row
      %Cell
        %Data{ss:Type="Number"}= address.id
      %Cell
        %Data{ss:Type="String"}= address.name
      %Cell
        %Data{ss:Type="String"}= address.released_on
      %Cell
        %Data{ss:Type="Number"}= address.price

What is the correct way to translate this html?
Edit
I changed the style attributes to the HTML style as suggested. Now, it exports the document but it "cannot be opened for some reason". Here is the updated code.
!!! XML
%Workbook(xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadshet" xmlns:html="http://www.w3.org/TR/REC-html40")
%Worksheet(ss:Name="Sheet1")
  %Table
    %Row
      %Cell
        %Data(ss:Type="String")ID
      %Cell
        %Data(ss:Type="String")Name
      %Cell
        %Data(ss:Type="String")Email
      %Cell
        %Data(ss:Type="String")Phone
  - @addresses.each do |address|
    %Row
      %Cell
        %Data(ss:Type="Number")= address.id
      %Cell
        %Data(ss:Type="String")= address.company_name
      %Cell
        %Data(ss:Type="String")= address.email
      %Cell
        %Data(ss:Type="Number")= address.phone


text:
Q: Does PushSharp require opening inbound ports to the machine it is running on? We are using PushSharp to send GCM (Google Android) Notifications. In the future we will also be using the IOS and WinPhone parts of the lib.
There are a few events like:

*

*OnDeviceSubscriptionExpired

*OnDeviceSubscriptionChanged

*OnNotificationFailed

I have never seen these events triggered after quite some testing. I now suspect that the communication might be asynchronous, and that we might need some ports opened to the machine running the service that hosts PushSharp.
If that is the case, which ports should be forwarded and is there any way to configure or tweak the endpoints?

A: No inbound ports are required. GCM requires the normal HTTP or HTTPS outbound ports (for the HTTP GCM Connection Server. The GCM Cloud Connection Server is different, but I'm quite sure it doesn't require inbound ports either, and anyway, PushSharp is probably using the HTTP GCM Server). APNS requires outbound 2195 and 2196 ports.
The events you mentioned are probably triggered by PushSharp when it gets an error response from GCM or APNS (or, for APNS, when it gets device tokens from the Feedback Service). In GCM the communication is synchronous (assuming PushSharp uses the HTTP GCM Connection Server). In APNS the communication is asynchronous, but the error responses are read by the client (i.e. your 3rd party server) from the same socket used to send the messages, so the APNS server is not initiating any communication with your server.


text:
Q: Android Studio (API 23) - I want to reuse a fragment across multiple activities, but with a unique layout in each activity Is this possible?
Essentially -
I want ActivityA to host FragmentA with layoutA, and I want ActivityB to host FragmentA with layoutB.  I can't seem to figure out a way to do it conveniently.
Thank you!
Sorry - I don't have any example code handy that's worth looking at!

A: I don't see a point for 2 layouts in same fragment file because binding the views and handle it will be big .. yes you can render different layouts depending on any flag you pass to fragment like this
override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val flag = requireArguments().getInt("AnyCustomFlag", 0)
    return if (flag == 1)
        inflater.inflate(R.layout.layout_a, container, false)
    else
        inflater.inflate(R.layout.layout_b, container, false)
}

A: You can check the activity class inside the onCreateView and assign the good layout
  @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(getActivity() instanceof  ActivityA ? R.layout.fragment_a : R.layout.fragment_b, container, false); ;
    }


text:
Q: Webpack and boostrap, remove styles from style tag I'm new with Webpack. Using webpack 4.26.
I was trying to install bootstrap. I'v install it but css styles wasn't build in a separate file. I'v solved this problem and now my config looks like this:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    entry: './app/index.js',
    output: {
        filename: 'app.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.(scss)$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader',
                    'sass-loader'
                ]
            },
            {
                test: /\.(png|svg|jpe?g|gif)$/,
                exclude: /svg[\/\\]/,
                loader: 'file-loader',
                options: {
                    name: 'images/[name].[ext]'
                }
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'style.css',
        })
    ]
};

Index.js:
'use strict'

import 'bootstrap';
import './index.scss';

index.scss
@import "~bootstrap/scss/bootstrap";

So now I have a separate file 'style.css' with all bootstrap styles, but, as I understand styles still included to bundle and rendered into  tag.
How can I remove it from bundle?


text:
Q: Enable nfc in android programmatically I need to enable NFC if it is OFF when launch my APP. I found this way but I need turn on when launch my app automatcly.
if (nfcAdapter == null) {
            // NFC is not available for device
            alertDialogNfc( "Sorry! This device do not support NFC" );
        } else if (!nfcAdapter.isEnabled()) {
            // NFC is available for device but not enabled
            alertDialogNfc( "Please, turn on the NFC" );
            startActivity(new Intent("android.settings.NFC_SETTINGS"));
}


text:
Q: Representation of variables in F=ma using a scatter plot I'm currently taking a Physics class in college, we just had our fourth lab which was about forces. We did experiments and collected data about the relationship between the variables in the equation F = ma. I have three variables in my dataset: Force (N), Mass (g), and Acceleration (m/s^2). How can I plot these three variables using a scatter plot (teacher's choice) and show a relationship between the three (if any)?

A: You do not necessarily need to plot only two single variables against each other in a plot.
You can also plot groups of variables against each other. For instance $F$ versus $m \cdot a$

This is done a lot in engineering where often several, more than two, (dimensionless) numbers are related with each other, using emperical correlations. (often some power law equation, for instance take the expressions for the rate of heat transfer in terms of dimensionless numbers $Nu = Re^a Pr^b$)
So imagine you would have some phyical law like:
$$F \propto  m^xa^y$$
Then you might:

*

*wish to show that for those coefficients you have constant $x=y=1$

*wish to explore that $x$ and $y$ may be varying (e.g. show different laws in the same graph)

*wish to show how $x$ and $y$ are varying with respect to some standard

In the first case you would have a very strong visual representation when you plot $F$ versus $m \cdot a$ because you get a straight line which people can interpret very easily.
In the second case you can not plot so easily versus $m \cdot a$ because the coefficients $x$ and $y$ may vary. Or at least you should not expect everything to be on a single straight line.
In the third case you may not have a constant $x$ and $y$ but you might still choose to F plot versus some product, e.g. $m \cdot a$. E.g. because it makes the graph easier, or you want to stress some difference (say you want to show that $F \neq m a$, then plotting $F$ vs $m a$ would be a very effective visual representation) .

If you browse these images (keywords Nusselt Reynolds Prandtl) on google you may get an idea/feeling of the different representations.

A: You will be doing what can be called an EDA step. Having three variants you can plot up to 9 scatter plots where half of them would be repeating (3 unique) from which your goal is to find (show) the dependent and the invariant variables.
If you find the works of astronomers in 1600s, their research was mostly tabling their observations in writing and looking for a constant. Having visualization tools now your teacher is hoping you figure out the relations, here linear with m as a constant, using scatter plots. This homework would only make sense if you don't know the relationship ahead.
Here is one simulated experiment data set, three weight groups (0.8kg, 1kg, 1.25kg) and for each weight, 30 students of the class are measuring acceleration while applying pretty much same force. Each student submits its 3 observation in the end to the teacher. What is the take outs from the plot from all the observations? That is what you are looking to figure out here.


text:
Q: JS permanent hover state with radio button behavior I'm trying to use user Wind Shear's permanent hover solution on a group of thumbnails.  However, I'd like the "permanent hover" state to only be applied to one thumbnail at a time.  So if I hover off a thumbnail and onto the page the permanent hover stays applied to that thumbnail, but when I hover onto a different thumbnail it should take the permeant hover off the first thumbnail and apply it to the new one.
html:

        Alpha

Hiya! And it persists

js:
$("#onabout").one("mouseover", function() {
    $("#onabout ul").addClass('permahover');
});

css:
ul {
    display: block;
    width: 200px;
}

ul li {
    display: block;
}

ul li a {
    display: block;
    border: 1px solid #000;
    background: #fff;
}

ul li a {
    display: block;
    border: 1px solid #000;
    background: #fff;
}

ul li ul {
    display: none;
}

ul li ul.permahover {
    display: block;
}

Here's the jsfiddle from Wind Shear's question: http://jsfiddle.net/jlratwil/w83BW/
The permanent hover function works great, but I can't figure out how to modify it to only apply to one thumbnail at a time. Thanks!

A: Use .on() instead of .one()
$("#onabout").on("mouseover", function() {
    $("#onabout ul").removeClass('permahover');
    $(this).find("ul").addClass('permahover');
});

A: Use .on instead of .one and remove the class then add it to the hovered element
$(".onabout").on("mouseover", function() {
  $('.permahover').removeClass('permahover');
  $(this).find("ul").addClass('permahover');
});

Demo


text:
Q: Please explain the following function which returns the size of an array
Possible Duplicate:
Can someone explain this template code that gives me the size of an array?

template <typename T,unsigned S>
unsigned ArraySize(const T (&v)[S])
{
    return S;
}

I understand the T and S, but my question is why do we have to declare v as a reference variable? Or maybe I'm misunderstanding this whole thing.
I appreciate the help!

A: The function accepts an array by reference, and because of this, type of element T and size S is deduced by the compiler. So it returns S which is nothing but the size of the array. In the absence of reference, it would decay into a pointer type. So there is no difference between these:
void f(int v[100]);  //declaration of f
void f(int v[200]);  //redeclaration of f
void f(int v[]);     //redeclaration of f
void f(int *v);      //redeclaration of f

All are exactly same. You can pass array of any size to all of these functions.

Coming back to ArraySize, the returned value of this function cannot be used as constant expression:
int a[10];
SomeClassTemplate<ArraySize(a)> obj; //error

See error  : http://ideone.com/4mdJE
So a better implementation would be this:
template <typename T,unsigned S>
char (&ArraySizeHelper(const T (&v)[S]))[S];  //no need to define it!
#define ArraySize(a) sizeof(ArraySizeHelper(a))

Now this is perfectly fine:
int a[10];
SomeClassTemplate<ArraySize(a)> obj; //ok

See ok : http://ideone.com/Zt3UY

A: If v wasn't a reference, then you would have this:
template <typename T,unsigned S>
unsigned ArraySize(const T v[S])
{
    return S;
}

But the use of [] in this context is just another way of writing
template <typename T,unsigned S>
unsigned ArraySize(const T *v)
{
    return S;
}

which would give you no size information.


text:
Q: Slow Android native events in Unity? I am using the AdMob plugin for Unity from here:
https://github.com/googleads/googleads-mobile-plugins
You can try opening their sample scene or attach their sample script for a quick implementation with these test ad unit values:
Banner: https://github.com/googleads/googleads-mobile-android-examples/blob/master/admob/BannerExample/app/src/main/res/values/strings.xml
Interstitial: https://github.com/googleads/googleads-mobile-android-examples/blob/master/admob/InterstitialExample/app/src/main/res/values/strings.xml
When I display an interstitial ad and press back or close, it seems like it takes an extra second to close the interstitial and return to my Unity app. Compare this to using AdMob in a native Android application, where it closes instantly.
I see that the unityplayer.ForwardNativeEventsToDalvik setting is true for these touch events/onBackPressed events to even be propagated, but is there a way to make it get sent faster, or cut out some interception on Unity's part? This delay hurts the user experience.

A: Adding this to my <activity> in the AndroidManifest.xml seemed to do the trick:
android:theme="@android:style/Theme.Translucent.NoTitleBar"

I assume that Unity runs with this theme by default so changing from one theme to another on close caused the slowdown.


text:
Q: How do I make a Perl Tk::Frame look like a LCD? I want a Tk::Frame to look like a LCD. Inside the frame I have a Tk::Label and a Tk::Entry. Does anyone know a font name or method to do this, maybe a Perl module?

A: I've used Steve Lidie's Tk::LCD to make an alarm clock, but had to hack in a few missing features.


text:
Q: Statistics - Chebyshev's rule, my answer is wrong for some reason? I have the following problem :
Determine what age interval will contain at least 95% of the data (Chebyshev's) ?
Now, I have standard deviation of 1.516, mean of 19.211.
The formula is $1-(1/k^2) = .95$ So I solve for k to get $\sqrt 2$.
Now, I calculate the interval by mean + $\sqrt 2$*standard deviation = RIGHT AGE INTERVAL
Why is this wrong? I get approximately $21.3578$.
The left interval, let's just skip it for now.
Is my logic off?

A: Your calculations do have an error: your $\sqrt{2}$ should be $\sqrt{\frac{1}{1-0.95}}=\sqrt{20}$.
You seem to have started with Chebyshev's inequality of the form $$\mathbb P(|X-\mu|\le k \sigma) \ge 1-\frac1{k^2}$$
The right hand side is $0.95$ when $k=\sqrt{20} \approx 4.472136$ so your interval should be $[\mu-k\sigma, \mu+k \sigma]$ and in this case $[12.431,25.991]$


text:
Q: How to separate groups using PCA? I have two groups: A) controls: $25\times2000$, B) patients: $12\times2000$.
Group A has one PC explaining a lot of the variance. (Suggesting a homogenous population?) Group B cannot be explained by the first 2 or 3 (each of the PCs seem to be dominated by single patients).
If I use the group A PC1 as an example of "normal control", is there a way to show how "far" or "close" each of the patients are from this? I.e. How can I establish that some patients are very similar to the controls and some aren't?

I have 25 controls but only 12 patients. Each of them have a spectrogram (time x freq x channels) that is collapsed down to 1 vector.I have tried PCA on just the controls and get a good 1st PC (it's not dominated by any one subject) and looks like the individual data. With patients alone, I do not get this. If I do the PCA on both patients and normals [controls] together, the 1st PC still looks like the normals but it doesn't separate the 2 groups. So it was suggested to me to take the PCA of just normals and then project the patients into this space but how to do that is unclear.
Just want to add - I don't think there are two populations; i.e., controls and patients are not very different (at least on the measure that I am using here). But, some patients are "farther apart" than others from the controls; i.e., some look like normals but others are very far from them.

A:
it was suggested to me to take the PCA of just normals and then project the patients into this space but how to do that is unclear

This is not difficult. Let's say that your control subjects data is combined in one matrix $\mathbf{X}$ with 25 rows and 2000 columns, and your patients' data -- in one matrix $\mathbf{Y}$ with 12 rows and 2000 columns. When you do PCA of your control subjects, you will get up to 24 (number of subjects minus 1) principal axes. Each principle axis is a vector in 2000-dimensional space. If you take the first principal axis $\mathbf{u}$ then you can project your control data onto this axis, obtaining $\mathbf{z_x} = \mathbf{X}\mathbf{u}$. This is the first principal component, it consists of 25 values, one for each subject.
Now if you need to project patients on the same axis, you simply compute $\mathbf{z_y} = \mathbf{Y}\mathbf{u}$. This will be a vector of length 12, the projection you were looking for.
Note that I would rather take two first principal axes and not just one, because then the projection onto this two-dimensional space can be nicely plotted as a scatter-plot. You can plot all your controls as black dots, and all your patients as red dots, this will give you a clear visualization.


text:
Q: Forcing UITextView to stay the same size while typing I have a UITextView that I shrink upon bringing up the keyboard. An issue I just ran into though is as I type past the keyboard, rather than the text start scrolling, the UITextView automatically gets bigger. How can I possibly turn this off?
EDIT
This is not a subclass, this is a plain old UITextView. It's definitely resized and gets visibly bigger (the box around the text extends past the keyboard). Not sure what you mean about flexible width/height. I tried setting it to grow and shrink with the window maybe? But that did nothing for me.
I've tried changing the content size and/or frame size, that didn't help.
I agree something very odd is going on here. Still looking for why it could be resizing.
EDIT
Nevermind. A bad fix I had to force the textview to refresh was being called unexpectedly and causing it to grow.

A: To my knowledge, a standard UITextView with no special flags applied shouldn't do that.  In fact, I don't know that a UITextView does that at all, so my response would be in the form of a question: are you sure that your UITextView is in fact resized to fit completely within the bounds of the visible area above the keyboard?  Are you using a plain ol' UITextView and not a subclass?  (I know that the TTTextEditor is a class from the Three20 project whose sole purpose is to grow as you type, which is why I'm suspicious about your class doing that by default)
If you want to make sure it doesn't resize, you can try turning off the flexible width and flexible height sections in the measurements tab in IB, and maybe also uncheck "auto-resizes subviews" on the UITextView's parent.  Although none of these should be making a difference, turning them off may help diagnose the real problem.


text:
Q: How do R# live templates interact with VS code snippets? R# has a feature called "live templates" that seems to duplicate the "Code Snippets" feature in built into VS, although it's probably more featureful.
How do the 2 features interact? E.g. I see R# has imported its templates from VS's snippets. What if I edit a VS snippet, that also already exists as a R# template?
VS version: 2015
R# version: 10

A: They don't interact at all, they're completely separate features. The imported tag that ReSharper uses is a bit of a misnomer. They're not really imported, just copied from the default set of VS snippets. The tag is intended to show that they provide the same functionality as VS snippets, but are separate.
If you edit a VS snippet, it won't affect a ReSharper template, and vice versa. ReSharper will use ReSharper templates in code completion and the editor, but will also expand a VS snippet if you type it and hit Tab. You can also use the keyboard shortcuts or VS menu items to invoke the default VS snippet insertion UI and insert VS snippets that way.


text:
Q: Google Mobile SDK for Business I'm currently using Google maps API and directions API for getting routes, however there is a limitation upto 2500 requests per day. so while searching for a way, got confused after i came across this link..
Google Maps Mobile SDK for Business: Android
Can anyone please explain the difference between this sdk and google maps API..?

A: its basically a software development kit that makes use of the google maps api and helps you in development of apps that use those apis... if request limitation is an issue try other opensource apis like argcis or tomtom etc

A: In order to use the individual SDK such as map, you would require a key. That key is persistent, meaning once you have one, you can keep using that same key in your app manifest, regardless of how many copies of the same app you have.
However, there is a daily limit imposed on how much keys can be requested per day from google to prevent abuse. With that said, I don't think you would have a problem of requesting one. If it is given out for today, just wait till tomorrow and the limit would be refreshed.
As for the Enterprise version, you get more support over the normal version. The main differences is that you get the Business SDK as a static library rather than one using the Google Play Services. That is all.


text:
Q: DBX error in Delphi XE3, when connecting to a SQL Server database When I try to connect to a MS SQL Server database using DBX an error pops up saying that the driver is not properly installed, or missing. I tried with ADO driver and it worked like charm, but the thing is that I need DBX driver to work because I want to modify an app that has been developed with DBX technology.
I reinstalled Delphi XE3, and also asked a friend of mine to test it and the error is the same. Does somebody has any ideea on how to solve it ?
The exactly message was this:

Borland.Data.TDBXError: DBX Error:  Driver could not be properly
  initialized.  Client library may be missing, not installed properly,
  of the wrong version, or the driver may be missing from the system
  path.

I must mention that I tried it on a local instance of MSSQL Server 2012 and on a remote MSSQL Server 2008 instance. My OS win8 x64;
Best regards,

A: This is most likely caused by the wrong version of the SQL Native Client installed on your system. DBX will only work with V10, while you probably have V11 installed. Try to install the V10 version of the client.


text:
Q: UDP receiving data on multiple ports Is it possible to receive data with recvfrom on 2 ports? I have a port which I use for user requests and another port for chat messages. Is it possible to bind two sockets, with different ports and receive data with one recvfrom()?
Regards
EDIT
Does this code work?
int socket_fd,socket_fd2;
struct sockaddr_in addr, chat_addr;

addr.sin_family = AF_INET;
addr.sin_port = htons(1234);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");

chat_addr.sin_family = AF_INET;
chat_addr.sin_port = htons(4321);
chat_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

bind(socket_fd2, (struct sockaddr *) &chat_addr, sizeof(struct sockaddr_in));
bind(socket_fd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in));

So I want to receive data on two different ports.

A: No, it's not possible to read from both sockets using a single call to recvfrom, since that function only takes a single socket file descriptor parameter.
You either need a thread per port, or a mechanism (e.g. select, poll) to tell which sockets have data waiting to be read.
In the latter case, once you know which sockets have pending data you can then call recvfrom on that specific socket to get the data you need, e.g.:
// set up select parameters
fd_set socks;
FD_ZERO(&socks);
FD_SET(socket_fd, &socks);
FD_SET(socket_fd2, &socks);

// find out which sockets are read - NB: it might be both!
int nsocks = max(socket_fd, socket_fd2) + 1;
if (select(nsocks, &socks, (fd_set *)0, (fd_set *)0, 0) >= 0) {
     if (FD_ISSET(socket_fd, &socks)) {
          // handle socket 1
          recvfrom(socket_fd, ...);
     }
     if (FD_ISSET(socket_fd2, &socks)) {
          // handle socket 2
          recvfrom(socket_fd2, ...);
     }
}

NB: this is just a rough and ready sample - real code would have error checking, etc.

A: The answer with select/poll method is right for UDP.
My previous answer was a mistake, due for some time I was confused by my working code, which in real life was to work with port-less protocols like ICMP and others.
However, coming back to UDP it all depends on which side you are, server or client.
When you send UDP packet you normally either bind a port you are using to the socket or an ephemeral port is assigned to it automatically upon sending the data with sendto(). So, normally later you may call recvfrom() to receive a reply, that normally is sent back to the port of your socket, which is bound or assigned. In this case with UDP you may use a single local socket and a single local port to communicate with two (and much more) different remote address and port combinations - think of something like a reverse server :-)
Also, depending on a protocol and system capabilities, you may use two sockets for one port or two sockets for a port-less protocol like ICMP - each socket in this case should receive its own copy of data received.
The above is just interesting, not practical.
Practical solution for you would be even no the proposed above select/poll between two sockets, yet a single socket with a separation by an internal protocol design - e.g. put something like channel identifier into your packets, you'll save port stack.


text:
Q: How to configure a Rails app with ES6 support I've created this sample app to test ES6 support with asset pipeline.
This setup uses browserify-rails gem and I followed its README instructions.
I can't understand why it works in development but fails when runs the precompile command:
$ env RAILS_ENV=production rake assets:precompile
rake aborted!
ExecJS::ProgramError: Unexpected token: name (Hello) (line: 11569, col: 6, pos: 326685)

Error
    at new JS_Parse_Error (/private/var/folders/xt/853lxmvx7yx2w8v4xyc92t4h0000gn/T/execjs20160203-64141-15mqs7ljs:2659:11936)
    at js_error (/private/var/folders/xt/853lxmvx7yx2w8v4xyc92t4h0000gn/T/execjs20160203-64141-15mqs7ljs:2659:12155)
    at croak (/private/var/folders/xt/853lxmvx7yx2w8v4xyc92t4h0000gn/T/execjs20160203-64141-15mqs7ljs:2659:20622)
    at token_error (/private/var/folders/xt/853lxmvx7yx2w8v4xyc92t4h0000gn/T/execjs20160203-64141-15mqs7ljs:2659:20759)
    at unexpected (/private/var/folders/xt/853lxmvx7yx2w8v4xyc92t4h0000gn/T/execjs20160203-64141-15mqs7ljs:2659:20847)
    at semicolon (/private/var/folders/xt/853lxmvx7yx2w8v4xyc92t4h0000gn/T/execjs20160203-64141-15mqs7ljs:2659:21320)
    at simple_statement (/private/var/folders/xt/853lxmvx7yx2w8v4xyc92t4h0000gn/T/execjs20160203-64141-15mqs7ljs:2659:24179)
    at /private/var/folders/xt/853lxmvx7yx2w8v4xyc92t4h0000gn/T/execjs20160203-64141-15mqs7ljs:2659:22152
    at /private/var/folders/xt/853lxmvx7yx2w8v4xyc92t4h0000gn/T/execjs20160203-64141-15mqs7ljs:2659:21493
    at block_ (/private/var/folders/xt/853lxmvx7yx2w8v4xyc92t4h0000gn/T/execjs20160203-64141-15mqs7ljs:2659:26198)
  (in /Users/rodrigora/Projects/browserify_test/app/assets/javascripts/application.js)new JS_Parse_Error ((execjs):2659:11936)
js_error ((execjs):2659:12155)
croak ((execjs):2659:20622)
token_error ((execjs):2659:20759)
unexpected ((execjs):2659:20847)
semicolon ((execjs):2659:21320)
simple_statement ((execjs):2659:24179)
(execjs):2659:22152
(execjs):2659:21493
block_ ((execjs):2659:26198)
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/execjs-2.6.0/lib/execjs/external_runtime.rb:39:in `exec'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/execjs-2.6.0/lib/execjs/external_runtime.rb:21:in `eval'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/execjs-2.6.0/lib/execjs/external_runtime.rb:46:in `call'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/uglifier-2.7.2/lib/uglifier.rb:212:in `run_uglifyjs'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/uglifier-2.7.2/lib/uglifier.rb:179:in `compile'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/uglifier_compressor.rb:25:in `evaluate'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/tilt-1.4.1/lib/tilt/template.rb:103:in `render'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/context.rb:197:in `block in evaluate'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/context.rb:194:in `each'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/context.rb:194:in `evaluate'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/bundled_asset.rb:25:in `initialize'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/base.rb:377:in `new'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/base.rb:377:in `build_asset'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/index.rb:94:in `block in build_asset'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/caching.rb:58:in `cache_asset'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/index.rb:93:in `build_asset'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/base.rb:287:in `find_asset'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/index.rb:61:in `find_asset'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/manifest.rb:211:in `block in find_asset'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/manifest.rb:257:in `benchmark'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/manifest.rb:210:in `find_asset'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/manifest.rb:119:in `block in compile'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/manifest.rb:118:in `each'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/sprockets/manifest.rb:118:in `compile'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-rails-2.3.3/lib/sprockets/rails/task.rb:70:in `block (3 levels) in define'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-2.12.4/lib/rake/sprocketstask.rb:146:in `with_logger'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/gems/sprockets-rails-2.3.3/lib/sprockets/rails/task.rb:69:in `block (2 levels) in define'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/bin/ruby_executable_hooks:15:in `eval'
/Users/rodrigora/.rvm/gems/ruby-2.2.4@browserfy/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => assets:precompile
(See full trace by running task with --trace)

Gemfile:
source 'https://rubygems.org'

gem 'rails', '4.1.14'
gem 'sass-rails', '~> 4.0.3'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0',          group: :doc
gem 'spring',        group: :development
gem "browserify-rails"

app/assets/javascripts/home.js
var Hello = require('./components/hello.jsx');
new Hello();
console.log('hi');

app/assets/javascripts/components/hello.jsx
"use strict";

class Hello {
  constructor() {
    $(window).ready(function() {
      $('body').append('Hello es6!');
    });
  }
}

module.exports = Hello;

package.json
{
  "name": "something",
  "dependencies" : {
    "browserify": "~> 10.2.4",
    "browserify-incremental": "^3.0.1",
    "babelify": "^7.2.0"
  },
  "license": "MIT",
  "engines": {
    "node": ">= 0.10"
  }
}

A: This is probably related to recent changes in the babel as well as in babelify.
Now most of the transformations were pushed out to presets, you can check it out at: https://babeljs.io/docs/plugins/
Now, if you look at the babelify's README you can see how the format should be passed to browserify:
$ browserify -t [ babelify --presets [ es2015 react ] ]

So, now given your context, you probably want the es2015 preset, to do that, firs install the preset:
$ npm install --save-dev babel-preset-es2015

Now, on your config/application.rb configure the command line options properly:
config.browserify_rails.commandline_options = "-t [ babelify --presets [ es2015 ] ]"

Now you are probably good to go.
If still in trouble, you may remove all the compiled assets and maybe the tmp/* files
I was able to get it up and running in your example.


text:
Q: How does JSON data get sent in an http request? Let's say I'm making the http request below, to update some record in a mongoDB database:
PUT
http://dev.mycompany.co/ping
{"id":4432, "name":"Jane Doe", "products":[ {"id":287}, {"id":434} ] }
Notice that there is an array of two objects inside the "products" property of the JSON above. I have data that is being sent in this general format, both through Fiddler and through a ruby script I've written.
When sent through Fiddler, my data in the JSON is correctly parsed and updated into my database.  When sent through my ruby script, the data in the JSON is not parsed correctly. I've been trying to figure out why this is. Now, I'm wondering how data is actually sent when a JSON is sent along with an http request. Can someone point me in the right direction?

A: After asking a few other questions on SO and doing a bunch more research, I've arrived at the following conclusions.
Q: How does JSON data get sent in an http request?
A: It depends on how you are sending the JSON data in the request (what is the content-type)
I've encountered two ways that JSON data is sent.

*

*Sent using content-type application/json
With this content-type, JSON data is sent literally as-is. The literal JSON data is stored as a string and sent with the request. If your JSON is complex, with nested objects and arrays and such, this is probably what you want.  For a working example of sending nested JSONs using Ruby's Net/HTTP, see the answer on this SO question I asked.

*Sent using content-type x-www-form-urlencoded
This is how Ruby's Net/HTTP requests typically get sent out. The form of these requests is something like: id=343?entity=Microsoft?foo=bar. This content-type is fine until you have a complex JSON.


text:
Q: How do I get what I want with Math.round in JAVA? I'm using this code to round a value:
Math.round(x * 100) / 100.0;

But it doesn't return what I need.
E.g.: x = 83.5067
What I want: 83.51
What I get: 83.5

A: if your output is a double it will work fine look here
public static void main (String[] args) throws java.lang.Exception
{
    double a = Math.round(83.5067 * 100) / 100.0;
    System.out.println(a);
}

will print 83.51

A: I suggest you use formatted output instead of rounding. Like,
double x = 83.5067;
System.out.printf("%.2f%n", x);

but, to do the requested rounding you might use
double x = 83.5067;
x = Math.round(x * 100);
x /= 100;
System.out.println(x);

Both output
83.51

A: I like to use BigDecimal for these kind of operations.
// Round it
final BigDecimal myRoundedNumber = BigDecimal.valueOf(83.5067).setScale(2, RoundingMode.HALF_UP);

// If you need it as a double
final double d = myRoundedNumber.doubleValue();

The setScale-method is flexible and you can set the number of decimals and the rounding mode you require.


text:
Q: Updating a List Instance I have a List Instance in Visual Studio. However, every time I deploy the solution, Visual Studio says there is already a list instance with the same URL on the site collection and it needs to delete it first before deploying the new one.
I would like to know if there is a way to upgrade the list instance so that the only things changed when I deploy the list instance will be whatever is new or different compared to the current state of the list instance on the site collection. I would like to maintain all the items in the list as well as the columns and other properties unless they are explicitly changed in Visual Studio.

A: You should use the new Feature upgrade functionality available in SP2010. You can edit the feature by selecting the Manifest Tab and clicking on Edit Options at the bottom of the screen.
Then you can add an UpgradeActions node like this:
<Feature xmlns="http://schemas.microsoft.com/sharepoint/" Version="1.0.0.0">
  <UpgradeActions>
    <VersionRange BeginVersion="0.0.0.0" EndVersion="1.0.0.0">
      <ApplyElementManifests>
        <ElementManifest Location="AdditionalFields\Elements.xml" />
      </ApplyElementManifests>
    </VersionRange>
  </UpgradeActions>
</Feature>

You need to give your feature a version number and use that for the EndVersion.
In the Elements.xml only include the new fields that you want to add.
After building your project, use Powershell (Update-SPSolution) to upgrade your solution.
Unfortunately, you need to execute code to do the actual upgrade on your feature.
But, this tool should help you with that part: http://spfeatureupgrade.codeplex.com/

A: By default, you should see a Deployment Conflicts dialog box when you redeploy your solution to your development computer; this should have warned you that your existing list instance would be overwritten. To change this behavior, select the List Instance in Solution Explorer, and then change the Deployment Conflict Resolution property (in the Properties window) to None. If this property is set to Automatic, then existing items will be automatically overwritten without the dialog


text:
Q: Selecting a node based on the intial context I have an XML file with the following structure:
<r>
  <a>
    <i>
      <k>1</k>
      <d>d1</d>
    </i>
    <i>
      <k>3</k>
      <d>d3</d>
    </i>
  </a>
  <b>
    <i>
      <k>1</k>
      <d>rd1</d>
    </i>
    <i>
      <k>2</k>
      <d>id2</d>
    </i>
    <i>
      <k>3</k>
      <d>rd3</d>
    </i>
  </b>
</r>

I select the i nodes under /r/a and iterate through them to find the associated nodes under /r/b and retrieve the value of their d nodes as follows:
$data = [];
$nodes = $domXPath->evaluate('/r/a/i');
foreach($nodes as $node) {
   $key = $domXPath->evaluate('string(k)', $node);
   $data[] = $domXpath->evaluate("string(/r/b/i[k=$key]/d)", $node);
}

This produces the correct result in $data:
[
  "rd1",
  "rd3",
]

My question is whether it is possible to do this without pulling the key out to PHP so something like:
$data = [];
$nodes = $domXPath->evaluate('/r/a/i');
foreach($nodes as $node) {
   $data[] = $domXpath->evaluate("string(/r/b/i[k=initial-context()/k]/d)", $node);
}

A: You can do this with a single XPath:
$nodes = $domXPath->evaluate('/r/b/i[k = /r/a/i/k]/d');
foreach($nodes as $node) $data[] = $node->textContent;

The expression says, for each /r/b/i node, allow only if its k node matches a corresponding k node under /r/a/i.


text:
Q: Using a Django project and static files in a subfolder of root I recently deployed a Django project to my DigitalOcean Droplet. I need to access it in a subfolder of root (i.e. www.domainname.com/). So far this works using the WSGI Aliasing in the apache config files. I am having trouble serving static js files though.
I am using the {% static %} tag in templates to do this. However my js files seem to always be replaced by the current page's html when I inspect them in the browser. Here are my static related settings in settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = '/var/www/html/<project name>/static'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "/static"),
]

UPDATE 1
Here's my apache configuiration:
In sites-available/default:
<Directory /var/www/>
       Options Indexes FollowSymLinks MultiViews
       AllowOverride All
       Order allow,deny
       allow from all
</Directory>

<VirtualHost <project name>:8000>
    ServerName <project name>
    ServerAlias <domain>/<project name>
    ServerAdmin <email>

    DocumentRoot /var/www/html/<project name>
    WSGIScriptAlias /<project name>/ /var/www/html/<project name>/<project name>/wsgi.py

    ErrorLog /var/www/html/logs/error.log
    CustomLog /var/www/html/logs/custom.log combined
    WSGIPythonPath /var/www/html/<project name>
</VirtualHost>

In apache2.conf:
WSGIScriptAlias /<project name> /var/www/html/<project name>/<project name>/wsgi.py
WSGIPythonPath /var/www/html/<project name>

<Directory /var/www/html/<project name>>
   <Files wsgi.py>
       Require all granted
   </Files>
</Directory>

UPDATE 2
It appears the .js files are being requested by appending the static path to the path of the current page, i.e.
<domain name>.com/<project name>/<app name>/<page>/<project name>/static/js/<js file name>

A: You need an Alias directive in your Apache configuration so your static files are served.
Unlike templates, which are rendered through Django views prior to being served, static files are generally served directly by the web server (or some separate service) for performance. After all you generally only want the file itself, so the overhead Django requires is unnecessary. This is discussed in Django's documentation here.
Without the Alias directive, the request is passed to Django for handling. Django changes the default behavior of Apache from serving files from DocumentRoot directly, to mapping URLs to views which then construct the response. So, depending on your urls.py arrangement, the static file request might result in a 404 page or a response (the HTML you're seeing) from a matching view.
To solve this, you can add
Alias /static/ /var/www/html/<project name>/static/

to your virtual host in your configuration file. This will tell Apache to serve files from your static directory when a request is made at a URI beginning with /static/.
For example, a URI of /static/index.js will cause Apache to serve the file /var/www/html/<project name>/static/index.js as a response.

Additionally you have an error in your VirtualHost. The address you're providing it is <project name>, which is not a valid option (see here). The virtual host address must be either an IP address, domain name, or the wildcard *.
Since <project name> is none of these, the virtual host is not matched to the anything, and the configuration within it is not applied. I would suggest fixing it by changing
<VirtualHost <project name>:8000>

to
<VirtualHost *:8000>

which will instead match on any host expected by the request.