Parar a aplicação depois de apresentar um erro de login

Question: No código abaixo, a aplicação desktop tem que fazer um login em um sistema, mas, quando o usuário/senha está errado, ele me dá a mensagem de erro, mas após eu dar o OK ele continua rodando. Tentei o environment.exit() e application.exit() mas não funcionaram. Não aconteceu nada.
Como faria para parar a aplicação e começar de novo? Ou voltar de onde parou?
public void ConsultarSistemaRJ(string codPrograma)
        {

            log.GravarLog("Sistema RJ", "");

            r.Espera("SELECIONE A OP", 17, 16, 29 );

            r.PutString("6", 17, 38);
            r.PutString("29", 17, 41);
            r.EnviaEnter();
            r.PutString(matricula, 8, 58);
            r.PutString(senha, 9, 58);
            r.EnviaEnter();

            **if (r.txTela.Contains("CEFSNP"))
            {
                login = false;
                MessageBox.Show("Login inválido!");
                return;
            }
            if (login == false)
            {
                Environment.Exit(0);
            }**

            r.Espera("PAS SIPAS", 11, 27, 35);

            r.PutString("PAS", 4, 15);
            r.EnviaEnter();
            r.PutString("001", 5, 15);
            r.EnviaEnter();

Comment: veja se ajuda: https://pt.stackoverflow.com/questions/205483/login-em-c-com-base-de-dados/205488#205488
Comment: a execução do `Application.Exit()` não é imediata, ele apenas sinaliza para o SO que a aplicação vai encerrar e depois encerra (qq coisa executando depois da linha irá executar), se o seu form for o principal da aplicação vc pode chamar `Close()` pra fechar o form e a aplicação irá encerrar
Answer: Descobri que era só colocar um return para parar o método(o que tinha nesse código acima), mas aí próximo método executava, o que ferrava tudo, pois o método anterior havia sido interrompido. Criei uma variável bool para que não executasse quando fosse false.


Merging two datasets by all possible ids in r

Question: I have two dataframes below:
df1 <- data.frame(id = c(11,22,33,44,55),
                  score = c(20,22,33,22,11))

df2 <- data.frame(id1 = c(11,22,NA,NA,8),
                  id2 = c(98,9,33,NA,24),
                  id3 = c(NA,NA,66,44,88),
                  id4 = c(NA,NA,NA,16,17))

> df1
  id score
1  11    20
2  22    22
3  33    33
4  44    22
5  55    11
> df2
  id1 id2 id3 id4
1   11  98  NA  NA
2   22   9  NA  NA
3  NA   33  66  NA
4  NA  NA   44  16
5   8  24   88  17

I need to merge the two datasets by id from df1 and four ids from df2. I also would like to keep any unmatched id s from the df1. How can I achieve the desired output as below at once?
df.merged <- data.frame(id = c(11,22,33,44,55),
                        score = c(20,22,33,22,11),
                        id1 = c(11,22,NA,NA, NA),
                        id2 = c(98,9,33,NA,NA),
                        id3 = c(NA,NA,66,44,NA),
                        id4 = c(NA,NA,NA,16,NA))

> df.merged
  id score id1 id2 id3 id4
1  11    20   11  98  NA  NA
2  22    22   22   9  NA  NA
3  33    33  NA   33  66  NA
4  44    22  NA  NA   44  16
5  55    11  NA  NA  NA  NA

Comment: Is there guaranteed to be at most one match in each row of `df2`?
Comment: yes, one variable is supposed to match for max.
Comment: But id `44` occurs twice in `df2`. Is this an error?
Comment: sorry, yes, corrected to 88.
Answer: You can paste together all the id's from df2, creating a regex pattern, then see where each pattern matches with rows of df1. I'd imagine that there is a simpler way to do this.
For each row rowwise(), paste all id's with "|" (regex or operator) in between. Then, remove extra NA's with str_remove_all("NA\\||\\|NA").
library(tidyverse)

df2_ids <- df2 %>%
  rowwise() %>% #for each row
  mutate(ids = across() %>% paste(collapse = "|") %>% str_remove_all("NA\\||\\|NA")) %>%
  pull(ids)

df2_ids
#> [1] "1|98|1|98" "2|9|2|9" "3|66|3|66" "4|16|4|16" "8|24|44|17|8|24|44|17"

Then, for each pattern, get which row of df1 matches it. If no match the length of the which(...) will be 0, and we save a NA.
df2$id <- df1$id[map_dbl(df2_ids, ~ which(grepl(.x, df1$id)) %>% {ifelse(length(.) >0,  ., NA)})]

Now, we have a suitable joining key, and can do a simple left_join (that keeps all rows of df1):
left_join(df1, df2, by = 'id')

This fails with a more complex case of df2, one where a row refers to multiple df1 rows. Below is a more general approach.
index <- map(df2_ids, ~ which(grepl(.x, df1$id)) %>% {`if`(length(.) >0,  ., NA)})

df2 <- df2 %>%
  uncount(map_dbl(index, length)) %>%
  mutate(id = df1$id[reduce(index, c)])

left_join(df1, df2)

Comment: thanks, I changed the id values since 1,2,3,4,5 could cause non matching patterns. can you run your solution for this updated id s please?
Answer: You can "semi-pivot" df2, so that there's one id column containing all ids while retaining columns id1 - id4, then join by id:
library(dplyr)
library(tidyr)

df2_semi_pivot <- df2 %>%
  mutate(across(id1:id4, .names = "{col}_pivot")) %>%
  pivot_longer(ends_with("pivot"), names_to = NULL, values_to = "id")

left_join(df1, df2_semi_pivot)

  id score id1 id2 id3 id4
1 11    20  11  98  NA  NA
2 22    22  22   9  NA  NA
3 33    33  NA  33  66  NA
4 44    22  NA  NA  44  16
5 55    11  NA  NA  NA  NA

Answer: i <- rowSums(array(match(unlist(df2), df1$id, 0L), dim(df2)))
i[duplicated(i) | !i] <- nrow(df2) + 1L
cbind(df1, rbind(df2, NA)[i,])
#>   id score id1 id2 id3 id4
#> 1 11    20  11  98  NA  NA
#> 2 22    22  22   9  NA  NA
#> 3 33    33  NA  33  66  NA
#> 4 44    22  NA  NA  44  16
#> 6 55    11  NA  NA  NA  NA


All possible values of $k$ such that $a\le k \le b$ and $k$ is a linear combination of a and b

Question: I am looking for a general rule for all possible integers $k\in(a,b)$ such that $k$ is can be expressed as a linear combination of $a$ and $b$.
I understand that k must be a multiple of $\gcd(a,b)$, since any linear combination of $a$ and $b$ will be a multiple of $\gcd(a,b)$. Is there a general formula for $k$ in terms of $a,b$?
Thanks in advance!
Comment: The reverse is also true : all the multiples of $(a,b)$ are expressible as such a linear combination . This follows from Bézout's theorem .
Comment: Could you elaborate what multiples of (a,b) mean? or did you mean gcd(a,b)? Because that's the answer I came up with too, as written in my answer below!
Comment: Yes , this is what I mean . Both notations are commonly used .It depends which you prefer .
Comment: Thanks for your reply! Now know the formal reasoning for what I was thinking!
Answer: With a little bit of thinking, I was able to answer it myself. It is actually quite obvious.
Since we know that k must be a multiple of gcd(a,b), and that a and b both are multiples of gcd(a,b)-
let gcd(a,b) be g. so, k includes all integers - a,a+g,a+2g,a+3g......,b-g,b.
And these are all the possible values of k!


Memcached - Single parent config, multiple child configs

Question: I am setting up a memcached server in production, and would like the ability to switch between various memory sizes simply by changing out a symlink from one config to another, however I do not want to copy and paste every config into every other config, is it possible to have a master config with multiple child configs?
Example:
# master config
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="128"
OPTIONS=""

# Name: memcached_256
# child config for cache server of 256
# include options from master config
CACHESIZE="256"

# Name: memcached_512
# child config for cache server of 512
# include options from master config
CACHESIZE="512"

Example dir listing:
ls /etc/sysconfig

memcached -> /path/to/my/version/controlled/configs/memcached_256

And if I ever need to upgrade, I can simply change the above symlink to:
memcached -> /path/to/my/version/controlled/configs/memcached_512

Then after changing out the symlink, simply restart the service. Or if there is a better way to accomplish this functionality, that would be appreciated as well.
Answer: It looks like those files are sourced by the initscript which starts memcached, and not read by memcached itself. You could therefore probably source the master configuration from the child configurations, for example:
/etc/sysconf/memcached_master:
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="128"
OPTIONS=""

/etc/sysconf/memcached_256:
. /etc/sysconfig/memcached_master
CACHESIZE="256"

/etc/sysconf/memcached_512:
. /etc/sysconfig/memcached_master
CACHESIZE="512"

And then symlink /etc/sysconfig/memcached to the child configuration you want to use.
Comment: Outstanding, this worked as described. I ended up symlinking the memcached_master to /etc/sysconfig so that way I would end up with a crazy path in the child config. Thanks for the help!


How do I list user defined types in a SQL Server database?

Question: I need to enumerate all the user defined types created in a SQL Server database with CREATE TYPE, and/or find out whether they have already been defined.
With tables or stored procedures I'd do something like this:
if exists (select * from dbo.sysobjects where name='foobar' and xtype='U')
    drop table foobar

However I can't find the equivalent (or a suitable alternative) for user defined types! I definitely can't see them anywhere in sysobjects.
Can anyone enlighten me?
Answer: Types and UDTs don't appear in sys.objects.
You should be able to get what you're looking for with the following:
select * from sys.types
where is_user_defined = 1

Comment: How can we get type's description (e.g. User Defined Table Type)?
Comment: @Naomi You can open Sql Server Management Studio then 1.go to your DB 2. expand [Programmability] 3. expand [Types] 4. expand [User-Defined table types] & you will see a list of your types.  See this image (https://i.stack.imgur.com/4HInu.png) for an example.
After that, right-click the UDT and a menu will pop up.  Select [Script User-Defined Table type as...] [Create to...] [New query editor]  A window will appear with the DDL (data definition language) which will show all the types that this UDT encompasses.
Answer: Although the post is old, I found it useful to use a query similar to this.
You may not find some of the formatting useful, but I wanted the fully qualified type name and I wanted to see the columns listed in order. You can just remove all of the SUBSTRING stuff to just get the column name by itself.
SELECT USER_NAME(TYPE.schema_id) + '.' + TYPE.name      AS "Type Name",
       COL.column_id,
       SUBSTRING(CAST(COL.column_id + 100 AS char(3)), 2, 2)  + ': ' + COL.name   AS "Column",
       ST.name                                          AS "Data Type",
       CASE COL.Is_Nullable
       WHEN 1 THEN ''
       ELSE        'NOT NULL'
       END                                              AS "Nullable",
       COL.max_length                                   AS "Length",
       COL.[precision]                                  AS "Precision",
       COL.scale                                        AS "Scale",
       ST.collation                                     AS "Collation"
FROM sys.table_types TYPE
JOIN sys.columns     COL
    ON TYPE.type_table_object_id = COL.object_id
JOIN sys.systypes AS ST
    ON ST.xtype = COL.system_type_id
where TYPE.is_user_defined = 1
ORDER BY "Type Name",
         COL.column_id

Answer: Original comment:
To expand on jwolly2's answer, here's how you get a list of definitions including the standard data type:
Edit in Comment:
I have just added an update to the Query aliasing/formatting to make the query more readable and updated the join key used to eliminate the need to filter out duplicate "system_type_id" values when "is_user_defined" = 0.
The idea here is that we can find information about types in the sys.types table.

When "is_user_defined" = 0, it is a built in type
When "system_type_id" matches "user_type_id" on the same record, it is a system type.
When "is_user_defined" = 1 the related system type will have the same "user_type_id" as the "system_type_id" on the user defined type
The "max_length" field refers to the max length in bytes (as opposed to characters - NVARCHAR(10) would be 20 / VARCHAR(10) would be 10)

Type Info Query:
SELECT  UserType.[name] AS UserType
        , SystemType.[name] AS SystemType
        , UserType.[precision]
        , UserType.scale
        , UserType.max_length AS bytes
            --This value indicates max number of bytes as opposed to max length in characters
            -- NVARCHAR(10) would be 20 / VARCHAR(10) would be 10
        , UserType.is_nullable
  FROM  sys.types UserType
      JOIN sys.types SystemType
          ON SystemType.user_type_id = UserType.system_type_id
             AND SystemType.is_user_defined = 0
 WHERE  UserType.is_user_defined = 1
 ORDER BY UserType.[name];

Comment: Why t2.name <> 'sysname'
Comment: @MuraliDharDarshan nvarchar and sysname share the system_type_id 231

More accurately we should be joining system_type_id from the t1(user defined type table) on user_type_id from the t2 (source type) table rather than excluding 'sysname'


Class instantiate 2 times on MainPage.xaml.cs

Question: I have a question. I'm working in a UWP application and i don't know how to use another class (external class _ViewModel) on my mainpage.xaml.cs. The class _vienmodel is already instantiate at the beginning of code (from App.xaml.cs class).
On the way that i do, i come 3 times on the constructor of my _viewmodel class :S
So when i come to the class MainPage.xmal.cs the value on my variable bras.Com.IsConnectionOk is false. But at the reality my variable is on true state.
Class MainPage:
namespace IHM_UWP
{
    ///
    /// Une page vide peut être utilisée seule ou constituer une page de destination au sein d'un frame.
    ///
    public sealed partial class MainPage : Page
    {
        public bool open = false;
        public bool close = false;
        /*public bool upAct = false;
        public bool downAct = false;
        public bool leftAct = false;
        public bool rightAct = false;*/

        private _ViewModel view = new _ViewModel(); // cette classe n'est pas bien implementé
        private Brush colorButton = new SolidColorBrush();

        public MainPage()
        {
            this.InitializeComponent();
            colorButton = Up.Background;

        }

        private void KeyDown_detect(object sender, KeyRoutedEventArgs e)
        {

            // si la connexion est établie alors on peut envoyer les trames pour les touches de direction
            if (view.Bras.Com.IsConnectionOk == true)
            {
                if (e.Key == Windows.System.VirtualKey.Up)
                {
                    // Effet visuel pour indiquer que l'on a cliqué sur la touche UP
                    Up.Background = new SolidColorBrush(Windows.UI.Colors.Green);
                    Down.Background = colorButton;
                    Left.Background = colorButton;
                    Right.Background = colorButton;
                    view.Bras.MoveArmUp();
                }
                if(e.Key == Windows.System.VirtualKey.Down)
                {
                    // Effet visuel pour indiquer que l'on a cliqué sur la touche DOWN
                    Down.Background = new SolidColorBrush(Windows.UI.Colors.Green);
                    Up.Background = colorButton;
                    Left.Background = colorButton;
                    Right.Background = colorButton;
                    view.Bras.MoveArmDown();
                }
                if (e.Key == Windows.System.VirtualKey.Right)
                {
                    // Effet visuel pour indiquer que l'on a cliqué sur la touche DOWN
                    Right.Background = new SolidColorBrush(Windows.UI.Colors.Green);
                    Up.Background = colorButton;
                    Left.Background = colorButton;
                    Down.Background = colorButton;
                    view.Bras.MoveArmRight();
                }
                if (e.Key == Windows.System.VirtualKey.Left)
                {
                    // Effet visuel pour indiquer que l'on a cliqué sur la touche DOWN
                    Left.Background = new SolidColorBrush(Windows.UI.Colors.Green);
                    Up.Background = colorButton;
                    Down.Background = colorButton;
                    Right.Background = colorButton;
                    view.Bras.MoveArmLeft();

                }
            }
        }
    }
}

Classe _ViewModel.cs:
namespace IHM_UWP
{
    public class _ViewModel : INotifyPropertyChanged
    {
        private GestionBras bras= new GestionBras(); //On peut ajouter cet instance dans la classe App.Xaml.cs?

        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged([CallerMemberName] string str = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(str));
            }
        }

        public _ViewModel()
        {

        }

        ///
        /// Commande pour lancer la connexion au bras
        ///
        private ICommand connect;

        public ICommand Connect
        {
            get
            {
                if (this.connect == null)
                    this.connect = new RelayCommand(() => this.Bras.ConnectAsync());
                return this.connect;
            }
        }

        ///
        /// Commande pour ouvrir la pince
        ///
        private ICommand ouvrirPince;

        public ICommand OuvrirPince
        {
            get
            {
                if (this.ouvrirPince == null)
                    this.ouvrirPince = new RelayCommand(() => this.Bras.OuvrirPince());
                return this.ouvrirPince;
            }
        }

        ///
        /// Commande pour fermer la pince
        ///
        private ICommand fermerPince;

        public ICommand FermerPince
        {
            get
            {
                if (this.fermerPince == null)
                    this.fermerPince = new RelayCommand(() => this.Bras.FermerPince());
                return this.fermerPince;
            }
        }

        // Class intermedaire pour la gestion de binding
        public GestionBras Bras { get => bras; set => bras = value; }

    }
}

Class EnvCoord.xaml.cs:

namespace IHM_UWP
{
    ///
    /// Une page vide peut être utilisée seule ou constituer une page de destination au sein d'un frame.
    ///
    public sealed partial class EnvCoord : Page
    {
        string xcoord = string.Empty;
        string ycoord = string.Empty;
        string zcoord = string.Empty;

        private _ViewModel view = new _ViewModel();

        public EnvCoord()
        {
            this.InitializeComponent();
        }

        private void CloseWindow(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(MainPage));
        }

        private void EnvoyerCoord_Click(object sender, RoutedEventArgs e)
        {
            xcoord = CoordX.Text;
            ycoord = CoordY.Text;
            zcoord = CoordZ.Text;

            view.Bras.SendCoorGeom(xcoord, ycoord, zcoord);

            Frame.Navigate(typeof(MainPage));

        }

    }
}

Class App.xaml.cs:
namespace IHM_UWP
{
    ///
    /// Fournit un comportement spécifique à l'application afin de compléter la classe Application par défaut.
    ///
    sealed partial class App : Application
    {
        public IHM_UWP._ViewModel view = new IHM_UWP._ViewModel();

        ///
        /// Initialise l'objet d'application de singleton.  Il s'agit de la première ligne du code créé
        /// à être exécutée. Elle correspond donc à l'équivalent logique de main() ou WinMain().
        ///
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        ///
        /// Invoqué lorsque l'application est lancée normalement par l'utilisateur final.  D'autres points d'entrée
        /// seront utilisés par exemple au moment du lancement de l'application pour l'ouverture d'un fichier spécifique.
        ///
        /// <param name="e">Détails concernant la requête et le processus de lancement.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Ne répétez pas l'initialisation de l'application lorsque la fenêtre comporte déjà du contenu,
            // assurez-vous juste que la fenêtre est active
            if (rootFrame == null)
            {
                // Créez un Frame utilisable comme contexte de navigation et naviguez jusqu'à la première page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: chargez l'état de l'application précédemment suspendue
                }

                // Placez le frame dans la fenêtre active
                Window.Current.Content = rootFrame;
            }

            if (e.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    // Quand la pile de navigation n'est pas restaurée, accédez à la première page,
                    // puis configurez la nouvelle page en transmettant les informations requises en tant que
                    // paramètre
                    rootFrame.Navigate(typeof(MainPage), e.Arguments);
                }
                // Vérifiez que la fenêtre actuelle est active
                Window.Current.Activate();
            }
        }

        ///
        /// Appelé lorsque la navigation vers une page donnée échoue
        ///
        /// <param name="sender">Frame à l'origine de l'échec de navigation.</param>
        /// <param name="e">Détails relatifs à l'échec de navigation</param>
        void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
        }

        ///
        /// Appelé lorsque l'exécution de l'application est suspendue.  L'état de l'application est enregistré
        /// sans savoir si l'application pourra se fermer ou reprendre sans endommager
        /// le contenu de la mémoire.
        ///
        /// <param name="sender">Source de la requête de suspension.</param>
        /// <param name="e">Détails de la requête de suspension.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            // Remettre tous les moteurs à leur position initial
            for (int i = 0; i < view.Bras.Moteur.Length; i++)
            {
                view.Bras.InitialPosition(view.Bras.Moteur[i].Num_pin);
            }

            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: enregistrez l'état de l'application et arrêtez toute activité en arrière-plan

            deferral.Complete();
        }
    }
}

How i can do to recover the _ViewModel class (with all the updated variables values) from my App.xaml.cs? I need to use _viewmodel on the Envcoord.xaml.cs and on my mainpage.xaml.cs
Thanks in advance :)
Comment: So you clearly instantiate _ViewModel class 3 times - in App.xaml.cs, in Envcoord.xaml.cs and in Mainpage.xaml.cs. To reuse same instance of your viewmodel, you have either to provide it through Dependency Injection or make it a static property in some class and just call to it from those pages.
Comment: Thanks but can you give me an example?
Comment: Make `view` property in App.xaml.cs as `public static IHM_UWP._ViewModel view = new IHM_UWP._ViewModel()`. And then remove `view` property from Envcoord.xaml.cs and Mainpage.xaml.cs and use that static property from your App class directly where you need it - i.e. `App.view.Bras.SendCoorGeom(xcoord, ycoord, zcoord)`.
Comment: But note, that using static properties usually indicates poor application design. Its way better to introduce some DI framework into your project and manage shared resources using services with different lifetime scopes. But unfortunately, can't help you with example how to do i this way, because it is not a 5 minute work to do.
Comment: Thank you i apply as you tell me to do, but this is not working because `this.InitializeComponent();` on the MainPage.xaml.cs calls once the _ViewModel Class. my value of `App.view.Bras.Com.IsConnectionOk` is still to false even if it change
Comment: Maybe that is sync issues, so connection is opened after `InitializeComponent()` is called? Because it looks like connection is opened in `async` manner.
Comment: Yes connection is open when i click on a button so it is not launched before Initializecomponent
Comment: So is `App.view.Bras.Com.IsConnectionOk` working correctly inside `KeyDown_detect` handler in MainPage.cs ?
Comment: no is not working. I launch my application and _viewmodel is call two times. when i launch the connection my variable IsConnectionOk change to true, but when i verified this value on my class MainPage.xaml.cs `App.view.Bras.Com.IsConnectionOk` it is false :/
Comment: If `_viewmodel` constructor is called twice, than you still have some multiple instances instead of using static property from `App` class. Search for `_viewmodel` constructor usages and make sure it is only instantiated once in `App` class.
Answer: Instead of creating a new instance in MainPage and EnvCoord, you should use the instance that you have already created in App.xaml.cs. You can access it using the App.Current property:
public sealed partial class EnvCoord : Page
{
    string xcoord = string.Empty;
    string ycoord = string.Empty;
    string zcoord = string.Empty;

    private readonly _ViewModel view;

    public EnvCoord()
    {
        this.InitializeComponent();
        view = (App.Current as App).view;
        DataContext = view;
    }

    private void CloseWindow(object sender, RoutedEventArgs e)
    {
        Frame.Navigate(typeof(MainPage));
    }

    private void EnvoyerCoord_Click(object sender, RoutedEventArgs e)
    {
        xcoord = CoordX.Text;
        ycoord = CoordY.Text;
        zcoord = CoordZ.Text;

        view.Bras.SendCoorGeom(xcoord, ycoord, zcoord);

        Frame.Navigate(typeof(MainPage));

    }
}

Comment: Thanks but is the same solution proposed by Yura but this is not working, i think my program instantiate twice my _ViewModel constructor but i don't know why. when i execute in my MainPage.xaml.cs `this.InitializeComponent();` it calls the _Viewmodel class but i don't know why
Comment: @AnnyVivas: Of course it's working. If an instance of your view model is created on `InitializeComponent()` you probably create another instance of the view model in your XAML markup: ``. You should not do this.
Comment: ohhhhh yes i have this on my MainPage.xaml :/. so i should delete this part of code of my MainPage.xaml? `

`      On this line: `view = (App.Current as App).view;` (MainPage.xaml.cs) "view" after point, is initialized on the app.xaml.cs class as? how? in propfull mode? or `public static IHM_UWP._ViewModel view = new IHM_UWP._ViewModel()`
Comment: Yes, and set the `DataContext` of the view in the constructor as per my edited answer: `DataContext = view;`


showing that cos(y)-cos(x)=2*sin((x+y)/2)*sin((x-y)/2)

Question: how can one show that $\cos(y)-cos(x)=2sin(\frac{x-y}{2})sin(\frac{x+y}{2})$ by just using trigonometrical equalities like additional theorems?
I was trying to show it by rewriting $cos(y)=cos(0.5y+0.5y)$ and then using the additional theorems, but somehow I do not have the result, that is needed.
Starting on the righthandside wasn't successfull either.
Thanks for helping
Comment: Maybe start with $\cos(s+t)=\cos s\cos t-\sin s\sin t$ and $\cos(s-t)=\dots$ and let $x=s+t$ and $y=s-t$.
Comment: @eur2718 Took a small spelling mistake out because I misswallowed my soda due to reading that...:)
Answer: I think the easier way to do it is by working with the right hand side, instead of the left hand side, making use of the addition formula for sine:
$$\begin{eqnarray}2\sin\left(\frac{x-y}{2}\right)\sin\left(\frac{x+y}{2}\right) &=& 2\left(\sin\left(\frac{x}{2}\right)\cos\left(\frac{-y}{2}\right)+\cos\left(\frac{x}{2}\right)\sin\left(\frac{-y}{2}\right)\right)\\
&&\times\left(\sin\left(\frac{x}{2}\right)\cos\left(\frac{y}{2}\right)+\cos\left(\frac{x}{2}\right)\sin\left(\frac{y}{2}\right)\right)\end{eqnarray}$$
Since cosine is even and sine is odd, we can simplify this to
$$2\left(\sin\left(\frac{x}{2}\right)\cos\left(\frac{y}{2}\right)-\cos\left(\frac{x}{2}\right)\sin\left(\frac{y}{2}\right)\right)\\\left(\sin\left(\frac{x}{2}\right)\cos\left(\frac{y}{2}\right)+\cos\left(\frac{x}{2}\right)\sin\left(\frac{y}{2}\right)\right)$$
This is just the difference of two squares, so we get
$$2\left(\sin^2\left(\frac{x}{2}\right)\cos^2\left(\frac{y}{2}\right)-\cos^2\left(\frac{x}{2}\right)\sin^2\left(\frac{y}{2}\right)\right).$$
Since $\sin^2x+\cos^2x=1$, we can rewrite this slightly as
$$2\left(\sin^2\left(\frac{x}{2}\right)\left(1-\sin^2\left(\frac{y}{2}\right)\right)-\cos^2\left(\frac{x}{2}\right)\sin^2\left(\frac{y}{2}\right)\right)$$
Expanding, we get
$$2\sin^2\left(\frac{x}{2}\right)-2\left(\sin^2\left(\frac{x}{2}\right)+\cos^2\left(\frac{x}{2}\right)\right)\sin^2\left(\frac{y}{2}\right)$$
We can see that the inner term has the Pythagorean identity so we can replace it with $1$ to get
$$2\sin^2\left(\frac{x}{2}\right)-2\sin^2\left(\frac{y}{2}\right)$$
Since $\cos(2x) = 1-2\sin^2(x)$, the above simplifies to exactly what we want.
Comment: You're very welcome :)


Equation involving fields

Question: Let $ K $ be a field and $f:K-\left \{ 0 \right \}\rightarrow K-\left \{ 0 \right \}$ a function with $f(f(x))=x^{-1},\forall x\in K-\left \{ 0 \right \}$ and $ f(1)\neq 1.$
Knowing that $ f^{2}(x)-f(x)+1=0 $ has an unique solution in $K-\left \{ 0 \right \} $, determine $ f(2)$.
I haven't found something useful yet.
Comment: so $f^2(x)$ is $f(x)^2$ in this context right?
Comment: Yes, it's $ f(x)^2 $.
Comment: $f$ is bijective.
Comment: I think that I proved that any field in which $x^2-x+1$ has only one root must have characteristic $2$, so $2=0$.
Comment: nevermind, the characteristic was $3$.
Comment: for an example consider $\mathbb Z_3$ and the function $f(x)=-x$
Answer: Suppose that $a$ is a root of the polynomial $x^2-x+1$.
Then $(x-a)$ divides the polynomial $x^2-x+1$.
This means that $(x-a)(x-a)=x^2-x+1$ (because the root is unique).
it follows that $x^2-2a+1=x^2-x+1$ and so $2a=1$ and $a^2=1$.
we conclude that $1=1^2=(2a)^2=4a^2=4$.
So the field must have characteristic $3$, and so $2=-1$.
Let $z=f(1)$. Notice $z^{-1}=f(f(z))=f(f(f(1))=f(1)=z$. It follows that $z^2=1$. The only two roots of the polynomial $x^2-1$ are $1$ and $-1$. We conclude $z=-1$.
So we have $f(1)=-1$, and since $1=f(f(1))=f(-1)$ we have $1=f(-1)=f(2)$.
Comment: Yeah I just got that, so $f(1)=-1$ and then $f(-1)=1$.
Comment: doesn't it follow $x^2-x+1=(x-a)(x-c)$?
Comment: I think 1 = 4 means that char $K$ is $3$ not $2$.
Comment: oh yeah, good point.
Comment: How does that help finding $f(2)$?
Comment: @SSepehr thanks for the help, that did the trick!
Comment: @EugenCovaci I think the OP means a field as in mathematics, these ones are always commutative. Maybe you are thinking of the fields where horses run around and stuff?
Comment: If $ 2a=1 $ and $ a^{2}=1 $ multiplying the first relation with $ a$, we get that $ 2a^{2}=a\Leftrightarrow 2=a $, so $f(2)=0$. It's correct, isn't it?
Comment: @ztefelina I don't see how you conclude $f(2)=0$ from $2=a$. (although the other steps look good)
Comment: That's because $ a$ is a root of $f^{2}(x)-f(x)+1$.(or $f(a)$ is a root of $x^2-x+1$).
Comment: Well, something is wrong with your reasoning. I proved $f(2)=1$. And there is an example of a función that works in the comments.
Comment: Its not clear how you finish to show $f(-1)=1$.
Comment: @ReneSchipperus let $z=f(1)$, we have $f(f(z))=f(f(f(1))=f(1)=z$. We conclude $z=z^{-1}$ and so $z^2=1$. The only other element satisfying this is $-1$.
Comment: Oh, I made a mistake in my "proof"..You're right. :)
Comment: yeah, I got a bit confused, but hopefully it's good now. Thanks for the improvements.

Equation involving fields


VBScript - Can we find out duration with seconds through code

Question: I have time in seconds... Like below
set seconds = 180 seconds
set seconds1 = 1500 Seconds
set seconds2 = 600 Seconds

based on above values output like below
duration = 00:03:00
duration = 00:25:00
duration = 00:10:00

like i need through VBscript pls help me
Comment: Combine [this](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/formatdatetime-function) with [this](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/datediff-function)?
Answer: You can manually build your HH:MM:SS string by dividing the total number of seconds into hours and minutes:
Function FormatSeconds(p_lngSeconds)

    Dim sReturn
    Dim lngTotalSeconds
    Dim iHours
    Dim iMinutes

    ' Copy value from parameter
    lngTotalSeconds = p_lngSeconds

    ' Calculate number of hours
    iHours = Int(lngTotalSeconds / (60 * 60))

    ' Subtract from total seconds
    lngTotalSeconds = lngTotalSeconds - (iHours * 60 * 60)

    ' Calculate numer of minutes
    iMinutes = Int(lngTotalSeconds / 60)

    ' Subtract from total seconds
    lngTotalSeconds = lngTotalSeconds - (iMinutes * 60)

    ' Build string
    sReturn = iHours & ":" & Right("0" & iMinutes, 2) & ":" & Right("0" & lngTotalSeconds, 2)

    FormatSeconds = sReturn

End Function

Going back to your question, you'd use this function thusly:
duration = FormatSeconds(seconds)

Comment: @RajuRaj a vbscript function can return anything. However, not every operation works on any data type, so when you use the return value from a function (or any value, in fact), you must take that into account. For example, you can multiply a number, but not a string (obviously). Note that VBScript is loosely typed, meaning that you do not beforehand specify the type of a variable, nor the return type of a function..
Comment: This function calling syntax is works in vbscript?
Comment: vbscript function return only boolean value like true or false only am i right?? if we return any string or in getting error like "Type mismatch"


How to login first time in the login panel

Question: I have finally managed to install aegir on a vps.
I have also set the dns of my domain and I can i can finally see my login panel.
The problem is that I don't have username and password.
The documentation says I should have a temporary link to set the password but I can't find that temporary link.
I tried to reset the password but obviously I can't receive any mail because I have never done any login so far.
There is any file that I can check to find username and password please?
Answer: You can always generate another temporary login link.  This recipe will log you into the VM, switch you to the Aegir user, and then generate the link.

ssh aegir.example.com
sudo -sHu aegir
drush @hostmaster user-login

The output will be a URL, which you can open in your browser.
Comment: Thank you so much, many many thanks   it works perfectly


Why is ethernet payload less than wifi payload

Question: Why is ethernet payload (which is 1500 bytes) less than 802.11 payload (which is 2272 bytes)? Given Ethenet has a more reliable medium.
Comment: You mean [MTU](http://en.wikipedia.org/wiki/Maximum_transmission_unit)? (Also consider adding practical background to your question, generally historical research is not  exactly on-topic for SO).
Comment: Hi, thank you for your answer. I'm studying electrical engineer and learning about layers of internet. When I reached Network Layer, the payload or the MTU as you said, according to the book, the MTU is less than 802.11. Hence, I was just curious why so
Answer: Probably historical reasons, ethernet was used with slow dial-up modems a 1500 bytes will occupy for about 1 second a 14.4kbps ethernet line.
When 802.11 was first introduced minimum speed was 1Mbps (over 70 times faster than 14.4kbps) hence larger MTU can be used without hogging the network.
Not sure where you got your numbers from, WiFi MTU can be larger (7981)


What's the notation for a function continuous in its domain?

Question: Suppose I have a function that is continuous in every point of its domain, but its domain is only a subset of the real numbers (for example $\mathbb{R}-\{1\}$). Can I say that the function is continuous in $\mathbb{R}$? If not, what's the best way to express it?
Comment: What is wrong with "continuous in its domain" or even just "continuous"?
Comment: continuous **on** its domain. No, you can't say it's "continuous on $\mathbb{R}$" because its domain is *not* $\mathbb{R}$. And "continuous *in* $\mathbb{R}$", or even "continuous *in* its domain", just sounds funny.
Comment: If you could say that it is continuous on $\mathbb R$ then where would it stop? You could say e.g. that it is continuous at $\mathbb C$ as well.
Answer: A function is well defined only if there are specified its domain and codomain. So, usually, to say that a function is continuous means that it is continuous on its domain , and this domain can well be a proper subset of $\mathbb{R}$.
Answer: You'd say that "f is continuous on its domain". No, you can't say that your example function is "continuous on $\mathbb{R}$" because its domain is not $\mathbb{R}$ – it omits 1. And "continuous in $\mathbb{R}$", or even "continuous in its domain", in general just sounds funny.
Comment: Thanks. I didn't know that the correct word is "on" because english is my second language, so thanks for that also.
Comment: English is a nightmare when it comes to these. You do something _at_ 7:00, _on_ Tuesday, _in_ October. Makes no sense.
Comment: @Akiva Weinberger  Haha I have to agree. I hadn't noticed that blizzard of prepositions -- my sympathies to anyone learning it. Not to mention spelling, which hasn't been revised since the Renaissance (5 different pronunciations of words ending in "-ough").


What is $\sum_{i=1}^m\sum_{j=i+1}^n \frac{1}{j}$

Question: What is $$\sum_{i=1}^m\sum_{j=i+1}^n \frac{1}{j}$$?
What I did
I know that
\begin{align*}
&\sum_{i=1}^m\sum_{j=i+1}^n \frac{1}{j}\\
&=\sum_{i=1}^m\sum_{j=i+1}^n \frac{1}{j}+\sum_{i=1}^m\sum_{j=1}^i \frac{1}{j}-\sum_{i=1}^m\sum_{j=1}^i \frac{1}{j}\\
&=\sum_{i=1}^m\sum_{j=1}^n \frac{1}{j}-\sum_{i=1}^m\sum_{j=1}^i \frac{1}{j}\\
&=m H_n-\sum_{i=1}^m\sum_{j=1}^i \frac{1}{j}\\
\end{align*}
but how to compute $\sum_{i=1}^m\sum_{j=1}^i \frac{1}{j}$?
I have some what related question here Find $\sum_{i=[1,\ldots,n], j=[1,\ldots,m]: i\neq j }\frac{1}{j}$
Answer: Hint: $$
\sum_{i=1}^m \sum_{j=1}^i \frac 1j =
\sum_{j=1}^m \sum_{i=j}^n \frac 1j =
\sum_{j=1}^m (m-j+1) \frac 1j = (m+1)H_m - m
$$
Comment: By the way you mean $m$ not $n$ in your answer, right?
Comment: I will accepted. The sysmtem tells me I have to wait 5 min.
Comment: Do you think I Should I assume that $n \ge m$ in my result?
Comment: @Boby why is that?
Comment: Actually, never mind. The result holds for any $n$ and $m$. Thank you for your help.


Do key signatures indicate changes in tablature fret numbers?

Question: I have a tab book for "Black Sabbath" and the song "Iron Man" for example, it has a key signature of bbb. I know this song is played in standard E tuning, and eg the main riff starts with a B + F# power chord on fret 2 string 5. However, the book I have seems to have all the fret numbers bumped by 1, as though the guitar were downtuned a half-step.
Is it normal for key signature changes to modify what a tablature shows, or is this tab book wrong?
The book is "Black Sabbath Anthology" ISBN-13: 978-0-8256-1084-4 by Amsco Publications, for reference; attached is a photo of the 1st page.
Comment: I think you mean three flats (not 'bbb'), which is the key of Eb major/C minor. Starting the riff on the third fret of that string (C) is appropriate for that key signature. If the song is actually in another key (regardless of how close it is to Eb/Cm), then the tab will change.
Comment: Most songs can be played in multiple places in the same key.  Also, the guitar can be tuned differently thus making the true notes map to different frets than you are used to.
Comment: Yes 3 flats... but I know this song is played in standard E tuning so that's where I get confused. There's nothing to indicate downtuning in the tab.
Comment: The version of the main riff in your book clearly doesn't start with "a B + D power chord".
Comment: Yes sorry I meant `B+F#` (str 5 fr 2, st 4 fr 4), but it's indicating `C+G` (str 5 fr 3, st 4 fr 5). The song is definitely played in the former. The tab is wrong.
Answer: Tab in itself has no direct reference to keys, key signatures or note names. There no need. It purely tells the reader where, on which fret of which string, to place fingers.
The key itself is a separate entity, and if a key changes, or there's an accidental note, it's shown directly as a different number , maybe on a different string, in the tab.
The factor to watch is the letter names at the beginning of the tab - not always EADGBe, or sometimes the legend - 'tune down a semitone to Eb', etc,
Better quality tab will have a stave as well, which helps with timing, and can occasionally clarify discrepancies in tab numbers.
Comment: That doesn't mean a great deal.  Tab is sometimes not as good or as accurate as it should be, and things like the band has downtuned might miss the tab writer's attention. Reference to the original track is the best solution, and working things out without relying on possibly unreliable tab will benefit in the future.
Comment: There is nothing to indicate downtuning.
Comment: So the tab is wrong?
Comment: Now that it's visible - no.
Comment: But it's literally the wrong note at those frets in standard tuning. I'm also confused: at the top of the tab it has chord description; the F5 shows the root note on fret 9 (indicating downtuning half a step), but the E5 root note is fret 7 (indicating normal tuning).
Comment: At the top, the chord windows, there is a space after the E chord. My guess is there should be a flat sign between the E and the 5. The F5 is shown on fret 8. Damn! My flat signing doesn't work in comments!!
Comment: The first fret shown in the diagram is fret 8, but the one indicating the root note is 9. Still, a missing `#` makes sense in the `E#5` and would indicate the guitar is downtuned.
Comment: There's a 2 fret difference, and there's a 2 fret difference between F and **Eb**.


What is the Guava equivalent of Scala's flatMap?

Question: Looking through https://github.com/google/guava/wiki/FunctionalExplained I see operations like transform, which will transform a list but keep the same cardinality. How can I perform a transform that results in a different cardinality? e.g. (pseudocode) List(1,2,3).transform(i => List(i, i)) -> List(1,1,2,2,3,3)
Comment: Since when is valid Scala a pseudocode? :)
Comment: @Natix I think Scala is actually more flexible in terms of syntax than pseudocode :)
Answer: As of version 13, there is transformAndConcat on FluentIterable.
Answer: I don't think there's a direct translation, but transform followed by concat should be equivalent.
Answer: In Eclipse Collections, collect() is the equivalent of Scala's map(), and flatCollect() is the equivalent of Scala's flatMap().
Here is an example usage of flatCollect with Java 8 Lambdas.
Note: I am a committer for Eclipse Collections.
Answer: Pay attention to one thing, though: Scala's map methods return new collections, while the transform() method in Guava returns a transformed view of the original collection. This is a very subtle difference. You need to decide whether the 'view over original collection' is appropriate for your context.


asp.net - ajax drop drag proplem

Question: i have a dragable "li" and i use ajax with asp.net. When I start the page drop-drag is working, but when I click the button it doesn't. How can I solve it? All help will be appreciated.

asp.net - ajax drop drag proplem


Schedule reboot at the specified time

Question: How to schedule a Windows server to reboot at a specified time?
It's about a Windows Server 2003 and Windows Server 2008.
Answer: The easiest way to schedule a simple reboot is to use the AT command along with the shutdown command from the command line.
For example, if you want the server to restart tonight at 2AM, it can be as simple as this:

at 2:00 shutdown /r /f

What the "AT" command does is automatically create a scheduled task for a certain command. It has a ton of parameters that you can specify to repeat it, but by default it'll just run whatever command you specify at the next instance of whatever time you specify.
If you need to change anything after you issue it, you can just go into Administrative Tools > Scheduled Tasks and modify the task.
Comment: Apparently this has been deprecated in Server 2012
Answer: Make a scheduled task that runs:
shutdown -r -t 01

Comment: If the task is scheduled to run once, there is a "delete this task if it is not scheduled to run again" checkbox under the Settings tab of the scheduled task properties window.  The scheduler will remove the task after it has run if not scheduled again.  Not sure how that will work in the case of a server reboot, though it is theoretically possible.
Comment: Can the scheduled task delete itself when the task is done?
Comment: Can't delete itself, but you can setup a one-time trigger so it'll only run once.
Comment: Or, if it is a one-time affair, use the /t xxx to set the shutdown to the desired future time. The delay value can be up to 10 years. (But since it is expressed in seconds, having a very long delay calls for a bit of calculus.)
Answer: I know this doesn't solve your whole problem but for versions of Windows Server since 2008, and in cases where you only need the server to reboot once, you don't need to bother with scheduled tasks. The built in shutdown command lets you specify a delay in seconds using the the -t parameter.
Eg, to restart in 12 hrs (or 43200 seconds):
shutdown -r -t 43200

Obviously to get a specific time you'll need some simple maths but it's a lot easier than messing around with scheduled tasks.
Comment: Is it possible (without script logging or similar) to get the state of such a command after it has been issued? That the time remaining until reboot is 3hrs, for instance?
Comment: @ErikE, The only way I know if is to issue to `shutdown -a` command which aborts the current shutdown. If no shutdown was scheduled, you'll get an error instead. I don't think it tells you *when* it was scheduled for though, and if you actually did want a shutdown you'll need to recreate it... so not ideal.
Answer: Try this guide (XP centric but should get you in the right direction)
http://www.electronics.dit.ie/techsupport/Green/How%20to%20schedule%20windows%20XP%20to%20shutdown.doc

Schedule reboot at the specified time


remove IIS 7 redirects

Question: I am trying to debug an IIS server that keeps redirecting *.html files to *.aspx...
it sends the following html in response to url.html:
<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <title>website title redirected</title>
    <META http-equiv="refresh" content="0;URL=url.aspx">
</head>
<body>
</body>
</html>
</code>
Where can i find the rules that dictate this?
Answer: Open IIS, look at properties for default website and look at document types (tab I think). There should be a list of default pages (i.e. default.html, default.aspx, etc.) If not there then there is a redirect option in the properties for each site. Check that and make sure its not redirecting from there.

remove IIS 7 redirects


Weird limit $\lim \limits_{n\mathop\to\infty}\frac{1}{e^n}\sum \limits_{k\mathop=0}^n\frac{n^k}{k!} $

Question: $$\lim \limits_{n\mathop\to\infty}\frac{1}{e^n}\sum \limits_{k\mathop=0}^n\frac{n^k}{k!} $$
I thought this limit was obviously $1$ at first but approximations on Mathematica tells me it's $1/2$. Why is this?
Comment: Very heuristically speaking, stopping the summation at $\frac{n^n}{n!}$ is stopping at the maximal summand, so it is somewhat reasonable to expect that the contribution up to that summand might be about the same as the contribution of the remaining summands.
Comment: This looks like a duplicate of [this question](http://math.stackexchange.com/q/160248).
Comment: @HagenvonEitzen. Good point, indeed ! Cheers.
Comment: This exact same question has been asked before here on this site.
Comment: Well if they made it easy to search for questions then that wouldn't be a problem.
Comment: It is well-known as the Bernstein limit.
Comment: It is more or less the probability that a Poisson-distributed random variable takes a value less than its mean.
Answer: You made a mistake since the summation goes to $n$ and not to infinity; then $$\sum \limits_{k\mathop=0}^n\frac{n^k}{k!} \neq e^n$$ In fact $$\sum \limits_{k\mathop=0}^n\frac{n^k}{k!}=\frac{e^n \Gamma (n+1,n)}{\Gamma (n+1)}$$ and so the limit you look for is then the limit of $\frac{\Gamma (n+1,n)}{ \Gamma (n+1)}$ when $n$ goes to infinity and this limit is $\frac{1}{2}$ as Mathematica told you.
Comment: Thanks. I wonder if there is an elementary way, without the gamma function.
Answer: In this answer, it is shown that
$$
\begin{align}
e^{-n}\sum_{k=0}^n\frac{n^k}{k!}
&=\frac{1}{n!}\int_n^\infty e^{-t}\,t^n\,\mathrm{d}t\\
&=\frac12+\frac{2/3}{\sqrt{2\pi n}}+O(n^{-1})
\end{align}
$$


Is $S_5$ generated by (1 3) and (1 2 3 4 5)?

Question: I proved that $S_4$ is not generated by $(1 \ 3)$ and $(1 \ 2 \ 3 \ 4)$, using that the partition $A = \{ \{ 1, 3 \}, \{ 2, 4 \} \}$ is invariant under the action of the elements of $\left \langle (1 \ 3), (1 \ 2 \ 3 \ 4) \right \rangle$, but if we take a permutation $\sigma \notin \left \langle (1 \ 3), (1 \ 2 \ 3 \ 4) \right \rangle$, for example $\sigma = (1 \ 2)$, then $\sigma A \ne A$. I tried to use the same reasoning for $S_5$, taking a partition $P = \{ \{1, 3 \}, \{ 2, 4, 5 \} \}$ and I got that $P$ is invariant under the action of $(1 \ 3)$, but isn't invariant under the action of $(1 \ 2 \ 3 \ 4 \ 5)$, that is, $(1 \ 2 \ 3 \ 4 \ 5)P \ne P$. Any tips to help me?
Comment: Anticipate that $S_p$, for $p$ prime, is generated by any $p$-cycle and any $2$-cycle... :)
Comment: Conjugating $(1~3)$ by a few powers of the $5$-cycle gets you an awful lot of transpositions.  I think it's quite likely that those two elements generate $S_5$.  Ask yourself, for instance, whether $S_5$ can have any subgroups of order $20$.
Comment: The complementary argument that proves a big generalisation of what you're trying to prove is given [here](https://math.stackexchange.com/q/64848/473276) and [here](https://math.stackexchange.com/q/515149/473276). But in this case I'd guess you're suppose to just get your hands dirty a bit, like Robert Shore suggests.
Comment: $(1,2,3,4,5)^2 = (1,3,5,2,4)$.
Answer: Start by recalling that, for $\sigma,\tau\in S_n$,
$$\tau=(a_1,a_2,...,a_k) \implies \sigma\tau\sigma^{-1} = (\sigma(a_1),\sigma(a_2),...,\sigma(a_k))$$
For example, setting $\sigma=(1\ 2\ 3\ 4\ 5)$ and $\tau=(1\ 3)$, we have
$$\tau=(1\ 3),$$
$$\sigma\tau\sigma^{-1}=(2\ 4),$$
$$\sigma^2\tau\sigma^{-2}=(3\ 5),$$
$$\sigma^3\tau\sigma^{-3}=(4\ 1),$$
$$\sigma^4\tau\sigma^{-4}=(5\ 2)$$
So, within $\langle \sigma,\tau \rangle$ we are able to transpose all elements at a distance of $2$ in either direction. This means that we can also transpose all elements at a distance of $2k, k\in\mathbb{Z}$, since of course
$$s_1=(i,\ i+2), s_2=(i+2,\ i+4)\implies s_1s_2s_1 =(i,\ i+4)$$
But in $\mathbb{Z_5}$, a distance of 4 in one direction is equal to a distance of 1 in the other, so we can now also swap any adjacent elements. Therefore the set of all adjacent transpositions is inside $\langle \sigma,\tau \rangle$, and so $S_5\subset \langle \sigma,\tau \rangle$, and we are done.
Note: The reason this didn't work in $S_4$ is that moving in a distance of $2k$ in either direction doesn't allow you to reach every element the same way it does in $S_5$.


SFTP: How to keep data out of the DMZ

Question: We are investigating solutions to the following problem:
We have external (Internet) users who need access to sensitive information. We could offer it to them via SFTP which would offer a secure transport method.
However, we don't want to maintain the data on server as it would then reside in the DMZ.
Is there an SFTP server that has "copy on access" such that if the box in the DMZ were to be compromised, no actual data resided on that box?
I am envisioning an SFTP Proxy or SFTP passthrough.  Does such a product exist currently?
Comment: You want a server that can asses sensitive data, unless it's comprimised, at which point it should no longer be able to access the data? How are you envisioning accessing the data (SMB, NFS, etc)? Are you looking for SFTP or FTPS; or open to either?
Comment: SFTP:  I'm envisioning a public SFTP server that stores no data locally.  When a user lists the files he has access to, the listing would be generated from a listing of an internal server.  When a user selects to retrieve a file, the SFTP would stream the data from an internal server. At the OS level of the SFTP server there would be no "directory" to list and no files to view.
Answer: Sounds like using HTTPS rather than SFTP would be the way to go. Run an HTTP proxy on a DMZ server and keep the data on an internal web server. If a user compromises the DMZ server and gets a shell they won't have access to the data. They will find out about the proxy but if you use basic auth they won't be able to access the data.
Comment: An SFTP proxy would achieve the same level of security.  Feel free to choose the underlying protocol that best suits your users.
Answer: Globalscape EFT server with the DMZ gateway does exactly what you are asking for
http://globalscape.com/eft/
Comment: thank you for answering the question that was asked.... Sorry it took me 2 years to select your answer
Answer: If you want to transfer restricted data to the Internet, the solution is not necessarily to give them access to the restricted network segment via the Internet.  In fact, I would strongly discourage it as you describe it.  What you ask is actually quite complicated to implement in a responsible manner.
For illustration, you have two network segments.  A DMZ and a private network.  Databases live in the private and Web servers live in the DMZ.  For security purposes, you fully restrict access to and from the private network using a firewall.  If the DMZ is compromised and the authentication data is stored on the server, the cracker will be able to access the restricted data.
This is where encryption requirements and key management techniques come in to place, which are exampled within the PCI DSS.  If you do not have an advanced encryption architecture, you will still risk the data in case of compromise even if it is not stored in the DMZ.
You could potentially implement a ETL and batch out the data.  Often, this solution dictates a need to have the data encrypted using strong encryption and then transferring via your preferred protocol.  Once the data is encrypted, the methods used to transfer it can be substantially more flexible.
Your exact situation is going to dictate how much effort is made to establish a production worthy solution.  If you a dealing with a one-off request, you might be best off manually satisfying it via a tool such as GnuPG.  Otherwise, you might need to build, find or buy an application.  An approach that is becoming more common is using a Web application to satisfy the security requirements, while still allowing the data to be accessible to those with less technical knowledge.
Comment: yup - it's hard which is why we were looking for an off the shelf product.  Thanks for the answer.
Answer: BTW it is easy enough to make a SFTP proxy if you don't need any features beyond port forwarding. You could use netfilter http://kreiger.linuxgods.com/kiki/?Port+forwarding+with+netfilter , fwtk http://sourceforge.net/projects/openfwtk/ , or even SSH port forwarding.
Answer: Jscape has an SFTP reverse proxy that should do what you want. See http://www.jscape.com/reverseproxy/index.html.

SFTP: How to keep data out of the DMZ


Adding (and) logic for a list of columns and generating feature

Question: I have requirement to create a feature by checking the fields of two different dataframes.
df1 is a dataframe created from mysqldb and it will be static, the values of column(required) from df1 can be moved from True or False.
below are more details.
df1=
flag    beta    required
alpha   A        TRUE
alpha   B        TRUE
alpha   C        FALSE
alpha   D        TRUE

df2=
name    A   B   C   D   E   F
roy     1   1   0   1   0   0
john    0   1   1   1   0   0
sam     1   1   1   1   1   1

I trying to create feature alpha_flag by using the column name "beta" from df1 if the required column is TRUE.
So the code for alpha_flag will be like below
df2['alpha_flag'] = np.where(df2['A']==1 and df2['B']==1 and df2['D']==1 , 1 , 0)

The difficulty i am facing is to choose only the columns that are mentioned as required true from df1 and dynamically update my 'alpha_flag' creation condition.
Answer: IIUC, you can use boolean indexing to select the beta rows where required is TRUE, then check if these columns in df2 is all equal with 1
df2['alpha_flag'] = df2[df1.loc[df1['required'].eq('TRUE'), 'beta'].tolist()].eq(1).all(axis=1).astype(int)

Note that if all required value is FALSE, this will cause selecting empty column from df2 and lead to empty dataframe manipulation which might cause unexpected behavior, so a more robust version would be
cols = df1.loc[df1['required'], 'beta'].tolist()
df2['alpha_flag'] = df2[cols].eq(1).all(axis=1).astype(int) if len(cols) else 0


t test for stationarity of time series

Question: How is the t test used for testing the stationarity of time series.
I have tried to search literature which says that if the mean , standard deviation and higher moments of the partitioned time series are not significantly different it can be called a stationary series, but I do not find it enough to perform the quantitative test myself
Comment: What do you think about my answer? Does it answer your question? If so, you may accept it by clicking on the tick mark to the left. Otherwise, you may ask for further clarification. This is [how Cross Validated works](https://stats.stackexchange.com/tour).
Answer: You test agaist specific alternatives, e.g. changing mean, changing variance, changing higher moments. For each one, one or more tests exist, and they are not necessary based on the $t$-test. The closest one could be the augmented Dickey-Fuller test with a $t$-statistic following a nonstandard distribution under the null hypothesis of presence of a unit root (a type of nonstationarity in the mean).

t test for stationarity of time series


After move, baby grand always sustained notes, pressed or not pressed

Question: After moving and assembling the baby grand by regular furniture movers, I played the piano and found that notes are sustained with or without pressing on the sustain pedal.
I believe they assembled back the pedals incorrectly underneath.
The movers denied any wrong doing and I can't blame them because they are not really piano movers.
The move was Oct 31, 2022.  And since I've been busy, I only got to try the piano this year in January and found the problem.
I don't have time and money to have tuners fix the problem so I'd like to fix it myself now.  After move tune-up even much later.
Attached are 2 images underneath that show views from the left and right sides of the metal rods going up to the lever.   Let me know if you need other views but I can only deliver after this weekend though.
Can anyone help me what you can notice is wrong so I can fix this myself.  What tools are needed?
Thanks for the help.
mi7babygrand
Comment: There's a part of me that wants to suggest that not being able to afford piano movers or a tuner is part of not being able to afford to own a piano. A grand piano at that. If it's a nice piano at all then you risk doing more harm than good by not having a pro look at it.
Comment: I would say that solving a mechanical problem without touching or seeing things moving with your own eyes is kinda hopeless. You have more chance trying to understand the way it should work yourself (like phoog is suggesting) than asking blind people in the internet probably !
Comment: I'll say, if it were I, I'd definitely call in a professional! And try to find one who won't be arrogant and scolding. That's not a great way to win customers, even if he's right! But pianos need servicing regularly anyway, and especially after a move. I'd call someone even if it were working normally!
Comment: First of all I've had this baby grand for30+ years. Its been moved 2x by non piano movers. The 1st time didn't have this problem. You are correct. All keys are sustained, with or without stepping on the pedal. As shown on photo with arrow, the lever goes up when pedal is pressed and back down when released. I read somewhere that pedal may not be connected to the damper inside the piano to the connection under the piano. I don't know where that is among the parts of the contraption involved. I called a piano tuner & he was very arrogant in scolding me for not calling piano movers when I moved a
Answer: I can't really tell what's wrong from the pictures, but I can offer some advice to help diagnose the problem.
First, I understand from the question that all of the notes with dampers are affected, so the piano is behaving as if you're constantly stepping on the pedal.  If that's not correct, stop reading and leave a comment explaining which notes are affected.
Second, if you're uncomfortable unscrewing and removing the pedal assembly and then replacing it then you should seek assistance from a handy friend, or just bite the bullet and call the piano tuner.  The piano surely needs tuning anyway, and fixing the dampers is probably just a question of realigning something that is out of alignment.
Third, a likely cause for this condition is indeed that the pedal is assembled incorrectly.  What does happen when you step on the pedal?  Is everything moving?  Does the pedal move as it normally does, along with the vertical rod and the lever shown in the picture?  If they are not moving normally, try unscrewing the pedal assembly and moving the lever manually.  If the dampers now work as expected, you can probably just put the pedal assembly back together carefully and everything should work as normal.  Be certain to check that the vertical rod also slides relatively freely before you put everything back together.
Finally, if you remove the pedal assembly and find that manipulating the lever directly does not solve the problem, then it's likely that some lever or rod has fallen out of alignment during the move.  (For example, the vertical wooden rod that extends upward from the wooden lever through the hole in the piano case may have fallen out of a socket at the other end, holding that piece in a higher position than it should and therefore keeping the dampers off of the strings.)   If that is the case then it will probably be necessary to remove the action (keys and connected parts) to get at the internal mechanism.  This isn't as hard as it sounds, but it's also not trivial.  If you're a confident tinkerer, you might give it a go, but, once again, if you're planning to get the instrument tuned anyway, just go ahead and do that.  The technician isn't likely to charge much to realign the mechanism.
Answer: All we can say for certain is that the mechanism that connects pedal and dampers is stuck in the 'dampers up' position.
Fortunately, it's a fairly simple mechanism, and it should be possible by inspection to see what's wrong.
But if you can't, I guess that after-move tuning will just have to be brought forward.  At least we can be confident that re-setting the pedal mechanism will only be a trivial addition to the tuning job.


updating automation results to Xray test cases within execution without creating additional test cases

Question: We use Xray for test case management and have automated few test cases. We use jenkins to execute the automated test cases and use the plugin to read the results xml file and update the test run. However, for every automated test case it created a new Xray test case. Is there a way to map every automated test case to existing test case in test execution?
Answer: The ability of mapping  automation results to a specific existing Test issue depends on the report format you use as detailed in the following link.
https://confluence.xpand-it.com/display/XRAY/Integrating+with+Testing+Frameworks
For example, with JUnit you cannot enforce a specific @Test annotated method to correspond to an existing Test issue (due to limitations of JUnit XML report format). However this is possible if you use TestNG, NUnit or Robot framework as shown in the following tutorials:

https://confluence.xpand-it.com/display/XRAY/Testing+using+TestNG+in+Java?src=contextnavpagetreemode
https://confluence.xpand-it.com/pages/viewpage.action?pageId=62269682&src=contextnavpagetreemode
https://confluence.xpand-it.com/display/XRAY/Testing+using+Robot+Framework+integration+in+Python+or+Java?src=contextnavpagetreemode

Last, you can also report results back to an existing Test issue if you use the Xray JSON format. More on that here
An example of Xray JSON report would be something like

<code>{
    "testExecutionKey": "DEMO-1206",
    "info" : {
        "summary" : "Execution of automated tests for release v1.3",
        "description" : "This execution is automatically created when importing execution results from an external source",
        "version" : "v1.3",
        "user" : "admin",
        "revision" : "1.0.42134",
        "startDate" : "2014-08-30T11:47:35+01:00",
        "finishDate" : "2014-08-30T11:53:00+01:00",
        "testPlanKey" : "DEMO-100"
    },
    "tests" : [
        {
            "testKey" : "DEMO-6",
            "start" : "2014-08-30T11:47:35+01:00",
            "finish" : "2014-08-30T11:50:56+01:00",
            "comment" : "Successful execution",
            "status" : "PASS"
        }
     ]
}</code>
Answer: Most likely the test cases you have created were not generic but manual type. Take a look at test definition of tests created by automated job. This definition must be copied to the actual test cases, but again, they need to be generic.


Using a common test function with chai that fails the test run

Question: I have a problem with my test.
I want this behaviour:
let chai = require('chai');
let expect = chai.expect;
describe('something', function() {
    it('fails', function() {
        expect([1,2,3].length).to.be.equal(4);
    });
});

This test fails.
Now I have common logic, so I want to have some common parts in a different function. For this I wrote something like:
let chai = require('chai');
let expect = chai.expect;
describe('something', function() {
    it('fail please', function() {
        check_fail([1,2,3]);
    });
});

let check_fail = async function(body){
    expect(body.length).to.be.equal(4);
}

This test will fail because check_fail is an asynchronous function. But I need it to be async because in the function I use awaits. How can this test fail and not pass?
Comment: you can do async test. Just add async at the beginning of the test definition, and use await when calling check_fail. That should make the test fail
Answer: It should be simple like in
describe('something', function() {
    it('fail please', async function() { // => add async
        await check_fail([1,2,3]); // => add await
    });
});

let check_fail = async function(body){
    expect(body.length).to.be.equal(4);
}

Hope it helps


Rotation matrix formula derivation?

Question: I would like to understand where to following formula for a 2-D rotation matrix is derived from:
$R =\frac{1}{a^2+b^2} \left(\begin{array}{cc} a^2-b^2 & 2ab\\ -2ab & a^2-b^2 \end{array}\right)$
I believe the answer is geometric and if it is, a picture would be nice.
Comment: What if $a=\cos t$ and $b=\sin t$?
Comment: @LordSharktheUnknown I would not like to bring sin and cos into this if possible.
Comment: To clarify, is this a matrix for a specific rotation?
Comment: @LordSharktheUnknown Well, $a$ may equal values greater than $1$ ...
Comment: What are $a$ and $b$ meant to be?
Answer: Consider the unit vector
$$\vec u=\left(\frac a{\sqrt{a^2+b^2}},\frac b{\sqrt{a^2+b^2}}\right).$$
The rotation that applies $(1,0)$ to $\vec u$ and $(0,1)$ to a unit vector orthogonal to $\vec u$ is described by the matrix
$$R=\frac1{\sqrt{a^2+b^2}}\begin{bmatrix}a&b\\-b&a\end{bmatrix}.$$
Applying the rotation twice, i.e. squaring the matrix gives
$$R^2=\frac1{a^2+b^2}\begin{bmatrix}a^2-b^2&2ab\\-2ab&a^2-b^2\end{bmatrix}.$$
Comment: Anyway, you shouldn't disregard the remark of  Lord Shark the Unknown.
Comment: isn't the matrix applying the rotation to the "opposite" direction now? Seems like the minus on the element that is set to b should be on the RH upper corner, not LH lower corner.
Comment: @Tony: a matter of convention.

Rotation matrix formula derivation?


What is wrong with the following URL encoding?

Question: https://twitter.com/intent/tweet?source=webclient&text=G%C5

produces the following error:
Invalid Unicode value in one or more parameters

btw, that is the Å character
Comment: When URL decoding `Å` in [this site](http://meyerweb.com/eric/tools/dencoder/) I get: `%C3%85`.
Comment: Where exactly is this error produced?
Comment: Just a question: Should that not be xC5?
Comment: @Bart - No. This is [URL encoding](http://en.wikipedia.org/wiki/Percent-encoding). The `%` is correct.
Comment: @Oded Okay, didn't know that. Just wondered. Thanks.
Answer: twitter expects parameters to be encoded as utf-8.
So Å is Unicode U+00C5, and represented as utf-8 is C3 85
With url-escape this means that the query should be ...&text=G%C3%85
Since I don't know how you are building that query (programming language/environment), I can't really tell you how to do it right. Only that you should convert your string to utf-8 before escaping.


The RPC server is unavailable. with hMailServer

Question: Everything was running fine, until I restarted the server (there may have been some updates installed as well during that restart) and now I can't connect to retrieve mail and Administrator comes up with this exception when I try to view the status:
<code>The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

ExceptionType: COMException
HelpLine:
Message: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
Source: Interop.hMailServer
StackTrace:    at hMailServer.LanguageClass.get_String(String EnglishString)
   at hMailServer.Administrator.Strings.Translate(String text)
   at hMailServer.Administrator.Strings.Localize(Control container)
   at hMailServer.Administrator.ucStatus..ctor()
   at hMailServer.Administrator.Nodes.NodeStatus.CreateControl()
   at hMailServer.Administrator.formMain.ShowNodeRepresentation(INode node)
   at hMailServer.Administrator.formMain.treeNodes_AfterSelect(Object sender, TreeViewEventArgs e)
   at System.Windows.Forms.TreeView.OnAfterSelect(TreeViewEventArgs e)
   at System.Windows.Forms.TreeView.TvnSelected(NMTREEVIEW* nmtv)
   at System.Windows.Forms.TreeView.WmNotify(Message& m)
   at System.Windows.Forms.TreeView.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
TargetSite: System.String get_String(System.String)
</code>
Since it was working before the restart I'm assuming it has something to do with components not starting up properly. RPC is running, so is SQL Server.
Windows Server 2008
hMailServer 5.3.3 B1879
MSSQL 2008
Comment: Start with the obvious - the Windows event logs. Tell us what they say about the problem. Right now both you and us are working in a vacuum.
Answer: Have you verified that your SQL server is running? If it is running, you might check to ensure that you can connect to it and it is responding/responsive.
Answer: Ahh yes, I figured out the problem yesterday, forgot to post reply. I decided to reinstall hMailServer, just to see if that solved the problem (you never know, eh?) and it threw an error which was far more descriptive than this stack trace - server version was wrong.
I remembered during migration to a new server I also updated hMailServer to newer version, from 5.3.2 to 5.3.3. With it I had to migrate the db as well, from MySQL to MSSQL. Everything went fairly well, but I remembered changing a value in hm_dbversion table from 5320 to 5330, assuming it should reflect hMailServer version. Oddly enough it was working fine until SQL Server was restarted, at which point it failed to connect. Changing it back to 5320 solved the problem.


How to do alignment on hex in string formatting

Question: Is there a way to align hexadecimal digits in string formatting? I feel like it has to be quite easy, and I'm just missing the formatting. For example:
ones_comp = 72510
print (f"2. Ones comp: {ones_comp:#0x>12}")

I'd like it to print something like:
2. Ones comp:       0x11b3e

Answer: You can do:
print(f"2. Ones comp: {ones_comp:>12x}")

which outputs:
2. Ones comp:        11b3e

or use the hex function if you really want the 0x prefix:
print(f"2. Ones comp: {hex(ones_comp):>12}")

which outputs:
2. Ones comp:      0x11b3e


Perfect Square Number, prime

Question: I want to show that $p^{p+1}+(p+1)^p$ is not perfect square number. ($p$ is prime number)
This is what I do
Assume $p^{p+1}+(p+1)^p=k^2$.
$(p+1)^p=(k+p^{\frac {p+1} 2})(k-p^{\frac {p+1} 2})$.
Let $2ab=p+1, gcd(a,b)=1$.
$k+p^{\frac {p+1} 2}=2^{p-1}a^{p}, k-p^{\frac {p+1} 2}=2b^p$.
Therefore $p^{\frac {p+1} 2}=|2^{p-2}a^p-b^p|$.
By Fermat's little theorem, $a\equiv 2b \pmod{p}$, and $2ab=p+1$, so $a=2b$. In this case I can show contradiction.
but, if $a=1$ I don't know how show contradiction.
Comment: F) You might want to clarify what you're asking for here. I'm not sure if that's a translation issue. IE Are you asking for help with the case of $ a =1, 2b = p+1$? are you asking for a solution verification?
Comment: @adola Every $p+\frac12$ should be $\frac{p+1}2$ instead.
Comment: A) IMO The "Let $2ab=p+1$" part might be written backwards (in terms of the flow of the proof). You should first show that $\gcd(k+.., k-..) = 1$ or 2, then proceed with cases. B) You only dealt with 1 case, and should consider the other 3 cases (e.g. $k+... = a^p, ak...=b^p$).
Comment: thank you for edit. I don't know how enter math in internet.
Comment: C) I'm not sure how you concluded that $ a = 2b$. In fact, we have $ a \equiv 2b \equiv \pm 1$, and from there can conclude that $ a = 1, 2b = p+1$.
Comment: to Calvin Lin. gcd(k+..,k-...) must be 2, because p=2 is not correct, and so p is odd prime. so k is odd number. so k+... and k-... are even number.
Comment: to Calvin Lin. 2ab=p+1 so a and b is below (p+1)/2. and a=2b(mod p) so we can conclude a=2b or a=1, 2b=p+1. I can show case1(a=2b) is contradiction. but I don't know a=1, 2b=p+1....
Comment: I can only respond to what I see in front of me, and whatever additional effort I'm willing to put in. You may be thinking it, but I (and most others here) are not mind readers. IMO What you wrote should have been in the question. D) Noted, I didn't work that far to eliminate gcd = 1. E) So from $a\equiv 2b$, we get that $ a^2 \equiv 1 \pmod{p}$ so $ a\equiv \pm 1 \pmod p$. We can eliminate $a \equiv -1$, which just leaves $ a = 1, 2b = p+1$.
Comment: @ThomasAndrews Originally, it was p+1/2. It's the OP's fault.
Comment: sorry my English is bad. I ask for help with the case of a=1, 2b=p+1. Honestly I didn't write every process in this page. because writing here is so hard to me. I think just this will be enough to ask help for a=1, 2b=p+1.
Comment: @Matholic English is not a very big problem here.. we have grammarians in here as well (:D).
Answer: Your proof is quite faulty (mathematically speaking, you omitted 2-3 cases i think), so I will reweite it entirely.
$$p^{p+1}+(p+1)^p=k^2\Leftrightarrow (p+1)^p=\big(k-p^{\frac{p+1}{2}}\big)\big(k+p^{\frac{p+1}{2}}\big)$$
Notice that $\text{gcd}(p+1;p)=1$ and $\text{gcd}\big(k-p^{\frac{p+1}{2}};k+p^{\frac{p+1}{2}}\big)|2\cdotp^{\frac{p+1}{2}}$, thus leading to $$\text{gcd}\big(k-p^{\frac{p+1}{2}};k+p^{\frac{p+1}{2}}\big)|2$$
$(p+1)^p$ is even so at least one of $k-p^{\frac{p+1}{2}}$ and $k+p^{\frac{p+1}{2}}$ is even, thus $$\text{gcd}\big(k-p^{\frac{p+1}{2}};k+p^{\frac{p+1}{2}}\big)=2$$
Note that case $p=2$ does not work, so from now on we will only work with $p\geq 3$
We can now safely assume that we have $2$ cases:
$1)$ $k-p^{\frac{p+1}{2}}=2\cdot a^p$ and $k+p^{\frac{p+1}{2}}=2^{p-1}\cdot b^p$ with $2ab=p+1$
$2)$ $k-p^{\frac{p+1}{2}}=2^{p-1}\cdot a^p$ and $k+p^{\frac{p+1}{2}}=2\cdot b^p$ with $2ab=p+1$
(notice that $a$ abd $b$ are not divisible by $p$)

Case $1)$: Using Fermat's little theorem, we get $k\equiv2a\pmod{p}$ and $k\equiv b\pmod{p}$ so $2a\equiv b\pmod{p}$ but $2ab\equiv 1\pmod{p}$ so either $b=1$ and $a=\frac{p+1}{2}$ or $b=p-1$ and $a=\frac{p+1}{2(p-1)}$.
Clearly when $a=\frac{p+1}{2(p-1)}$ we get a contradiction (unless $p=3$, which is a special case, we can easily see that $4^3+3^4$ is not a perfect square)
So $b=1$ and $a=\frac{p+1}{2}$ But $k=2^{p-1}b^p-p^{\frac{p+1}{2}}$ so if $b=1$ then $2^{p-1}> p^{\frac{p+1}{2}}$ which is clearly false for all primes $p$.
So we only get contradictions in this case.

Case $2):$ Again, using the same method we get $2b\equiv a\pmod{p}$ so with the same reasoning $a=1$ and $b=\frac{p+1}{2}$
We know $k=2\cdot a^p+p^{\frac{p+1}{2}}=2^{p-1}\cdot b^p-p^{\frac{p+1}{2}}$ so we get $$2+p^{\frac{p+1}{2}}=2^{p-1}\cdot \big(\frac{p+1}{2}\big)^p-p^{\frac{p+1}{2}}$$ which can we rewritten as $$2(1+p^{\frac{p+1}{2}})=2^{p-1}\cdot \big(\frac{p+1}{2}\big)^p$$
We assumed $p\geq 3$ so $p\equiv 1$ or $3\pmod{4}$
If $p\equiv 1\pmod{4}$, $1+p^{\frac{p+1}{2}}\equiv 2\pmod{4}$ so $$v_2(2(1+p^{\frac{p+1}{2}})=2$$ but $$v_2(2(1+p^{\frac{p+1}{2}})=v_2(2^{p-1}\cdot \big(\frac{p+1}{2}\big)^p)\geq p-1$$ giving us $$3\geq p$$ so contradiction; we assumed $p\equiv 1\pmod{4}$
If $p\equiv 3\pmod{4}$ then $\frac{p+1}{2}$ is even, so $p^\frac{p+1}{2}\equiv 1\pmod{4}$ (any odd perfect square is $1\pmod{4}$) so we have again that $1+p^{\frac{p+1}{2}}\equiv 2\pmod{4}$ so $$v_2(2(1+p^{\frac{p+1}{2}})=2$$ giving us the same result, $3\geq p$, which would lead to $p=3$, which we established is a contradiction.

Thus, there is no prime $p$ for which $p^{p+1}+(p+1)^p$ is a perfect square.
Comment: Nitpickery: if $p=2$ then your initial hypothesized factorization into $(k\pm p^{(p+1)/2})$ isn't possible (since you don't have a difference-of-squares in the first place), so you can't really imply the contradiction that you do further down. Instead I think you just want to handle that case by explicit calculation.
Comment: True, true, I am editing it in. Sorry for the bad proof-writing
Comment: It is now fixed.
Comment: Thank you very much! I will study your proof and if I have more question(If I can't understand) about your proof, I'll add comment
Comment: Hi. in case 2) I think $ k=2^{p-1}+p^{p+1/2}=2(p+1/2)^{p}-p^{p+1/2} $ is right. isn't it?
Comment: Or... in case 2) is using 1) and not $ b^{2}==1(mod p) $ but $ 4a^{2}==1(mod p).$..?
Comment: if this is right.. you skip proof about 2)?? @Vlad
Comment: i tried again... um... $4a^{2}==1 (mod p) $ is same conclution in case 1).. And so in case2) k is wrong, I think. If I fix that, I get $ p^{(p+1)/2}=((p+1)/2)^{p}-2^{p-2}$ and still I don't know how I get contradiction... please help me.

Perfect Square Number, prime


Windows Storage Spaces - a useful replacement for RAID6?

Question: // short update at the bottom
// another update is near the bottom to reply to a suggested edit
So, at first I had this idea: Find a virtual driver to set up and use software raid on windows. Result: Failed even with support from developer.
The next idea then came into my mind after watching a YouTube video about virtualization: Put in a 2nd rather cheap gpu for a linux system that runs bare metal and set up my windows in a VM with my main gpu via passthrough. This way I could had used mdadm/lvm and let linux do all that software raid stuff. Result: Failed - due to some weird issues with my motherboard not liking the 2nd gpu at all.
Then I read something about Windows Storage Spaces and that it is able to provide fault tolerance comparable with a software RAID6 (as far as I understand it's done by filesystem shadow copies spread accross the physical drives). So I gave it a try and got it working (although it required some manual lines in powershell as the gui version doesn't expose some of the advanced settings).
As this was just in a VM the test performance was rather bad, but I noticed that data are written multiple times, which can sometimes end up in the drives are used rather unevenly. As an example: One of the virtual disks only had about 2GB written to where as another drive had about 4GB written to. So, whatever distribution algorithm is used (it doesn'T look like round-robin but more like most available physical space first) it's far from how I would expected a software RAID6 to behave.
I also noticed it's rather wasteful to make use of physical disk space. My test was using 8 disks with 50GB each. A mdadm software RAID6 resulted in about short of 300GB useable space, the storage spaces one with only about 250GB - so another 15% "penalty". Ok, I guess that's all that overhead and such, but even from a software RAID I expected to make a bit better use out of my physical disk space.
I then tested what happens if I start to remove drives, and as I had it set up with -PhysicalDiskRedundancy 2 it was able to survive it and all test data were still all available.
So, overall it seem to fit my needs for a software raid on windows supporting raid6-like fault tolerance to survive a double failure (that is: failing a 2nd drive while rebuilding the 1st failed one). About the performance: Well, it'S software raid - and as I'm currently using fakeRAID (basically a driver-specific software raid shadowed by the bios) there will be not that much more system performance impact as I have right now.
What really made me think thrice about it: There are currently two major issues: a) it can't be mounted on a linux system (I had not yet tested if and how it may can be mounted in a recovery environment) and b) in the current win10 2004 are a lot of issues already caused data loss as reported by some users on different forums.
Why am I asking this: The main "issue" is that I currently don'T have the financial options to invest in new/better hardware. I only have to spare what I currently own. Hence I'm searching for a software solution. I tried WinBTRFS as it claimed to support software RAID for it's volumes, but I wasn't able to set it up correctly even with the help from its developer. So, the base question boils down to: Is using storage spaces a vailable option if one can't afford hardware RAID or other solutions like virtualization (due to hardware incompatibility)? Sure, I have many of my "really important" data backed up on an external drive, but still: I rather would build some reliable system instead of going the "I believe in that nothin will happen" way.
// update
Just as a small update about if and how you can access such a virtual disk via WinPE: I just downloaded the current 2004 ADK and created a fresh WinPE image. As I had to use PowerShell to access the information I just copied the instructions found on the ADK PE documentation. After that I created an ISO and booted that in the VM. Without any further commands it was available right from the boot. As I read on the MSDN forums this is only true for Client versions of Windows. On Server versions storage spaces start up in a readonly and detached state (I guess for safety). So in order to read from it one have to attach it manually. To write to it, obviously, one have to change it from readonly to readwrite - but as my question on that was about how to read data in a recovery environment for me writing to such a volume isn't needed.
// additional reply
As DarcyThomas suggested in his comment, here're my background why I currently use a RAID5 and why I think to have the need for migrate to a more safer style like RAID6:

Am I doing it for the small read speed advantage: Although I noticed that the array is capable of streaming data a bit faster than one of the drives is able to on its own it only really shows when I copy large files resulting in long sequential reads. When I deal with a lot of small files, which cause a lot of random I/O, the performance sometimes get worse compared to a single drive. As for write speeds it's about the same story. So, to answer this question: No, speed advantage is surely not what I'm aiming for, hence I'm ok with the even worse "penalties" a RAID6 implies.

Am I doing it as a cheap backup? One surely would try to argue yes. And I sure take advantage from still have all data available if one of the drives fail. Sure, I do have the really important data on another offline drive, so in a catastrophic loss of the array (i.e. due to hardware malfunction or the board going up in smoke) I still will have my important data safe. But I for sure do take advantage of the convenience to not have to worry about a drive failing as much as if I would use them as single drives (or maybe in another configuration). I already had two drives failed (both rather short time after moving - so it's possible that it was physical transport damage both times instead of the drive worn out) and the rebuild times were quite long (about 14 hours for just 3 TB).

Do I really need that one single large volume? Although another debatable question to keep it short I would reply to it simple with: Yes, at least for convenience. I have the array already filled up more than 1/3 and managing such vast amount of data across multiple drives/volumes would result in a chaos (at least for me). Another neat side effect: If someone comes by with like new stuff (music, movies, etc) I can just "dump" it on the array and can reorganize and de-duplicated later without have to worry to clog up on of the drives. I'm someone with a brain like a fly: I would forget I had put data on another drive after a few hours and would take another to find it again. Just have it all in one place treats me.

As for "online" backup solutions: Yes, I know they're out there. And yes, I also know there're some one can get for free or at least cheap. And sure I would have the ability to write myself some small encryptor/decryptor code making use of asymmetric keys to secure the symmetric one rather than using passphrases. And it's not like I won't trust them. But same goes true as in number 3: Over time I would just simply forget about a few of them. And although I have a rather fast connection (250/50) having all my data across the net isn't something I'm looking towards to. But I guess that's just a personal thing.

So, to summarize: Moving on from 5 drive RAID5 to 8 drive RAID6 for me is just the next logical step. The investment will be rather low (just for the additional drives + one or two simple HBAs) and done right it shouldn't depend on proprietary stuff like the one I'm using right now. Yes, I figured out how to access a storage space from a recovery environment, but this requires its proprietary spec to stay the same without sudden changes cause incompatibilities (like the chaos with just office documents). Maybe this addition may help others in the future for replies.
Comment: I think you need to define what problem you are trying to solve. RAID solves 2 problems (depending on the configuration) Increase in speed with concurrent read/write, and redundancy. If one disk dies you have a backup. Do you need either of these and if so why? Could you just use a service like Dropbox or rsync for redundancy/backup? Then you only need to worry about speed ,and you can use a simpler RAID configuration for that. This doesn't answer your question. But it may be worth considering, so you don't get stuck in a rabbit hole trying to shave a yak!
Comment: I have added some additional information in respect to your comment to maybe clear up some things. Thanks for that great input. If it would had been its own answer it sure would had deserved some upvotes.
Answer: Windows Parity Spaces are dog slow and (according to Microsoft) aren't designed for anything except archive workloads. Microsoft keeps trying to improve write performance say implemented log missing from the hardware RAIDs, but lack of the battery-powered write back cache takes away all the fun. You can however try to improve writes by telling Spaces you have UPS.
https://docs.microsoft.com/en-us/windows-server/storage/storage-spaces/deploy-standalone-storage-spaces
Set-StoragePool -FriendlyName  -IsPowerProtected $True
Another point is to use ReFS and Storage Spaces combined into so-called Mirror-Accelerated-Parity, writes will end up inside SSD tier to die on HDD tier later.
https://docs.microsoft.com/en-us/windows-server/storage/refs/mirror-accelerated-parity
http://knowledgebase.45drives.com/kb/kb450193-creating-mirror-accelerated-parity-volumes-and-storage-tiers-in-storage-spaces-windows-server-2019/
Unfortunately this isn't 100% supported scenario for anything except Storage Spaces Direct (which is another can of worms on its own).
I'd suggest Linux MDRAID+XFS due to its stellar stability and lots of proven deployments or old stock LSI hardware RAID card from eBay if you absolutely need to stick with Windows Server OS.
Comment: We have very different experience with Storage Spaces Direct (node lock ups, data corruption with ReFS, various performance issues etc) and have no plans to re-implement it anytime soon.
Comment: S2D in Windows 2019 had an initial issue with lost quorum in small 2 nodes cluster and there was a huge chance to get all storage offline after enabling maintenance mode on one server for patching or graceful restart. This issue might be already solved in some of winter patches. I deploy Starwind VSAN for small clusters by customers as an alternative to S2D, because it was developed for such usage.
P.S. ReFS is also not so "resilient" as promised - https://bit.ly/2XqpJGC.
Comment: It's a client OS, no server. I already had the idea to use a linux bare metal and run win as VM, but to use my main gpu via passthrough it would need a 2nd for linux - which my board doesn't like at all (it doesn't even boot with 2nd gpu). As I use the rig for games I'm stuck to win platform as not many of them run native on linux - and wine performance is even worse. It's also not supposed high performance, OS runs on its own drive, but it has to be reliable. It should also accessible by rescue system (still testing this one). Sorry for short reply, but you know comment length limit.
Comment: Storage Spaces Direct (S2D? AzSHCI?) is anything but reliable tech. ReFS turning itself into RAW under heavy load or after reaching specific volume capacity is what people see in the wild. https://forums.veeam.com/veeam-backup-replication-f2/windows-2019-large-refs-and-deletes-t57726-150.html
Comment: Just one note - I am not sure where Storage Spaces Direct is a can of worms. Using it without ANY problems since Server 2019 came out. Anything earlier - ouch - but that version upward is rock solid and stays up even during patch reboots (rolling upgrade - nice). The only time we really take it down these days is when there is a hard reason to take down power (i.e. major rework on the UPS line). Last time when we installed a bypass switch so we can move from UPS to Net - otherwise it works and works and works and works. WIth VERY good performance thanks to a lot of SSD write caches.
Answer: "Windows Storage Spaces - a useful replacement for RAID6?"
If by "RAID6" you mean "I hate my data and want to get to it in as slow a way as possible" then yeah, sure - we lost 62TB of data to it at one point, luckly had a backup of it all but never again.
EDIT: Don't trust to Windows software RAID, don't trust to double parity hardware RAID of a great capacity, always follow 3-2-1 backup rule and "In backup we trust".
Comment: Disc = optical disk, spinning rust is called "Disk" in English. Chopper3 clearly stated "we recovered from backup" so your "RAID isn't a backup" remark is pointless.
Comment: that is not a helpful answer, but a personal anecdote. Please edit to provide some context and reasons
Comment: I tried to improve Chopper3's reply with a short summary, but in general I agree with him and think his maybe a bit emotional reply IS an answer. Peace! :)
Comment: This link about 3-2-1 backup rule should help. https://www.vmwareblog.org/3-2-1-backup-rule-data-will-always-survive/
Comment: I'm not sure I can follow this one, but to reply: By RAID6 I mean an array of 6 or more physical drives working together to withstand a double-failure like having a 2nd drive fail during rebuild the 1st failed one. I'm aware that this is still by no means an excuse for a separate backup, but even my consumer grade fakeRAID already saved me from data loss 2 times. Also: Again, as this is NOT a server but only a private machine used to run games performance doesn't really that much. How did you even end up with 62TB in a single RAID6 without nesting? That sounds more like a multi-error to me.
Comment: Speed is an issue, but "you can not attribute a loss on SPD. I had the pleasure of watching a file server with Raid 6 die within 5 minutes due to 2 discs failing. RAID is never a guarantee for data. It is not designed for this.


Passar parâmetros no GET

Question: Estou tentando fazer um GET para validar um usuário usando o cpf e senha,usando o DAO, porém estou com dúvida na hora de passar o parâmetro.
Segue o codigo get
<code>   private Usuario usuarioLogado;

    @GET
    @Path("/{cpf}/{senha}")
    public String Autenticar(@PathParam("cpf") String cpf,@PathParam("senha") String senha  ) {

    UsuarioDAO usuarioDAO = new UsuarioDAO();
    usuarioLogado = usuarioDAO.autenticar(cpf, senha);

        Gson gson = new Gson();
        String json = gson.toJson(usuarioLogado);

        return json; }
</code>
Segue o DAO
<code>public Usuario autenticar(String cpf, String senha) {
        Session sessao = hibernateUtil.getFabricaDeSessoes().openSession();

        try{
            Criteria consulta = sessao.createCriteria(Usuario.class);
            consulta.createAlias("pessoa", "p");

            consulta.add(Restrictions.eq("p.cpf", cpf));

            SimpleHash hash = new SimpleHash("md5", senha);
            consulta.add(Restrictions.eq("senha", hash.toHex()));

            Usuario resultado = (Usuario) consulta.uniqueResult();

            return resultado;
        } catch (RuntimeException erro) {
            throw erro;
        } finally {
            sessao.close();
        }
    }
</code>
Comment: E qual sua dúvida?
Comment: De qualquer forma é uma péssima prática você passar a senha aberta através da URL do seu GET.
Comment: Então, isto que imaginei, e queria saber como eu poderei fazer esta autenticação sem passar na URL a senha.
Comment: A minha dúvida é se teria outra forma de se fazer esta consulta de autenticação.
Answer: Como você precisa enviar usuário e senha, em vez de utilizar um GET você deveria utilizar POST, pq ué já evita que o usuário e senha apareçam na URL.
Mesmo assim, você precisa utilizar https para submeter esse formulário de usuário e senha, caso contrário alguém pode interceptar a comunicação de rede e obter o conteúdo do post, junto co usuário e senha.

Passar parâmetros no GET


Remove tagging on node view

Question: I am building a social network with Drupal. I have the following requirement:

A person who adds a post can tag his friends when adding his posts.
His tagged friends can untag themself when viewing the post.

Requirement #1 was met by the amazingly efficient entity reference view widget (see my recent answer).
But how to achieve requirement #2 ?

What is the best way to implement such a feature?

Is there any inline editing tool (such as the edit module) for entity reference fields?
Does editablefields really works for Drupal 7?
Should I just implement it using the Rules Link module?
Any other approach?

Please advise.
Comment: You could do it custom by appending the link to the tag with the term/node id in the callback url and processing it with ajax/js.
Answer: I tried to define a custom field formatter but it didn't find the hook.
In the end it was much easier to use the Entity Reference Views Formatter module, then theme the view field to add the desired behavior to the relevant link. I used the rules_link module to define the untag link, then added the untag link into the field's theme. Next time I should probably use a tpl.php file as well.
File: views-view-field--with--block--field-with.tpl.php

<?php
  global $user;
  $my_uid = $user->uid;
  $node = node_load ($row->nid);
  $results = db_query(      // Load the field without loading the entire node.
    "SELECT field_with_target_id
       FROM field_data_field_with
      WHERE entity_id = :entity_id",
    array(':entity_id' =>$row->nid));

  $lines = "";
  foreach($results as $result) {
    $uid = $result->field_with_target_id;
    $account = user_load((int)$uid);
    $rendered = l(mymodule_get_realname($account), "user/$uid");
    $untag = "";
    if ($uid == $my_uid) {
      $rules_link = rules_link_load('un_tag_me');
      $untag = render(rules_link_render_link($rules_link,$row->nid));
      $untag = str_replace (
        array("<div ", 'title="x"'),
        array("

Remove tagging on node view