Generate only valid configurations with constraints

Question: I have just begun working on a project that involves some scheduling optimization, and I am worried that I am in math waters over my head. I was wondering if you could think of any clever way to do the following.
Here's the basics:

You have x number of time slots
You have y number of faculty interviewers
You have z number of applicants interviewing
x and y do not have to be equal (there can be different numbers of interviewers and interviewees)
It is possible for a time slot to have no one being interviewed.
These make up a table as a schedule where the Row headings are the interviewers (represented by numbers), the Column headings are the time slots (represented by numbers), and the cells themselves are the applicants who are interviewing.

Constraints:

A z digit can only appear once in each row/column like Sudoku
(because an applicant can't interview with the same interviewer twice
and he/she can't interview twice at once).
There has to be exactly 3 of each z number in the entire table (because all applicants have to interview exactly 3 times).

Eventually, some formula will be used to calculate a weighted score for each valid configuration to determine a "best" state of the board. For explanation's sake, we'll just say it's something like 2a + 5b where a and b are different kinds of qualities interviewers have in common with applicants, but this isn't important for now.
I was trying to come up with some way of generating all possible valid configurations and eventually calculating the score of each valid configuration, finally picking the one with the highest score. I ran into some issues in finding a clever way to do so.
Initially, I wasn't feeling clever and thought about brute forcing it, but that is basically impossible because of the great variety of possibilities.
Can you think of any more clever way for me to prune back some of the erroneous configurations or a clever way to just generate valid boards for weighted score checking?
Comment: IMO if you want to ultimately choose the combination with the best weighted score, then you should formulate the problem as an integer linear programming problem, find a solver and solve it.
Comment: I would consider your problem as a case of the [School Timetable Problem](http://en.wikipedia.org/wiki/School_timetable). Did you have a look at it?
Comment: [Here's a video of an open source school timetable problem implementation](http://www.youtube.com/watch?v=4meWIhPRVn8) (in java though:/ )
Answer: Here is a quite simple Constraint Programming model in MiniZinc which - given the proper solver - generates all the possible valid solutions for (my interpretation of) the problem. However, as @TimChippingtonDerrick points out, for more complex problem instances there are too many solutions.
That said, if the objective (obj = "2a + 5b") somehow can be stated in the model (e.g. using some extra data of the interviewer/applicants etc), it's just a matter of changing it to an optimization problem, i.e. minimizing or maximizing that objective.
So, here is the MiniZinc model for a simple problem instance (x=10, y=5, z=10, and m=3). Note: in the interview table, the value 0 (zero) represents that there is no interview for the interviewer at that time.
include "globals.mzn";

int: x = 10; % number of time slots
int: y =  5; % number of faculty interviewers
int: z = 10; % number of applicants interviewing

int: m = 3; % number of times each applicants will be interviewed

% decision variables
% The interview table:
%   1..y: rows (interviewers)
%   1..x: columns (time slots)
array[1..y, 1..x] of var 0..z: s;

% solve satisfy;
solve :: int_search([s[i,j] | i in 1..y, j in 1..x], first_fail, indomain_random, complete) satisfy;

constraint

    % A z digit can only appear once in each row/column like Sudoku (because an applicant
    % can't interview with the same interviewer twice and he/she can't interview twice at once).
    forall(a in 1..z) (
       % rows
       forall(i in 1..y) (
          %sum([bool2int(s[i,j] = a) | j in 1..x]) <= 1
          alldifferent_except_0([bool2int(s[i,j] = a) | j in 1..x])
       )
       /\
       % columns
       forall(j in 1..x) (
          % sum([bool2int(s[i,j] = a) | i in 1..y]) <= 1
          alldifferent_except_0([bool2int(s[i,j] = a) | i in 1..y])
       )
    )

    % There has to be exactly 3 of each z number in the entire table
    % (because all applicants have to interview exactly 3 times).
    /\
    forall(a in 1..z) (
       count([s[i,j] | i in 1..y, j in 1..x], a, m)
    )
;

% constraint
%   % symmetry breaking: assign applicant a to interviewer a in time a (if possible)
%   forall(a in 1..z where a <= y) (
%      s[a,a] = a
%   )
% ;

output [
   "x (number of time slots (rows): " ++ show(x) ++ "\n" ++
   "y (number of interviews (columns): " ++ show(y) ++ "\n" ++
   "z (number of applicants): " ++ show(z) ++ "\n"
]
++
[
  if j = 1 then "\n" else " " endif ++
    show_int(2,s[i,j])
  | i in 1..y, j in 1..x
];

For this problem (x=10, y=5, z=10) there are a huge number of solutions. Here are two of them:
x (number of time slots (rows): 10
y (number of interviews (columns): 5
z (number of applicants): 10

5  2 10  8  0  6  7  4  3  9
3  1  5  7  0  2  9  6  8  4
8  0  0  5  6  1 10  3  0  7
2 10  1  0  0  9  0  0  0  0
0  0  0  0  0  4  0  0  0  0
----------
x (number of time slots (rows): 10
y (number of interviews (columns): 5
z (number of applicants): 10

 5  2 10  8  0  6  7  4  3  9
 3  1  5  7  0  2  9  6  8  4
 8  0  0  5  6  1 10  3  0  7
 2 10  0  1  0  9  0  0  0  0
 0  0  0  0  0  4  0  0  0  0

(This MiniZinc model is also here: http://www.hakank.org/minizinc/interview_scheduling.mzn )
A numerical comment on a simpler problem (x=6,y=3,z=3, m=3) to show the multitude of the problem: There are 317760 different solutions when not using the symmetry breaking (which is commented out in the code). With the symmetry breaking it's far less solutions: 1300. Here's one of these solutions:
1  0  0  3  2  0
3  2  1  0  0  0
0  1  3  2  0  0

Answer: Its sort of unstated in the replies above, probably because it is obvious to some of us, but just trying to enumerate all the legal combinations will only work in very small test cases of this sort of problem. You will quickly hit the wall in computation time if you attempt a naive implementation.
As suggested by others, you will need to look into using some optimisation tools if you want to do this for real-scale problems. Either one of the free solvers like COIN-OR, glpk or lpsolve; or one of the commercial tools - they can get expensive but if you have a big enough problem, then they are easily worth their cost.


How to start Drawer Layout below the toolbar in Android?

Question: Here is my main xml file:
  <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        android:id="@+id/nav_drawer">

    <android.support.design.widget.CoordinatorLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context="com.example.amit.rssreader.MainActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

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

        <include layout="@layout/content_main" />

    </android.support.design.widget.CoordinatorLayout>
        <android.support.design.widget.NavigationView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            app:menu="@menu/navigation_menu"
            android:layout_gravity="start">

        </android.support.design.widget.NavigationView>
    </android.support.v4.widget.DrawerLayout>

This is what is happening

I want to have the drawer below the Action bar .This wasnt a navigation Drawer Activity, the navigation drawer has been added later by xml.
Answer: I think this might help you:

Modify the xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

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

    <android.support.v4.widget.DrawerLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.design.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <include layout="@layout/content_main" />
        </android.support.design.widget.CoordinatorLayout>
    </android.support.v4.widget.DrawerLayout>
</LinearLayout>

Create theme for activity without toolbar in values/styles.xml and apply it to your activity in AndroidManifest file:

And to make it working, make the onCreate method of your activity to look like this:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    final DrawerLayout drawerLayout = (DrawerLayout)
        findViewById(R.id.drawerLayout);

    ActionBar supportActionBar = getSupportActionBar();
    if(supportActionBar != null) {
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        supportActionBar.setHomeButtonEnabled(true);
    }

    setSupportActionBar(toolbar);

    final ListView drawerList = (ListView)
        findViewById(R.id.drawerList);
        drawerList.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
        new String[] { "Item 1", "Item 2", "Item 3" } ));

        drawerLayout.setScrimColor(Color.TRANSPARENT);

        ActionBarDrawerToggle actionBarDrawerToggle =
        new ActionBarDrawerToggle(this, drawerLayout,
                toolbar, R.string.app_name, R.string.app_name);

        actionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(drawerLayout.isDrawerOpen(drawerList)) {
                drawerLayout.closeDrawers();
            } else {
                drawerLayout.openDrawer(drawerList);
            }
        }
    });

    drawerLayout.addDrawerListener(actionBarDrawerToggle);

    actionBarDrawerToggle.syncState();
}

And this is how does it work.


getting checked checkboxes values mvvm light wpf

Question: I have one usercontrol where am showing the main categories as buttons from the database. By clicking on Main Category button, a new user control is getting opened with list of items in that respective category clicked. I am binding the Item Names of that category in a xaml using TexbBlock and also am showing the checkboxes with each Items to select. I want to get the values of checkboxes after selecting them and clicking on the Done button. Checkbox values should be the items ID in the database. How to get the selected checkbox values.
Here is the xaml for the same:

<code>                        <!--<Button  Content="{Binding CategoryName}" Margin="5"/>-->
                        <TextBlock Text="{Binding SubCategoryName}" HorizontalAlignment="Center" VerticalAlignment="Top"  />
                        <CheckBox Grid.Row="3" />
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
</code>
Kindly suggest?
Thanks,
Tarun
Answer: I think what you need to do, is have a boolean property on you ViewModel that is called "Checked" (or something similar) then bind it to your checkbox
<code>IsChecked="{Binding Checked, Mode=TwoWay}"
</code>
The "Mode=TwoWay" will mean that when you Check the CheckBox, the binding will automatically update the property on your ViewModel.
Hope this helps
Comment: @Ben. How to keep the selected checkbox values in collection after clicking on the button. Kindly Suggest?
Comment: @Tarun, if you have the checkbox bound to your view model, you can simply iterate through the collection and say "If MyViewModel.Checked Then...". Make sense?
Comment: @Ben. Yes. Will try n let u know. Thanks
Comment: @Ben. I have tried that one but didnt get success. Please elaborate.

Thanks.
Comment: What do you mean by no success? Can you set a breakpoint on the Set of the Checked property, and make sure that when you check the checkbox, it sets the property value correctly? Do you actually have a collection of this ViewModel to iterate through?
Comment: Yes I have the collection CategoriesItems in my viewmodel and IsSelected property in the Model. If I checked some checkboxes,am getting true values by setting the breakpoint. How to loop through the collection in viewmodel and storing those selected values in database. Kindly Suggest?
Comment: Here is my collection:

private ObservableCollection _categoriesItems;
        public ObservableCollection CategoriesItems
        {
            get
            {

                return _categoriesItems;
            }
            set
            {
                _categoriesItems = value;
                RaisePropertyChanged("CategoriesItems");
            }
        }
Comment: @Ben. Finally Got it.

Thanks.


How can I use the box plot to explain the Empirical Rule for a normal distribution?

Question: I am wondering if I can use the box plot to explain the Empirical Rule for a normal.distribution. I don't know if the Empirical Rule can be explaines using the box plot or not, but I just looked at some materials on the Internet and found that there is some relationship between the box plot and nor distributions. Hope to hear some explanations.
Comment: John Tukey partially justified his formulas for the fences in a boxplot by computing the rates at which outliers and far outliers would be expected for a Normal distribution.
Comment: It's a relatively simple multiple and it results in an expected outlier rate of just under 1% for Normal distributions.  If it were changed to 2.0, the rate would drop to 0.07% and if it were set only at 1.0, the rate would soar to over 4%.  Since Tukey used boxplots to analyze smallish batches of data (comprising five to a few hundred values), a rate of 1% would tend not to produce outliers or, for the largest batches, only a handful of outliers -- at least for Normally distributed data.
Comment: Why is 1.5 multiplied for the whiskers?
Comment: Just under 1% of the ...? What do you by that?
Comment: My computation predicts about 1.4 outliers in a normal sample of size 200. My simulation, just now added, shows an average of about 1.6 outliers in normal sample of size 200.  Either way, you might say that's a little 'under 1%' of the observations.
Comment: @Bruce A more precise statement would replace "under 1%" by "0.7%," perfectly in keeping with your simulations.  But simulation is not needed here.  I computed the value in `R` as `pnorm(-qnorm(.75) * (1+3)) * 2`
Answer: The Empirical Rule with which I am familiar looks at sample means and standard deviations. (For example, the interval $\bar X \pm S$ often contains about 68% of the sample elements.)
Boxplots look at medians and interquartile ranges.
Of course, a boxplot is constructed so that (nearly) 50% of the data is 'contained' within the box.
The ER is often said to apply to "mound shaped" (i.e., roughly normal) samples, as you suggest. Boxplots are often used to explore samples suspected of not coming from normal distributions.
So it does not seem an explanation of the ER in terms of boxplots would be straightforward. If you have some particular idea in mind, please explain it in more detail.

Addendum on per Comments.
Computing normal probabilities. If you look at a standard normal curve and the probabilities
of intervals with endpoints $=3,-2,-1,0,1,2,3,$ then you get
$P(Z \le -3) = 0.0013,\,$ $P(Z \le -2) = 0.0228,\,$ $\dots\,,
P(Z \le 3) = 0.9987.$
See the computations in R below. You can get essentially the
same values from a printed table of the standard normal PDF.
round(pnorm(-3:3), 4)
[1] 0.0013 0.0228 0.1587 0.5000 0.8413 0.9772 0.9987

Then, with a little arithmetic, you can get

$P(-1 \le Z < 1) = 0.8413 - 0.1587 = 0.6826 \approx 68\%,$
$P(-2 \le Z < 2) = 0.9772 - 0.0228 = 0.9544 \approx 95\%,$
$P(-3 \le Z < 3) = 0.9987 - 0.0013 = 0.9974 \approx 100\%,$

as in the Empirical Rule.
Here is a plot of a standard normal distribution with blue vertical lines
at $\pm 1$ (one standard deviation from the mean $0,$ brown vertical lines
at $\pm 2 (\mu\pm 2)$ and red vertical lines at $\pm 3.$
curve(dnorm(x), -4, 4, lwd=2, ylab="PDF",
      main="Standard Normal Density Function")
 abline(v=0, col="green2"); abline(h=0, col="green2")
  abline(v=c(-1,1), col="blue")
  abline(v=c(-2,2), col="brown")
  abline(v=c(-3,3), col="red")

The colored lines divide the area under the standard normal density curve into eight regions. From left to right the areas are as follows:
$$0.0013, 0.0215, 0.1359, 0.3413, 0.3413, 0.1359, 0.0215, 0.0013,$$
If you paste these areas together properly, you will get the probabilties
mentioned in the Empirical rule. For example, the area between the two blue lines is $0.3413+0,3413 = 0.6826,$ the area between the two brown lines
is $0.1359 + 0.3413 +0.3413 +0.1359 = 0.9544,$ etc.
diff(round(pnorm(-3:3), 4))
[1] 0.0215 0.1359 0.3413 0.3413 0.1359 0.0215

For samples of at least moderate size for a normal distribution
approximately the same proportions apply. For example, a sample
of size $n = 200$ from $\mathsf{Norm}(\mu = 100, 15),$ you would
expect to see about $2(68)=126$ observations in the interval $[85,115].$ Such a sample in R shows $74 + 55 = 129,$ which is
not far from the approximate value from the Empirical rule (where the last probability is sometimes given as "all or almost all".)
set.seed(2020)
x = rnorm(200, 100, 15)
summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  54.15   89.03  101.01   99.95  110.91  148.02

cp = seq(40, 160, by=15)
hist(x, br=cp, col="skyblue2", label=T, ylim=c(0,100))

Frequency of outliers in boxplots. Here is a brief discussion of a somewhat similar approach for
boxplot outliers. Consider again the distribution $\mathsf{Norm}(100, 15).$ Its lower and upper quartiles are $89.883$ and
$110.117,$ respectively. So the IQR of the distribution is
$20.235.$
qtl = qnorm(c(.25,.75), 100, 15)
qtl; diff(qtl)
[1]  89.88265 110.11735
[1] 20.23469

Then according to the "1.5IQR rule" for declaring outliers,
we can predict that the lower and upper fences (below and above
which observations are considered outliers) are anticipated to be
$59.53$ and $140.47,$ respectively. Consequently, we might anticipate $99.3\%$ of a sample from this distribution will not
be outliers.
fnc = c(89.883-1.5*20.235, 110.117+1.5*20.235)
fnc
[1]  59.5305 140.4695
diff(pnorm(fnc, 100, 15))
[1] 0.9930236

So in the sample of size $n=200$ observations x above from
this distribution we might expect about $.007(200) = 1.4$ outliers.
Actually, there are exactly three outliers in our sample.
boxplot.stats(x)$out
[1]  54.41853 148.02448  54.14975

A simulation in R can show the average number of outliers seen
in 100,000 samples of size $n=200$ from this distribution is about $1.63,$ as follows:
set.seed(1026)
nr.out = replicate(10^5, length(boxplot.stats(rnorm(200, 150, 15))$out))
mean(nr.out)
[1] 1.62818
summary(nr.out)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  0.000   0.000   1.000   1.628   2.000  14.000

Comment: Thank you for the answer. While I am looking on the Internet, I have found this  blog and it  explains the ER using the integration. It says that the probabity is 68% between -1 and +1 standard deviation and also data values lie within the range but I don't really get it. I know that the integration means the probability for the fixed range but the blog also says that there are 68% of the data values. How come it shows the intefration and says that there 68% of the data values? https://towardsdatascience.com/understanding-the-68-95-99-7-rule-for-a-normal-distribution-b7b7cbf760c2
Comment: 'Integration' for normal probabilities has to be done by some sort of approximation (or simulation) because the CDF of a standard normal distribution cannot be written closed form for use with ordinary integration. That is why we have printed tables of normal CDF and computer procedures to get normal probabilities (The function pnorm in R, used in my Addendum, is based on a very accurate 'rational approximation' to the standard normal CDF.)  [Possibly relevant link](https://math.stackexchange.com/questions/1635250/what-are-numerical-methods-of-evaluating-p1-z-leq-2-for-standard-normal-z)
Comment: I don't know why it does not come straight to my head. I feel that I understand it half way but I don't know what makes still confused about it. Anyway, thanks for the appendum and I will thank more about it.
Comment: What is the first thing in the half you don't understand?
Comment: What I am realy confused about is rhat how come the probability means the number of observations in the normal and standard normal distributions. I didn't read your additional writing yet.
Comment: I guess you're asking about the connection between the probabilities and the various numbers of standard deviations in a normal curve. Maybe the newly posted graph of the standard normal distributions with vertical lines at various numbers of standard deviations from the mean. Hope that helps.


I am unable to create a variable in template.php that I later want to use in node--content-type.tpl.php

Question: In template.php I have created the following function.
function mytheme_preprocess_node__post_esl_material(&$variables){
  $variables['linking'] = 'yes baby';
}

In node--post-esl-material.tpl.php I am trying to print $linking, but it is not working. The reason I am trying this is because I heard from an expert in Drupal saying:

Template files are usually used to change the CSS. You do not want to put too much PHP logic here. The PHP logic is typically included in your template.php file.

Therefore the objective, after getting the above code to work, would be to:

Create a $article variable in template.php.
Swap the following code from node--post-esl-material.tpl.php into template.php.
if (empty($content['field_article'])) {
  echo '';
}
else {
  echo '
';
  echo '
ARTICLE
';
  echo '
';
  print render($content['field_article']);
  echo '
';
  echo '
';
}

Print $article in node--post-esl-material.tpl.php and hence, have the PHP logic within template.php.

I am using Drupal 7 with the Stark theme.
Answer: These are the steps I would take to resolve (re-trying after each step)

Clear theme registry cache - /admin/config/development/performance - Clear Cache
Use the more general function mytheme_preprocess_node($variables), clear cache, try again

If the more general function works, your issue is likely that you have incorrectly named the template, try:kpr($vars['theme_hook_suggestions']) if you have the Devel Module installed.  If not, you should. Otherwise you can print_r($vars['theme_hook_suggestions']).  Is your template included in there?
Comment: When I try using mytheme_preprocess_node($variables) and refresh my site (I am developing my site on localhost) the site goes completely blank. This is the reason why I was trying to do it with the other function. Do you know why my site goes blank if I try using mytheme_preprocess_node($variables) in template.php?
Answer: I have found the mistake. I was using mytheme_preprocess_node($variables) twice within the template.php. I have included $variables['linking'] = 'yes baby'; within the first function and deleted the second one and know it works fine. Thanks for your help.
Comment: That's why you got a white screen (you should turn on some debugging in your development environment) after following the steps I gave, but it doesn't answer your original question (unless using `hook_node_preprocess()` is acceptable.
Comment: It doesn't solve the original question but using the function mytheme_preprocess_node(&$vars) works perfectly so I haven't tried doing it with the original function mytheme_preprocess_node__post_esl_material(&$variables).


Posso criar uma Foreign Key entre 3 tabelas?

Question: Eu tenho 3 tabelas principais na minha base de dados:
Actors, MoviesData e SeriesData.
Cada filme e cada série tem os seus próprios atores, mas séries e filmes podem partilhar o mesmo ator. Como é que crio uma foreign key entre Actors.ActorID, MoviesData.ActorID e SeriesData.ActorID?
Answer: Não será uma FK entre 3 tabelas, será uma tabela independente (Actors) e duas dependentes da Actors mas independentes entre si.
As ligações serão:

Actors e MoviesData
Actors e SeriesData

Ou seja, cada uma das tabelas dependentes terão uma FK com a tabela Actors
Basta criar uma PK em Actors(que será no caso o ActorID), e em cada uma das outras tabelas criar um campo (caso não houver) que será ligado ao Actors.ActorID, por exemplo Actors.ActorID.
Então crie as FK em cada uma das tabelas, no SQL Server a sintaxe seria essa:
ALTER TABLE MoviesData
ADD FOREIGN KEY (ActorID) REFERENCES Actors(ActorID);

Answer: Amigo depende da estrutura que você está criando e os relacionamentos podem mudar:
Caso sua estrutura tenha um ator por serie e filme você pode adicionar uma chave estrangeira em movies e series para actors:
ALTER TABLE MoviesData
ADD FOREIGN KEY (Actors) REFERENCES Actors(ActorsID);

ALTER TABLE SeriesData
ADD FOREIGN KEY (Actors) REFERENCES Actors(ActorsID);

Caso a sua estrutura Movies e Seires possam ter mais de um Actor então sua estrutura é de N:N, muitos para muitos. Então deve ser criado 2 tabelas de racionamento para MoviesData e SeriesData:
CREATE TABLE MoviesData_Actors (
         ActorsID   INT UNSIGNED  NOT NULL,
         MoviesDataID  INT UNSIGNED  NOT NULL,
         PRIMARY KEY (ActorsID, MoviesDataID),
         FOREIGN KEY (ActorsID)  REFERENCES Actors(ActorsID),
         FOREIGN KEY (MoviesDataID) REFERENCES MoviesData(MoviesDataID)
)

CREATE TABLE SeriesData_Actors (
         ActorsID   INT UNSIGNED  NOT NULL,
         SeriesDataID  INT UNSIGNED  NOT NULL,
         PRIMARY KEY (ActorsID, SeriesDataID),
         FOREIGN KEY (ActorsID)  REFERENCES Actors(ActorsID),
         FOREIGN KEY (SeriesDataID) REFERENCES SeriesData(SeriesDataID)
)

Porém caso queria criar uma tabela de relacionamento entre as 3 tabelas basta criar uma tabelas com as 3 chaves e referencia-las.
CREATE TABLE SeriesData_Actors (
         ActorsID   INT UNSIGNED  NOT NULL,
         SeriesDataID  INT UNSIGNED  NOT NULL,
         MoviesDataID  INT UNSIGNED  NOT NULL,
         PRIMARY KEY (ActorsID, MoviesDataID  ,SeriesDataID),
         FOREIGN KEY (ActorsID)  REFERENCES Actors(ActorsID),
         FOREIGN KEY (MoviesDataID) REFERENCES MoviesData(MoviesDataID),
         FOREIGN KEY (SeriesDataID) REFERENCES SeriesData(SeriesDataID)
)

Espero ter Ajudado.


An Inquiry About the Sum of Limits

Question: The limit law $\lim_{x\to c}[f(x)+g(x)]=\lim_{x\to c}f(x)+\lim_{x\to c}g(x)$ is true given that $\lim_{x\to c}f(x)$ and $\lim_{x\to c}g(x)$ both exist. I also know that $\lim_{x\to c}[f(x)+g(x)]$ can exist even if both $\lim_{x\to c}f(x)$ and $\lim_{x\to c}g(x)$ don't (i.e. if $g=-f$). I was wondering whether  $\lim_{x\to c}[f(x)+g(x)]$ can exist if the limit of one function exists while the limit of the other doesn't, and if not, how I would go about to prove this.
This is for a proof in which I want to make the statement "since I know that $\lim_{x\to c}[f(x)+g(x)]$, either  $\lim_{x\to c}f(x)$ and $\lim_{x\to c}g(x)$ both exist or both don't exist. Since we know $\lim_{x\to c}f(x)$ exists, we therefore know that $\lim_{x\to c}g(x)$ exists."
Answer: If both limits$$\lim_{x\to c}\bigl(f(x)+g(x)\bigr)\text{ and }\lim_{x\to c}f(x)$$exist, then the limit $\lim_{x\to c}g(x)$ must exist too, since $g(x)=\bigl(f(x)+g(x)\bigr)-f(x)$.
Answer: If $\lim_{x\to c} f(x)$ exists and $\lim_{x\to c} g(x)$ does  not exist then $\lim_{x\to c} (f(x)+g(x))$ cannot exist because $ g(x)=[f(x)+g(x)]-f(x)$

An Inquiry About the Sum of Limits


Arquivo Em linguagem C

Question: Tenho Um arquivo Nesse seguinte formato:
https://mega.nz/#!DwxXRIzK (link para download do arquivo ler);
[105][32][55][10][32][32][32][32][32][32][32][32][32][32][32][32][32][32][32][32][32][82][101][108][101][97][115][101]...

preciso fazer a leitura dos dados nesse formato:
105 32 55 10 32 32 32 32 32...[32][32][32][32][32][32][32][32][32][32][32][32][82][101][108][101][97][115][101]...

eu estou usando o treicho de código:
while( c != EOF) {

    fscanf(ler, "%c", &c);
    fscanf(ler, "%d", &num);
    fscanf(ler, "%c", &a);

    fprintf(traduzido, "%d ", num);

}

mas o looping nunca se encerra, também estou usando este:
while(fscanf(ler, "%c", &c)  && fscanf(ler, "%d", &num)   &&   fscanf(ler, "%c", &a)   != EOF) {

    fprintf(traduzido, "%d ", num);

}

mas ele não para de ler o arquivo, sempre passa de duas a tres linhas.
Qual o erro e porque do erro? Como posso fazer a leitura desse arquivo e deixar no jeito que quero, se tiver uma maneira mais fácil?
Olha o código por completo:
int main(void)

int num;
char c;

FILE *ler;
FILE *traduzido;

ler = fopen("readme.code.txt", "r");
traduzido = fopen("traduzido.txt", "w");

if(ler == NULL || traduzido == NULL) {
    printf("Erro Na aberura do Arquivo");
}

while(1) {
    if (fscanf(ler, "%c", &c) <= 0){
        break;
    }

    fscanf(ler, "%d", &num);
    fscanf(ler, "%c", &c);

    fprintf(traduzido,"%d ", num);
}

while(fscanf(traduzido, "%d", &num) != EOF) {
    printf("%c", num);
}
system("pause");

Comment: O correto é verificar a saída do `scanf`. Eu já respondi uma pergunta semelhante à essa, mas obviamente está perdida no mar de respostas.
Comment: Nesta resposta eu falo um pouco sobre o retorno do `scanf`: https://pt.stackoverflow.com/a/253415/64969; creio que vá ajudar
Comment: Por sinal, esse fluxo poderia ser tratado como o fluxograma dessa questão: https://pt.stackoverflow.com/a/251865/64969; "a": leitura, "b": se aconteceu o fim do arquivo, termina o loop
Comment: Dei uma olhada, mas consigo, faço a leitura até o ultimo item do arquivo mais ai para ali, fica em um looping
Comment: `while( fscanf(ler,"%c", &c) != EOF ){

        fscanf(ler, "%d", #);
        fscanf(ler, "%c", &c);
        fprintf(traduzido, "%d ", num);

    }` a porcaria desse código não deveria parar  ? ele fica em looping
Comment: Calma, jovem. Na resposta, eu pus na condição se o retorno fosse positivo. Na documentação linkada, tem dizendo que, caso desse erro, retornaria um valor negativo (não especificando qual valor negativo). No caso, `EOF` é um valor negativo possível em 2 bilhões existentes. Talvez trocar essa diferença por um `> 0` ou `>= 0` (eu não lembro o que o retorno 0 quer dizer...) seja melhor
Comment: O Problema é que nunca Retorna < 0, sempre positivo, eu sinceramente não sei o problema da minha verificação, ja to irado aqui, não vai nunca
Comment: As reticências são literais ou são apenas um recurso estilístico para indicar que pode ter mais coisa? Se for a segunda opção, tente fazer um exemplo de entrada e saída mínimos para tentarmos reproduzir. Por exemplo, com 3 números seria o suficiente
Comment: Jura que subiu o arquivo no mega uploads? Por que não ter um exemplo menor e viável?
Answer: O fscanf devolve:

A quantidade de elementos lidos e atribuídos a variáveis
0 se não conseguiu associar nenhum elemento
EOF, que corresponde a -1 caso tenha chegado ao fim do arquivo

Nesse caso e assumindo que a estrutura do seu arquivo é sempre [numero] pode testar especificamente por valores iguais ou inferiores a 0 no primeiro fscanf:
while(1) { //agora while infinito
    if (fscanf(ler, "%c", &c) <= 0){
        break; //se não conseguiu ler o próximo [ termina o while
    }

    fscanf(ler, "%d", &num);
    fscanf(ler, "%c", &c);

    fprintf(traduzido, "%d ", num);
}

Note que pode usar a mesma variável c pois não está a fazer nada com ela.
Se quiser jogar pelo seguro, e ficar resistente a alterações nos formatos pode testar todos os fscanf:
while(1) {
    if (fscanf(ler, "%c", &c) <= 0 ||
        fscanf(ler, "%d", &num) <= 0 ||
        fscanf(ler, "%c", &c) <= 0){
        break;
    }

    fprintf(traduzido, "%d ", num);
}

Teste do programa trocando fprintf por printf para ser mais fácil de ver:

Teste com o arquivo sugerido readme.code.txt :

Edit:
Em relação ao resto do programa que tem o problema está na leitura de um ficheiro que foi aberto para escrita.
Feche o ficheiro traduzido depois de escrever e abra-o de novo para leitura:
while(1) {
    if (fscanf(ler, "%c", &c) <= 0){
        break;
    }

    fscanf(ler, "%d", &num);
    fscanf(ler, "%c", &c);

    fprintf(traduzido,"%d ", num);
}

fclose(traduzido); //fechar a escrita
traduzido = fopen("traduzido.txt", "r"); //agora abrir para leitura

while(fscanf(traduzido, "%d", &num) != EOF) {
    printf("%c", num);
}

No entanto mais eficiente era simplesmente escrever o conteúdo do que está a ser lido diretamente na tela, em vez de utilizar o arquivo traducao para escrever e depois para ler:
while(1) {
    if (fscanf(ler, "%c", &c) <= 0){
        break;
    }

    fscanf(ler, "%d", &num);
    fscanf(ler, "%c", &c);

    fprintf(traduzido,"%d ", num); //grava no arquivo a tradução
    printf("%c",num); //e simultaneamente escreve na tela a conversão
}

Fica bem mais eficiente e simples.
Comment: @JeffersonQuesado Sim é de facto uma opção interessante que otimiza ainda mais os recursos
Comment: @Fernando Testei com o `[105][32][55][10][32][32][32][32][32][32][32][32][32][32][32][32][32][32][32][32][32][82][101][108][101][97][115][101]` que estava na pergunta e funcionou na perfeição. Pode colocar na pergunta o conteúdo exato do arquivo, para que eu possa testar e reproduzir o problema ?
Comment: Hmmmm, lembrei de algo interessante.. `%*c` lê a informação e a descarta, portanto não precisaria nem colocar a variável `c` em jogo
Comment: O problema é que passa, por exemplo, ele lê até o ultimo numero mais ai começa a vim alguns repetidos, ele para de ler o arquivo e está vindo lixo da memoria
Comment: @Fernando O arquivo tem quebras de linha ? Como está exatamente o conteudo do arquivo?
Comment: Sem quebra de linha, esse é o final do arquivo, [101][100][46]... já o arquivo traduzido vem assim ->  101 100 46  99 111 109 47 100 101 108... ele para depois de umas 10 linhas, tipo no fina do arquivo ler, tem um espaço, por exe, [101][100][46]...............................................
Comment: Coloquei um link com o arquivo
Comment: @Fernando pede chave para aceder ao arquivo, melhor talvez colocar no pastebin ou outra alternativa semelhante.
Comment: https://mega.nz/#!blAGiBrD!aYphUoyfUbwlF8wiAu25QsewmE2aD0merkIpWapDt_Y
 tenta esse
Comment: @Fernando funcionou bem. Há outra coisa qualquer que não deve estar a fazer corretamente, talvez no resto do programa. Se quiser posso incluir um print também da execução com esse arquivo.
Comment: Poste sim então, deve ser problema aqui se ai deu certo
Comment: @Fernando Veja na minha edição como funcionou. Note no entanto que escrevendo cada numero lido na tela, ainda leva 4 segundos até terminar.
Comment: Estou tentando resolver aqui, deixa eu verificar o codigo dnv, tenta imprimir assim prinf("%c", num)   isso ai é um texto, se tiver curiosidade pra ver '-'
Comment: Olhe o meu código lá na pergunta, me ajuda a achar o erro ?
Comment: @Fernando Editei a resposta, já contemplando o código que colocou.
Comment: Cara eu te amo, vlw mesmo, era só aquilo e eu não entendia, vlw pela paciência, verdade, poderia imprimir direto lá... mas de qualquer jeito eu teria que ler depois, essa só foi a primeira parte, tenho mas umas duas, agora a missão é colocar o numero de linha
Comment: Vou fazer uma resposta baseada na sua mesclando com os resultados que obtive neste experimento: https://ideone.com/3WFf96
Comment: @JeffersonQuesado Parece me uma boa ideia. Quanto mais respostas, mais possíveis soluções e mais conteúdo oferecemos à comunidade! :)
Comment: Agora obtive o resultado que eu queria: https://ideone.com/FeohUm ; sabia que era possível ignorar marcas de formatação de uma entrada arbitrária através do `scanf`
Answer: Vim aqui apenas mostrar demais possibilidades à resposta do @Isac, usando recursos do scanf para remover essa formatação.
Para começar, achei estranho ler o valor de um caracter em uma variável temporária para ignorar. Lembrei então que em algum lugar eu havia visto algo sobre a leitura que não preenchia os valores (vide documentação), a leitura indicada pelo modificador *; por exemplo, scanf("%*c") vai ler um caracter da entrada e ignorá-lo. Então, fiz um teste sobre essa leitura ignorando caracteres:
#include <stdio.h>

int main(void) {
    int i;

    scanf("%*c%d%*c", &i);
    printf("%d\n", i);

    return 0;
}

Para a entrada [123], o resultado foi 123, conforme o esperado.
Então eu me lembrei de que é possível ignorar a formatação propriamente dita da entrada. Basta colocar os caracteres desejados a serem ignorados à esquerda antes do %d, e os caracteres a serem ignorados à direita após o %d. No caso, o formato seria  [%d], porque desejo ignorar o abre colchetes [ à esquerda e o fecha colchetes ] à direita:
#include <stdio.h>

int main(void) {
    int i;

    scanf(" [%d]", &i);
    printf("%d\n", i);

    return 0;
}

Testei para a entrada [145], obtendo 145 como saída. Se prestar atenção, eu pus um espaço no começo da string de formato para evitar conflitos com quebras de linhas, pois meu teste envolvia um número entre colchetes por linha. Você pode ver o meu teste completo no ideone.
Então, isso significa que a leitura proposta pelo @Isac poderia ser substituído por uma dessas opções.
Original:
while(1) {
    if (fscanf(ler, "%c", &c) <= 0){
        break;
    }

    fscanf(ler, "%d", &num);
    fscanf(ler, "%c", &c);

    fprintf(traduzido,"%d ", num); //grava no arquivo a tradução
    printf("%c",num); //e simultaneamente escreve na tela a conversão
}

Proposta 1, com %*c:
while(1) {
    if (fscanf(ler, "%*c%d%*c", &num) <= 0){
        break;
    }

    fprintf(traduzido,"%d ", num); //grava no arquivo a tradução
    printf("%c",num); //e simultaneamente escreve na tela a conversão
}

Proposta 2, com string de formatação ignorando os colchetes:
while(1) {
    if (fscanf(ler, "[%d]", &num) <= 0){
        break;
    }

    fprintf(traduzido,"%d ", num); //grava no arquivo a tradução
    printf("%c",num); //e simultaneamente escreve na tela a conversão
}

Comment: Todos os métodos funcionam como esperado,  esse último ["%d"]  provavelmente é o mais eficiente, já que não precisa de mais variáveis e leitura, obrigado pela ajuda também
Comment: Consegui, mó facim
Comment: Falar de eficiência é complicado, teria de testar bastante... posso tentar atualizar depois essa resposta com um _corpus_ de teste adequado para o  _benchmark_
Comment: Não precisa desse trabalho todo não, rlx
Comment: Moço sei que já estou pedindo demais, mas não tem como tu me dar uma luz, eu estou tentando fazer isso olha [https://lh3.googleusercontent.com/VxB5_DGTFpef1uuwhFreh0cqabgfnC5EyWTSk1PourwcHyY9WCGQuD5Y-eGRQo6n_qsUmYhWdQPJOXeQHicB=w1680-h917]  mas não consigo fazer com que fique só na primeira linha, eu to gerando 80 a 140 mb de texto, nada ver o que eu estou fazendo. (coloquei a foto do google Drive)
Comment: Moço, pela sua descrição deu uma preguiça de ver... sem falar que meu computador não tá ajudando em nada, nem consigo trabalhar sem precisar reiniciar a cada 30 min
Comment: Tudo certo então

Arquivo Em linguagem C


Generalization of sesquilinear form?

Question: If a sesquilinear form is a generalization of a bilinear form, what is a generalization of a sesquilinear form ?
I don't like this reasoning

There's no need for a generalization of a sesquilinear form. They exist to fix a certain issue with bilinearity in the context of inner products. An inner product needs to have v.v greater than 0 for nonzero vectors. If we assume full bilinearity with complex coefficients, then (iv).(iv) =(i.i)(v.v) = -v.v
  This then shows that (iv).(iv) is strictly negative. This is an issue. Sesquilinearity fixes this. There's then no defect to fix. Mathematicians don't just event things on what if adventures. There needs to be a reason, and there's no reason to expand beyond sesquilinearity in this context.

because in my opinion restrict sesquilinear form to correct some bilinear form issues is deprecated.
If by hypothesis a generalization makes sense for a different reason, why would you use this generalization?
However, how these forms can be generalized?
Comment: What does this have to do with category theory?
Comment: In Latin, sesqui means "one and a half", so a generalisation would be a "one-linear form", see [wikipedia](https://en.wikipedia.org/wiki/Sesquilinear_form). However, whether or not this is sensible, is up to you.
Comment: a sesquilinear form allows one of the arguments to be "twisted" **in a semilinear manner** I think that one-linear form is not a generalization, maybe a generalization of semilinear manner I try to understand, maybe something this https://www.tandfonline.com/doi/abs/10.1080/0025570X.1970.11976031
Comment: I mean, one of the arguments is still linear, but the other is something weaker, no problem. It is twisted in a **quarterlinear manner**.
Answer: One generalisation would be to replace $i \mapsto -i$ and the identity by some other field automorphisms:
Let $F$ be a field, $V$ an $F$-vector space, and $\alpha,\beta$ automorphisms of $F$. Then we can define a map $\gamma \colon V \times V \to F$ to be $(\alpha,\beta)$(linear? colinear? equilinear? something else?) if
$$ \gamma(\lambda u,v) = \alpha(\lambda)\gamma(u,v) , \\
\gamma(u+v,w) = \gamma(u,v) + \gamma(v,w) , \\
\gamma(u,\lambda v) = \beta(\lambda) \gamma(u,v) , \\
\gamma(u,v+w) = \gamma(u,v)+\gamma(u,w) . $$
This is consistent with the vector space axioms since $\alpha,\beta$ are automorphisms.
One could go further, to multi-not-quite-linear maps, by adding more automorphisms and more arguments.
The disadvantage to this approach is that there are no nontrivial automorphisms of $\mathbb{Q}$ or $\mathbb{R}$, and the only well-behaved automorphism of $\mathbb{C}$ is the one that sends $i \mapsto -i$, i.e. complex conjugation. Therefore there's not an awful lot of promise in this extension for the three most commonly used fields.

Generalization of sesquilinear form?


Extraction of sha1 from X.509 openssl certificate in Java

Question: I must write a Java implementation of an X.509 openssl certificate parser, but I have a problem: I do not know how to get the sha1 for the validation of certificates.
Can anyone help me to understand what I should do? I know that there is a method getTBSCertificate() in Java, but I have to rewrite it for my purpose.
Comment: Have a look here: http://stackoverflow.com/questions/143523/x509-certificate-parsing-libraries-for-java
Answer: Assuming you mean the sha1 which is commonly shown as the 'fingerprint' in the browsers and OS tools -- you need 1) the raw cert as DER; and then 2) sha1 it and 3) translate that to the usual double-digit-hex/colon separated string.
As to 1; getEncoded() from   java.security.cert.Certificate gets you that.
As to 2: MessageDigest has that function.
As to 3: I'll leave that to you :)
... someFoo(X509Certificate cert) {
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    System.out.println("  Subject " + cert.getSubjectDN());
    System.out.println("   Issuer  " + cert.getIssuerDN());
    sha1.update(cert.getEncoded());
    System.out.println("   sha1    " + toHexString(sha1.digest()));
    System.out.println();
  }

should do the trick. This output matches that of the java keytool.
Dw.
Comment: That's correct for the fingerprint indeed. My guess is that the question may also be about verifying the signature... Here are a couple of recent related questions: [about fingerprints](http://security.stackexchange.com/q/14330/2435) and [about signatures (and CAs)](http://stackoverflow.com/q/10411433/372643).


Concatenate two dataframes without loosing columns

Question: I've tried concatenating two dataframes using pd.concat([df1, df2], axis = 1), however this does not keep all of the column names in df1.
import pandas as pd
from datetime import timedelta
df = pd.DataFrame({
        'date': ['2001-02-01','2001-02-02','2001-02-03', '2001-02-04'],
        'future_date': ['2001-02-01','2001-02-02','2001-02-03', '2001-02-04'],
        'x Value': [100, 200, 300, 400],
'x1 Value': [100, 200, 400, 400],
'x2 Value': [100, 300, 300, 400],
'xN Value': [200, 200, 300, 400]})

df2 = (df1['future_date'] + pd.Timedelta(5, unit='days')).to_frame()
pd.concat([df1, df2], axis = 1).tail(10)

When I return pd.concat([df1, df2], axis = 1).tail(10) I only get the future_date column values.
Desired dataframe:
    future_date date       x Value  x1 Value    x2 Value    xN Value
0   2001-02-01  2001-02-01 100  100 100 200
1   2001-02-02  2001-02-02 200  200 300 200
2   2001-02-03  2001-02-03 300  400 300 300
3   2001-02-04  2001-02-04 400  400 400 400
4   2001-02-05
5   2001-02-06
6   2001-02-07
7   2001-02-08

I've also tried
new_df = pd.concat([df2, df1(columns=df1.columns.tolist())], ignore_index=True)

TypeError: 'DataFrame' object is not callable

Answer: You need to create the missing columns first.
for col in df.columns:
    if col not in df2.columns:
        df2[col] = None

df2 = pd.concat([df, df2], ignore_index=True)

         date future_date x Value x1 Value x2 Value xN Value
0  2001-02-01  2001-02-01     100      100      100      200
1  2001-02-02  2001-02-02     200      200      300      200
2  2001-02-03  2001-02-03     300      400      300      300
3  2001-02-04  2001-02-04     400      400      400      400
4        None  2001-02-06    None     None     None     None
5        None  2001-02-07    None     None     None     None
6        None  2001-02-08    None     None     None     None
7        None  2001-02-09    None     None     None     None


Delete any path alias by language

Question: We are running Drupal 8.8.5. I can see duplicate aliases when I look at /admin/config/search/path.
Unfortunately, there are many duplicate aliases on our website with 6000 URLs. The /node/1 node has three translations: en, es, and zh-hans.  /node/1 also has a second entry for es containing a duplicate path alias which I would like to delete.
I need to find a way to programmatically delete path aliases. If I have Create, Read, Update and Delete (CRUD) operations on the path/alias/langcode, I can create a solution to eliminate the duplicates.
The following code obtains the alias data associated with the node whose ID is equal to 1 and dumps the Path, Alias and LangCode.
$alias = \Drupal::entityTypeManager()->getStorage('path_alias')->load('1');
var_dump($alias->getPath());
var_dump($alias->getAlias());
var_dump($alias->language()->getId());

The base language of the website is English, and the last var_dump() yields en.  So far so good.
How can I gain access to the alias data for these two languages?  I know the following works.
$alias_es = \Drupal::service('path_alias.manager')->getAliasByPath('/node/1','es');

I need to delete the duplicate Spanish path alias to accomplish my goal, so I need to figure out how to use entities which have a delete() method.  You might think the following code should work.
$alias_es = $alias->getTranslation('es');

It returns:

InvalidArgumentException: Invalid translation language (es) specified.

I also tried $alias->getTranslationLanguages(), which returns an array with only one element (['en'] => object(Drupal\Core\Language\Language)).
It appears that our original $alias = \Drupal::entityTypeManager()->getStorage('path_alias')->load('1'); only has one language translation which is English.
How can I gain access to the path aliases for es and zh-hans?
Answer:
How can I gain access to the path aliases for es and zh-hans?

To get all path alias by language for instance es:
$path_alias_manager = \Drupal::entityTypeManager()->getStorage('path_alias');
// Load all path alias for this node for es language.
$alias_objects = $path_alias_manager->loadByProperties([
  'path' => '/node/' . $nid,
  'langcode' => 'en'
]);

I need to delete the duplicate Spanish path alias

$path_alias_manager = \Drupal::entityTypeManager()->getStorage('path_alias');
// Load all path alias for this node for es language.
$alias_objects = $path_alias_manager->loadByProperties([
  'path'     => '/node/' . $nid,
  'langcode' => 'es',
]);

// Get the actual associated spanish path alias to your node.
$spanish_associated_alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $nid, 'es');
foreach ($alias_objects as $alias_object) {
  // If its not the actual alias delete it.
  if ($alias_object->get('alias')->value !== $spanish_associated_alias ){
    $alias_object->delete();
  }
}

Answer: Thank you @berramou!
There were two cases to deal with in my situation: (1) an alias that does not match the current alias for a language and (2) a duplicate alias for the same language that matches the current alias.  The following code identifies both of these case.  The code does not delete the offending alias objects.  Please look at your case first and see if the code works for you before removing the commented alias object delete.
$path_alias_manager = \Drupal::entityTypeManager()->getStorage('path_alias');

$nids = \Drupal::entityQuery('node')
  ->execute();

$n = 0;
foreach($nids as $nid) {

  $alias_objects = $path_alias_manager->loadByProperties([
    'path' => "/node/$nid",
  ]);

  foreach(['en','es','zh-hans'] as $lang)
    $current_alias[$lang] = \Drupal::service('path_alias.manager')->getAliasByPath("/node/$nid",$lang);

  $aliases = [];
  foreach($alias_objects as $ao) {
    $lang = $ao->language()->getId();
    $alias = $ao->getAlias();
    $path = $ao->getpath();
    if($current_alias[$lang] != $alias) {
      delete_ao($ao,$alias_objects,$current_alias[$lang],'not current');
    } else {
      if( isset($aliases[$lang]) ) {
        delete_ao($ao,$alias_objects,$current_alias[$lang],'duplicate');
      } else {
        $aliases[$lang] = $alias;
      }
    }
  }
  if($n++ == 100)exit;
}

function delete_ao($ao,$alias_objects,$current,$why) {
  $lang = $ao->language()->getId();
  print_aos($alias_objects);
  print ">> delete as $why: ";
  print_ao($ao);
  if($why == 'not current')
    print ">> current_alias for $lang: $current\n";
  print "\n";
  // $ao->delete();
}

function print_ao($ao) {
  print $ao->getPath() . ', ' .
        $ao->getAlias() . ', ' .
        $ao->language()->getId() . "\n";
}
function print_aos($alias_objects) {
  foreach($alias_objects as $ao)
    print_ao($ao);
}

Delete any path alias by language


Update from select MySQL

Question: I am trying update the amount between "%2017-08-01%" and
"%2017-08-07%" to the amount from the next date "%2017-08-07%" where the e.auto="true" in the transaction table. However, the mysql is returning

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
  near 'FROM user as u JOIN e_wallet as e ON e.id =
  u.ewallet JOIN transacti' at line 1

update t set t.amount = (
                          select t.amount
                          FROM user as u
                          JOIN e_wallet as e ON e.id = u.ewallet
                          JOIN transaction as t on t.user = u.id
                          where e.auto="true"
                                and t.create_date like "%2017-08-07%"
                        )
FROM user as u
JOIN e_wallet as e ON e.id = u.ewallet
JOIN transaction as t on t.user = u.id
where e.auto="true"
      and t.create_date BETWEEN "%2017-08-01%" and "%2017-08-07%"

Comment: `%2017-08-01%"` isn't a date. It's a string that contains something that looks like a date between `%` characters
Comment: `BETWEEN` can't be used with wildcard characters (`%`). It's designed for dates and numbers, not for strings.
Comment: @diiN__________ it works with strings that contain dates as well. This string though doesn't contain a valid date. I suspect there's a different error though. Once it's fixed, the next one will be about the date literals. Or **worse**, the query will work without producing results
Comment: Ok that was my bad, but my query still return the same error
Comment: @JohnWick read the error and look for the syntax error it mentions in the place mentioned. We are busy trying to format that long string into a query
Comment: @JohnWick in the meantime, if you can't understand exactly where the error is,  extract *parts* of the query and check that they work.
Comment: It still returns the same error 1064, starting from the "From user" line. Even the select query inside the bracket is working, but right after the bracket, it returns an error
Comment: Everything after the bracket, ) FROM user as u -> this part is not working properly. But the query within the bracket is almost the same as the one outside
Comment: And both are weird. The inner query will return *multiple* values unless there is only a single transaction per day
Answer: If you ignore the subquery, your UPDATE query looks like:
UPDATE t
SET t.amount = ...
FROM user AS u ...
JOIN e_wallet AS e ...

You can't have a FROM clause in an UPDATE query, and that's what's causing the syntax error. The syntax is:
UPDATE tablename AS t1
JOIN tablename2 AS t2 ON ...
JOIN tablename3 AS t3 ON ...
SET ...
WHERE ...

So it should be:
UPDATE transaction AS t
JOIN user AS u ON u.id = t.user
JOIN e_wallet AS e ON e.id = u.ewallet
SET t.amount = (
  select t.amount
  FROM user as u
  JOIN e_wallet as e ON e.id = u.ewallet
  JOIN transaction as t on t.user = u.id
  where e.auto="true"
        and t.create_date like "%2017-08-07%"
)
WHERE e.auto = "true"
AND t.create_date BETWEEN "2017-08-01" and "2017-08-07"

This should solve the syntax error, but I'm not sure it will do what you want. The subquery isn't correlated with the main query, so it will return the amounts of all transactions that meet the criteria. But when you use a subquery as an expression it has to return at most one row. You probably just want to join with the transaction table a second time.
UPDATE transaction AS t
JOIN user AS u ON u.id = t.user
JOIN e_wallet AS e ON e.id = u.ewallet
JOIN transaction AS t1 ON t1.user = t.user
SET t.amount = t1.amount
WHERE e.auto = "true"
AND t.create_date BETWEEN "2017-08-01" and "2017-08-07"
AND t1.create_date LIKE '%2017-08-07%'

Comment: Your query is a lot simpler than I thought, didnt know we could actually simplify it that way

Update from select MySQL


Color map not changing with imshow()

Question: I am applying KMeans to an image, but when I try to use cmap to change the color, it doesn't do anything. How could I do it?
im = io.imread("image.jpg") / 255
x, y, z = im.shape
im_2D = im.reshape(x*y, z)
kmeans = KMeans(n_clusters=3, random_state=0)
kmeans.fit(im_2D)
im_clustered = kmeans.cluster_centers_[kmeans.labels_].reshape(x, y, z)

fig, ax = plt.subplots(1, 2)
ax[0].imshow(im)
ax[0].set_title("Original")
ax[1].imshow(im_clustered, cmap="jet")
ax[1].set_title("Segmented using k=3")
plt.show()

EDIT:
This is the output using the code above:

This is what I would like the output to be, if using the jet cmap:
Comment: @DavidG I am not sure what you mean. I tried other ones, but those didn't change anything either.
Comment: I didn't find any difference in both(with or without `cmap`). Would you show us the expected output?
Comment: @MaheryRanaivoson I have added the current output and the expected output
Answer: You can use ax[1].imshow(kmeans.labels_.reshape(x, y), cmap='jet').
The current im_clustered contains rgb values. To apply a colormap you need scalar values.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from sklearn.cluster import KMeans

with cbook.get_sample_data('ada.png') as image_file:
    im = plt.imread(image_file)
x, y, z = im.shape
im_2D = im.reshape(x * y, z)
kmeans = KMeans(n_clusters=3, random_state=0)
kmeans.fit(im_2D)
kmeans.cluster_centers_ = np.clip(kmeans.cluster_centers_, 0, 1)
im_clustered = kmeans.cluster_centers_[kmeans.labels_].reshape(x, y, z)

fig, ax = plt.subplots(1, 3, figsize=(10, 4))
for ax_i in ax:
    ax_i.axis('off')ax[0].imshow(im)
ax[0].set_title("Original")
ax[1].imshow(im_clustered, cmap="jet")
ax[1].set_title("Segmented using k=3")
ax[2].imshow(kmeans.labels_.reshape(x, y), cmap="jet")
ax[2].set_title("Segmented, k=3, jet cmap")
plt.show()

Color map not changing with imshow()


Functions from a set of numbers to a set of letters?

Question: Say I have two sets, $A = \{1, 2, 3\}$ and $B = \{a, b, c\}$. I know how to find regular functions with all numbers however how do I find a function that is $f: A\to B$?
Answer: Your function will $f$ will be a subset of $A \times B$ such that $(x,y), (x, z) \in f$ implies $y = z$ and also $\{x \in A : \exists y(y \in B \; and \; (x, y) \in f)\} = A$. Example : $f = \{(1, a), (2, b), (3, c)\}$ or $f = \{(1, a), (2, a), (3, a)\}$ (if you don't want it to be bijection).
Comment: You also need to require that its domain is $A$.
Comment: @AsafKaragila sure thank you
Answer: Functions are not necessarily given by formulas with addition, or sine and exponentiation.
Functions are just collections of ordered pairs, which satisfy a certain property. When we write $f\colon A\to B$ we mean to say that:

$f$ is a collection of ordered pairs $\langle a,b\rangle$ such that $a\in A$ and $b\in B$.
For every $a\in A$ there is exactly one ordered pair $\langle a,b\rangle$ in $f$. Then we can say that such $b$ is $f(a)$.

In small sets you can just write, instead of ordered pairs, the values that $f$ returns. For example, $f(1)=1,f(2)=3,f(3)=1$ is a function from $A$ to itself. You can use a similar way to write down a function from $A$ to $B$.


Método de escolha com while

Question: Tenho duas opções e o programa deve dizer qual foi escolhido, caso a entrada seja errada deve pedir para repetir o pedido.
Problemas: Opção 2 repete 2 vezes até acertar. A opção 1, não diz o um nome que não esta no script
print('''Choice your number
[1] Banana
[2] Apple ''')

    option = int(input('Your option: '))
    while option != 1 and 2:
        print('Try again')
        option = int(input('Your option: '))
        if option == 1:
            print('Banana choiced')
        elif option == 2:
            print('Apple choiced')

Comment: Possível duplicata de [Como fazer com que o sistema exiba uma mensagem de erro quando não for número?](https://pt.stackoverflow.com/questions/256342/como-fazer-com-que-o-sistema-exiba-uma-mensagem-de-erro-quando-n%c3%a3o-for-n%c3%bamero)
Comment: @AndersonCarlosWoss embora pareça mesmo, não acho que seja porque ela tem uma peculiaridade de que as opções válidas são testadas. Eu achei até que poderia ser o mesmo caso da que eu respondi anteriormente, mas é um pouco diferente.
Comment: Sou suspeito para comentar, mais certamente não são.
Answer: É mais fácil do que parece:
print('''Choice your number
[1] Banana
[2] Apple ''')
while True:
    option = int(input('Your option: '))
    if option == 1:
        print('Banana choiced')
        break
    elif option == 2:
        print('Apple choiced')
        break
    print('Try again')

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Como você verifica as opções aceitas e se uma delas for digitada deve encerrar a execução é só encerrar o laço quando entrar em uma delas (break). Se não entrar nas opções permitidas e validadas com if ele só fica no laço indefinidamente até digitarem o que vale.
Comment: realmente é simples, estou a dar os meus primeiros passos em Python. agradeço ajuda.

Método de escolha com while


NullpointerException no mock da Repository

Question: Estou usando JUnit5 e ao criar o teste levo o seguinte erro:
java.lang.NullPointerException: Cannot invoke "com.example.gerenciadordetarefas.repository.task.TaskRepository.save(Object)" because "this.taskRepository" is null
Alguém pode me ajudar a solucionar o erro acima?. Entendo que ele não consegue fazer mock da repository mas não sei o por que.  Aqui em baixo estão os códigos.
Obs: Minha service esta com a injeção de dependecia de User usando @Lazy por que eu estava tendo erro de circular dependencies.
Minha classe de teste :
<code>@ExtendWith(MockitoExtension.class)
class TaskServiceTest {
@Mock
private TaskRepository repository;
@InjectMocks
private  TaskService service ;

@Mock
private UserService userService;
private static final String TASK_ID_1 = "652d960af866034b686cca97";
private static final String TASK_ID_2 = "252d960af866034b686cca92";
private static final String USER_ID_1 = "642f6ab6813d692cef4795cc";

private final User user1 = User.builder()
        .id(USER_ID_1)
        .name("Maria Silva")
        .assignedTasks(new ArrayList<>())
        .build();
private final Task task = Task.builder()
        .title("teste")
        .description("teste aqui")
        .dateOfCreation(LocalDate.now())
        .dueDate(LocalDate.now())
        .assigne(Collections.singletonList(user1))
        .build();

private final TaskDto taskD = TaskDto.builder()
        .title("teste")
        .description("teste aqui")
        .dateOfCreation(LocalDate.now())
        .dueDate(LocalDate.now())
        .assigne(Collections.singletonList(USER_ID_1))
        .build();

@BeforeEach
void setUp() {

    Mockito.lenient().when(userService.getUserById(USER_ID_1)).thenReturn(user1);
    Mockito.lenient().when(repository.save(Mockito.any(Task.class))).thenReturn(task);
    Mockito.lenient().when(repository.findById(TASK_ID_1)).thenReturn(Optional.of(task));
}

@Test
@DisplayName("Verificar se o objeto Task está sendo criado ")
void createTask() {
    service.createTask(taskD);
    verify(repository, times(1)).save(task);

}
</code>
Minha Service:
<code>@Service
public class TaskService {
@Autowired
private TaskRepository taskRepository;
private final UserService userService;
@Autowired
public TaskService(@Lazy UserService userService) {
    this.userService = userService;
}

public TaskDtoResponse createTask(TaskDto taskDto) {
    Task task = TaskMapper.taskDtoToTask(taskDto);
    this.addToAssigne(taskDto, task);
    taskRepository.save(task);
    return TaskMapper.taskToTaskDtoResponse(task);
}

public TaskDtoResponse updateTask(TaskDto dto, String id) {
    this.getTaskById(id);
    Task task = TaskMapper.taskDtoToTask(dto);
    this.addToAssigne(dto, task);
    task.setId(id);
    taskRepository.save(task);
    return TaskMapper.taskToTaskDtoResponse(task);
}

public Task addToAssigne(TaskDto taskDto, Task task){
    List<String>assigne = taskDto.getAssigne();
    assigne.forEach(id -> {
        User user = userService.getUserById(id);
        task.getAssigne().add(user);
    });
    return task;
}
</code>
Minha Repository:
<code>@Repository
public interface TaskRepository extends MongoRepository<Task, String> {
@Query("{_id: {$in:?0}})")
List<Task> findByIds(List<String> ids);
}
</code>
Answer: Você está recebendo este erro porque o @InjectMocks não suporta injeção de dependência mista.
A classe TaskService tem dependência mista: UserService usa injeção no construtor, enquanto TaskRepository usa injeção na propriedade/atributo.
<code>@Service
public class TaskService {
  @Autowired
  private TaskRepository taskRepository;
  private final UserService userService;
  @Autowired
  public TaskService(@Lazy UserService userService) {
    this.userService = userService;
  }
</code>
A documentação do @InjectMock diz que "Mockito injetará mocks apenas por um meio e nesta ordem: construtor, propriedades ou métodos."
Eu sugiro mover a injeção do TaskRepository para o construtor:
<code>@Service
public class TaskService {
  private final TaskRepository taskRepository;
  private final UserService userService;
  @Autowired
  public TaskService(@Lazy UserService userService, TaskRepository taskRepository) {
    this.userService = userService;
    this.taskRepository = taskRepository;
  }
</code>
Depois desta alteração, você vai ter que refatorar o código. Algo mais que eu gostaria de destacar é que o time do Spring recomenda usar dependência pelo construtor sempre que possível.
Comment: Muito obrigada, estava quebrando a cabeça aqui.


Maven parallel build wrong order

Question: I'm trying to speed up my maven build with parallel processing. The project is multi-modular with nested modules. The structure is like:

parent

m1
m2
sub-parent (a project that doesn't generate an artifact, but a folder with resources for m3 to use)
m3

Edit: now I even see, that at least once m3 did its copying goal before sub-parent even starts, thus used the result of previous build before sub-parent started its clean.
If I do mvn dependency:tree -Dverbose -Dincludes=my.packages.* I see that sub-parent is correctly listed in the dependencies of m3. However, sometimes (rarely) parallel build mvn -T 1C clean install fails, because m3 build is being executed earlier than sub-parent.
Is there a workaround to enforce order? I know you can't set it directly. The thing is, I cant put sub-parent as a dependency to m3, because it doesn't have an artifact. And I don't sure I need it, because dependency tree shows that maven knows about this dependency.
Edit: I've added a sample minimal project. https://github.com/Imaskar/build-order . Except that sub/keystore need to be swapped for real one. Interestingly, here dependency tree doesn't show sub as a dependency of m3. How to tell m3 to depend on it, despite the fact that sub is not built to a jar file?
Comment: If you need to be sure having build sub-parent before m3 you simple have to define a dependency to sub-parent in m3 which makes sense cause the sub-parent will be used in m3.....
Comment: First if you have resources in a different module than they are used this is the first mistake...furthermore if you say "sub parent" does that mean you have packaging "pom" ?
Comment: Every project here has a `pom.xml`. The sub-parent one gathers artifacts from some other modules and signs them. m3 copies the result to itself. If m3 would do that, unnecessary jars would come along.
Comment: What do you mean by "gathers" artifacts? And sign them? Can you make and example project which shows the given situation? Apart from that if m3 builds earlier than sub-parent your dependencies between the modules are wrong.
Comment: Gathers=copies to its folder by declaring them as dependencies. Then maven-jarsigner-plugin is fired over that folder. This strucure is kinda ad-hoc to be able to build project as a descktop app and as a jnlp web app. I'll try to make an example, but it'll take a while.
Comment: https://github.com/Imaskar/build-order
Comment: if defined as a dependency, it fails with something like "could not resolve sub-parent.jar", because sub-parrent does not produce jar artifact.
Answer: Ok, I figured it out some time ago,  but wanted for anyone to take the credit. The solution is declaring a dependency with
<type>pom</type>

Maven parallel build wrong order


File save upload doesn't replace existing file despite FILE_EXISTS_REPLACE

Question: I'm trying to force replacement of existing file with same name, if a new version is uploaded by user. I've seen a lot of posts about this topic but none that I could find addresses how to force the replacement.
I'm using a custom form, and here's the code I've been trying to make work during the form validation:
<code>  $file = file_save_upload(
      'file',
      array(
        'file_validate_is_document' => array(), // Validates file is really a document.
        'file_validate_extensions' => array('pdf doc ppt pps avi mpg mov wmv'), // Validate extensions.
      ),
      'public://',
      FILE_EXISTS_REPLACE
  );
</code>
The revised file (let's say "file.jpg") is uploaded, but inevitably Drupal creates a new copy and renames it file_0.jpg, file_1.jpg, etc for each new version.
I even tried to programmatically delete the original file using "file_delete" prior to committing the upload but I still get the copy!
Any help would be appreciated.
Answer: This is drupal's default behaviour and a known issue. It has been addressed a couple of ways.
The Upload File Replace module addresses this issue by swapping the filenames so the new file retains the original name.
The Media Update module allows in situ replacement of media files (part of the Media project).
You could either make use of one of these modules, or use them as a model for your own function.
Comment: Perfect, thanks @triskelion for all the options. I ended up using the Upload File Replace.
Answer: I managed to make it work using the following code.
<code>$file = file_save_upload('file', $validators);
// If the file passed validation:
if ($file) {
    // I PLACED IT IN THE NEXT LINE
    if ($file = file_move($file, 'public://', FILE_EXISTS_REPLACE)) {
        // Save the file for use in the submit handler.
        $form_state['storage']['file'] = $file;
    } else {
        form_set_error('file', t('Failed to write the uploaded file to the site\'s file folder.'));
    }
} else {
    form_set_error('file', t('No file was uploaded.'));
}
</code>
Answer: <code>$file_temp = file_save_data($attachment->data, 'public://<my_files_locatioin>/<my-filename.pdf>' , FILE_EXISTS_REPLACE);
</code>


Windows Server 2012 R2 kernel threads increase until the system hang

Question: I have a small problem with my Windows Server 2012 R2. At the moment the problem is that the threads from "NT Kernel & System" increase every second until they reach 16k, and then the server becomes very slow or hangs. When I try to debug the process with Process Explorer:

Here you can see that something spawned a new thread and wait. I've tried to stop all my services but i can't find a solution. Have any of you had the same problem in the past?
Comment: Are you running Process Explorer as an elevated process? You may be logged in with an administrator account, but please be sure to still right-click on Process Explorer and select "Run as administrator." That should get you access to the process and thread info.
Comment: Can you right-click on the process and see the full path?
Comment: No if i make a double-click i get the info "Unable to access thread" and right-click has no function.
Comment: Yes it's running as Administrator but the same. I'm loggedin as Domain Admin so a should have enough rights but i've testet it and no chance...
Comment: Just to be clear, you still need to "Run as administrator" even when you are logged in as a Domain Administrator. (You can thank UAC for that.)
Comment: Yes ;) but i have no access...
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/59142/discussion-between-stony-and-sturdyerde).
Comment: So, what was the answer here?
Answer: This explains the issue. Combination of KB4019215  and bad iSCSI connections.
https://www.reddit.com/r/sysadmin/comments/6cum10/headsup_2012_r2_servers_with_iscsi/
Comment: That fix isn't installed on my system. And i don't use iSCSI anymore. I have uninstalled all iSCSI packages. So i don't thing that this is the problem.
Comment: I've checked iSCSI again. The service was not running but the old connection was active after restart the service. Now i've deleted all connections and i think it looked good now.


GRE traffic not forwarded to local subnet

Question: I have two debian machines in difference locations and want to enable routing between the two internal subnets via GRE.
My general routing is already working, meaning any internal machine directs traffic towards the two machines which are connected via GRE and also traffic is send through the tunnel, but when receiving this traffic it's not forwarded into the local subnet anymore.
My configuration on those two machines (not using actual IPs):
Host A (172.19.0.1):
ip tunnel add tun0 mode gre remote 172.20.0.1 local 172.19.0.1
ip addr add 10.10.10.1/24 dev tun0
ip link set tun0 up

Host B (172.20.0.1):
ip tunnel add tun0 mode gre remote 172.19.0.1 local 172.20.0.1
ip addr add 10.10.10.2/24 dev tun0
ip link set tun0 up
echo 1 > /proc/sys/net/ipv4/ip_forward

Pinging either machine on the tunnel interface IPs (10.10.10.1 and 10.10.10.2) works flawlessly, but when I try to ping an internal IP through the tunnel by e.g. running ping 10.100.77.8 -I tun0 on Host A I don't get a response. tcpdump shows that there is not even one generated which indicates that the packet never hit's the interface after being unpacked by the GRE.
root@hostb:~# tcpdump -i any host 172.19.0.1
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on any, link-type LINUX_SLL (Linux cooked), capture size 262144 bytes
10:36:10.983403 IP 10.10.10.1 > 172.20.0.1: GREv0, length 88: IP 10.10.10.1 > 10.100.77.8: ICMP echo request, id 20422, seq 8, length 64
10:36:10.983419 IP 10.10.10.1 > 10.100.77.8: ICMP echo request, id 20422, seq 8, length 64
10:36:11.991415 IP 10.10.10.1 > 172.20.0.1: GREv0, length 88: IP 10.10.10.1 > 10.100.77.8: ICMP echo request, id 20422, seq 9, length 64
10:36:11.991427 IP 10.10.10.1 > 10.100.77.8: ICMP echo request, id 20422, seq 9, length 64

I cannot see the ICMP packet coming in on target machine 10.100.77.8. There are no rules in iptables configured while default action is always ACCEPT.
Answer: Problem solved. rp_filter was enabled for the tunnel interfaces
$ cat /proc/sys/net/ipv4/conf/all/rp_filter
1
$ cat /proc/sys/net/ipv4/conf/tun0/rp_filter
1

Changing both of those to 0 fixed the issue.
Answer: Seems like something wrong in the source address select, because you have the internal tunnel address in the outer header of the GRE packets. The source address of the outer header should be 172.19.0.1, not 10.10.10.1.

10:36:10.983403 IP10.10.10.1> 172.20.0.1: GREv0, length 88:\
   IP 10.10.10.1 > 10.100.77.8: ICMP echo request, id 20422, seq 8, length 64

Check the output of the ip route get 10.100.77.8 on the host A. Also check the output of the ip route get 10.100.77.8 from 10.10.10.1 iif tun0 on the host B. If you see something like invalid cross-device link you should disable the rp_filter.
Also, show the output of 'ip -4 r ls' command from the both hosts.
Comment: The packet was generated on the machine hosting the GRE so it selected this as source IP. Wasn't the issue in this case. I figured out that by default rp_filter is activated on the machines for new interfaces. Deactivating this solved the issue. Will compose a final answer to this.
Comment: It's not a normal situation. The drops by `rp_filter` is just a side effect of other issue. You have the uncomplete routing setup. Check the output of `iptables-save`. It'll list the full firewall rule set.
Comment: As said there are no configurations done in iptables. But here you go:
`*filter:INPUT ACCEPT [0:0]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [0:0]COMMIT`
Comment: I cannot explain the source address mismatch, but it's will affect to your configuration in the future.
Answer: Another issue I've bumped into today which had a similar manifestation was due to a bug in CentOS 8.3 and VXLAN or GRE tunnels.
The solution was to disable tx-checksum-ip-generic with ethtool -K nic1 tx off.
According to the Redhat solution, issue should get fixed in Redhat 8.4.


If a family of meromorphic functions is normal near each point in a region, then it's normal in the region

Question: Here's a question from Ahlfors Complex Analysis.
I'm worried that I have a gross misunderstanding of normal families, because it seems like there's not very much work involved in solving it. It's from Secton 5.5.5 "Normal Families".

If the family $\mathfrak{F}$ of analytic (or meromorphic) functions is not normal in (a region) $\Omega$, show that there exists a point $z_0$ such that $\mathfrak{F}$ is not normal in any neighborhood of $z_0$. Hint: A compactness argument.

Question: Is the following correct?
I thought I'd try to show the contrapositive:
If a family $\mathfrak{F}$ of analytic/meromorphic functions on a region $\Omega$ is such that for every $z_0$ in the region there is a neighborhood $N(z_0)$ on which $\mathfrak{F}$ is normal, then the family is normal on $\Omega$ itself.
If Ahlfors means normal in the classical sense, then I don't see what work is involved, because it seems like you just apply Marty's Theorem: The expressions
$$
\rho(f) = 2\frac{|f'|}{1 + |f|^2}
$$
are locally bounded in each $N(z)$, so are locally bounded in $\Omega$. By Marty's Theorem the family is normal in the whole region. This doesn't even use his hint.
Alternatively, if you want to use his compactness hint, I guess you can just as easily show equicontinuity on compacta & use Arzela-Ascoli: For any compact $E$ in the region, cover it with finitely many open discs $B_{\delta_i/4}(z_i)$ such that the family is normal on each $B_{\delta_i}(z_i)$. It's equicontinuous on each closed disc $\overline{B}_{\delta_i/2}(z_i)$. Now do the usual thing: Given $\epsilon$ find $r_i$ for each disc, and take $r = \min\{\delta_1/4, \dots, \delta_N/4, r_1, \dots, r_N \}$, etc...
Answer: From the definition of normality as "every sequence of functions  contains a subsequence which converges uniformly on compact subsets in the spherical metric" (I don't remember if this is the one in the book), I would argue as follows. Let $K\subset \Omega$ be a compact set. Cover it by disks $D_i$ such that the family $\mathcal F$ is normal in $2D_i$. Choose a finite subcover by $D_{i_1},\dots, D_{i_n}$. Given any sequence in the family, choose a subsequence that converges uniformly on $D_{i_1}$, from it choose a subsubsequence that converges uniformly on $D_{i_2}$, etc. The result is a subsequence converging uniformly on $K$.
Okay, so far this subsequence depends on $K$; we need one that converges uniformly on every compact subset of $\Omega$. Use the standard device of exhaustion: $\Omega = \bigcup_{n=1}^\infty \Omega_n$ where  $\overline{\Omega_n} \subset \Omega_{n+1}$ for all $n$. (One   construction  is to fix $x_0\in\Omega$ and let $\Omega_n$ be the connected component of   $x_0$ in the set $\{x\in\Omega: \operatorname{dist}(x,\partial \Omega)>1/n\}$.) We have a subsequence converging uniformly on $\overline{\Omega_1}$; from it choose a subsequence  converging uniformly on $\overline{\Omega_2}$, ... the process is infinite but the diagonal selection produces the desired subsequence.
Comment: You need to extract a subsequence from $(f_n)$ that converges uniformly on _all_ compact $K\subset \Omega$, not for every $K$ extract a subsequence converging uniformly on $K$. You need the diagonal-sequence construction for that (or attack it from a different angle, I guess).
Comment: Maybe then one of Ahlfors' goals for the problem is to demonstrate the utility of that direction of Arzela's Theorem. Hmmm...
Comment: I'll accept the improved version of the answer, although this diagonal subsequence argument doesn't seem really that much easier than proving the similar portion of Arzela-Ascoli. Thanks for everyone's input.


Algorithm did not converge - Multinomial mixed model (mblogit)

Question: I'm trying to fit a multinomial mixed model with the mclogit package (using the mblogit function).
But, as I adjusted the model, I'm receiving the following message and I could't find any info about this related to this specific package:
Iteration 1 - Deviance = 63629.04
Iteration 2 - Deviance = 60300
Iteration 3 - Deviance = 60032.35
Iteration 4 - Deviance = 60023.69
Iteration 5 - Deviance = 60023.66
Iteration 6 - Deviance = 60023.66
converged

Iteration 1 - Deviance = 58065.79
Iteration 2 - Deviance = 56439.73
Iteration 3 - Deviance = 56349.22
Iteration 4 - Deviance = 56339
Iteration 5 - Deviance = 56336.96
Iteration 6 - Deviance = 56336.49
Iteration 7 - Deviance = 56336.38
Iteration 8 - Deviance = 56336.36
Iteration 9 - Deviance = 56336.34
Iteration 10 - Deviance = 56336.32
Iteration 11 - Deviance = 56336.31
Warning messages:
1: Cannot find an appropriate step size, giving up
2: Algorithm did not converge.

The model gives the results and I'm unaware of problems in the summary, but this message pop up. This is problematic? And what could be the problem with the data set?
This is the coding that I'm using to run the model:
mblogit(formula = dropout ~ sex + age_group +
secondary_school,
random = ~ 1 | institution,
data = stud.db)

And this is a head of the dataset:
  A tibble: 220,899 x 5
  institution sex   age_group      secondary_school dropout
        <int> <fct> <fct>          <fct>            <fct>
 1           1 M     25 to 29 years Public school    Enrolled
 2           1 F     25 to 29 years Public school    Enrolled
 3           1 M     Above 30 years Public school    Enrolled
 4           1 M     Above 30 years Private school   Enrolled
 5           1 F     Above 30 years Public school    Stopout
 6           1 M     Above 30 years Private school   Enrolled
 7           1 F     Above 30 years Private school   Enrolled
 8           1 M     25 to 29 years Private school   Dropout
 9           3 F     25 to 29 years Public school    Enrolled
10           1 M     25 to 29 years Federal school   Enrolled

Thanks a lot.
Edit 1:
Changed the variable institution to factor, but have the same problem. I also would like to add unique classes into the random parameter, nested within the institutions (5.110 unique classes in the institutions). Tried like this:
mblogit(formula = dropout ~ sex + age_group +
secondary_school,
random = ~ 1 | institution/class_id,
data = stud.db)

Again, it returns the results, but gives the following message and also the variance between institutions and institutions/classes are all inflated and negative.
Warning messages:
1: Moment equations give negative variances.
  Your model appears to be misspecified.
  I will use a dummy covariance matrix.
2: Cannot find an appropriate step size, giving up
3: Algorithm did not converge.

I tried to use a glmer with a simple binary response, and everything works fine. But would be important to specify the type of educational outcome in my analysis.
Comment: Hi, you should provide at least an extract of your data to reproduce your example.
Answer: I entered in contact with the author of the package, which replied to me the following message. The package is working fine right now it seems:
the algorithm seems to be broken in the 0.6.1 version.

This is corrected in the 0.7.1 version which is now available from Github.

See https://github.com/melff/mclogit/releases/latest
````


Benefit in getting Orthogonal dimensions from a data set

Question: What are the benefits of getting a new data set in which all their dimensions are independent from an original data set (applying PCA)?
we know we can reduce the storage space needed, speed up computation or remove redundant features after doing PCA for example.
but What computations in a statistical or probabilistic point of view are expedited or benefited  when all dimensions are orthogonal?
Comment: Saying "dimensions", are you speaking of axes or of variables? (Non)ortogonality of axes that span the space isn't always a synonym to (un)correlatedness of variables.
Comment: I am talking about variables
Answer: It's not just the orthogonality, but the ordering from large to small eigenvalues that's useful, because it aids data reduction.
For example, principal components regression is a technique for dealing with when the variances of regression coefficients become highly inflated owing to collinearity of the predictors. You do PCA on the predictors, regress the response on the principal components, then transform the estimates back to the original set of predictors. If you use all the PCs, you get the same results as you would by regressing directly on the original predictors. If you use a subset of the largest you get a different result - you've introduced some bias, but hopefully reduced the variance of the coefficient estimates.
Outlier detection is another use of PCA: observations that aren't extreme in the original variables can be extreme in the smaller principal components because they go against the correlation structure of the other variables.  Such observations won't necessarily stick out even in scatterplots of all pairs of the original variables.


Selecting next input field (jQuery)

Question: I have a jQuery UI slider. All works great using this code:
Form

<input readonly="readonly" name="padding" id="padding" type="text" value="5" />

This is the JavaScript code that I use to get the value of the textfield:
JS Code
$('div.ui-slide').each(function(i){

    if( $(this).attr('min') != undefined && $(this).attr('max') != undefined ) {

        $(this).slider( {
                        min: parseInt($(this).attr('min')),
                        max: parseInt($(this).attr('max')),
                        value: parseInt($(this).next("input").val()),
                        step: parseInt($(this).attr('inc')) ,
                        slide: function( event, ui ) {
                            $( this ).next("input").val(ui.value);
                        }
                    });

        $(this).removeAttr('min').removeAttr('max').removeAttr('inc');

    }

});

The Issue:
I need to place both the slider and the textfield inside a table, specifically each in there own "td". When I do this I can no longer retrieve the values of the textfield using the above JS code.

<input readonly="readonly" name="padding" id="padding" type="text" value="5" />

Chrome development tools gives me this error.

Uncaught TypeError: Cannot call method 'addClass' of undefined

I figured it has to do with this line of code:
value: parseInt($(this).next("input").val()),

I am unsure though how to get the value of the next "input" once it is inside a table cell.
Answer: instead of overusing next() find the proper input element in table row:
parseInt($(this).closest("tr").find('input[name="padding"]').val()),

jQuery docs:

http://api.jquery.com/closest/
Comment: Thanks for the tip. That solved it. Got it working using value: parseInt($(this).closest("tr").find('input').val()),

Selecting next input field (jQuery)


Why in an inconsistent axiom system every statement is true? (For Dummies)

Question: I would like to know if someone can explain in a somehow down to earth (almost logic free) way why is it true that in an axiom system where there is some statement $P$ such that $P$ and its negation $\lnot P$ are true, then every statement in the system is true?
I'm not sure if this can be done, but basically since I don't know any formal logic at all, I'm interested in seeing if at least the argument can be conveyed in an intuitive way, or if the idea can be explained without talking about first or second order logic and using symbols like $\top$, $\bot$, and $\vdash$.
This previous question is like the formal version (which I don't understand) so maybe my question can be thought of as a version for dummies of that question.
Thanks a lot in advance.
Comment: One comment: this might just be a quibble or it might actually be helpful: formal systems don't in themselves deal with **truth**: rather they deal with **provability**.  It sounds really weird to say that $P$ and $\lnot P$ are both true in your formal system.  Rather you are saying that $P$ and $\lnot P$ are both provable, which is not contradictory but even rather banal...after all, maybe your formal system just proves everything(!).  The correspondence between truth and provability *is* addressed in formal logic -- notably, Godel's Completeness Theorem -- but that's another story entirely.
Comment: It really comes down to the implication. If you accept that "false implies false" and "false implies true" are both true, then the result follows from basic modus ponens. The problem is "material implication" does not match well with linguistic implication, which makes a "for dummies" or "intuitive" explanation somewhat difficult. Much like the fact that "a or b" can be true when both a and b are true, which strikes a lot of people as very strange (being used to exclusive or from natural language).
Comment: Please feel free to edit the tags since I didn't know which tags to put. Maybe an "elementary logic" tag would have been more appropriate. And if someone feels the expression "for dummies" I used in the title makes it seem impolite, I would gladly remove it from the title.
Comment: @PeteL.Clark: So in a perfect formal system (a system that will prove everything that is true, and disprove everything that is false) provability is equivalent to truth?
Comment: I'm aware of *Gödel's Incompleteness Theorem*, but is it possible to create a perfect formal system if you could use an infinite number of axioms? If so, how many perfect formal systems are there?
Answer: I'll try to say this all in plain English:
Let's say we decide to accept the following two facts: (1) "I am a fish", and (2) "I am not a fish". Just keep those in mind.
Now let's pick any old statement, say: (3) "You can fly". Now let's prove that the statement is true!
Alright, we've already accepted that (1) "I am a fish". Of course, any time I have a true statement P, I can make a new true statement by making the statement "P or Q is true." Because to check if an 'or' statement is true, I only need to check that one of them is true. (If I tell you "My name is Dylan OR I can spit fire," you don't need to wait around with a fire extinguisher to tell if that statement is true. It's true because the first part of it is true).
So by this logic, the statement (4) "I am a fish or you can fly" must be true (since the first part is true.)
OK, but now let's say, in general, I have some 'or' statement "P or Q" and I know for a fact that the whole statement is true. If I also know that P is false then I can conclude that Q is true. Right? Because an 'or' statement is true if and only if at least one of the statements inside it is true, so if I rule out one of them the other one must be true. (So if I always tell the truth and I tell you that you have a billion dollars in your bank account OR I just ate a sandwich, you can check your bank account and quickly conclude that I just ate lunch... unless you're very wealthy.)
Alright, so far so good. We know the statement "I am a fish or you can fly" is definitely true. But wait, we also know that the statement "I am a fish" is false (remember, it's one of the things we assumed in the very beginning!). So that means, by what we just talked about, that the statement "You can fly" must be true.
So voilà! Using the magic of a contradictory system, we've proven you can fly!
Comment: Maybe one should elaborate on the possibly subtle difference between "I am not a fish" being true and "I am a fish" being false ...
Comment: This is great! I got it, so it must be simple enough for anybody to understand.
Comment: YOu can probably find on-line an account of the time Bertrand Russel proved that he was the Pope.
Comment: +1 for for the reference to dylan spitting hot fire...how you gone choke a legend?!
Comment: Nice answer. That method of argument is called disjunctive syllogism http://en.wikipedia.org/wiki/Disjunctive_syllogism.
Comment: Thanks a lot Dylan. This is a really nice answer. Besides you made me laugh a couple of times while reading it. It's a shame I can't upvote twice =)
Comment: Carl's answer is correct. It is not correct to say that every statement is true in a logically inconsistent statement. It is only reasonable to say that at least one statement is both true and false, within such a system.
Answer: It is somewhat misleading to say "every statement is true" about an inconsistent theory. This might be a point of confusion in this question, and in general the difference between "truth" and "provability" causes many other confusions, so we have to be careful to distinguish them.
"Truth" is a property that a statement has in a particular model. In other words a particular statement is either true or false in a particular model, assuming the statement is written in a formal language compatible with the model.
An inconsistent theory has no models at all. If you have no models, there's no model in which any particular statement can be true. It is correct to say that every statement in the language of the theory is provable from an inconsistent theory, and that every statement in the language of the theory is semantically entailed by the theory. But it's an abuse of language to say that every statement is "true" in the theory: true in what model?
Sometimes, when people are writing an informal proof, they say things like "assume $A$ is true" or "assume $B$ is false". But these are just figures of speech; the actual proof system usually has other ways of dealing with hypotheses than to mark them as "true" and "false". Alternatively, you can view those sayings as abbreviated forms of "assume $A$ is true in some fixed, unspecified model", "assume $B$ is false in our fixed, unspecified model". That interpretation of the informal proof is fine for any consistent theory. But that interpretation is more difficult for inconsistent theories. Because there are no models, it will be a counterfactual statement.
Answer: The answers in the prior question all employ syntactic consequence, i.e. consequence by proof in some formal system. It may be clearer to instead consider this as a semantic consequence, i.e. $\rm\ S\models Q\ $ means that $\rm\:Q\:$ is true in every model ("possible world") where every member of $\rm\:S\:$ is true. Thus $\rm\ \{P, \lnot P\}\models Q\ $ is true vacuously, since there are no models where both $\rm\:P\:$ and $\rm\:\lnot P\:$ are both true, i.e. there is no model witnessing a counterexample to that consequence, where every element of $\rm\:S\:$ is true but $\rm\:Q\:$ is false. You can find some further discussion in the Wikipedia article on this Principle of Explosion.
Comment: Thanks a lot Bill. I guess I'll have to dig up some terminology from formal logic though.
Answer: In most formal logics, the rules of the system force the principle of explosion (as pointed out by Bill Dubuque).  However, there are interesting logics where contradictions do not necessarily propagate like this.  This kind of logic is called paraconsistent logic.
Your lack of intuition about this question is perhaps because people usually are able to deal gracefully with contradiction.  In contrast, classical logic defines away contradiction: this makes the deductive system much tidier, but it makes it harder to use logic to model real-world situations.
Answer: In basic sentence logic: there is a sentence $P$ such that $P$ implies $S$ and $P$ implies $\lnot S$.
 Then, start assuming any statement $\lnot Q$ in your system. Then introduce the sentence $P$, from which $S$ and $\lnot S$ follow. Then the assumption of $Q$ leads to the conclusion $S \land \lnot S$, so by reduction, $\lnot Q$ follows. You can do this for any sentence $Q$ in your system.
Answer: In an inconsistent system you can prove a false proposition. Suppose $F$ is a false proposition. Let $P$ be a proposition. We will show that $P$ is true.
Since $F$ is false, $\lnot F$ is true. It follows that $\lnot F \vee P$ is true. Why? Because for every true propostion $X$, $X\vee Y$ is also true for any proposition $Y$.
What can we deduce from $\lnot F \vee P$? We assumed that $F$ is true, from which it follows that $\lnot F$ is  false. But if $\lnot F \vee P$ is true, which we showed, at least one of $\lnot F$ or $P$ must be true. Since $\lnot F$ is false, $P$ must be true.
Alternative proof:
$X$ implies $Y$ is equivalent to $\lnot\ X \vee Y$. Let's say $X$ is false. It follows that $\lnot X$ is true, which implies $\lnot X \vee Y$, which is equivalent to $X$ implies $Y$. Since we assumed $X$ to be true, we can conclude that $Y$ is true.
Answer: "inconsistent" means that if you ask the same question twice, you get a different answer. To say that you get the answer "true" every time is "consistent". The definition of "negative proposition" (the opposite of a proposition) is meant for the purpose of getting a negative result in the event the proposition gets a positive. So if we want to make a system which is "consistent" and gives the same result for a proposition and its negation, we cannot do it within the accepted meaning of the definitions "consistent" and "negation"
Comment: What do you mean by "ask"? If you ask whether the statement is provable, you will get the same answer every time. If you ask whether it's true in a particular model, you'll get the same answer every time as well.  What question is being asked twice but getting different answers?
Comment: I asked ZFC the following question "Is the continuum of size $\aleph_1$?" and once it said "Yes!" and once it said "No way". This answer is *too* informal that it loses the mathematical point to it.
Comment: So what then does it mean "Inconsistent Axiom System"? any examples?
Comment: Furthermore: To test a statement in a system and see if it is true or false, you suppose it is consistent. If you know it is "Inconsistent", what do you expect?
Comment: @Asaf Karagila: I do not see why it is *too* - **informal** to have a mathematical point to it. It presents the **intuition** behind some of the concepts raised in the question. The person asking the question put the **intuition** tag so this more lay style suites this post. Formality is relavent to other tags.
Comment: @Panos: If you are willing to stipulate the axioms of first order logic including the basic properties of $=$ (being an absolute equivalence relation) then $\{\forall x(x\neq x), \forall x(x=x)\}$ is an inconsistent system (in fact only the first sentence is enough, the second follows is provable from the empty set under what I had said before). To read more about it, search for the **principle of explosion**.