python subprocess.call and pipes

Question: I have a script in which I am trying to use subprocess.call to execute a series of shell commands, but which appears to have some commands omitted when executed.
Specifically:
#!/usr/bin/python
import tempfile
import subprocess
import os
import re

grepfd, grepfpath = tempfile.mkstemp(suffix=".xx")
sedfd,  sedfpath  = tempfile.mkstemp(suffix=".xx")

# grepoutfile = open( grepfpath, 'w')
sedoutfile  = open( sedfpath,  'w' )

subprocess.call(['cp','/Users/bobby/Downloads/sample.txt', grepfpath])

sedcmd = [ 'sort',
           grepfpath,
           '|',
           'uniq',
           '|',
           'sed',
           '-e',
           '"s/bigstring of word/ smaller /"',
           '|',
           'column',
           '-t',
           '-s',
           '"=>"' ]

print "sedcmd = ", sedcmd
subprocess.call( ['ls', grepfpath ] )
subprocess.call( ['sort', '|', 'uniq' ], stdin = grepfd )
subprocess.call( sedcmd,  stdout = sedoutfile )

And it generates this as output:
python d3.py
sedcmd =  ['sort', /var/folders/3h/_0xwt5bx0hx8tgx06cmq9h_4f183ql/T/tmp5Gp0ff.xx', '|', 'uniq', '|', 'sed', '-e', '"s/bigstring of word/ smaller /"', '|', 'column', '-t', '-s', '"=>"']
/var/folders/3h/_0xwt5bx0hx8tgx06cmq9h_4f183ql/T/tmp5Gp0ff.xx
sort: open failed: |: No such file or directory
sort: invalid option -- e
Try `sort --help' for more information.
The first 'sort: open failed: |:No such file... is from the first subprocess call ['sort','|','uniq'], stdin = grepfd )
The 'sort: invalid option -- e  .. is from the second subprocess call (sedcmd).
I have seen a lot of examples that use pipes in this context -- so what am I doing wrong?
Thanks!
Comment: If you're trying to use shell features like pipes, you will need to pass a string (not a list) and set `shell=True`.  Read the `subprocess` documentation for details.
Answer: This is a class that will run a command with an arbitrary number of pipes:
pipeline.py
import shlex
import subprocess

class Pipeline(object):
    def __init__(self, command):
        self.command = command
        self.command_list = self.command.split('|')
        self.output = None
        self.errors = None
        self.status = None
        self.result = None

    def run(self):
        process_list = list()
        previous_process = None
        for command in self.command_list:
            args = shlex.split(command)
            if previous_process is None:
                process = subprocess.Popen(args, stdout=subprocess.PIPE)
            else:
                process = subprocess.Popen(args,
                                           stdin=previous_process.stdout,
                                           stdout=subprocess.PIPE)
            process_list.append(process)
            previous_process = process
        last_process = process_list[-1]
        self.output, self.errors = last_process.communicate()
        self.status = last_process.returncode
        self.result = (0 == self.status)
        return self.result

This example shows how to use the class:
harness.py
from pipeline import Pipeline

if __name__ == '__main__':
    command = '|'.join([
        "sort %s",
        "uniq",
        "sed -e 's/bigstring of word/ smaller /'",
        "column -t -s '=>'"
    ])
    command = command % 'sample.txt'
    pipeline = Pipeline(command)
    if not pipeline.run():
        print "ERROR: Pipeline failed"
    else:
        print pipeline.output

I created this sample file to for testing:
sample.txt
word1>word2=word3
list1>list2=list3
a>bigstring of word=b
blah1>blah2=blah3

Output
a       smaller   b
blah1  blah2      blah3
list1  list2      list3
word1  word2      word3

Answer: So if in a command you want to use shell pipes you can add shell=True in subprocess:
so it will be like this:
sedcmd = 'sort /var/folders/3h/_0xwt5bx0hx8tgx06cmq9h_4f183ql/T/tmp5Gp0ff.xx | uniq | sed -e "s/bigstring of word/ smaller /" | column -t -s "=>" '
subprocess.call(sedcmd, shell=True)

But be carefull with shell=True, it's strongly discouraged to use it : subprocess official documentation
So if you want to use pipes without shell=True you can use subprocees.PIPE in the stdout , and here's an example on how to do it: stackoveflow answer

python subprocess.call and pipes


How to call bloc inside initState method?

Question: I need to call the fetchProfile() method and get the profileState.user data in the initState method right after the page opens. Tell me, how can I write this correctly, how can I correctly call Cubit inside the initState method?
 @override
  void initState() {
    SchedulerBinding.instance.addPostFrameCallback((_) {
      _emailDialog();
    });
    super.initState();
  }

cubit
class ProfileCubit extends Cubit<ProfileState> {
  final UserRepository _repository;
  ProfileCubit(this._repository) : super(ProfileInitial());

  Future fetchProfile() async {
    try {
      final User? user = await _repository.me();
      if(user != null) {
        emit(ProfileLoaded(user));
      } else {
        emit(ProfileError());
      }
    } catch (_) {
      emit(ProfileError());
    }
  }

state
abstract class ProfileState {}

class ProfileInitial extends ProfileState {}

class ProfileLoaded extends ProfileState {
  final User? user;
  ProfileLoaded(this.user);
}

class ProfileError extends ProfileState {}

Answer: You can check the Readme of flutter_bloc. There is a full tutorial and you can learn a lot.
@override
void initState() {
  super.initState();
  context.read<ProfileCubit>().fetchProfile()
}

Wrap BlocListener for your widget tree. You can listen to ProfileLoaded state here and get the user data immediately.
BlocListener<ProfileCubit, ProfileState >(
  listener: (context, state) {
    // Do whatever you want.

  },
  child: Container(),
)

Comment: Can I then call ProfileLoaded.user in initState ?
Comment: No, you just interact ProfileLoaded state with UI(Widget tree). Why do you want to call in initState?
Comment: I want to receive data when the page is opened
Comment: I edited my reply. You can try BlocListener.
Answer: If your intention is to run the method fetchProfile directly when the widget (page in this case) will be built, I'd run the method when providing the bloc using cascade notation as such:
home: BlocProvider(
        create: (_) => ProfileCubit()..fetchProfile(),
        child: YourPageOrWidget(),
      ),

The fetchProfile() method will be called as soon as the Bloc/Cubit is created.
Note that by default, the cubit is created lazily, so it will be created when needed by a BlocBuilder or similar. You can toggle that so it isn't created lazily.
Comment: As I said, you shouldn't do that in initState. Use a `BlocBuilder` in the build method and react there based on state.
Comment: Can I then call ProfileLoaded.user in initState ?
Comment: You can, but it is not guaranteed that it is set. I would say that no you shouldn't? In initState you shouldn't (really can't) be depending on futures to be completed. You should rather let your UI display something else until `ProfileLoaded` state is set. This call: `await _repository.me();` in the cubit... it could take XYZ seconds, let's say 30 seconds... you shouldn't "lock" the UI then..
Comment: can you show me how to correctly select ProfileLoaded.user in initState so that I can use this value further.
Comment: I have tried if (state is PrifileLoaded) state.user.isEmail. But this condition was not met in initState


Prove) Suppose $x_n\to\infty$. Then every subsequence $x_{n_k}\to\infty$.

Question: I don't think this statement is true. What if the sequence $x_n = 1$ for all even numbers but $x_n$ is a strictly monotone sequence when $n$ is odd? Then the sequence $x_n$ is a divergent sequence but still has a convergent subsequence, by making $n_k$ a sequence of even numbers.
Is my counterexample valid?
Comment: No, it's not valid. If $x_n\to\infty$ then for every $M>0$ there is some $N$ such that $n\geq N$ implies $x_n\geq M$. Your example doesn't satisfy this condition.
Answer: Let $(x_{\phi (n)}) $ be a subsequence of $(x_n) $ with $x_n\to +\infty $.
for $A>0$, there exist $N>0$ such that
$$n>N\implies x_n>A $$
but $$\phi (n)\ge n $$ thus
$$n>N\implies \phi (n)>N$$
$$\implies x_{\phi (n)}>A $$
$$\implies \lim_{n\to+\infty}x_{\phi (n)}=+\infty .$$
Your counterexample is not good cause
$\lim x_n $ doesn't exist.
Answer: There's something subtle here.
If you define "convergence to infinity" as: For every $A\in \mathbb{R}$ there exists $N_A$ such that if $n > N_A$ then $\lVert x_n \lVert > A$, in that case, the statement that you are trying to refute is valid.
The sequence $x_n = n + (-1)^nn$ does not "converge to infinity" by the definition above even though there are arbitrarily large terms for $n$ sufficiently large. Maybe that is the example you were trying to show, but it doesn't adjust to the premise.
Maybe the confusion comes from the fact that "divergence" and "convergence to infinity" are used interchangeably, which is wrong.
Answer: How do the even terms $x_n =1$ get larger and larger? For example $x_n \to \infty$ requires that from some $N$ onward (meaning all $n>N$) $x_n$ mus be greater than, say, $2345$. Surely there are even $n$ which are $> N$.


Wedges with label parameter, but none label in result

Question: I am beginner with python (3.4) and matplotlib. I want to create a wedge with the following code:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch(patches.Wedge(center=(0,0), r=0.9, theta1=90, theta2=120, facecolor="red", label="Test"))
plt.xlim(-1, 1)
plt.ylim(-1, 1)
fig1.savefig('wedge1.png', dpi=90, bbox_inches='tight')
plt.show()

All Looks fine, but the Label isn't in the plot? Any idea?
Answer: You are missing a plt.legend(). You just need to add it anywhere before the plt.show (also before fig1.savefig if you want it saved in the image) and after all your plots:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch(patches.Wedge(center=(0,0), r=0.9, theta1=90, theta2=120, facecolor="red", label="Test"))
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.legend()  # <--- here
fig1.savefig('wedge1.png', dpi=90, bbox_inches='tight')
plt.show()

Have a look here for further details on how to use legends.
Comment: Thank you. Simple, but you must know it.
Comment: @Geosucher Yep, indeed. I would suggest you (in case you are interested), to have a look to the [scipy's matplotlib lecture notes](http://www.scipy-lectures.org/intro/matplotlib/matplotlib.html). They are a series of lecture notes that include an overview of all-you-need from matplotlib (in this case, they have more lecture notes) to use the most of it. Also, please consider upvoting/accepting the answer in case it helped you.


Is there a need to account for confounders if crude association is not significant?

Question: Background: Swallowing exercises are prescribed to head and neck cancer patients during radiotherapy to prevent swallowing impairment
Aim: Determine impact of swallowing exercise compliance on swallowing impairment
Method: Retrospective review of database between 2015 and 2020. We included everyone which met the criteria within that period
Result:

non-compliant
compliant

Swallowing impairment
7
25

No swallowing impairment
4
8

OR=0.56 (p=0.50) - using fisher exact test
Issue:
When examining differences in baseline characteristics (using fisher exact test), we found significant association (p=0.016) between compliance and T-staging. There was a larger proportion of T1 patients in the compliant group vs the non-compliant group. Which is not unexpected as patients with smaller tumors experience less side effects and thus is more likely to comply to the exercises.
So do we still need to account for this if we have already determined there is no significant association between compliance and swallowing impairment?
If so, I understand we can account for it either through regression or stratified analysis. Given the small sample size, regression is not the best option. So I would think stratified analysis using Cochran-Mantel-Haenszel test.
For the Cochran-Mantel-Haenszel test, what do we report? Just the common OR vs the crude OR, the p-value, and whether there is a confounding effect?
Comment: Is the first p-value .05? "So do we still need to account for this if we have already determined there is no [is this correct?] significant association...". I find confidence interval reporting is usually helpful, and helps the reader to get a quicker understanding.
Comment: We used a Fisher exact test to determine the association between compliance and swallowing impairment, and the p-value of that test is 0.50. OR=0.56, 95% CI=0.13-2.42
Comment: Thanks. Just looking at the table without doing the calculation I wrongly thought was a mistake.
Answer: Just so I get this right:

The study is intended to assess the effect of exercise compliance on swallowing impairment.

T staging is a confounder (I don't know what T1 is, you're going to have to explain that) because size of the tumor affects the ease of the exercise, and size of the tumor also affects the impairment (larger meaning more likely to be impaired).

First off, I don't think it is a good idea to test for confounding using a statistical test.  That T staging is a confounder is something that you should have accounted for even before getting data.  So either you suspect this is a confounder (classic confounding case, X<-Z->Y and X->Y) and you should account for it, or you don't suspect it to be a confounder.
If you suspect it to be a confounder then CMH test sounds fine to me (assuming T staging is a truly discrete variable with not too many categories as opposed to some continuous variable which has been dichotomized).  If you perform the test, report the group odds ratios with confidence intervals, the test statistic for the CMH test, the degrees of freedom of the test, and the p value.
Comment: Thank you for the help!

Yes, you are right on the first bullet point.

 As for the 2nd bullet point, I agree too that T-staging is a confounder. T-staging is split into 4 levels (T1,T2,T3,T4), depending on the size of the tumor (T1 being the smallest and T4 being the largest).

Btw, does "group odds ratio" refer to the common odds ratio or the stratum-specific odd-ratio?
Comment: @user224743 group odds ratio refers to the stratum specific odds ratios


Where does console output go in an IIS hosted app?

Question: Say I have a WCF app hosted in IIS.  And in that app I run this line of code:
 Console.WriteLine("Testing, testing 1 2 3");

Where will that be written to?  Or is it ignored and just lost?
Is there someway to capture it when needed?
Comment: If it's hosted in IIS, then it's the same as ASP.NET, so this post should answer it for you http://stackoverflow.com/questions/137660/where-does-console-writeline-go-in-asp-net  - I'd recommend using System.Diagnostics.Debug.WriteLine instead, you have options to where that goes.
Answer: Nowhere.  More specifically:

NullStream, which is defined as "A Stream with no backing store.".
  All the methods do nothing or return nothing. It is an internal class
  to Stream. The following code is taken from Microsoft's source code.
Basically, when one of the Console write methods is call the first
  time, a call is made to the Windows API function GetStdHandle for
  "standard output". If no handle is returned a NullStream is created
  and used.

quoted from here: https://stackoverflow.com/a/2075892/12744
actually, the same answer goes to on to address the second part of your question too:

To actually redirect Console output, regardless of the project type, use
  Console.SetOut(New System.IO.StreamWriter("C:\ConsoleOutput.txt")),

Comment: The second part of this answer is a gem - it answers "How do I see Console output in an IIS Web app".   NOTE:  I found that I had to add "Console.Out.Flush();" after every Console.WrriteLine... call to get the output to show up in the file as soon as the WriteLine call is made.
Comment: There is just missing that part: "writer.AutoFlush = True"


pesquisar milhares de strings em milhares de arquivos

Question: Estou com o seguinte problema: nosso sistema é parametrizável, e esses parâmetros ficam em uma tabela. Só que nos últimos 25 anos muitos programadores mexeram no sistema e criaram e usaram esses parâmetros sem documentá-los. Por isso estou com esta tarefa de documentar isso.
A primeira parte é localizar todos estes parâmetros em toda a base de código do sistema, que é feito em ASP clássico, ASP.NET, C#, Delphi, Oracle pl/sql e JavaScript.
Preciso pesquisar mais de 3500 strings em mais de 20000 fontes, eliminando ao máximo os falso-positivos, que são nomes de campo iguais aos nomes de parâmetros, variáveis internas com nome igual ao dos parâmetros, etc, etc, etc, por isso preciso pesquisar essas mais de 3500 strings garantindo que elas estejam entre plics ('), ou entre aspas (") ou entre espaços, tabs, pontos, ou no começo ou no final da linha.
Estou usando para isso um script em powershell.
A expressão abaixo me atende em quase tudo, menos quando a string aparece no começo ou no final da linha:
(?sm)[\s\W]+WS_URL_CONSULTA_CNPJ_SERASA[\s\W\n]+

Alguma dica de como eu faria para incluir como condição a string acima aparecer no começo da linha OU no final da linha? Sendo que nestes casos ela não estaria entre plics ou aspas.
Comment: Você poderia usar a tua regex com as seguintes adições: `^(?sm)[\s\W]+WS_URL_CONSULTA_CNPJ_SERASA[\s\W\n]+` para as strings iniciadas pela sua regex ou `(?sm)[\s\W]+WS_URL_CONSULTA_CNPJ_SERASA[\s\W\n]+$` para as string terminadas com a sua regex.
Comment: Olá. Sua sugestão não resolve o problema mas me deu uma dica pra resolver o problema: usar várias expressões. Eu fiz assim:     [\s\W]+WS_URL_CONSULTA_CNPJ_SERASA[\s\W]+|[\s\W]+WS_URL_CONSULTA_CNPJ_SERASA[\s\W]*$|^[\s\W]*WS_URL_CONSULTA_CNPJ_SERASA
Answer: Se tiver certeza de que cada parâmetro começa e termina com um carácter de palavra ([0-9_a-zA-Z]), pode usar limites de palavra \b.
$regex = [regex] "\b$( $WS_URL_CONSULTA_CNPJ_SERASA )\b"

$data -match $regex

"Encontrou: $($matches[0])"


ViewPager switch without showing the in between fragments

Question: I have a ViewPager that holds 4 fragments. When I switch from fragment1 to fragment3 or fragment4 by clicking on my bottom navigation bar, it always shows the in between fragments for a fraction amount of time. The behavior is like it has to pass fragment 2 and 3 to arrive to fragment 4. Is this normal? If so, is there a way to disable this in between animation?
Code in my home activity which holds the 4 fragments are like this:
/**
 * view pager.
 */

public void setupViewPager(ViewPager viewPager){
    Log.d(TAG, "setupViewPager: setting up viewPager.");
    SectionsStatePagerAdapter adapter = new SectionsStatePagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new HomeFragment(), "HomeFragment");
    adapter.addFragment(new HashtagFragment(), "HashtagFragment");
    adapter.addFragment(new ChattingFragment(), "ChattingFragment");
    adapter.addFragment(new SettingFragment(), "SettingFragment");
    viewPager.setAdapter(adapter);
}

public void setViewPager(int fragmentNumber){

        mViewPager.setCurrentItem(fragmentNumber);

}

public void enableViewPagerSwitch(){

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if(bottomNavigationView.getMenu().getItem(position).isChecked()){
                bottomNavigationView.getMenu().getItem(position).setChecked(false);
                Log.d(TAG, "onPageScrolled: position is " + position);
            }
        }

        @Override
        public void onPageSelected(int position) {

            bottomNavigationView.getMenu().getItem(position).setChecked(true);

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

}

/**
 * navigation bar.
 */

private void setupBottomNavigationView(){
    Log.d(TAG, "setupBottomNavigationView: setting up Bottom navigation bar.");
    BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationView);
    Menu menu = bottomNavigationView.getMenu();
    MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
    menuItem.setChecked(true);
}

private void enableNavigation(){
    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()){
                case R.id.ic_home:
                    setViewPager(0);
                    break;

                case R.id.ic_hashtag:
                    setViewPager(1);
                    break;

                case R.id.ic_chat:
                    setViewPager(2);
                    break;

                case R.id.ic_setting:
                    setViewPager(3);
                    break;
            }

            return false;
        }
    });

}

ViewPager adapter:
public class SectionsStatePagerAdapter extends FragmentStatePagerAdapter{

private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public SectionsStatePagerAdapter(FragmentManager fm) {
    super(fm);

}

public void addFragment(Fragment fragment, String title){
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

Thanks!
Answer: You can use ViewPager#setCurrentItem(position, false);
The second boolean tells the ViewPager not to scroll to the item, but show it immediately.
Check the documentation here


Courant-Hilbert's Book: Weyl's asymptotic law for eigenvalues - Planar domains

Question: In the book Strauss W.A. Partial Differential Equations - an Introduction (Wiley, 2008, 1st Ed.) page $311$, there is a comment

Now an arbitrary plane domain $D$ can be approximated by unions of rectangles just as in the construction of a double integral (and as in Section $8.4$). With the help of Theorem $5$, it is possible to prove Theorem 1 (i.e. $(1)$ is Weyl's asymptotic law for eigenvalues on planar domain). The details are omitted but the proof may be found in [CH].

I'm trying actually to find the proof of $(1)$ in the book Methods of Mathematical Physics (Volume II) of Courant-Hilbert, but it is not clear where it is. Is there anyone could help me to find the page in that book?
Answer: You are looking in the wrong volume.
You should look in Vol I, Chapter VI, Section 4, Subsection 4 starting on page 436. The title of that section is "Asymptotic Distribution of Eigenvalues for an Arbitrary Domain".
Good luck!


Twitter-bootstrap modal doesn't work in angular

Question: I am trying to implement a bootstrap modal in angular 7, but the modal is not working.
In my angular.json file in scripts I am including jquery.min.js and bootstrap.min.js in this order.
My component.html:
<button type="button" class="catalogue-button btn btn-primary btn-lg" data-toggle="modal"
         data-target="catalogueModal">Katalog</button>

Modal Heading

                     <button type="button" class="close" data-dismiss="modal">×</button>

                     Modal body..

                     <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

When I click on the button nothing happens. The browser console is empty too.
I am using this https://www.w3schools.com/bootstrap/bootstrap_modal.asp
Comment: did you added reference to the bootstrap css? ``
Comment: yes, I added the reference in the `angular.json` file
Comment: is there a reason your using twitter-bootstrap? why not use an adapted [ng framework](https://valor-software.com/ngx-bootstrap/#/modals) with bootstrap :)
Answer: To open a modal do the following modifications in your code:
insert new button into your component.html file:
<button (click)="showModal()">Show</button>

In your typescript file for the same component add this method:
  showModal() {
    $("#catalogueModal").modal('show');
  }

at the top of the file before @Component add this line:
declare var $: any;

Comment: mm we should try to avoid manipulating the dom directly through jquery in Angular..
Answer: Take a look at ngx-bootstrap. Its an ability to use bootstrap "the angular way" without the need of jquery.
It is well documented and you will find many small examples. Here is the documentation for using a modal.


Is my time series exhibiting stationarity?

Question: I'm a beginner in time series analysis so I'm uncertain whether or not this data is stationary according to the ACF plot; I can observe a fast decay but on the other hand, a lot of the lines exceed -0.4 or 0.4. How would you conclude this?
Comment: Clearly not stationary, with a correlation between consecutive points of about 0.7.
Answer: When using the ACF plot to diagnose stationarity, usually the rate of decay (into insignificant territory) in  ACF values is of greater concern that the actual ACF values. If the ACFs decay slowly, that is usually a sign of non-stationarity.
Without context of your data, and due to your ACFs' wave-like behavior breaching the significance range and high lag 1 ACF, there is evidence of non-stationarity; but I'd advise using a statistical test to be sure.
There are several statistical tests for stationarity, including:

The Ljung-Box test for non-zero correlations at lags 1-20. The null hypothesis is that the series is non-stationary. Small p-values suggest that the series is stationary.

The Augmented Dickey–Fuller (ADF) t-statistic test: The null hypothesis is that the series is non-stationary. Small p-values suggest that the series is stationary.

Personally, I use the ADF test most frequently.
Comment: ADF null hypothesis is *not* that the series is non-stationary. It is that it has a unit root. If we reject the null hypothesis (i.e. p-value ≤ 0.05) it means the mean of the series is stationary. It says nothing about the variance. A dataset can have stationary mean but still be classed as non-stationary due to its variance.


How to display a contact list entry when typing the @ symbol?

Question: Following is the code that I'm using
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_dropdown_item_1line, result);
        AutoCompleteTextView textView = (AutoCompleteTextView)
        findViewById(R.id.ContactDisplay);

        Pattern p = Pattern.compile("@");
        Matcher m = p.matcher(textView.getText().toString());
        Log.d(textView.getText().toString(),"Msssssssssssssssssggg");
        boolean b = m.matches();
        if (b == true)
        {
         textView.setThreshold(0);
         textView.setAdapter(adapter);
        }

But I'm not getting any contacts by typing @ symbol. Should I have to use key-events?
Answer: Try this pattern:

Pattern p = Pattern.compile("^@$");


Updating the value of a react-final-form Field component with a onSelect function call?

Question: I'm doing a react application with typescript and using react-final-form, I'm using some react libraries to integrate the google places and geocoder APIs: "react-places-autocomplete": "^7.2.1" and "react-final-form": "^6.3.0"
The problem I'm having is updating the value in the react-final-form field after the user selects one of the suggestions delivered by the auto complete component on the onSelect: Below are some excerpts of the code:
onSelect Functions:
const handleCitySelect = (selectedCity: string) => {
    geocodeByAddress(selectedCity)
      .then(results => getLatLng(results[0]))
      .then(latlng => {
        setCityLatLng(latlng);
      }); <-- Here I need to update the field with selectedCity
  };

  const handleVenueSelect = (selectedVenue: string) => {
    geocodeByAddress(selectedVenue)
      .then(results => getLatLng(results[0]))
      .then(latlng => {
        setVenueLatLng(latlng);
      }); <-- Here I need to update the field with selectedVenue
  };

React final form:
      <FinalForm <-- react-final-form component

        validate={validate}
        initialValues={activity}
        onSubmit={handleFinalFormSubmit}
        render={({ handleSubmit, invalid, pristine }) => (
          <Form onSubmit={handleSubmit} loading={loading}> <-- semantic-ui-react component
            <Field
              name="title"
              placeholder="Title"
              value={activity.title}
              component={TextInput}
            />
            <Field
              name="description"
              placeholder="Description"
              rows={3}
              value={activity.description}
              component={TextAreaInput}
            />
            <Field
              component={SelectInput}
              options={category}
              name="category"
              placeholder="Category"
              value={activity.category}
            />
            <Form.Group widths="equal">
              <Field
                component={DateInput}
                name="date"
                date={true}
                placeholder="Date"
                value={activity.date}
              />
              <Field
                component={DateInput}
                name="time"
                time={true}
                placeholder="Time"
                value={activity.time}
              />
            </Form.Group>

            <Field <-- field I need to update after the onSelect callback
              component={PlaceInput}
              name="city"
              placeholder="City"
              options={{ types: ["(cities)"] }}
              value={activity.city}
              onSelect={handleCitySelect}
            />
            <Field <-- field I need to update after the onSelect callback
              component={PlaceInput}
              name="venue"
              placeholder="Venue"
              options={{
                location: new google.maps.LatLng(cityLatLng),
                radius: 1000,
                types: ["establishment"]
              }}
              value={activity.venue}
              onSelect={handleVenueSelect}
            />
<...>

The PlaceInput is a custom component that servers as a wrapper around the PlacesAutocomplete component that does the suggestions according to what the user types.
Thanks to anyone who can suggest a solution. I scoured the Internet and couldn't find a quick fix to something that I feel should be a no-brainer. If more explanations are needed please let me know or more code excerpts.
Cheers,
Answer: To set the field value, your PlaceInput needs to call input.onChange(newValue).
Also, you should not be passing a value prop to Field. That's only for checkboxes and radio buttons.
Comment: Hello Erik, thanks for your reply, but your suggestion is still not very clear to me. I do pass the input.onChange but I'm not sure where should I call that method. Here is a link to the github [link]https://github.com/luisfguzman/Reactivities/blob/master/client-app/src/app/common/form/PlaceInput.tsx if you could check it out. Also you said to not pass a value prop to Field but I'm using this component ActivityForm as for create and edit an Activity, so what is the correct method to initialize the data when user is editing an Activity? Thanks again for your help is greatly appreciated it!
Comment: Hmmm... A sandbox would be really helpful here.
Comment: Hi Erik, I created a sandbox for the client-app which is my react-typescrit front end: [link]https://codesandbox.io/s/github/luisfguzman/Reactivities/tree/master/client-app But it doesn't have the connection to the API which is a DotNetCore application. I have deployed it to azure for the full integration: [link]https://intermingle.azurewebsites.net/ The problem I'm having is when creating/editing and activity the City/Venue fields of the form aren't updated when the user selects one of the suggestions. Let me know if this helps. Thanks again!


Azure - error on starting with multiple web role projects

Question: If I have more than one webroles(projects, not instances) in my application, I get this error: (I only get it if I attach a web role. It works fine wit as many worker roles projects as I want)
Microsoft Visual Studio
Windows Azure Tools for Microsoft Visual Studio
There was an error attaching the debugger to the IIS worker process for URL 'http://127.0.0.1:5100/' for role instance 'deployment(21).CloudPOC.WebRoleToHostDataService.0'. Unable to start debugging on the web server. The web server is not configured correctly. See help for common configuration errors. Running the web page outside of the debugger may provide further information.
Click Help for more information.
OK
What is wrong here? I can't understand it and I need a webservice project!
Answer: Make sure you are starting the Azure project rather than the Web Project itself. You might have set the Web Role as the startup project, and if you do that you'll find that IIS runs the Web App rather than the Azure Dev Fabric, meaning any Dev Fabric specific stuff (like config settings per role) aren't available causing problems.
What you're meant to do is let the Azure Dev Fabric (Compute Simulator) fire up all your roles for you, and it'll also work out if it needs to open a web browser etc.
So right click on the Azure Cloud project, set that as the Startup Project, and try again.
Hope that helps,
Andy
EDIT thought of something else!
Make sure your web.config is compiling to allow debug="true". If you have added a new WebSite to your solution, it won't be so by default:
<system.web>
    <compilation debug="true" targetFramework="4.0" />
Comment: adding debug="true" worked for me.  I made sure to remove the debug attribute in my release config transform.
Answer: I had similar issue which got resolved with following steps.

Make sure you have correct version of .net framework 4.0 is intalled. (.Net Framework 4.0.30319 is the latest version)
Uninstall if there isany other .Net 4.0 framework in present on your system by going to Add And Remove programs.
Go to %windir%\Microsoft.NET\Framework64 physical location and remove unwanted .Net framework 4.0 folder
Answer: I've also had this problem and it happened when I upgraded my app to 4.0... I ran without debugging and got the following error:
There is a duplicate 'system.web.extensions/scripting/scriptResourceHandler' section defined
and after researching that error, I found this:
http://forums.asp.net/t/1571308.aspx/1
which says there's currently a bug w/ vs2010 and 4.0... I took the answers recommendation and commented out the extensions section and it worked for me... Another possible solution.


How to update sql query dynamically - jquery

Question: I am trying to figure out how I can update my sql query dynamically.
On the main page, I have a pagination script that counts how many pages there will be:
<?php
function generate_pagination($sql) {
  include_once('config.php');
  $per_page = 3;

  //Calculating no of pages
  $result = mysql_query($sql);
  $count = mysql_num_rows($result);
  $pages = ceil($count/$per_page);

  //Pagination Numbers
  for($i=1; $i<=$pages; $i++)
  {
    echo '
'.$i.'
';
  }
}
?>

I then have in the body of the same page this line of code to populate the page numbers:
<?php generate_pagination("SELECT * FROM explore WHERE category='marketing'"); ?>

So, that line is displaying the necessary amount of page numbers to be displayed for just the 'marketing' category.
The problem that I am having is with that single line of code. I want to make the category dynamic, so instead of it being hardcoded to 'marketing' I would like jquery to get the id of an element and place it in.
The element would be this link that I have on the same page:
Marketing

So, when the user clicks that link, I am trying to place the id of the link in the category section of the query using jquery.
I hope that made sense, and if anyone can assist me on this that would be great.
Comment: Is this in an AJAX request, or a normal pageload?
Comment: This is an Ajax request.
Comment: Can you post your current ajax call?  Easier to directly answer that way
Answer: First, the PHP side:
<?php
function generate_pagination($sql) {
  include_once('config.php');
  $per_page = 3;

  //Calculating no of pages
  $result = mysql_query($sql);
  $count = mysql_num_rows($result);
  $pages = ceil($count/$per_page);

  //Pagination Numbers
  for($i=1; $i<=$pages; $i++)
  {
    echo '
'.$i.'
';
  }
}
?>

<?php generate_pagination("SELECT * FROM explore WHERE category='" . mysql_real_escape_string ( $_POST ['category'] ) . "'"); ?>

Then in your jquery post:
$("a.category").click(function() {
  $.post("test.php", { category: $(this).attr("id") },
    function(data){
      //Load your results into the page
    });
});

On click we take the ID, pass it to the server as a post variable category, then on the server, grab it, escape it properly for security, and use that query.  Load your results the same way you are now, that part doesn't change.


Area of triangle described as a determinant

Question: Let T be a triangle with vertices $P_1=(x_1,y_1), P_2=(x_2,y_2)$ and $P_3=(x_3,y_3)$. Show that the area of the triangle is equal to $\frac{1}{2}\det M$, where $$M= \begin{bmatrix}x_1&x_2&x_3\\y_1&y_2&y_3\\1&1&1\end{bmatrix}.$$
Comment: They're the same since the determinant of a matrix is the same as the determinant of its transpose.
Comment: Thanks. Actually the x's are in the first column, the y's in the second and the 1's in the third. Sorry that I made such a mess. i am hoping to learn some other formatting soon.
Answer: Hint: $$\det M=\det\begin{bmatrix}x_1&x_2&x_3\\y_1&y_2&y_3\\1&1&1\end{bmatrix}=\det\begin{bmatrix}x_1-x_3&x_2-x_3&x_3\\y_1-y_3&y_2-y_3&y_3\\0&0&1\end{bmatrix}.$$
And try to decompose the vectors $\vec{P_3P_1}=(x_1-x_3,y_1-y_3),\vec{P_3P_2}=(x_2-x_3,y_2-y_3)$ along the $x,y$-axes direction.
Answer: First, notice you don't change the determinant by subtracting the first column from the two others. You have then
$$\det M= \left|\begin{array}{ccc}x_1&x_2-x_1&x_3-x_1\\y_1&y_2-y_1&y_3-y_1\\1&0&0\end{array}\right|$$
$$\det M= \left| \begin{array}{cc}x_2-x_1&x_3-x_1\\y_2-y_1&y_3-y_1\end{array}\right|$$
That is, the determinant of two vectors $\vec{P_1P_2}$ and $\vec{P_1P_3}$. To simplify notation, assume now that you compute the determinant and scalar product of two vectors $\vec{u}$ and $\vec{v}$, with coordinates respectively $(x,y)$ and $(x',y')$. And denote the norm of these vectors by simply $u$ and $v$.
The determinant is $xy'-x'y$, and the scalar product is $xx'+yy'$.
Now compute the sum of squares of these two numbers:
$$\left(xy'-x'y\right)^2+\left(xx'+yy'\right)^2=(x^2+y^2)(x'^2+y'^2)=u^2v^2$$
But the scalar product is also $uv \cos \theta$, where $\theta$ is the angle between $\vec{u}$ and $\vec{v}$.
Thus, $\det(\vec{u},\vec{v})^2 = u^2v^2-u^2v^2\cos^2 \theta = (uv \sin \theta)^2$, or :
$$|\det(\vec{u},\vec{v})| = |uv \sin \theta|$$
From trigonometry you know the area of a triangle $ABC$ is $S=\frac{1}{2}bc \sin A$ (see why here).
When you apply this to your determinant, you find that $\frac{1}{2}|\det(\vec{u},\vec{v})|$ is the area of the triangle formed by $\vec{u}$ and $\vec{v}$.
Now let $\vec{u}=\vec{P_1P_2}$ and $\vec{v}=\vec{P_1P_3}$, and you're done.


Continuity of the operation in a topological group.

Question: Consider a topological group $\mathrm{D},$ whose group operation I shall denote multiplicatively. The following result must be true but I fail to find a proof of it (except in the commutative case, which is not what I need). Consider a permutation $\sigma$ of $1, \ldots, p.$

Is the mapping $\mathrm{D}^p \to \mathrm{D}$ given by $(x_1, \ldots, x_p) \mapsto x_{\sigma(1)} \cdots x_{\sigma(p)}$ continuous with respect to the product topology on $\mathrm{D}^p$ induced by that of
  $\mathrm{D}$?

Again, in the commutative case $\sigma$ has no effect, thus one can write
$$(x_1 \cdots x_p) (y_1 \cdots y_p)^{-1} = (x_1 y_1^{-1}) \cdots (x_p y_p^{-1});$$
one can consider then a neighbourhood $\mathrm{T}$ of the neutral element and another neighbourhood $\mathrm{K}$ (of the neutral element again) such that $\underbrace{\mathrm{K} \cdots \mathrm{K}}_{n \text{ times}} \subset \mathrm{T}$, then it suffices to take $x_i \in y_i \mathrm{K}$ for $1 \leq i \leq p$. I ask now, can this proof be modified slightly to allocate the noncommutative case?
Answer: The permutation is largely irrelevant; your map is just the
composition of the permutation-of-coordinates map $D^p\to D^p$
(which is a homeomorphism) with the multiplication map
$\mu_p:(x_1,\ldots,x_p)\to x_1\cdots x_p$.
The continuity of $\mu_p$ is an induction on $p$. For $p=2$
this is part of the definition of topological group. In general
if $\mu_p$ is continuous, so is $(x_1,\ldots,x_{p+1})\mapsto
x_1\cdots x_p$. Clearly $(x_1,\ldots,x_{p+1})\mapsto x_{p+1}$
is continuous. From the continuity of multiplication,
$\mu_{p+1}:(x_1,\ldots,x_{p+1})\to (x_1\cdots x_p)x_{p+1}$ is continuous.
Comment: I was avoiding induction, sort of. I really would have expected there to be an argument of the style "shrinking of neighbourhood" because I just needed to make $x_1 \cdots \big( x_{p - 1} (x_p y_p^{-1}) y_{p - 1}^{-1} \big) \cdots y_1^{-1}$ "small" (borrowing the language for the real line) and for this it was enough to demonstrate neighbourhoods $V_k$ existed such that $x_{k - 1} V_k y_{k - 1}^{-1} \subset V_{k - 1}$; I couldn't find a proof of this either taht didn't rely on induction I will accept your answer after a day or so just if anyone else want to contribute.


How many parameters are in a gated recurrent unit (GRU) recurrent neural network (RNN) layer?

Question: The title says it all -- how many trainable parameters are there in a GRU layer? This kind of question comes up a lot when attempting to compare models of different RNN layer types, such as long short-term memory (LSTM) units vs GRU, in terms of the per-parameter performance. Since a larger number of trainable parameters will generally increase the capacity of the network to learn, comparing alternative models on a per-parameter basis is an apples-to-apples comparison of the relative effectiveness of GRUs and LSTMs.
Answer: The original GRU paper "Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation" by Kyunghyum Cho et al. does not include bias parameters in their equations. Instead, the authors write

To make the equations uncluttered, we omit biases.

which does not help a reader understand how the authors envisioned using bias neurons; nor does it allow readers to easily count the number of bias neurons.
So we have to look elsewhere. According to Rahul Dey and Fathi M. Salem, "Gate-Variants of Gated Recurrent Unit (GRU) Neural Networks":

... the total number of parameters in the GRU RNN equals $\color{blue}{3 (n^2 + nm + n)}$.

where $m$ is the input dimension and $n$ is the output dimension. This is due to the fact that there are three sets of operations requiring weight matrices of these sizes.
Dey and Salem outline the GRU in this manner:

The GRU RNN reduce the gating signals to two from the
LSTM RNN model. The two gates are called an update gate $z_t$
and a reset gate $r_t$. The GRU RNN model is presented in the
form:
$$\begin{align}
h_t &= (1 - z_t)\odot h_{t-1} + z_t \odot \tilde{h}_t \\
\tilde{h}_t &= g(W_h x_t + U_h(r_t \odot h_{t-1}) + b_h)
\end{align}$$
with the two gates presented as:
$$\begin{align}
z_t &= \sigma(W_z x_t + U_z h_{t-1} + b_z) \\
r_t &= \sigma(W_r x_t + U_r h_{t-1} + b_r)
\end{align}$$

and in the beginning of the paper, they lay out the notation used as

$W$ is an $n \times m$ matrix, $U$ is an $n \times n$ matrix and $b$ is an $n \times 1$ matrix (or vector)
for a hidden state of size $n$ and an input of size $m$.

These parameters counts might differ from what you find in software. It seems that some software (e.g. PyTorch, Keras) has made the decision to over-parameterize the model, by including additional bias units. In these software implementations, the total parameter count is given as
$$
\color{blue}{3 (n^2 + nm + }\color{red}{2}\color{blue}{n)}.
$$
This appears to change three of the GRU equations:
$$\begin{align}
\tilde{h}_t &= g(W_h x_t + b_{hW} + U_h(r_t \odot h_{t-1}) + b_{hU}) \\
z_t &= \sigma(W_z x_t + b_{zW} + U_z h_{t-1} + b_{zU}) \\
r_t &= \sigma(W_r x_t + b_{rW} + U_r h_{t-1} + b_{rU})
\end{align}$$
which we can see is algebraically the same, using the substitution $b_{iW} + b_{iU} = b_{i}$. I'm not sure why software would do this. Perhaps the intention is to create the GRU using compositions of existing linear layer classes, and biases are included in both linear layers. Perhaps this parameterization works better with CUDA devices for some reason.
Here's a toy script to verify this behavior, using torch==1.12.1.
import torch.nn as nn

def count_parameters(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)

if __name__ == "__main__":
    n = 7
    m = 5
    gru = nn.GRU(input_size=m, hidden_size=n, num_layers=1)
    print(count_parameters(gru)==3 * (n ** 2 + n * m + 2 * n)) # True

Answer: should be 3*(n^2+nm+2n).
(1) W for input -> hidden
3nm
(2)b for input -> hidden
3*n
(3)W for hidden -> hidden
3nn
(4) b for hidden -> hidden
3*n
(1)+(2)+(3)+(4) = 3*(nm+n+nn+n) = 3(n^2+m*n+2n)
check https://pytorch.org/docs/stable/generated/torch.nn.GRU.html
for cross validating or the original GRU paper.
Comment: Can you show me where in the the original GRU paper the authors explicitly state the trainable parameters for bias neurons?


Pentaho CDE table component change drop down pagination values

Question: I created new CDE reports and that CDE report I was selected table component and set my datasource. In my datasource contains more records so in table component I was set paginate properties to true when I preview my dashboards then in table component shows pagination with select options with values 10,25,50,100 by default. How should I change this select options values as per user defined because instead of 10,25,50,100 in select I want to set my own values like 50,100,150,200 etc. how this should change in pentaho CDE table components?
Answer: Search for Menu in file script.js (full path is /biserver-ce/pentaho-solutions/system/pentaho-cdf/js/script.js) and edit select option values.
OR
Go to line no 3114 in script.js (full path is same as mentioned above),find  text Menu and edit its values.
This will resolve your problem.


Postgresql 9.2.15 on Centos 7.2 failed to bind to ipv4

Question: Ran the following for a fresh install.
yum install postgresql-server postgresql-contrib
postgresql-setup initdb
systemctl start postgresql

With standard config, no changes or anything.
Nov 02 10:33:17 xxx.org pg_ctl[87482]: LOG:  could not bind IPv4 socket: Address already in use
Nov 02 10:33:17 xxx.org pg_ctl[87482]: HINT:  Is another postmaster already running on port 5432? If not, wait a few seconds and retry.

But it actually has binded to 127.0.0.1:5432 fine. I ran netstat -anp before postgres started and 5432 port isn't in use. After I started postgresl I can see it has binded to 5432 successfully.
netstat -anp | grep 5432
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      12421/postgres
unix  2      [ ACC ]     STREAM     LISTENING     46516    12421/postgres       /tmp/.s.PGSQL.5432
unix  2      [ ACC ]     STREAM     LISTENING     46514    12421/postgres       /var/run/postgresql/.s.PGSQL.5432

I installed it on another identical server last week with the same image and it is perfectly fine. I compared the pg version and the /etc/hosts file and they are the same.  I even copied the same postgres conf over and it still gave me the same problem. Postgresql is started and I can connect fine! just annoying that it  is throwing up that message when it starts.
Answer: listen_addresses = '*'
port = 5432

Turns out that you need this in postgresql.conf. Even though by default, it binds to that port!


Proof of $0! = 1$

Question: I have been recently studying binomial theorem and in that we very frequently encounter factorials. But one queer thing which I found is $0!$. Even more queer is its value which is

$0! = 1$.

I was told this fact and I accepted it(without any proof). But I am still confused about it.
How can we prove that $0!= 1 $?
Comment: It's the definition of the factorial at $n=0$, so there's nothing to prove.
Comment: @user2369284 There isn't a proof as this is the definition. It's a definition we make so that we can make formulas a lot simpler for ourselves. Think about this: why do we say that $1$ is not prime? On the surface, it doesn't seem like we _need_ to, but we say that $1$ isn't prime because it makes theorem statements simpler. Similar reasoning applies here: we don't _need_ to but it makes statements simpler.
Comment: For any cardinal $c$ the notation $c!$ designates the order of the group of permutations of a set of cardinal $c$.
Comment: Basically, this is just a convention. But notice how nicely this agrees with general formula $n!=n\cdot(n-1)!$ (take $n=1$).
Comment: @ireallydonknow So is it really by definition? Is there no proof to it?
Comment: Yes. It's by definition.
Comment: It's a special case of the [empty product](http://en.wikipedia.org/wiki/Empty_product)
Comment: What is your definition of $n!$? Without a definition you cannot prove anything.
Comment: As the local worshipper of simplicity, I hope my answer wins the "Keep It Simple" award.
Answer: We can order $n$ elements in $n!$ ways. $0$ elements can be ordered in just one way.
One can choose $k$ of $n$ elements in ${n \choose k} = \frac{n!}{k!(n-k)!}$ ways. Obviously,
$$1 = {n\choose n} = \frac{n!}{n!\cdot 0!}\text{.}$$
Also, $0! = 1$ agrees with Euler's function $\Gamma$, for which $\Gamma(n) = (n-1)!$ holds.
These are not proves, but only good reasons why should $0!$ equal $1$.
Comment: You can also include the point(as others have posted) that $0! = 1$ by definition as $n! = \frac{(n+1)!}{n+1}$.
Answer: As the other answers pointed out, $0! = 1$ is rather a definition than a thing we could prove, but there is some motivation behind it:

First of all, it is a common convention, that the empty sum $\sum_\emptyset=0$ has value $0$. It seems to be a natural definition, because if we add something to the sum, we want to be able to sum by forming the disjoint union of the two sets: $$\sum_{x\in A} x + \sum_{x \in \emptyset} x = \sum_{x \in A \cup \emptyset} x = \sum_{x \in A}.$$
In the same way, we often define $\bigcup_\emptyset =\emptyset$ and $\prod_\emptyset = 1$. The latter gives us: $$n!:=\prod_{k=1}^nk \Rightarrow 0! = \prod_{k=1}^0 = \prod_\emptyset k = 1.$$ Thus, setting $0!$ is consistent to other conventions.
Another answer comes from real analysis. By the Bohr-Mollerup Theorem, there is only one function $f:\Bbb R^+ \rightarrow \Bbb R$ that satisfies:

$f(x+1)=xf(x) \forall x \in \Bbb R$
$f$ is logarithmic convex
$f$ interpolates the factorial in a sense that for $n \in \Bbb N$: $f(n+1) = n!$

This function is the Gamma-function and it has value $\Gamma(1) = 1$ corresponding to  $0! = 1$. Thus setting $0! = 1$ can also be considered to be a natural choice.
Answer: You can prove it from the definition of the factorial operation, which defines $0!=1$.  The question you should be asking is why we define it this way.
One argument in favor of this definition is that it preserves the important property that $$(n+1)! = (n+1)\cdot n!$$ even when $n=0$.  If we want to use this property to reason about factorials, we either need to accept that $0!=1$ or else be prepared to fill our arguments with special exceptions for $n=0$.
A different kind of argument proceeds from the objects that the factorial function is intended to model.  $n!$ is intended to be the number of ways of making an ordered list of $n$ distinct objects.  So for example $3!=6$ because there are six ways to order a list of three items:
$$\begin{array}{ccc}
(123) & (132) & (312) \\
(213) & (231) & (321) \end{array}$$
And $2! = 2$ because there are two ways to order a list of two items:
$$\begin{array}{cc}
(12) & (21)\end{array}$$
And $1!=1$ because there is one way to order a list of one item:
$$\begin{array}{c}
(1)\end{array}$$
And $0!=1$ because there is one way to order a list of zero items:
$$\begin{array}{c}
()\end{array}$$
$()$ is unquestionably a list of zero items, so why wouldn't you count it?
Answer: Note that:
$$n! = \frac{(n+1)!}{n+1}$$
So you can apply this for $0$. Actually it's quite nicely explained here
Answer: \begin{align}
4! & = 24. \quad \text{Divide by 4 and get:} \\
3! & = 6. \quad \text{Divide by 3 and get:} \\
2! & = 2. \quad \text{Divide by 2 and get:} \\
1! & = 1. \quad \text{Divide by 1 and get:} \\
0! & =
\end{align}
Fill in the blank.
Not a proof, but this may shed some light.
Also, notice that when you multiply no numbers at all, you get $1$.  That's also been asked about here.  That's why $x^0=1$.
Answer: There is no proof for this statement, since $0! = 1$ is just a convenient and nice definition in many applications.
For instance, if you would like to think of $n!$ as the number of bijective maps from an $n$ element set to itself, then there is only one bijective map from an empty set to itself.
The other to interpret factorial is through the $\Gamma$ function defined as $\Gamma(z+1) = z \Gamma(z)$. If $z \in \mathbb{Z}^+ - \{1\}$, then $\Gamma(z) = (z-1)!$. Hence, if we would like to extend the notion of factorial beyond positive integers using the $\Gamma$ function, setting $z=1$, we get that $1! = 1 \cdot 0!$, which forces $0! = 1$.

Proof of $0! = 1$


Sessão Laravel - Public para Controller

Question: Estou fazendo um formulário que contém um Captcha.
O Captcha é gerado por um script PHP que monta uma imagem.
E eu coloquei o script na pasta public do Laravel 4.
Quando o código do Captcha é gerado é colocado em sessão:
session_start();
$_SESSION['numCaptcha'] = $code;

Depois ao enviar os dados do formulário, envio para um Controller, que tem a função:
public function enviaContato() {
   echo $_SESSION['numCaptcha'];
   die();

   # Verificação de Captcha
   if (empty(Session::get('numCaptcha')) || strcasecmp(Session::get('numCaptcha'), Input::get('numCaptcha')) != 0) {
      Session::flash('error', "Captcha Inválido");
   }
}

Desse jeito que fiz acima não está pegando o valor da sessão. Já fiz também:
Session::get('numCaptcha')
Mas também não funcionou.
Ecziste alguma restrição ?  Tem como fazer de outra forma ?
Então, como fazer uso da sessão do public  para o Controller.
Comment: Você não acha melhor usar uma biblioteca de captcha `Laravel` ?
Comment: Usei essa para o `Laravel 4`. Ele usa o session do próprio laravel e o `validation`. É bom sempre tentar utilizar o máximo (ou tudo) que é recurso do `Laravel`. https://github.com/mewebstudio/captcha/tree/master-l4
Comment: Pra gerar a imagem basta fazer no HTML `{{ Captcha::img() }}`. Eu gosto muito! Eu uso nesse sistema : http://pbh.portaltmt.com.br
Comment: É. Se fosse pelo menos o `Laravel 4.2`. Pode acreditar: Do `4.0` para o `4.2` existem alguns recursos que já me fazem falta (se estivesse usando o `4.0`)
Comment: Pode ser. Tem alguma na manga ?
Comment: Pois é. Tenho consciência disso. Mas a versão do Laravel desse site que estou atualizando é o 4.0. Dá até receio de atualizar o `composer.json` e dar problema no site.
Comment: Não custa nada tentar, já mandei rodar aqui o composer com a biblioteca.
Comment: No way. Não funcionou nessa versão. **The requested package mews/captcha could not be found in any version, there may be a typo in the package name.**
Answer: Primeiramente, você deve verificar a configuração do Laravel. O Laravel (como a maioria dos frameworks), não usa a sessão nativa do PHP. Não me lembro se há alguma forma de configurar isso.
Sendo assim, as sessões de $_SESSION e Session::get são salvos em mecanismos diferentes (O PHP salva da sua forma padrão, e o Laravel salva num arquivo dentro da pasta app/storage).
Então, ou seu código tem que ser transformado para "php puro" ou para "laravel puro".
Você citou nos comentários que não conseguiu instalar a biblioteca desejada. Então, aqui vai um captcha "na mão" (uma solução em "laravel quase puro") que eu utilizei um de nossos sistema em Laravel - Talvez seja útil no seu caso.
Route::get('captcha', function()
{

    $word = [0 => null, 1 => null];

    for ($i = 0; $i < 4; $i++) {
        $word[0] .= chr(mt_rand(97, 122));
        $word[1] .= chr(mt_rand(97, 122));
    }

    $word = implode(' ', $word);

    Session::put('captcha_word', $word);

    $font = public_path('recaptcha/fonts/recaptchaFont.ttf');

    $image = imagecreatetruecolor(172, 50);

    $color = imagecolorallocate($image, 0, 0, 0);
    $white = imagecolorallocate($image, 255, 255, 255);

    imagefilledrectangle($image, 0, 0, 172, 99, $white);
    imagettftext($image, 22, 0, 5, 35, $color, $font, Session::get('capcha_word'));

    $tempCapcha = tempnam(null, 'captcha');

    imagepng($image, $tempCapcha);

    return Response::make(File::get($tempCapcha), 200, ['Content-Type' => 'image/png']);
});

A verificação se daria da seguinte forma:
if (Session::get('captcha_word') == Input::get('algum_input_com_captcha'))
{

}

E no HTML, pra exibir o Captcha, você poderia fazer assim:

Observação: Observe que é necessário salvar a fonte usada pelo Captcha no path especificado na rota.
Atualização: O trecho da variável $word pode ser alterado para o código ficar mais limpo, usando apenas uma linha para declará-lo.
Assim:
$word = trim(chunk_split(Str::random(8), 4, ' '));

Comment: Deu certo. Uma observação apenas é os nomes das suas variáveis de sessão estão diferentes no código. Não sei se você alterou para postar aqui. **capcha** e **captcha**.
Comment: Não, é o nosso código que está errado. Vou alterar no meu sistema. Tenho mania de escrever `captcha` errado

Sessão Laravel - Public para Controller


Is a white Double Bass okay for practice?

Question: I have been playing double bass for 3 years, and I have been borrowing a bass. However, as I can no longer buy a bass, I am looking to buy/rent one. The best one I have found is this White one. It is a good price, and has nice reviews. I have also seen a similar Brown one, and it is the same quality, but for a higher price. In the past, I have borrowed a brown one, and I was wondering if it is ok to use a white bass. I would use it at home most of the time, but I may take it out to a performance/audition some time. Would the white bass be okay to use? Thanks!
Comment: Upvoted: question make sense, because in this case higher price does not mean better quality, but is just  material issues.
Answer: Seemingly odd question! I guess they'll both sound and play about the same, and if it's mainly for home practice, colour shouldn't be an issue. One of the reasons solid colours are cheaper is that the wood doesn't have to be bookmatched or even have a nice grain pattern, because it's been painted over.
That may very slightly affect the sound, but for practice purposes, so what? I guess most orchestral players prefer a natural double bass is that it's going to blend in better with the other basses, (and maybe looks more pro...) but as a single player in, say, a jazz group, it won't matter at all. The closed eyes test is probably the best one!
Comment: SInce the two links are for basses from the same manufacturer, they're probably identical machine-made units w/ different final paint job.
Comment: Can't see why not. Snob value may come in at that point! Could be that colour prejudice raises its ugly head! You'll just have to be the best player and thus be accepted!
Comment: Thanks for your answer! One quick question: If I were to perform in a local ensemble (in which there were multiple basses), and I had to bring my own bass, would it generally be ok to use the white one?
Comment: @CarlWitthoft - yes, except that the brown one has woodgrain showing, rather than a solid paint colour.
Answer:
Would the white bass be okay to use?

If it sounds good, plays good, and feels right to you, then for your own use at home, why not?
Since you're just looking for a practice instrument, and you are budget conscious, you needn't be too picky, but an instrument should feel right to you, if you can make it so while meeting your budget: Many of us feel a personal bond with certain instruments and/or certain instruments inspire us to play better or in a certain way. Often this has to do simply with appearance - superficial perhaps, but such is human nature. I'll admit to having sold off perfectly good instruments just because I didn't like their "look and feel".

performance/audition some time

That's a bit more tricky. A white double bass is unusual (a white electric is not) - you will stick out and people may tend to focus on you. They might expect something special from a musician who calls attention to themselves with an unusual instrument. (Even if that's not your intent, people think what they think...)
If you do play very well, it could be an advantage - "Wow - that guy with the white bass was really cutting it up!" But if you're just average, or you have a bad night (it happens to all of us) you may end up with remarks like this - "That guy with the white bass - who does he think he is, Sting? He messed up in three places and the rest of the time he was just barely keeping time." So you might want to think twice about that.
As for an audition, I'd recommend against it:
You should not come to an audition with something that might seem like a gimmick or excessive showmanship (again - even if you don't mean it that way, people will often take it that way). Band leaders generally want someone who is going to play the music well and not "make waves" or create distractions with something unusual, such as a white double bass.
Consider an audition like a job interview: If you're going to interview for a job in an office in a big city, you probably don't want to wear a white satin suit with an iridescent pink tie...
(Bass player studio legend has it that when working with certain producers, if a bass player shows up for an audition and isn't playing a Fender bass, they automatically don't get the job. Call it what you will - makes no difference - "people are funny", and music people all the more so.)
I have participated in auditions. I know from experience that people take your appearance and the appearance of your instrument into consideration:
Once we auditioned a guitarist for a band. The guy was a good enough musician - sufficient for what we needed and he seemed to fit in, personality-wise. He was playing a nice black Fender Telecaster - that was just right. But he was wearing this very garish "gaucho" strap to hold his guitar. It clashed with him and with the whole band. A few guys wanted to keep him out entirely just because of that. (Again: Music people often have such peculiarities.) Myself and one of the guitarists were the "leaders" - we told him he had the gig but he had to come with an ordinary strap. He had no problem with that and he worked out fine.

Note: @LaurencePayne has given some excellent advice in his answer, regarding a used instrument. That's provided you know and understand the used market. If so, you can do very well. If not, get someone who knows how to deal with used instruments - you can get ripped off if you're not savvy. Two good places to check:  Reverb.com, TalkBass.com.
Answer: Get the traditional colour. There's no downside to this decision bar a few dollars.
But also cast around the local second-hand market. There's probably a better deal on a better instrument available.  Call some bass players, someone will know someone with an instrument for sale.


OperationCompleted já havia sido chamado na operação e outras chamadas são ilegais. Background Worker

Question: Estou desenvolvendo uma aplicação onde me deparei com um erro que andei consultando, mas não consegui entender exatamente a forma de corrigir. Resumindo:
Criei um formulário que abre como Dialog e me dá a opção de selecionar um arquivo .xlsx. Ele importa todos os valores da planilha e enquanto lê os valores adiciona ao banco Mysql.
Adicionei a classe BackgroundWork para efetuar o processo de contagem da operação e retornar em um progressBar. Porem toda vez que executa um insert na tabela quando vai fazer a leitura da posição atual que está para passar o progresso, retorna a seguinte mensagem;

Gostaria de uma ajuda para entender onde estou errando.
Segue código abaixo.
public partial class ImportCFOPForm : Form
    {
        private FormServices FormServices { get; set; }
        private BackgroundWorker Worker { get; set; }
        private CFOPController Controller { get; set; }
        private CFOPForm CFOPForm { get; set; }
        private FormLoad FormLoad { get; set; }
        private int InitParmForm { get; set; }
        public string filePath { get; set; }

    public ImportCFOPForm(CFOPController _controller, Form _form)
    {
        InitializeComponent();
        SetController(_controller);
        SetCFOPForm((CFOPForm)_form);
        FormLoad = new FormLoad();
        InitValuesForm();
        RunDialog();
    }

    private void WorkerProgress_DoWork(object sender, DoWorkEventArgs e)
    {
        LoadSpreadsheetAsync();
    }

    private void WorkerProgress_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        ProgressBarDefault.Value = e.ProgressPercentage;
        LblValuePorcent.Text = $"{ProgressBarDefault.Value}%";
    }

    private void WorkerProgress_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //display("");
    }

    private void ImportCFOPForm_MouseDown(object sender, MouseEventArgs e)
    {
        FormServices.MoveForm(this);
    }

    private void BtnOk_Click(object sender, System.EventArgs e)
    {
        if (InitParmForm.Equals(1))
        {
            LblIsValid.Visible = false;
            LblProgress.Visible = true;
            LblValuePorcent.Visible = true;
            ProgressBarDefault.Visible = true;
            BtnOk.Visible = false;
            WorkerProgress.RunWorkerAsync();
        }
        else
        {
            this.DialogResult = DialogResult.OK;
        }

    }

    private async void LoadSpreadsheetAsync()
    {
        IExcelDataReader excelReader;
        FileStream stream = File.Open(this.filePath, FileMode.Open, FileAccess.Read);
        string[] returnPosition = new string[2];

        if (Path.GetExtension(this.filePath).ToUpper().Equals(ConstantValues.TYPE_XLS))
        {
            excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
        }
        else
        {
            excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        }

        var conf = new ExcelDataSetConfiguration
        {
            ConfigureDataTable = _ => new ExcelDataTableConfiguration
            {
                UseHeaderRow = true
            }
        };

        DataSet result = excelReader.AsDataSet(conf);
        var dataTable = result.Tables[0];

        //excelReader.Close();

        if (dataTable.Rows.Count > 0)
        {

            int totalProgress = dataTable.Rows.Count;

            try
            {
                for (var i = 0; i < totalProgress; i++)
                {
                    WorkerProgress.ReportProgress((int)(i + 1 * 100 / totalProgress));

                    string input = dataTable.Rows[i][0].ToString().Trim();

                    if (!string.IsNullOrEmpty(input))
                    {
                        char[] charsToTrim = { '*', '.' };
                        input = input.TrimStart(charsToTrim);

                        int finalString = input.Length;
                        string cfopValue = $"{input.Substring(0, 1)}.{input.Substring(1, finalString - 1)}";
                        string description = dataTable.Rows[i][1].ToString();
                        string application = dataTable.Rows[i][2].ToString();

                        var db = new CFOPDB()
                        {
                            CFOPValue = cfopValue,
                            Description = description,
                            Application = application
                        };

                        if (!db.CFOPValue.Equals(string.Empty))
                        {
                            returnPosition = await Controller.Insert(db);

                            if (returnPosition[0].Equals(ReturnMsgVersionEnum.sucess.ToString()))
                            {
                                Controller = SessionStorage.NewCFOPController();
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FormLoad.DialogSimpleMsg(
                            CFOPForm,
                            string.IsNullOrEmpty(ex.InnerException.Message)
                            ? ex.Message
                            : ex.InnerException.Message,
                            TypeMsgReturnEnum.ERRO.ToString(),
                            MessageBoxIcon.Error);
            }

            if (returnPosition[0].Equals(ReturnMsgVersionEnum.sucess.ToString()))
            {

                FormLoad.DialogSimpleMsg(
                            CFOPForm,
                            $"A planilha {stream.Name}, foi importada com sucesso.",
                            TypeMsgReturnEnum.SUCESSO.ToString(),
                            MessageBoxIcon.Information);
            }
            else
            {
                FormLoad.DialogSimpleMsg(
                                CFOPForm,
                                returnPosition[1],
                                TypeMsgReturnEnum.ERRO.ToString(),
                                MessageBoxIcon.Error);
            }
        }
    }

    private void InitValuesForm()
    {
        WorkerProgress.WorkerSupportsCancellation = true;
        WorkerProgress.WorkerReportsProgress = true;
        FormServices = new FormServices();
        InitParmForm = 1;
        LblIsValid.Visible = true;
        LblProgress.Visible = false;
        LblValuePorcent.Visible = false;
        ProgressBarDefault.Visible = false;
        BtnOk.Visible = true;
    }

    private void RunDialog()
    {
        OpenFileDialog openDialog = new OpenFileDialog();
        //openDialog.Filter = "*.xlsx";

        openDialog.Title = "Selecione o Arquivo";

        if (openDialog.ShowDialog() == DialogResult.OK)
        {
            this.filePath = openDialog.FileName;
        }
    }

    private void SetController(CFOPController _controller)
    {
        this.Controller = _controller;
    }

    private void SetCFOPForm(CFOPForm _cfopForm)
    {
        this.CFOPForm = _cfopForm;
    }

Answer: O Problema é que você está chamando um método assíncrono dentro do backgroundWorker.
Quando ele é chamado, o backgroundWorker finalizar sua execução, e dentro de LoadSpreadsheetAsync você chama o ReporProgress (mas o backgroundWorker já finalizou sua execução...)
o que acontece de fato é que você inicia uma nova thread no backgroundWorker, e chama um método assíncrono iniciando outra thread novamente.
retire a opção de async do LoadSpreadsheetAsync que deve resolver esse problema
Comment: Boa tarde Rovann Linhalis.
Nosso perfeito, obrigado pela dica, editei o método insert como síncrono e corrigi o método LoadSpreadsheet e resolveu o problema.
Muito obrigado pelo auxilio.


GWT MVP Storing session data

Question: I'm having a mvp application and I need to temp save some height data from a ResizeablePanel (within the panel is a DockPanel which needs to be init with a certain height in px). Now I'm not sure whats the best way to do this. webcontext, eventbus ?
Answer: You can store it in your View or in your Activity/Presenter. You can even store it in your entry point class. There is no single correct answer here - it all depends on your requirements and patterns that you use.
There is no need to get EventBus or sessions involved.

GWT MVP Storing session data


While loop not terminating when an array equals the terminate condition array. Java. First java class please be patient. Thank you

Question: Was wondering if there was a reason that the while loop was not terminating if the arrays equal eachother, the one condition was an array set to all 2s and then when the Die array reaches all 2s I wanted the while loop to terminate. Thank you for any help.
Stuck in the mud dice game, 2 players will roll 5 dice each, and the person with the highest total wins, if one player rolls a 2
they are stuck in the mud and unable to continue rolling for the rest of the game
import java.util.*;
public class StuckInTheMud {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("What is player ones name?");
        String firstPlayer = keyboard.nextLine();
        System.out.println("What is player twos name?");
        String secondPlayer = keyboard.nextLine();
        Player playerOne = new Player(firstPlayer);
        Player playerTwo = new Player(secondPlayer);
        while (playerOne.getDice() != playerOne.endGame() || playerTwo.getDice() != playerTwo.endGame()) // this is the while loop that wont terminate
        {
            pressEnterKeyToContinue(firstPlayer); // these are the turns looping
            playerOne.playerTurn(firstPlayer);
            pressEnterKeyToContinue(secondPlayer);
            playerTwo.playerTurn(secondPlayer);
        }
    }
    public static void pressEnterKeyToContinue(String playerName) // using a continue method so the game doesn't contine on its own
    {
        System.out.println("\n" + playerName + ", press Enter key when you are ready to roll!");
        Scanner nextTurn = new Scanner(System.in);
        nextTurn.nextLine();
    }
}

import java.util.*;

public class Player { // this is the player class
   private int score;
   private Die[] dice = new Die[6];
   private String playerName;
   private int roundScore;
   private int totalScore;

   public Player(String playerAlias) {
    playerAlias = playerName;
    score = 0;
    for (int i = 0; i != dice.length; i++) {
        dice[i] = new Die(6);
        dice[i].setValue(1);
    }
   }

   public void playerTurn(String playerName) {
    roundScore = 0;
    int twoRoll = 0;
    System.out.print(playerName + " it is your turn, here come the dice.\n");
    for (int i = 0; i != dice.length; i++) // This for loop will add random dice roll integers into the players array
    {
        if (dice[i].getValue() != 2) {
            dice[i].roll();
            if (dice[i].getValue() != 2) {
                System.out.println("For roll number " + (i + 1) + " you got a " + dice[i].getValue() + "!");
                roundScore(dice[i].getValue());
            } else {
                System.out.println("For roll number " + (i + 1) + ", you got a 2! Die " + (i + 1) + " is now stuck in the mud!");
                twoRoll = 1;
            }
        } else {
            System.out.println("Die " + (i + 1) + " is stuck in the mud since you rolled a 2, it cannot be used for the rest of the game!");
        }
    }
    if (twoRoll == 0) {
        System.out.println("\nYour total score this round was " + getRoundScore() + ".");
        totalScore(roundScore);
        System.out.println(playerName + ", your total score for the game is " + getTotalScore() + "!");
    } else {
        System.out.println("\nSince you rolled a 2, the score for this round is 0");
        roundScore = 0;
        totalScore(roundScore);
        System.out.println(playerName + ", your total score for the game is " + getTotalScore() + "!");
    }
   }

   public void roundScore(int singleRoll) {
    roundScore += singleRoll;
   }

   public int getRoundScore() {
    return roundScore;
   }

   public void totalScore(int roundScore) {
    totalScore += roundScore;
   }
   public int getTotalScore() {
    return totalScore;
   }

   public Die[] getDice() {
    return dice;
   }

   public Die[] endGame() {
    Die[] endGame = new Die[6];
    for (int i = 0; i != endGame.length; i++) {
        endGame[i] = new Die(6);
        endGame[i].roll();
        endGame[i].setValue(2);
    }
    return endGame;
   }
}

// Die Class
// 4/21/22
// Zachary Strickler

import java.util.Random;

/**
   The Die class simulates a six-sided die.
*/

public class Die // this is the die class
{
    private int sides; // Number of sides
    private int value; // The die's value

    /**
       The constructor performs an initial
       roll of the die.
       @param numSides The number of sides for this die.
    */

    public Die(int numSides) {
        sides = numSides;
        roll();
    }

    /**
       The roll method simlates the rolling of
       the die.
    */

    public void roll() {
        // Create a Random object.
        Random rand = new Random();

        // Get a random value for the die.
        value = rand.nextInt(sides) + 1;
    }

    /**
       getSides method
       @return The number of sides for this die.
    */

    public int getSides() {
        return sides;
    }

    /**
       getValue method
       @return The value of the die.
    */

    public int getValue() {
        return value;
    }

    public int setValue(int setValue) {
        value = setValue;
        return value;
    }
}

Comment: `getDice()` always returns `dice`, and `endGame()` always creates a new array and returns it.  Those are never going to be the same array.  My guess is that you want to compare the contents of the arrays, and terminate if they have the same sequence of numbers?  If that
Comment: @azurefrog, I ended up fixing it, thank you. I actually just wrote an override method for .equals and ended up being able to compare the objects that way.  It worked perfectly, thank you for clearing up what I needed to do and what was actually happening.
Comment: Just for FYI,  the problem with this approach is that whenever you override equals()  you also need to override hashcode().   Better to just use Arrays.equals(arr1, arr2));
Answer: You while loop test includes
playerTwo.getDice() != playerTwo.endGame()

By using the = operator, you are saying 'are these two arrays the same array object?'.  Looking at the endGame method you can see that can never be true, you are creating a new array object every time you call that method, so could never be the same one as
playerTwo.getDice().

Instead of checking to see if they are the same object, you really want to know if they have the same values.  There are some other ways of doing that. I'll give you a hint, look at java.util.Arrays package.
 https://www.geeksforgeeks.org/java-util-arrays-equals-java-examples/
 https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
 https://www.geeksforgeeks.org/compare-two-arrays-java/

Comment: thank you for the resources. After A while of using the array.equals I was still having no luck but I realized the two arrays could not compare like that, I ended up writing a simple override method in my Die class which let me compare the object arrays. Thank you!


Iphone "Go" button is redirecting to previous page

Question: I'm working on a web application which has multiple screens, every screen has 2 submit buttons(1 is the Back button and the other is next button)
like below.
 <input name="back" class="btn btn-outline-secondary mr-2" type="submit" value="Back" formnovalidate formaction="firstname.lastname@example.com">
 <input name="submit" class="btn btn-primary" type="submit" value="Submit">

So when I click on Back button it will redirect to previous page and the next button redirects me to next page.
This is working fine in web. But when I open this application in Iphone safari browser, and click on Go button in Iphone Keyboard, it is redirecting me to the previous page.
This should behave like the Next button in the form.
I had this same issue with Android phone too.
Comment: Well, it's the first `type="submit"` button, it seems reasonable that it'd be the default behaviour. Does it have to be a `submit` button…?
Comment: Yes, I've to save the form when I click on Back button, Since I don't want to fire the validations on back button I've formnovalidate attribute to that
Comment: The below solution is working fine... But now I've another requirement: The Next button will be disabled until all mandatory fields are filled, so when I click on GO button when the Next button is disabled it is redirecting me to previous page... but it should not do that instead do nothing... how can I achieve this??
Answer: Rootcause of the issue is, Since the first button which is placed in the form is Back and is of type=submit,  it seems reasonable that it'd be the default behaviour.
So to fix this issue I changed the order of the buttons by using order concept in bootstrap 4.
Below is the fix which worked for me.
 <input name="submit" class="order-2 btn btn-primary" type="submit" value="Next">
 <input name="back" class="order-1 btn btn-outline-secondary mr-2" type="submit" value="Back" formnovalidate formaction="email@example.com">


Quando uma function terminar a outra termina também multiprocessing funções assíncronas

Question: Estou usando a biblioteca multiprocessing, rodando duas def ao mesmo tempo, porém quero que ao terminar uma das duas def a outra que ainda está executando também termine no meio do processo.
Exemplo:
from multiprocessing import Process

def a():
    while True:
        print('a')
        break

def b():
    while True:
        print('b')

if __name__ == '__main__':
    pA = Process(target=a)
    pB = Process(target=b)

Então... no código acima que jeito que faria para quando der o break na função a, consequentemente também terminasse a função b (que está se repetindo).
Agradeço Desde já
Comment: talvez usando a função [quit()](https://stackoverflow.com/questions/19747371/python-exit-commands-why-so-many-and-when-should-each-be-used) no final das duas funções
Comment: Vou tentar armazenar os processos feitos em um list e passar esse list como parametro e então da terminate em cada um. Vou testar
Answer: Neste seu caso eu usaria uma classe e consideraria uma variável interna da classe como parâmetro, faça o teste:
from multiprocessing import Process

class Classe:
    processar = True

    def a(self):
        while True:
            print('a')
            break

        self.processar = False

    def b(self):
        while self.processar is True:
            print('b')

if __name__ == '__main__':
    classe = Classe()
    pA = Process(target=classe .a)
    pB = Process(target=classe .b)

Segue abaixo um modelo do que uso pessoalmente:
import threading
import time

def run_thread(job_function):
    job_thread = threading.Thread(target=job_function)
    job_thread.start()

class Classe:
    processar = True

    def processar_a(self):
        for x in range(1, 100):
            print("processar_a: {}".format(str(x)))

        self.processar = False

    def processar_b(self):
        while self.processar is True:
            print("processar_b")

if __name__ == "__main__":
    classe = Classe()

    run_thread(job_function=classe.processar_a)
    run_thread(job_function=classe.processar_b)

    while classe.processar is True:
        time.sleep(3)

Comment: Note que essa solução é para multi threading, não para multiprocessing. Em processos distintos, um worker não tem como "ver" o atributo da classe do outro worker - estão em processos separados - é necessário usar sim o Event, ou algum outro mecanismo de comunicação, como multiprocessing.Queue
Comment: a primeira listagem aqui não deve funcionar - como está, não faz nada mesmo, já que não é chamado o método ".start" de cada "Process"; eles são preparados, ficam prontos pra rodar e o programa se encerra. Se isso for arrumado, e o exemplo for alterado para algum que faça diferença o sinal (e não um único print em cada processo), não vai funcionar por que a classe está em processos diferentes - (e mesmo que estivesse no mesmo processo, não funcionaria por que são instancias separadas, cada uma veria seu `self.processar` distinto)
Comment: Eu tinha resolvido com o Event() do multiprocessing, mas sua resposta foi a melhor solução que vi até agora, Obrigado.
Comment: entendi seu ponto de vista, mas aqui nunca tive problemas das variáveis estarem em instâncias separadas pois foi declarado dentro de `classe = Classe()`. Mas pode ser que o último exemplo do Augusto Vasques seja a [melhor solução](https://pt.stackoverflow.com/a/504716/180585) do `multiprocessing`
Answer: Se não há necessidade de termino imediato do processo pB é possível com o método terminate() sinalizar de um processo a outro que seja finalizado passando sua referência por meio dos parâmetros args ou kwargs do constructor da classe Process.
from multiprocessing import Process

#Parâmetro p é o processo que será finalizado ao termino dessa função.
def a(p):
    while True:
        print('a')
        break
    p.terminate()             #Termina o processo p.

def b():
    while True:
        print('b')

#Troca a ordem de criação dos processos para que a referência pB fique disponível a pA no momento de sua criação.
pB = Process(target=b)
pA = Process(target=a,kwargs={"p":pB})
pB.start()                     #pB é inicializado primeiro pois do contrário pA pode terminar antes de pB começar.
pA.start()
pA.join()
pB.join()

Infelizmente inverter o raciocínio para testar dentro de pB se o processo pA inda está vivo com is_alive() não funciona pois só o processo pai pode testar seus filhos:
#Esse código irá gerar erro...
from multiprocessing import Process

def a():
    while True:
        print('a')
        break

def b(p):
    while p.is_alive():
        print('b')

pA = Process(target=a)
pB = Process(target=b, kwargs={"p": pA})
pA.start()
pB.start()
pA.join()
pB.join()

Process Process-2:
Traceback (most recent call last):
  File "/usr/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
    self.run()
  File "/usr/lib/python3.8/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "main.py", line 9, in b
    while p.is_alive():
  File "/usr/lib/python3.8/multiprocessing/process.py", line 160, in is_alive
    assert self._parent_pid == os.getpid(), 'can only test a child process'
AssertionError: can only test a child process

Mas a verificação pode ser feita no processo principal onde tanto pA e pB são processos filhos:
from multiprocessing import Process

def a():
    i = 0
    while i < 100:
        print('a')
        i+=1

def b():
    while True:
        print('b')

pA = Process(target=a)
pB = Process(target=b)
pB.start()
pA.start()
while pA.is_alive():
  pass
pB.terminate()
pA.join()
pB.join()


Integral equation $\int_0^{\infty} \phi(t) \sin(\omega t)dt=g(\omega)=\frac {1}{\omega^2+2},\omega>0, 0$ otherwise. Find $\phi(t)$

Question: Find $\int_0^{\infty} \phi(t) \sin(\omega t)dt=g(\omega)=\frac {1}{\omega^2+2},\omega>0, 0$ otherwise. Find $\phi(t)$.
Here is what I tried but I came to a strange result and don't know if it's correct.
I prolonged the $\phi(t)$ function to make it odd so I could prolong the integral over the all real axis and we have:
$$\int_{-\infty}^{\infty}\phi(t)\sin(\omega t)dt = 2g(w)$$
We multiply by $-i$ on both sides and we get:
$$-i\int_{-\infty}^{\infty}\phi(t)\sin(\omega t)dt = -2ig(w)$$
Since $\phi(t)$ is odd we have:
$$\int_{-\infty}^{\infty}\phi(t)\cos(\omega t)dt = 0$$
If we add them togheter we get:
$$\int_{-\infty}^{\infty}\phi(t)e^{-i\omega t}dt = -2ig(w)$$
We use the inversion formulae now:
$$f(\omega)=\frac 1{2\pi}\int_{\mathbb{R}}F(t)e^{i\omega t}dt$$
Where $F(t)$ would be the fourier transform of $f$.
Thus, we get:
$$\phi(t)=\int_{-\infty}^{\infty}\frac {-2i}{\omega^2+2}e^{-i\omega t}d\omega$$
Using residuum theorem we only have to evaluate the functions residues in $i\sqrt{2}$.
And we get:
$$\phi(t) = -\frac{e^{-\sqrt{2}t}}{\sqrt{2}}$$
And I feel like it's not completely correct.
Comment: I don't blame you for your misgivings:$$-\frac{1}{\sqrt{2}}\int_0^\infty\sin(\omega t)\exp(-\sqrt{2}t)dt=-\frac{1}{\sqrt{2}}\Im\int_0^\infty\exp(-(\sqrt{2}-i\omega)t)dt=-\frac{1}{\sqrt{2}}\Im\frac{1}{\sqrt{2}-i\omega}\\=-\frac{1}{\sqrt{2}}\Im\frac{\sqrt{2}+i\omega}{2+\omega^2}=-\frac{1}{\sqrt{2}}\frac{\omega}{2+\omega^2}.$$
Comment: If you mean $\Im$ (which you can write with `Im`), it's "imaginary part of".
Comment: What's that symbol after the first equal sign?
Comment: So to speak, here you checked if the Fourier transform backwards gives what it should, right? Then why did you start this with sin and from 0 to infinity and not with $e^{-i\omega t}$ and from -infinity to infinity?
Comment: I was checking whether it worked in your original problem, which uses $\int_0^\infty\sin(\omega t)dt$ instead of $\int_{-\infty}^\infty\exp(-i\omega t)dt$.
Comment: @J.G. Then What I did wrong?
Comment: I suspect the solution has $\lim_{t\to0^+}\phi(t)\ne0$, so you can't extend it to an odd function without it becoming discontinuous.
Comment: @J.G. Then how should I proceed?
Comment: That depends. Where did the problem come from? Given the discontinuity sought at $\omega=0$, are you sure a solution exists?
Comment: @J.G. It's from an exam, It probably should have, I'm not sure
Comment: For $\omega > 0$, $H(\omega)=\int_0^{\infty} \phi(t) \sin(\omega t)dt$ then $H(-\omega) = -H(\omega)$ so as the OP stated it there is no solution
Comment: @reuns can you please re-explain? Why exactly there isnt any solution?
Comment: Because $\frac1{\omega^2+2}$ is even while $H(\omega)$ is odd.
Comment: but if phi is odd and sin is odd then H must be even
Comment: With $H$ defined as I and you did it is odd
Comment: @reuns I don't get it, I defined phi as odd, sin is also odd, then that H must be even and then has a solution, if I would define phi as even then H is odd thus it doens't have any solutions, What am I missing?
Comment: The function you defined is $\int_0^\infty$ not $\int_{-\infty}^\infty$
Comment: Continue........
Comment: Both $F(\omega)=\int_{-\infty}^{\infty} \phi(t) \sin(\omega t)dt$ and $H(\omega)=\int_0^{\infty} \phi(t) \sin(\omega t)dt$ are odd.That's completely obvious so how can you be stuck at this ?
Comment: Why?? Because is $\phi$ is odd and $\sin$ is odd then $\phi \times \sin$ is even... and odd means $\phi(-t) = -\phi(t)$
Answer: Here is a completely dumb answer that solves your question. As the comments noted, there appeared to be an odd mismatch between the equation and the placement of $\omega$, namely odd/even-ness. Put another way,
$$\lim_{\omega\to 0^+} \frac{1}{\omega^2+2} = \frac{1}{2}$$
but the integral seems to vanish there. The way I found to fix it was to suggest that perhaps $\phi$ has a pole of order $1$ at $\omega = 0$
$$\int_0^\infty \phi(t) \sin(\omega t)dt = \int_0^\infty \frac{f(t)}{ \omega } \sin(\omega t) dt$$
Next, I recognized that form of $g(\omega)$ from the result of integration by parts of trig functions times exponentials, namely
$$\int_0^\infty e^{-at}\sin(\omega t) dt = \frac{\omega}{\omega^2+a^2}$$
Picking $a=\sqrt{2}$ leads us to our final answer:
$$\phi(t) = e^{-\sqrt{2}t}\frac{H(\omega)}{\omega} \implies \int_0^\infty \phi(t) \sin(t) dt = g(\omega)$$
where the factor of $H(\omega)$, the Heaviside step function, ensures that the integral vanishes for $\omega < 0$. It seems you almost had it, but made the assumption that $\phi(t)$ must be independent of $\omega$. Unfortunately, that assumption would lead you to the contradiction above.
There is no unique answer, either, as
$$\phi(t) = \frac{2}{\pi t}\frac{H(\omega)}{\omega^2+2}$$
would have also worked and was the first answer I arrived at.


php matches any / match any operator equivalent

Question: I frequently find myself writing things like if($var == 'bob' || $var == 'steven || $var == 'james'){ ...
Is there a slicker way in php to check whether a var matches any operator?  Or do I have to write my own function like:
function matches_any($question, $pos_answer, $pos_answer, $pos_answer, $pos_answer, ...){
// Call the function args, get the first one, get the rest, compare all the rest, return true if any match, return false by default.
}

Which would be used thus:
if(matches_any($var, $bob, $steven, 'james', $william)){ ...

Answer: You can use in_array()
if(in_array('value_to_test', array($var, $bob, $steven, 'james', $william))) {}

$matches = array($var, $bob, $steven, 'james', $william);
if (in_array('james', $matches)) {
  // TRUE
}

Comment: @yes123 Noticed and fixed before seeing your comment
Comment: Yeah, was planning on using in_array inside the custom function.  Was kinda hoping that there was a native php equivalent to my otherwise custom function, but I guess either using in_array in the place or using the custom function in the place is what I'll have to resort to.
Answer: Ideally you should avoid hard-coding any values into your code -- if you keep content in data structures (=think 'config' or 'database'), you will minimize your chances for running into this problem because you're processing abstractions rather than specific values. This means changing your concept from "these are the definite people who can ever do this" into "let's ask another facility whether this guy can do this"
If you absolutely positively must have a function like what you described, you can do it with func_get_args():
function matches_any()
{
    $haystack = func_get_args();
    $needle = array_shift( $haystack );

    return in_array( $needle, $haystack );
}

(Untested)
Comment: yeah, that matches_any was about what I was planning if I had to end up writing it myself.  But I really don't get your comment about hard-coded values?  I guess you mean things like 'bob' and 'james' as opposed to $bob and $james (just in case their content changes)?  If so, then yeah, I agree in general, those were just used as quick examples.  Oh, and I was only using names because that's what came to mind first, I think that you're saying that hard-coding access via names would be bad, which yeah, it would.  :D
Comment: My point was that if you constantly run into situations where you have to handle similar exhaustive 'if' clauses, then you should consider why you're running into them. It might be that by changing your approach you could entirely avoid the problem rather than having to find a way around it.
Comment: True, really I wasn't specific in the question, I usually tend to keep my code as simple as possible myself, but these days I'm doing a lot of refactoring of horrible code, which is where I encounter this kind of thing, and being able to simplify it down to a single short sentence would be of great benefit.


Como cadastrar usuário com o modo editável desativado usando angularjs e xeditable?

Question: Gostaria que o dado já tivesse feito um trigger no "save", ou algo do tipo, na hora de incluir o usuário, ele aparecer sem estar no modo de edição.
Veja meu exemplo no FIDDLE.
Como poderia resolver isso?
Estou usando esta biblioteca.
Obs: mais detalhes da questão está na resposta do comentário do Lucas.
Comment: Eu não consegui entender direito qual a dúvida @IvanFerrer.
Comment: Oi Lucas, se vc notar no exemplo do fiddle, quando crio um usuário novo, ele vem com os campos editáveis na tabela (com inputs), veja que eu já preenchi os dados, então não preciso editar, nem salvar, era para carregar apenas mais uma linha na tabela. Eu gostaria de faze isso direto, sem precisar clicar em save.
Comment: A ideia é que a edição seja posterior à inclusão.
Answer: Descobri como fazer funcionar:
É so colocar isso na tag do form:
<code><form shown="false">
</code>