Obter valor Inteiro em em final .00 e valor float em .01 até 0.9

Question: Tenho este código abaixo que é de uma calculadora, porém estou com um problema: queria retornar um valor float quando se divide 5 / 2 = 2.5 e retornar um valor inteiro quando se divide 4 / 2 = 2 e não 2.0!
Alguém pode me ajudar quanto a isso? O código é este:
public class CalcActivity extends Activity
{
    TextView tvScreenCalc;
    String currentString="0",previusString=null;
    boolean isTempStringShown=false;
    int currentopperand=0;
    @Override public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calc);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT);
        tvScreenCalc=(TextView)findViewById(R.id.tvScreenCalc);
        int numberButtons[]={R.id.button0,R.id.button1,R.id.button2,R.id.button3,R.id.button4,R.id.button5,R.id.button6,R.id.button7,R.id.button8,R.id.button9};
        NumberButtonClickListener numberClickListener=new NumberButtonClickListener();
        for(int id:numberButtons)
        { View v=findViewById(id);
            v.setOnClickListener(numberClickListener);
        }
        int opperandButtons[]={R.id.buttonPlus,R.id.buttonMinus,R.id.buttonDivide,R.id.buttonTimes,R.id.buttonDecimal,R.id.buttonClear,R.id.buttonEquals};
        OpperandButtonClickListener oppClickListener=new OpperandButtonClickListener();
        for(int id:opperandButtons)
        { View v=findViewById(id);
            v.setOnClickListener(oppClickListener);
        }
        setCurrentString("0");
    }
    void setCurrentString(String s)
    { currentString=s;
        tvScreenCalc.setText(s);
    }
    class NumberButtonClickListener implements OnClickListener
    { @Override public void onClick(View v)
    { if(isTempStringShown)
    { previusString=currentString;
        currentString="0";
        isTempStringShown=false;
    }
        String text=(String)((Button)v).getText();
        if(currentString.equals("0"))setCurrentString(text);
        else setCurrentString(currentString+text);
    }
    }
    class OpperandButtonClickListener implements OnClickListener
    { @Override public void onClick(View v)
    { int id=v.getId();
        if(id==R.id.buttonClear)
        { isTempStringShown=false;
            setCurrentString("0");
            previusString=null;
        }
        if(id==R.id.buttonDecimal)if(!currentString.contains("."))setCurrentString(currentString+".");
        if(id==R.id.buttonPlus||id==R.id.buttonMinus||id==R.id.buttonTimes||id==R.id.buttonDivide)
        { currentopperand=id;
            previusString=currentString;
            isTempStringShown=true;
        }
        if(id==R.id.buttonEquals)
        { double curr=Double.parseDouble(currentString);
            double result=0;
            if(previusString!=null)
            { double prev=Double.parseDouble(previusString);
                switch(currentopperand)
                { case R.id.buttonPlus: result=prev+curr; break;
                    case R.id.buttonMinus: result=prev-curr; break;
                    case R.id.buttonTimes: result=prev*curr; break;
                    case R.id.buttonDivide: result=prev/curr; break;
                }
            }
            setCurrentString(Double.toString(result));
        }
    }
    }
}

Comment: Se nas pesquisas que faz não aparece o que quer, é porque não está a fazer as pesquisas certas! :D. Parecendo que não ainda é preciso ter algum conhecimento para saber o que procurar. Como pequeno aparte, comece por indentar o código quem tem muito mais impacto e efeitos positivos do que possa pensar. Em relação ao problema em si, pode ver se o resultado da divisão é igual ao mesmo resultado convertido em `(int)`, isso permite-lhe saber se deveria ter decimais ou não.
Comment: Só usar algum formatador que, quando for apenas zero apos a virgula, remova a casa decimal, nao precisa trocar o tipo
Comment: E como faço isso? Sou novo na programação, e nas pesquisas que faço, nunca aparece o que eu quero!
Answer: Tem muitas maneiras, eis algumas:
Usando RegEx
static String autocasas(double numero)
{
   return String.valueOf(numero).replaceAll("(\\.?0+|\\.)$","");
}

Veja funcionando no IDEONE.
Basicamente estamos trocando qualquer quantidade de zeros (0+) no final da linha ($) por "vazio" (""), e em seguida trocando qualquer ponto no final da linha também por vazio.
Usando operações de String
static String autocasas(double numero)
{
   String[] partes = String.valueOf(numero).split("\\.");
   if (partes[1].equals("0")) return String.valueOf(partes[0]);
   return String.valueOf(partes[0]) + "," + String.valueOf(partes[1]);
}

Resultado:
System.out.println(autocasas(5.0/7.0)); // 0,7142857142857143
System.out.println(autocasas(5.0/2.0)); // 2,5
System.out.println(autocasas(123));     // 123

Veja funcionando no IDEONE.
Basicamente estamos dividindo a string em um array pelo ponto decimal.

Como estamos usando um double, sempre vai haver um ponto decimal para dividir;
se a segunda parte for um zero "solto", retorna só a primeira;
se tiver duas, concatena com uma vírgula.

Note que é uma base apenas, depois você otimiza.
Comment: pow, bom saber, talvez por achar um detalhe insignificante nao procurei ir atras, mesmo porque a gambi funcionava, mas assim limpa bem o código,
valeus mano veio!
Comment: **NOTA:** com float também funciona normalmente. Veja: https://ideone.com/clo5Dg
Comment: Poderia me mostrar como meu código ficaria? Como falei, sou muito ruim em programação, e não faço ideia de onde e como faço pra adapta-lo ao meu código! ;(
Comment: Ei @Bacco, valeus amigao, quer dizer que eh assim que trato o "." para passar como parâmetro de ".split()", caramba man, nao sabia, kkkk,
apanhei aqui e tive de fazer a famosa "gambi", e peor, kkkk, passei a "gambi" na reposta, rererere
Comment: agora te pergunto, porque tem de ter duas "\\", tu saberia dizer?
Comment: @ArmandoMarquesSobrinho o split aceita uma expressão regular, não uma string comum; O ponto sozinho significa "qualquer caractere". A primeira barra invertida é pra escapar a barra seguinte (para o Java), a segunda é para escapar o ponto. Ou seja, em java \\ vira \ numa string. Em regex, `\.` vira o caractere "ponto" literalmente. O `$` em RegEx significa "fim da linha, e a sequência `0+$` significa "um ou mais zeros no fim da linha". Treine aqui: http://regexpal.com
Comment: @DennisWadson basta copiar a função "autocasas" do jeito que está e usar no seu código.
Comment: Então é só eu por em qualquer parte do código?
Comment: @Bacco, colei teu código lá, mas não sei como usar? Pode me explicar em que parte colo ele?
Comment: setCurrentString(autocasas(result));
Answer: Uma forma simples de perceber se o resultado tem parte decimal ou não é comparando com a conversão do valor em inteiro. Ou seja para saber se 2.5 não tem parte decimal seria fazer 2.5 == (int)2.5 que lhe iria dar falso.
Para obter um float com duas casas depois da virgula pode usar String.format usando %.2f como especificador de formato.
Combinando estas duas ideias pode ter a seguinte função para obter o resultado como String:
public static String obterResultadoFormatado(float res){
    if (res == (int)res){
        return String.valueOf((int)res);
    }
    else {
        return String.format("%.2f", res);
    }
}

Que depois chama diretamente com o resultado do calculo:
float num1 = 5;
float num2 = 4;

Log.d("CalcActivity", obterResultadoFormatado(num1 / 2)); // 2,50
Log.d("CalcActivity", obterResultadoFormatado(num2 / 2)); // 2

Comment: Poderia me mostrar como meu código ficaria? Como falei, sou muito ruim em programação, e não faço ideia de onde e como faço pra adapta-lo ao meu código! ;(
Answer: Eu costumo fazer assim nesses casos:
// ...
float vf = 5/2;
String [] vs = String.valueOf(vf).replace(".","_").split("_");
int vi = Integer.parseInt(vs[0]);
// ...

no caso acima, tive problemas com split(".") uma certa vez, por isso usei realce(".","_") para evitar.
esse trecho de código faz o seguinte:
Converte a tua variavela float para uma string com String.valueOf(...);.
Separa ela em duas usando ...replace(...,...).split(...);.
Depois pega a primeira parte do vetor criado e converte ele para inteiro novamente com Integer.parseInt(...);.
espero que seja isso que voce esteja querendo.
Comment: Poderia me mostrar como meu código ficaria? Como falei, sou muito ruim em programação, e não faço ideia de onde e como faço pra adapta-lo ao meu código! ;(


How to remove/uninstall Angular7?

Question: I am trying to unistall angular7 but it's still showing me angular 7. I want to install Angular6.
For Uninstall:
sudo npm uninstall -g angular-cli
sudo npm cache clean
sudo npm install -g @angular/cli@6.*

But it still showing me Angular7.
Comment: Why would you want to go from 7 to 6?
Comment: sudo npm uninstall -g angular-cli  --purge
Comment: What command are you running that shows Angular 7?
Comment: After doing this all process then  i am checking version....ng v
Answer: sudo npm uninstall -g @angular/cli

angular-cli was Angular 2, it has been @angular/cli since Angular 4.
Comment: Another Issues:-npm ERR! path /usr/bin/ng
npm ERR! code EEXIST
npm ERR! Refusing to delete /usr/bin/ng: ../lib/node_modules/angular-cli/bin/ng symlink target is not controlled by npm /usr/bin
npm ERR! File exists: /usr/bin/ng
npm ERR! Move it away, and try again.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/pranavshete/.npm/_logs/2019-06-21T06_40_38_823Z-debug.log
Answer: Simply you can uninstall the existing version, clear cache forcefully and reinstall the version which you want.
sudo npm uninstall -g @angular/cli
sudo npm cache clean --force
sudo npm install -g @angular/cli@6.*

This will work for sure.
Thanks.
If it works then mark it as answer.
Answer: You need to run this command..
npm install -g @angular/cli
Also u need to update package.json file,where its version is defined
Change the "@angular/cli": "6.4.1"
After that again run the below command
npm install
Comment: I think the formatting got a bit messed up here... Shouldn't they be updating the package.json then performing the install?

How to remove/uninstall Angular7?


How to fill up with numbers a $3 \times 3$ square with almost no information given?

Question: The problem is as follows:
Each of the blank square must be filled using a positive number such the product of the numbers in each column and each row to be equal to $1$. Also the product of the four numbers which occupy the $2 \times 2$ square must be 2. Find the sum of the digits of the number to be written in the center square painted with color.

The alternatives given are:
$\begin{array}{ll}
1.&4\\
2.&6\\
3.&5\\
4.&7\\
\end{array}$
I'm stuck with this problem at the very beginning as I'm not sure if there exists some sort of methodology or approach that can be used. There is also the fact that I don't know what's meant by the phrase "the four numbers which occupy the $2 \times 2$ square must be 2". I believe that what it was intended to be asked is that there are four zones in the $3 \times 3$ square which can be $2 \times 2$, two in the upper portion of the square and the other two in the lower portion, but still I'm not sure about this. Can somebody with experience solving these kind of riddles help me?. I'd appreciate if there could be some sort of logic that can be explained with many details as possible so I can understand what's going on. Typically I would try to offer some attempt into solving this, but I really have no idea on what to do other than just guessing.
Comment: Are the numbers integers or real numbers? If the numbers are only integers ,then the only way to get the product equal to 1 would be when all numbers are equal to 1
Comment: The problem "silly" because it is a literal contradiction: if the product of positive integers must be 1, then these integers must be 1, no other option, so the product of some other subset cannot be 2
Comment: Then, as @The points out, the problem is pretty silly. For the product of a bunch of positive integers to be one, each of the integers must be one
Comment: If an answer was found, as the OP I would really appreciate you can post what did you do to get to that answer.
Comment: They are integers.
Comment: @GerryMyerson Sorry, I don't know why you meant the problem is silly?. Could it be that the person who posed this made it too simple?. Or am I overlooking something?. I'm slow with these riddles. :(
Comment: @Servaes The OP says **integer positive numbers**. So, they can't be fractions.
Comment: I think you have to go back to wherever you got this problem, make sure you have quoted it exactly correctly, and then let them know the problem is busted.
Comment: Anything to say, Chris? Two answers, numerous comments, no reaction from you.
Comment: Are you still here, Chris?
Comment: @Gerry Myerson I'm deeply sorry I did not meant to abandon this question. I had to take an exam and I could not came back until today to review all the feedback. I'm voting to reopen this question.
Comment: You can (and should) engage with what others have contributed even while the question is closed, Chris.
Comment: @GerryMyerson I tried to understand the intended purpose of the one who posed this question. Some inputs say it is a contradiction but the only answer which has come up with a solution doesn't really help me much. I left a comment under the existing answer but I'm unsure if the one who wrote that may reply given the elapsed time.
Comment: The user who posted that answer has given a "reply" by deleting the answer. I think you should read through the inputs that say it's a contradiction and think about them until you come to accept that conclusion or until you find a way out of it.
Comment: To repeat what others have pointed out to you: the only way a product of positive integers can be $1$ is for each of the integers to be $1$. You refer to "the $2\times2$ square", but it's unclear what you mean by this. And whatever you mean by this, the product of the four numbers occupying that square can't be $2$, as each of the four numbers has to be $1$. So the problem is a nonsense as stated, and there's really nothing anyone can do for you under the circumstances.
Comment: Gone again, Chris?
Comment: @GerryMyerson Sorry. I haven't gone. I tried to revisit and retry doing this problem by my own. Upon inspecting the original source I'm still perplexed by the meaning of $2\times 2$ square. I guess that the intended purpose is to  *divide* the whole magic square into 4 subections of $2 \times 2$ squares starting from the top left and ending in the bottom right, hence becoming four sectors.
Comment: @GerryMyerson I have read the problem again from the original source and I noticed that it did not mentioned anything about *integers*, the problem only mentioned positive numbers. So it can be a real number (as with integers do generate a contradiction). But if this is the case what would be the way to solve this problem?.
Comment: And you were so insistent that you had read the problem carefully and copied it perfectly and it had to be integers. Jeez. Anyway, the way to solve the problem is the way Inactive solved it for you when you first posted it two weeks ago.
Comment: @GerryMyerson I'm sorry I thought that I copied it as it was in the source. But when I compared with what was written then I noticed that the word *integer* was not in the original problem. As I was in a rush I did added this part as similar problems before this had that word included. But again, I tried to do it by my own and my guess is it can be $4$?. But I'm not sure to prove that.
Comment: Inactive got the middle number to be $16$, which has digit sum $7$, which is alternative $\#4$.
Comment: @GerryMyerson The answer is no longer visible which makes it difficult for me to understand how did he got to that number. I wish to have access to that answer. Can it be reverted?. As it stands now, no new answers can be added to a closed question.
Comment: You have only yourself to blame for the closure of the question, and for not taking more careful note of the answer before its owner deleted it (and for leading the owner to delete it by insisting the answer was wrong). I voted to undelete that answer, but no one has joined me yet. Anyway, it was just a lot of arithmetic, I'm sure you can reproduce it. The user did assume that each of the four $2\times2$ squares had product $2$. After that, it's just a lot of number-chasing. Go for it!
Comment: @GerryMyerson Okay. I appreciate your help. If I had commented earlier probably he would had not deleted his answer. However trying to reproduce with what one had solved reverts me back to the original problem which is what method can be used as it turns out that I have to do different trials.
Answer:
Each of the blank square must be filled using an integer positive number such the product of the numbers in each column and each row to be equal to $1$.

Trivially, this means that all entries are $1$. But at the same time

Also the product of the four numbers which occupy the $2 \times 2$ square must be 2.

This is a contradiction. So if you've stated the problem correctly, it is wrong.
Comment: I revised this problem and in the original source it didn't mention anything about the numbers being integers. So I assume it can allow reals, hence fractions. Would this ease or make this problem not be a contradiction?. Can you help me with that?


The distribution of the limit random variable

Question: Produce a sequence of random variables $\left\{X_{n}\right\}_{n \geq 0}$ as follows: Let $X_{0}=q$ with probability 1, where $q \in(0,1)$ is some constant. For $n \geq 1,$ let $X_{n}=X_{n-1}^{2}$ with probability $1 / 2$ and $X_{n}=2 X_{n-1}-X_{n-1}^{2}$ with probability $1 / 2 .$ Prove that $\left\{X_{n}\right\}_{n \geq 0}$ converges almost surely, and find the distribution of the limit random variable.
Thanks for your help!
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Answer: In order to talk about almost sure convergence we need the sequence $\{X_n\}_{n\geq 0}$ to live on the same probability space. So to formalize your question let $(\Omega,\mathcal{F}, \mathbb{P})$ be a probability space and let $\{Z_n\}_{n\geq 1}$ be an i.i.d sequence such that $\mathbb{P}(Z_n=1)=1/2=\mathbb{P}(Z_n=0)$. Your sequence can now be defined as:
$$
\begin{align}X_0:&=q\\
X_n:&=\mathbf{1}_{\{Z_n=1\}}X_{n-1}^2+\mathbf{1}_{\{Z_n=0\}}(2X_{n-1}-X_{n-1}^2)
\end{align}
$$
Can we use some symmetry of the random walk from  $X_{n-1}$ to $X_{n}$? (hint: martingale convergence theorem)
We now assume $X_n\longrightarrow X$ a.s. on $\Omega$. Is it possible for some $\omega\in\Omega$ that $X(\omega)\in(0,1)$? What does this tell us about the distribution of $X$?
Comment: Thanks for your kindly help!


Is it possible to have unit names added to each call to a function in a different unit?

Question: One of the problems I often run into, is that I will include 'Windows' in my uses clause, and then I will later add 'JwaWinBase' for some specific calls.
However, many of the functions in the 'Windows' unit are the same as in JwaWinBase, and I start getting errors in my main unit, all over the place, until I fix all my calls by pre-pending the correct unit name, like this:
Old:

CreateProcessAsUser(...)

New:

Windows.CreateProcessAsUser(...)
JwaWinBase.CreateProcessAsUser(...)

What I want to know, is if there is a way to have the unit name automatically pre-pended to every call to a function in another unit? This way, before I added JwaWinBase to my uses clause, I could have the 'Windows' unit name pre-pended to any function calls. Then adding JwaWinBase wouldn't give me any errors.
I'm currently using Delphi 2007.
Answer: There isn't.
However, the function calls are handled in the reverse order they're in the uses clause, so that if you have this:
uses
  Windows, JwaWinBase;

... it will call Jwa functions by default. However, if you reverse them:
uses
  JwaWinBase, Windows;

... it should call the Windows functions by default, and you can preface your Jwa functions as required.
Answer: If you really need the resolution on a per-routine base, you could try inline forwarders:
procedure Blah; inline;
begin
  Windows.Blah;
end;

procedure Blubb; inline;
begin
  JwaWinBase.Blubb;
end;

// later:
procedure UseThem;
begin
  Blah; // calls Windows.Blah
  Blubb; // calls JwaWinBase.Blubb
end;

at the beginning of the implementation section (completely untested :-)).
Answer: Maybe it's enough to just switch the order of the two units in the uses clause.
Answer: If you use an editor like CodeRush (D7 and before) or Castalia or even the template feature of D2009, you can create templates that expand to what you want AS you enter them. Then you can keep the Windows, jwaWinBase order in the uses section. You can set jcpau to expand to jwaWinBase.CreateProcessAsUser while cpau expands to CreateProcessAsUser or to Windows.CreateProcessAsUser depending on your preference. You'd only have to go through the various functions in jwaWinBase and make templates for them to be safe.
Otherwise, I think it's search and replace on a case-by-case basis.


Is it possible to use multiple "character sets" in a visual studio 2010 project?

Question: As you know, in visual studio 2010(c++) we have noset, unicode and MBCS character sets, and we can set it by menus or by preprocessor directive like #define _UNICODE.
   I'm working on a project, it has a file that uses MBCS characterset to produce information (in fact it parse a html file!), and other files in the project work by unicode character set to support assian languages. I've test it by adding #define _MBCS for the file and #define _UNICODE for main file, but received some compiler errors.
   Now is there anyway to solve this problem?
Comment: What are the errors that you get?
Comment: @ivan Along with a [MCVE] of course.
Comment: for example like this: atlconv.h(776): error C2440: 'return' : cannot convert from 'LPCTSTR' to 'LPCOLESTR'
Comment: Are you saying that data is in different character encodings.  Or are you saying that your source files are in different character encodings?
Comment: The file get html file as an array of bytes. And Analyse it. If I use unicode, I should convert it to wchar_t that is time consuming and may be not safe.
Answer: LPCTSTR is the pointer to TCHAR (string).  It maps to either LPWSTR (wide char string) or LPCSTR (ansi string) depending if the _UNICODE or UNICODE defines were set.  All of this TCHAR stuff was a holdover from the Windows 9x days when the earlier versions of Windows didn't have Unicode support in their APIs, but developers wanted to target compiling for both NT and 9x.  All of this should be well deprecated by now.
My advice - get rid of all your TCHAR code and be explicit when using ANSI vs. UNICODE strings.

Convert all your project settings to Unicode.
Explicitly convert all LPTSTR, LPCTSTR, TCHAR, variables to be explicitly, LPWSTR, LPCWSTR, or WCHAR.  Or when explicitly dealing with ANSI strings: LPSTR (char*), LPCSTR (const char*), or CHAR (char).
Be explicit when calling Win32 APIs.  Use the "A" version of APIs when you want to process an ANSI string (e.g. CreateWindowA vs. CreateWindowW).
MultiByteToWideString and WideStringToMultiByte are your friends.
Comment: Thanx. In case number 3, for example the file uses BYTE pTag[1024]; array or _tcsupr((_TCHAR*)pTag) and _tcscmp((_TCHAR*)pTag, state) and _tcscpy(result, (_TCHAR*)state); functions, and using Unicode makes results to be uncorrect!
Comment: Same thing for C runtime functions.  Either use `strcpy / strcmp` or `_wcscpy / _wcscmp` explicitly.  The fact that the existing code was explicitly casting is scary to begin with.
Comment: Thanx. and what about "BYTE pTempData[FRAME_BUFFER_SIZE]; InternetReadFile(hURL, pTempData, numberOfBytesToRead, &numberOfBytesRead);" function? pTempData contains html file! And I think converting it to wchar_t does not work!
Comment: InternetReadFile will copy the **bytes** of the HTML file into your byte buffer. After InternetRealFile returns, you'll likely have a set of ascii bytes in your pTempData.  So at this point you should null terminate this array and copy to an allocated `char*` or `char[]` buffer.  It's up to you if you want to convert this string to Unicode - it depends on what you want to do and/or the source enccoding of that HTML file.
Comment: Thanx. I think I must try it again!


ConfigNameException: Missing namespace in Config object name xxx

Question: Drupal\Core\Config\ConfigNameException: Missing namespace in Config object name media_entity_file_replace. in Drupal\Core\Config\ConfigBase::validateName() (line 97 of core/lib/Drupal/Core/Config/ConfigBase.php).
i don't quite get what i have done wrong in my config form
media_entity_file_replace/src/Form/MediaEntityFileReplaceSettingsForm.php
namespace Drupal\media_entity_file_replace\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Configure media_entity_file_replace settings for this site.
 */
class MediaEntityFileReplaceSettingsForm extends ConfigFormBase {

Answer: The error comes from Drupal\Core\Config\ConfigBase:
public static function validateName($name) {
  // The name must be namespaced by owner.
  if (strpos($name, '.') === FALSE) {
    throw new ConfigNameException("Missing namespace in Config object name {$name}.");
  }
...

Do you reference a configuration object somewhere in your form without a period? For example:
$config = \Drupal::config('config_with_no_namespace');

Comment: This is the reason. I understand why the reason of the exception is not much clear: The documentation for `\Drupal::config()` doesn't make it explicit; it just says that the name of the configuration object, passed to the method, typically corresponds to a configuration file. If the configuration file is media_entity_file_replace.yml, passing *media_entity_file_replace* to `Drupal::config()` seems correct.
Comment: I agree that it's not clear. I'm sure you get it, but for people who may be confused by this, the rationale is that it avoids configuration name clashes - you might have a configuration for your module called `general_settings` but so might many other modules, namespacing it with the module name ensures it's unique, e.g. `mymodule.general_settings`.
Comment: fixed with renaming config/install/media_entity_file_replace.settings.yml and $config = $this->config('media_entity_file_replace.settings');


Get Last file in Last year Last month Folder using Excel 2016

Question: I have a script that is getting the last file from the folder and saving it with current date for daily report logs. However, the problem I have ran into this month is that my script isn't able to look at last year December and getting the last file in that folder. I had to manually copy the file over. Could someone help me with my script.
Dim WB1 As Workbook
Dim WB2 As Workbook
Dim oPath As String
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
Dim oPath2 As String
' Turn off Display Alerts and Screen Updates
Application.DisplayAlerts = False
Application.ScreenUpdating = False
' Open Current Year - Month Folder find the last file in the folder and open it (if Error GoTo error label)
oPath = "X:\Resource_Management\Historical_Files\Pre_Consolidated_Fund_Status_Workbooks\" & "FY" & _
    Year(Date) & "\" & MonthName(Month(Date), False)
    If Right(oPath, 1) <> "\" Then oPath = oPath & "\"
    MyFile = Dir(oPath & "*.xlsx", vbNormal)
    If Len(MyFile) = 0 Then
        GoTo GetPreviousFile:
    End If
    Do While Len(MyFile) > 0
        LMD = FileDateTime(oPath & MyFile)
        If LMD > LatestDate Then
            LatestFile = MyFile
            LatestDate = LMD
        End If
MyFile = Dir
Loop
Workbooks.Open oPath & LatestFile
GoTo CreateFolder:

CreateFolder:
Application.DisplayAlerts = False
Application.ScreenUpdating = False
' Check for year folder and create if needed
If Len(Dir("X:\Resource_Management\Historical_Files\Pre_Consolidated_Fund_Status_Workbooks\" & "FY" & _
    Year(Date), vbDirectory)) = 0 Then
    MkDir "X:\Resource_Management\Historical_Files\Pre_Consolidated_Fund_Status_Workbooks\" & "FY" & Year(Date)
End If
' Check for month folder and create if needed
If Len(Dir("X:\Resource_Management\Historical_Files\Pre_Consolidated_Fund_Status_Workbooks\" & "FY" & _
    Year(Date) & "\" & MonthName(Month(Date), False), vbDirectory)) = 0 Then
    MkDir "X:\Resource_Management\Historical_Files\Pre_Consolidated_Fund_Status_Workbooks\" & "FY" & _
    Year(Date) & "\" & MonthName(Month(Date), False)
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
GoTo SaveFile:
End If

SaveFile:
' Save File
    Application.DisplayAlerts = False
    Application.ScreenUpdating = False
    ActiveWorkbook.SaveAs Filename:= _
        "X:\Resource_Management\Historical_Files\Pre_Consolidated_Fund_Status_Workbooks\" & "FY" & _
        Year(Date) & "\" & MonthName(Month(Date), False) & "\" & _
        "Consolidated_Fund_Status-CURRENT_DATA-" & Format(Application.WorkDay(Date, 0), "mm.dd.yyyy") & _
        ".xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    ' Save any changes on exit, Turn on Screen Updates and Alerts
    ActiveWorkbook.Close SaveChanges:=True
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    Exit Sub

' Open file from last months folder and the last file in that folder (on Error Resume Next)
GetPreviousFile:
    Application.DisplayAlerts = False
    Application.ScreenUpdating = False
    On Error Resume Next
    MyPath = "X:\Resource_Management\Historical_Files\Pre_Consolidated_Fund_Status_Workbooks\" & _
        "FY" &Year(Date) & "\" & MonthName(Month(Date - 1), False)
        If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
        MyFile = Dir(MyPath & "*.xlsx", vbNormal)
        If Len(MyFile) = 0 Then
            'MsgBox "No Files were found...", vbExclamation
        End If
        Do While Len(MyFile) > 0
            LMD = FileDateTime(MyPath & MyFile)
            If LMD > LatestDate Then
                LatestFile = MyFile
                LatestDate = LMD
            End If
        MyFile = Dir
        Loop
        Workbooks.Open MyPath & LatestFile
        GoTo CreateFolder:
' Turn back on Display Alerts and Screen Updates
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Comment: Try `Year(DateAdd("m", -1, Date)) & "\" & MonthName(Month(DateAdd("m", -1, Date)))`
Comment: So in this portion of the script make it something like this
Comment: So in this portion of the script make it something like this `GetPreviousFile:
    Application.DisplayAlerts = False
    Application.ScreenUpdating = False
    On Error Resume Next
    MyPath = "X:\Resource_Management\Historical_Files\Pre_Consolidated_Fund_Status_Workbooks\" & "FY" &Year(DateAdd("m", -1, Date)) & "\" & MonthName(Month(DateAdd("m", -1, Date)))
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "*.xlsx", vbNormal)
If Len(MyFile) = 0 Then  ' MsgBox "No Files were found...", vbExclamation
End If`
Comment: Yes, you can use it there or anywhere you need the previous month's date. Alternatively, you could create a variable with this date-string and then just use that: `Dim lastMonth As String; lastMonth = Year(DateAdd("m", -1, Date)) & "\" & MonthName(Month(DateAdd("m", -1, Date)))`, then `MyPath = "X:\Resource_Management\Historical_Files\Pre_Consolidated_Fund_Status_Workbooks\" & "FY" & lastMonth`
Answer: This was answered by PeterT
Yes, you can use it there or anywhere you need the previous month's date. Alternatively, you could create a variable with this date-string and then just use that:
Dim lastMonth As String; lastMonth = Year(DateAdd("m", -1, Date)) & "\" & MonthName(Month(DateAdd("m", -1, Date))), then MyPath = "X:\Resource_Management\Historical_Files\Pre_Consolidated_Fund_Status_Workbooks\" & "FY" & lastMonth

– PeterT
Answer: After some time I needed to find a better way to get my end results and this is what i came up with. I worked on creating a FUNCTION to calculate the work days of the month. My code to look something like this:
Function WorkdayOfMonth(ByVal dtInput As Date) As Integer
    Dim dt As Date
    Dim i As Integer
    If Weekday(dtInput, vbMonday) < 6 Then
        For dt = DateSerial(Year(dtInput), Month(dtInput), 1) To dtInput Step 1
            If Weekday(dt, vbMonday) < 6 Then i = i + 1
        Next dt
        WorkdayOfMonth = i
    Else
        WorkdayOfMonth = 0
    End If
End Function

I placed this FUNCTION at the end of my sub and for my sub I modified my code to look something like this:
Dim oPath, FPath, MyPath, MyFile, LatestFile, FiscalYR, CFYMnth, PRFYMnth, PRFYear As String
Dim Lastrow, lCopyLastRow, lDestLastRow As Long
Dim LatestDate, LMD As Date
Dim wsCopy, wsDest As Worksheet

If MonthName(Month(Date), False) = "October" Then
    FiscalYR = Year(Date) + 1
    ElseIf MonthName(Month(Date), False) = "November" Then
        FiscalYR = Year(Date) + 1
        ElseIf MonthName(Month(Date), False) = "December" Then
            FiscalYR = Year(Date) + 1
    Else
        FiscalYR = Year(Date)
End If

PRFYear = FiscalYR - 1
CFYMnth = MonthName(Month(Date), False)
PRFYMnth = MonthName(Month(Date) - 1, False)

    ' Turn off Display Alerts and Screen Updates
Application.DisplayAlerts = False
Application.ScreenUpdating = False

    ' Open Month Folder find the last file in the folder and open it ()
If CFYMnth = "October" Then
    If WorkdayOfMonth(Date) > 0 And WorkdayOfMonth(Date) <= 3 Then
    End If
    MyPath = "X:\Resource_Management\Historical_Files\Final_Consolidated_Fund_Status_Workbooks\" & _
        PRFYear & "\" & PRFYMnth
        If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
        MyFile = Dir(MyPath & "*.xlsx", vbNormal)
        If Len(MyFile) = 0 Then
            'MsgBox "No Files were found...", vbExclamation
        End If
        Do While Len(MyFile) > 0
            LMD = FileDateTime(MyPath & MyFile)
            If LMD > LatestDate Then
                LatestFile = MyFile
                LatestDate = LMD
            End If
        MyFile = Dir
        Loop
        Workbooks.Open MyPath & LatestFile
    GoTo FinalConsolFSWSaveAsProcess
Else
    If Len(Dir("X:\Resource_Management\Historical_Files\Final_Consolidated_Fund_Status_Workbooks\" & _
        FiscalYR & "\" & CFYMnth)) = 0 Then
        oPath = "X:\Resource_Management\Historical_Files\Final_Consolidated_Fund_Status_Workbooks\" & _
                FiscalYR & "\" & PRFYMnth
                If Right(oPath, 1) <> "\" Then oPath = oPath & "\"
                MyFile = Dir(oPath & "*.xlsx", vbNormal)
                If Len(MyFile) = 0 Then
                        'MsgBox "No Files were found...", vbExclamation
                End If
            Do While Len(MyFile) > 0
                    LMD = FileDateTime(oPath & MyFile)
                    If LMD > LatestDate Then
                    LatestFile = MyFile
                    LatestDate = LMD
                    End If
            MyFile = Dir
            Loop
            Workbooks.Open oPath & LatestFile
        GoTo FinalConsolFSWSaveAsProcess
    Else
        oPath = "X:\Resource_Management\Historical_Files\Final_Consolidated_Fund_Status_Workbooks\" & _
            FiscalYR & "\" & CFYMnth
            If Right(oPath, 1) <> "\" Then oPath = oPath & "\"
            MyFile = Dir(oPath & "*.xlsx", vbNormal)
            If Len(MyFile) = 0 Then
                'MsgBox "No Files were found...", vbExclamation
            End If
            Do While Len(MyFile) > 0
                LMD = FileDateTime(oPath & MyFile)
                If LMD > LatestDate Then
                    LatestFile = MyFile
                    LatestDate = LMD
                End If
        MyFile = Dir
        Loop
        Workbooks.Open oPath & LatestFile
    GoTo FinalConsolFSWSaveAsProcess
End If
End If

FinalConsolFSWSaveAsProcess:
    ' Save File in current month and FY location
ActiveWorkbook.SaveAs Filename:= _
"X:\Resource_Management\Historical_Files\Final_Consolidated_Fund_Status_Workbooks\" & _
    FiscalYR & "\" & CFYMnth & "\" & _
    "FY" & FiscalYR & " Consolidated_Fund_Status_Workbook-" & _
    Format(Application.WorkDay(Date, 0), "mm.dd.yyyy") & _
    ".xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    ' Save any changes on exit, Turn on Screen Updates and Alerts
ActiveWorkbook.Save
ActiveWorkbook.Close SaveChanges:=True
    ' Turn back on Display Alerts and Screen Updates
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

This is working perfectly for what I need it to do. I hope this helps others.


Bootstrap embed responsive is not formatted well for mobile browser in landscape

Question: I am using the latest version of bootstrap and included the responsive embed for my youtube videos with the bootstrap container. The container sizes the video well within the constraints on the container however, the video looks very large while in landscape, taking up too much space. I think this is becuase the bootstrap container class changes its width based on media-queries which works fine for mobile devices in portrait but not well for mobile devices in landscape. Here is the standard code that I am using:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

Is there any way that I can fix the container so that it improves the formatting of the video in landscape?
Comment: post a screenshot. I just recreated it and it looks just fine to me.
Comment: Due to width-media query, you need to scroll videos in landscape view because it is taking lot of space in width, is this what you meant?
Comment: @ZombieChowder if you run the code snippet without being in full-page mode, you can clearly see that you have to scroll the entire iframe because it is clearly too large. This is because the bootstrap container class resizes based on the width-media query and does not account for device height. So when a phone is in landscape you have to scroll the entire iframe. I want the iframe to shrink in size so that the full iframe is displayed without scrolling when the user changes screen orientation to landscape. The container class does not account for this edge case.
Comment: @AjinkyaRathod yes, that is correct. I want to correct this issue. It has to do with the height of the device because the Bootstrap container class accounts for the width of the window but doesn't account for changes in height. Scrolling wouldn't be necessary if the device height was bigger but the device changes media-height when the user changes screen-orientation to landscape. It only matters for mobile/tablet devices.
Comment: Maybe wrap it on a row and col and limit the size of the column on bigger screen like with col-lg-6
Answer: TL;DR

The non recommmended way (Adding vh )

The core issue is that mobile browsers (I'm looking at you, Chrome and Safari) have a "helpful" feature where the address bar is sometimes visible and sometimes hidden, changing the visible size of the viewport. Rather than adjusting the height of 100vh to be the visible portion of the screen as the viewport height changes, these browsers instead have 100vh set to the height of the browser with address the address bar hidden. The result is that the bottom portion of the screen will be cut off when the address bar is visible, thus defeating the purpose of 100vh to begin with.
A better solution (window.innerheight)
One way to get around this issue is to rely on javascript instead of css. When the page loads, setting the height to window.innerHeight will correctly set the height to the visible portion of the window. If the address bar is visible, then window.innerHeight will be the height of the full screen. If the address bar is hidden, then window.innerHeight will be the height of just the visible portion of the screen, as you'd expect.Source
This works perfectly fine until you do not resize your browser window.
If you resize the window, you need to change height according to new window.innerheight. This can be achieved by calling a function everytime the window resizes or the element (i.e video) resizes
Full Code

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

When the video will load, onload() event will be fired and the height of the video will be the innerheight of the current window and this will work well for mobile devices in potrait views as well as landscape views
Comment: How to do that for only mobile devices in landscape?

`function my_function() { if (window.matchMedia("(orientation: landscape)").matches && window.innerWidth <580) { document.getElementById('embed1').style.maxHeight = window.innerHeight; }} `

This will do the job, but if you want to detect mobile devices, refer [this](https://stackoverflow.com/questions/11381673/detecting-a-mobile-browser)

The disadvantage is that, there is no way for testing this bcoz if you resize the browser in developer options, the browser will NOT detect the device as mobile device.
Comment: This worked for me thanks! I do have a navbar at the top of the window and a footer at the bottom so I had to subtract their `outerHeights` from `window.innerHeight` minus an additional 30px to make the video fit well. I also have the video's `min-width: 100%` so that it would be responsive and fit within the container's and column's width for any screen size. I also need to change the video's width for this case too. Any simple idea's on how to do that for only mobile devices in landscape?
Comment: Also, one thing that I noticed is that the max-height for all videos isn't always consistent as I change screen orientation, so sometimes it works and other times it doesn't. Here is what I did: `$(".yvideo").each(function(index) {
    let video = $(".yvideo").get(index);
    video.style.maxHeight = window.innerHeight - $("#top_navbar").outerHeight(true) - $("#footer").outerHeight(true) - 30;
  });`


Any tips on learning bar chords for guitar-playing?

Question:
Possible Duplicate:
How can I best learn to play barre chords?

I am trying to practice songs with bar chords every now and then, but was wondering if anyone had any tips to learn to play bar chords well/comfortably.
Answer: Practice, practice, and keep practising!
One thing I used to find was useful is just switching between (say) a D and a Bm chord. Concentrate on getting all the notes to ring out properly and do it slowly and carefully. Then gradually build up speed. You'll find the muscles in your hand will develop and your fingers will begin to find the right positions naturally after a while.


Computer Networks bonus: find MTU less than 1500

Question: This is a bonus question in my Networks class: I have to find a destination for which the path MTU < 1500 bytes.
For example using the command
traceroute -F www.uwaterloo.ca 1500 works, and traceroute -F www.uwaterloo.ca 1501 doesnt.
So I need to find a destination that will fail under 1500 (and no it can not be a private network, that would be cheating).
I am suspecting this is a trick because nearly all IP over Ethernet implementations use the Ethernet V2 frame format, which supports 1500 MTU.
Any ideas?
Comment: PPPoE (e.g., DSL lines) is a good place to try.
Comment: @kce - homework questions are *not* off topic, but you need to be honest (the op has been), and show your prior learning (which the op has), explain what you *think* the answer is and ask for feedback. The OP has sufficiently fulfilled most of these, and thus it can stay.
Comment: Check if there are any PPP connections, or any ATM or frame relay ones perhaps (e.g. leased lines). Those may have a smaller MTU. Or anything encapsulated in VPN-type connections.
Comment: Got any modems (e.g. 'dialup') nearby?
Comment: Homework questions are off-topic. Please read the [FAQ](http://serverfault.com/faq).
Comment: @MarkHenderson - I stand corrected.
Comment: No, you don't "need to find a destination that will fail under 1500". You simply need to test with a packet larger than the MTU of the target. The 1500 is an example, not an absolute. As for the use of a private network being cheating, how to do classify getting others to help you with your homework? Sure looks like cheating to me.
Comment: @John Gardeniers  to your first part of your comment, yes i agree i know that. As for the 2nd part about cheating, you need to lighten up, we have all semester to give him the answer for a miniscule 2% bonus to our final grade. I am being resourceful and honest, and as so I will also inform him how i came about finding my answer (if i do at all)
Answer: How much time do you have? You can brute force this. For example like this bash script:
while [ 1 ]
do
    ip=`expr $RANDOM \* $RANDOM`;
    traceroute -F -I $i 1472 2>/dev/null >/dev/null
    if [ $? -ne 0 ]
    then
        echo Traceroute with 1472 bytes failed for $i
        exit
    fi
done

Caveat: This message displays IPs as an integer, you'll have to convert it to a dot separated octal format. Also, note that traceroute uses ICMP by default. In that case you need to set the data size to 1472 bytes (1472 + 8 bytes ICMP header + 20 bytes IP header) = 1500 bytes.
Comment: You probably want to do two pings—one with a fairly small packet and one with the larger (1500 byte packet), and see which hosts only respond to the small one. Two pings will be much quicker than a traceroute.
Comment: You can cheat creatively! Change your home router's outbound interface MTU. Or set up a linode VPS (therefore you get a public IP), change the eth0 MTU to less than 1500. The question is, in case of the latter is it worth the $19 monthly fee ;-).
Comment: Agree, you can also make educated guesses and pick IP ranges without trying random ip addresses.
Comment: i have used your idea but with pinging, and am currently running 50 processes of this script in parallel. lets hope the school doesn't ban my account. so far im just getting "connect: invalid arguement" which means some pings are trying to ping ip address that starts with 0 for example. Will let you know how this goes
Comment: so i talked to students who already took this course and apparently nobody has been ever able to answer this question in all the years he has taught the course. Also no luck with brute force
Comment: @Stefan: I'm somewhat surprised you can't find one *anywhere*, though I suppose the last time I had one (temporarily) in a network I was using, it was painful. A lot of people configure firewalls to break PMTUd, yet leave it enabled on their servers. Or at least did back in the early 2000s.
Comment: @skjaidev - I like your thinking. That's the sort of initiative I look for when I'm hiring ;)
Answer: Search on internet for an IP assigned to an ADSL modem (most of them are using PPPoE or PPPoA). Run durring your ping tests a tcpdump icmp and pay attention to ICMP Fragmentation Needed (Type 3, Code 4). If you see that you found your target.


Syndrome computation of BCH code

Question: I'm just trying to understand one basic property of BCH code. It was mentioned in many articles that, for binary BCH code, syndrome computation has such property: $$S_{2i+1} = (y(\alpha^{i+1}))^2=S_i^2$$, where $y(x)$ is the received codeword. However, I wonder if all the polynomial evaluation over the finite field elements under the same cyclotomic cosets can be done in a similar way. For example, for $GF(2^3)$, $\{\alpha^3,\alpha^5,\alpha^6\}$ is the coset, where $\alpha^6 = \alpha^{3*2} \ \text{and} \ \alpha^5 = \alpha^{3*2^2 mod \ 7}$. As shown above, $S_5 = S_2^2$. However, isn't that $S_4 = S_2^{2^2}$? The prove is shown as follows $$S_2^{2^2} = (y(\alpha^3))^{2^2} \\ = y(\alpha^{12 \ mod \ 7}) \\ = y(\alpha^{5}) \\ =S_4$$. Can someone helps me verify if this is true? Note: For binary BCH code, $(y(\alpha^3))^{2^2} = y(\alpha^{12})$ is valid. For the reference, this property is mentioned in this article: "Generalized Integrated Interleaved Codes" by Yingquan Wu.
Edited version:
Since this question is not clear, I would like to simplify it into one short question. For $GF(2^8)$, is $$y(α^{49})=(y(α^{19}))^{2^4}$$ right or wrong? If it is wrong, can someone prove it to me?
So the conclusion by @rcgldr:
The above equality is correct. And, $S_{48}=S_{18}^{2^4}$
Comment: Can you _provide a reference_ to at least one article which states that $S_{2i+1}$, which typically means the value of $y$ evaluated at $\alpha^{2i+1}$ and not the square of the value of $y$ at $\alpha^{i+1}$ , equals $S_i^2$??  As a general rule, $S_{2i} = y(\alpha^{2i}) = y(\alpha^i)^2 =  S_i^2$
Comment: The reference is attached in the question. Actually, both are the same thing. Just that $S_i = y(\alpha^{i+1})$ in this situation.
Comment: The point of my question is that this property does not restrict to the case of taking the square. The syndromes corresponding to the finite field elements in the same cyclotomic coset can be computed in the same manner
Comment: @DilipSarwate - This works because in larger fields, $S_2^4 = S_{11}$, and in GF(2^3), $S_{11} = S_{11\%7} = S_4$.
Answer: This question uses nonstandard notation.
From the equation fragment $(y(\alpha^{i+1}))^2=S_i^2$ used by the OP, it seems that in the OP's world, the following definition is believed to apply:
$$S_i \stackrel{\Delta}{=} y(\alpha^{i+1}) \tag{1}$$
in contrast to the more usual $S_i = y(\alpha^i)$.  Now, noting that $0^2=0$ and $1^2=1$, we have that if $f(x)$ denotes a polynomial with coefficients in $GF(2)$, then
$$[f(x)]^2 = \left(\sum_k f_k x^k\right)^2 = \sum_k (f_k)^2 x^{2k}
= \sum_k f_k x^{2k} = f(x^2)$$
so that
$$(y(\alpha^{i+1}))^2 = y(\alpha^{2i+2}) \tag{2}$$
to which we apply the OP's convention $(1)$, viz. that the subscript on $S$ is $1$ less than the superscript on $\alpha$, to arrive at the result that
$$S_{2i+1} = y(\alpha^{2i+2}) = [y(\alpha^{i+1})]^2 = S_i^2$$
as claimed by the OP.
The OP then asks with respect to $GF(2^3)$ where $$\left\{\alpha^3, (\alpha^3)^2, (\alpha^3)^{2^2}\right\} = \left\{\alpha^3, \alpha^6, \alpha^{12}\right\} = \left\{\alpha^3, \alpha^6, \alpha^{5}\right\}$$
that while in his world,
$$S_2 = y(\alpha^3) \implies S_2^2 = (y(\alpha^3))^2 = y(\alpha^6) = y(\alpha^{5+1}) = S_5 ~\text{vide}~ (1),$$ he is not absolutely sure whether
$S_2^4$ equals $S_4$ or not.  Well,
$$S_2^4 = y(\alpha^{12}) = y(\alpha^{7+5}) = y(\alpha^5) = y(\alpha^{4+1}= S_4 ~\text{vide}~ (1)$$
sure enough.

And yes, the OP's claim that in $GF(2^8)$, $\alpha^{49} = (\alpha^{19})^{2^4}$ is perfectly correct. Those used to working with finite fields would simply use the law of exponents to write
$$19 \times 16 = 304 = 255+49$$ to verify the claim.
Comment: Using the questions naming convention, in a larger field, $S_2^4 = S_{11}$, but in GF(2^3), $S_{11}$ maps to  $S_4$. Likewise in a larger field, $(\alpha^{19})^4 = \alpha^{304}$, but in GF(2^8), $\alpha^{304}$ maps to $(\alpha^{49})$
Answer: The question uses non-standard naming convention for the syndromes:
$$S_i = y(\alpha^{i+1})$$
Using the questions naming convention, the odd syndromes $S_1, S_3, S_5, ... $ are powers of other syndromes, therefore redundant and optionally skipped when using Berlekamp Massey decoder:
$$S_1 = (y(\alpha^1))^2 = S_0^2$$
$$S_3 = (y(\alpha^2))^2 = S_1^2 = S_0^4$$
$$S_5 = (y(\alpha^3))^2 = S_2^2$$
$$S_7 = (y(\alpha^4))^2 = S_3^2 = S_0^8$$
$$S_9 = (y(\alpha^5))^2 = S_4^2$$
$$S_{11} = (y(\alpha^6))^2 = S_5^2 = S_2^4$$

In GF(2^3), does $S_4 = S_2^4$ ?

Yes. In a larger field, $S_2^4 = S_{11}$. In GF(2^3), $S_{11} = S_{11\%7} = S_4$.

In GF(2^8), does $S_{48} = S_{18}^{16}$?

Yes. In a larger field, $S_{18}^{16}$ = $S_{303}$. In GF(2^8), $S_{303} = S_{303\%255} = S_{48}$.

Using standard naming convention for syndromes common to BCH code and Reed Solomon code:
$$S_i = y(\alpha^i)$$
$$S_{2i} = S_i^2$$
If using Berlekamp Massey decoder, then even syndromes (S2, S4, S6, ...) are redundant and can be skipped (see next section), while odd syndromes (S1, S3, S5, ...) are required in order to decode.
For smaller fields of $GF(2^n)$, an even syndrome of higher order $a$ greater than $2^{n-1}$ and less than $2^{2n-2}$ will map to an odd syndrome of lower order $b$: $S_a = S_{a\%(2^{n-1})} = S_b$ This allows $S_b$ to be calculated by using the formula $S_b = S_a = S_{a/2}^2 = S_{a/4}^4 = $ ... .
Note - unlike BCH code, for Reed Solomon code, all syndromes are required.

To explain why the formula works for even syndromes but not odd, in GF(2^n):
$$(a+b)^2 = a^2 + b^2$$
$$(a+b)^3 = a^3 + a^2 b + a b^2 + b^3$$
$$(a+b)^4 = a^4 + b^4$$
$$(a+b)^5 = a^5 + a^4 b + a b^4 + b^5$$
$$...$$
$$(a+b+c\ +...)^2 = a^2 + b^2 + c^2 + ... $$
Consider a 2 error case in GF(2^8) with reducing polynomial hex 11d, 6 syndromes, with errors at x^4 and x^8. Using hex:
$$S_1 = (2^1)^4 + (2^1)^8 = 0d $$
$$S_2 = (2^2)^4 + (2^2)^8 = 51 $$
$$S_3 = (2^3)^4 + (2^3)^8 = 42 $$
$$S_4 = (2^4)^4 + (2^4)^8 = d1 $$
$$S_5 = (2^5)^4 + (2^5)^8 = de $$
$$S_6 = (2^6)^4 + (2^6)^8 = c9 $$
For the even syndromes:
$$S_1^2 = ((2^1)^4 + (2^1)^8)^2 = ((2^1)^4)^2 + ((2^1)^8)^2 = (2^2)^4 + (2^2)^8 = S_2$$
$$S_2^2 = ((2^2)^4 + (2^2)^8)^2 = ((2^2)^4)^2 + ((2^2)^8)^2 = (2^4)^4 + (2^4)^8 = S_4$$
$$S_3^2 = ((2^3)^4 + (2^3)^8)^2 = ((2^3)^4)^2 + ((2^3)^8)^2 = (2^6)^4 + (2^6)^8 = S_6$$
But this strategy doesn't work for the odd syndromes.
Comment: Ok. But, for GF(2^8), why $y(\alpha^{49})$ cannot computed from $y(\alpha^{19})$. As $\alpha^{49} = \alpha^{19*2^4 \ mod \ 255}$. This two finite field elements belong to the same cyclotomic coset.
Comment: I don't think you understand my question.  I know that when taking an odd power of a polynomial, the power can not be directly applied to the coefficient of the polynomial as shown in the second and fourth equation. However, for the way of constructing the cyclotomic coset, some finite field element with odd power can be derived by each other.
Comment: For example, consider GF(2^8). $\{\alpha^{19},\alpha^{19*2},\alpha^{19*2^2},\cdots,\alpha^{19*2^7}\}$ is the one of the coset. Taking the modulo of $2^8-1 = 255$, the coset is constructed as $\{\alpha^{19},\alpha^{38},\alpha^{49},\alpha^{76},\alpha^{98},\alpha^{137},\alpha^{152},\alpha^{196}\}$.
Comment: You can see that $(\alpha^{19})^{2^4}=\alpha^{19*2^4 \ \text{mod} \ 255}=\alpha^{49}$. Therefore, why $y(\alpha^{49}) = (y(\alpha^{19}))^{2^4}$ is wrong, which I really don't get it.
Comment: To explain how the second equation is derived, since $y(x)$ is a binary polynomial and we are taking an exponent of power of 2, $(y(\alpha^{19}))^{2^4}=y(\alpha^{19*2^4 \ \text{mod} \ 255}) = y(\alpha^{49})$.
Comment: I do not intend to use $\alpha^{19}$ as a primitive element. You did not specifically answer the question I ask above. Why $y(α^{49})=(y(α^{19}))^{2^4}$ is wrong.
Comment: The modification you made above does not prove whether if this equality is right or wrong.
Comment: $\alpha$ is defined as a primitive element here.
Comment: I saw your revised answer. The point of my question is not focusing on the odd syndromes of BCH codes. Some of the odd syndromes can be computed in a much simpler method as I mentioned above. Specifically for the equality that I've shown above, can you prove if it is right or wrong? Or there is no point for me to keep my discussion with you further.
Comment: Your statement regarding $S_4 = S_2^4$ is wrong. I'm really don't know why taking the module will change the result. For example, $y(x)=1+x+x^3$. $y(\alpha^5) = 1+\alpha^5 + \alpha^{15 \ \text{mod} \ 7 = 1}$. $(y(\alpha^3))^{2^2} = 1+(\alpha^3)^{2^2} + (\alpha^9)^{2^2} = 1+ \alpha^5 +\alpha^{9*4 \text{mod} \ 7 = 1}$.
Comment: You are throwing those statements to me without actually prove it whether if it is right or wrong.
Comment: Which part of the equation shows that it involves higher-order syndromes that exceed the range for GF(2^n)? We are computing the same syndromes, just that the actual computation of this method involves modulo, which is the backbone of FINITE FIELD.
Comment: You seem to say that $S_2^4 = S_{11}$ which is not considered in the syndrome computation of GF(2^3)
Comment: If this statement is true, the whole idea of cyclotomic coset is collapsed.
Comment: This is not true. The actual computation of $S_2^4$ involves modulo. It is not equal to $S_{11}$.
Comment: Please answer my questions. 1) is $(y(α^3))^{2^2} = y(\alpha^5)$? 2) If this is equal, why $S^4_2 \neq S_4$? This has nothing to do with $S_{11}$ and the range of $GF(2^3)$.
Comment: $S_2^4 = S_4$ won't affect the actual implementation of BKM algorithm. $S_{2i+1}=S_i^2$ is the backbone of the BKM algorithm of BCH code as it shows the odd iteration of BKM can be skipped. The point of saying $S_2^4 = S_4$ is just simplifying the syndrome computations. It does not affect the discrepancies result of the even iterations as not all even syndromes can be computed in the same way. Only those in the same CYCLOTOMIC COSET have this property. So can you please answer my questions above? This will take no end if you keep avoiding to answer my questions specifically.
Comment: Thats why I mention 100 of times. $S_2^4=S_4$ does not follow the same property, $S_{2i+1}=S_i^2$. But it actually can be computed in that way. I'm really don't understand why you keep saying the equality, $S_2^4=S_4$, is not true. This won't affect the BKM results as not every even syndromes computed in this way, where only those in the same CYCLOTOMIC COSET.
Comment: Can you prove it to me if the value of $S^4_2$ is not equal to $S_4$.
Comment: More questions are asked in the chat.@rcgldr

Syndrome computation of BCH code


Do Push Notifications with content-available work for users that have disabled Push Notifications?

Question: I'm looking into reliable ways of updating an iOS app with content of critical importance, when instructed to do so by a server.
This would have to trigger regardless of the state of the app (foreground, background, not running, etc). Most sources seem to indicate that Push Notifications with the content-available: 1parameter are able of doing this.
My question is, what happens if the user either presses Cancel when prompted to allow the app to receive push notifications, or turns them off afterwards ? Is he only not going to receive alerts anymore, or will the push notifications be entirely ignored (including the content update) ? And if so, is there any other iOS feature that would reliably allow me to update the app's content (regardless of app state and without the user being able to disable it) ?
This is about iOS 7 and above.
Comment: Yes, the user who selected cancel when the enable push notification prompt is shown, will not receive any push notification payload.
Comment: But you can still use iOS Background App Refresh feature from ios 7 and above: http://www.devfright.com/ios-7-background-app-refresh-tutorial/
Answer: If user disallows the push notifications , you can not send them the notifications forcefully.
What kind of data you want to update afterwards?
Most of the data can be changed dynamically by web services...
Comment: My use case is: Each user is contacted by me once a year or so, and offered an additional feature within the app. The feature already exists within the app, but the user does not have access to it. I want to remotely and instantly enable that feature. Edit: Since I only need to trigger this once per year per user or so, the previously recommended Background App Refresh would be highly ineffective in terms of network usage, and it would also not enable me to update instantly as I cannot control exactly when it's triggered. How would a web service help me with this ? Thanks for the quick reply.


Performatic structure without data duplication

Question: Say I have the following classes:
public class Tagged {

    private List<String> tags;
}

public class ContainerOfTagged {

    private List<Tagged> tagged;
}

With this structure, whenever I need to find a Tagged with a specific tag, I need to iterate over all the tagged in ContainerOfTagged, and iterating over all tags of each Tagged. That could affect performance depending on the size of the lists.
A simple solution would be changing the ContainerOfTagged class to use a Map, mapping tags in lists of Tagged:
public class ContainerOfTagged {

    private Map<String, List<Tagged>> tagMapping;
}

Now all I need to do is provide a tag, and the Map will return all Tagged with said tag. However, by doing this I'm causing data duplication, since the same tags exist in both the Tagged and ContainerOfTagged classes.
So, is there a way to solve this problem with a performatic solution that doesn't duplicate data?
Comment: There are solutions for this, and this questions has been raised before on this site with different formulations. Other questions describe this as bi-multimaps, or as N:M relationships (using database terminology). Examples: http://stackoverflow.com/questions/8066109/bidirectional-multi-valued-map-in-java and http://stackoverflow.com/questions/3926642/how-to-implement-nm-relation-in-jva
Comment: Do you have so much data in the `ContainerOfTagged` that the memory usage is really an issue?
Comment: No, you can't avoid the duplication if you don't want to iterate.
Comment: Is an array an option ? Or can Tagged be an enum ? Also if the nunmber of tags is reasonable you can have a ContainerOfTagged for each tag.
Comment: @AndyTurner Memory usage is not a issue at the time. The current issue is performance when finding all Tagged with a specific tag.
Comment: @Flumen then just duplicate the data.
Comment: @c0der Sorry, but I fail to see how arrays or enums would help here. The ideia is that these classes would be part of project A, and other projects (which will depend on project A) would define the tags, so I can't know them beforehand.
Comment: @AndyTurner The problem with data duplication is that whenever I add/remove a tag in one place, I'll have to do so in the other place. In the long run, it will most likely cause many bugs.
Comment: If the number of tags is reasonable you can have a ContainerOfTagged for each tag which may make the search shorter. It will add some data but will not duplicate data.
Answer: You can't really avoid "duplicating" the tags, but remember that you are not really duplicating them as the Lists and Maps only store references to the tag string, not the values (however, the references are likely to take up quite a lot of space in themselves).
The problem is that you need two indexes:

You need to find the list of tags, given the Tagged object.
You need to find the Tagged object, given a tag.

Ideally, your solution would look like this.You can solve your concerns about things getting out-of-sync by having a single method to manage tagging.
Note that in Tagged you should use a Set instead of a list to avoid duplication of tags.
public class Tagged {
    Set<String> tags;
}

public class TagContainer {
    Map<String, Tagged> tagIndex;

    public tag(String tag, Tagged tagged) {
        tagged.tags.add(tag);
        tagIndex.put(tag, tagged);
    }

If memory utilisation is a major concern you could try some kind of reference compression. Using this technique, you could store your tags in a array and then refer to them by index. If you had few enough, you could use a byte or short instead of a reference, but the code would be a lot messier and I would not recommend it.
EDIT:
In my first post, I proposed that Tagged should be an interface called Tagable. This is cleaner, but lengthens the solution, so I reverted to a class. Howevever, you could perhaps consider having a Tagable interface and implement this in the Tagged class.
public interface Tagable {
    Set<String> getTags;
    tag(String tag);
}


Autocomplete com texto de div

Question: Opa, seguinte, tenho uma lista de links, o que preciso é que ao digitar num textbox esta lista seja filtrada por texto, é possível?
Seria uma especie de autocomplete sem banco de dados.
Comment: Deixa eu ver etendi, você tem digamos uma lista ja pronta em um JSON que contem seus links, ai você precisa de um select com um text input para filtrar a lista de links, sem precisar que a pessoa precise ver a lista toda para encontrar. e isso?
Comment: Quase, no caso não teria json, a consulta seria feita no conteúdo dentro do href, seria um tipo de sugestões, em que no momento da digitação os dados fossem filtrados.
Comment: Show de bola, fico no aguardo. Vlw
Answer: A Maneira mais simples de fazer o que você precisa e usando o angular JS, procure aprender um pouco mais sobre esse podoreso framework de javascript.
deixo um exemplo abaixo de como se faz a função que você precisa.
      <!DOCTYPE html>

              <input type="text" name="name" ng-model="filtro" value="">

{{item.site}}

Autocomplete com texto de div


Getting defined edges of filter:blurred image with background cover

Question: So i'm trying to make my background cover my entire screen and remain fixed, but i would like to use background-size: cover to make it fit on different screen ratios. Unfortunately, filter: blur() adds a nasty blurred edge to the picture which i don't want at all, so i'm looking for a way to fix it. On stackoverflow the suggestion is usually to move the picture's edges out of the viewport, but apparently with background-size: cover that simply doesn't work. Is there another way?
CSS snippet:
#background {
    position: fixed;
    height: 100%;
    width: 100%;
    filter: blur(5px); //blur
    background: linear-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, .5)), url("../Resources/img/background-medium.jpg") no-repeat center 35% fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

(#backgroundis just an empty div)
Answer: Place the #background in a container and add transform: scale(1.1) to the #background
.container {
   position: fixed;
   height: 100%;
   width: 100%;
   overflow: hidden;}

#background {
   height: 100%;
   width: 100%;
   filter: blur(5px); //blur
   background: linear-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, .5)), url("../Resources/img/background-medium.jpg") no-repeat center 35% fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
   transform: scale(1.1);}


Null input character spamming Linux tty

Question: My Linux TTY is being spammed by null characters, which are preventing me from logging in. This is the case on all 6 TTY inputs. This issue seems to come and go randomly. I have tried disconnecting and reconnecting all hardware.
Any help is much appreciated :)
!
Comment: Try entering this: `tput reset` followed by Control-J.
Comment: @codeforester No luck, I can't even log in on the TTY inputs (only the X login) due to the characters spamming my login
Answer: Try to hit the capslock key and hold shift to type your login and password, after this you can try configure the system

Null input character spamming Linux tty


Lower bound of an integral

Question: How might I find a constant $k>0$ s.t. $\int\limits_0^1|f(x)|dx\geq k\max\{|f(x)|:x\in[0,1]\}$ for all continuous $f$ defined on $[0,1]$? Thank you.
Comment: No such constant $k > 0$ exists. Imagine a "triangular spike" of height $1$ and base $2\epsilon$; The integral of this function is $\epsilon$. Since $\epsilon > 0$ can be picked arbitrarily small, the left hand side can be arbitrarily small compared to the right.
Comment: I don't think that's possible. ''smooth out'' the functions $f_n(x)=\cases{n, &0<x<1/n\cr 0&x\ge 1/n}$
Comment: The maximum is a local property, while the area under the curve is a global property. As indicated in responses and comments, those two characterisations of a continuous integrable function are unrelated.
Answer: For any positive integer $n$, let $f_n(x)=x^n$.  On $[0,1]$, the maximum of $f_n(x)$ is $1$, and $\int_0^1 f_n(x)\,dx=\frac{1}{n+1}$.
Thus any $k$ with the desired property must be $\le \frac{1}{n+1}$ for all $n$, so cannot be positive.
Answer: Posting my comment as an answer. It gives a different example that is useful to keep in mind as well.
Fix an arbitrary $\epsilon > 0$ and imagine a "triangular spike" function with height of the triangle being $1$ and base $2\epsilon$. Precisely, I mean the function
$$
f(x) =
\begin{cases}
\frac{x}{\epsilon}, &0\leq x \leq \epsilon,
\\
2 - \frac{x}{\epsilon}, &\epsilon \leq x \leq 2\epsilon,
\\
0, &2\epsilon \leq x \leq 1.
\end{cases}
$$
(Exercise: Verify that $f$ is continuous.) For this function, $\int_{0}^1 |f(x)| dx$ is just the area of the triangle, i.e., $\frac12 \cdot 1 \cdot 2\epsilon = \epsilon$. On the other hand, $\| f \|_{\infty} := \sup \{ |f(x)| \mid 0 \leq x \leq 1 \}$ is $1$. Hence, the quantity
$$
\frac{\int_{0}^1 |f(x)| dx}{\| f \|_{\infty}}
$$ can be arbitrarily close to $0$, and so there does not exist any $k > 0$ satisfying your requirements.

Lower bound of an integral


Use all cores when tar and splitting

Question: I'm trying to make my tar command to use all cores (8), I got it working when I pack into a single pack like this: tar -I pigz -cf packed.tar.gz folder/.
It is working as it should, it uses all cores.
But when I need to pack into multiply files I can't get it to use all cores, this is my command: tar cvzf - folder/ | split --bytes=4GB - packed.tar.gz.
How can I make this command to use all cores and not only one?
Thanks for all inputs.
Answer: With multithreaded file compression tool pigz:
tar -I pigz -cvf - folder/ | split --bytes=4GB - packed.tar.gz

Use all cores when tar and splitting


How do I make the date input field the scrolling type rather than having to type in the date?

Question: I can't figure out the right words to use to find this for myself. So instead of having to type something like 06 24 2015 or something I could select it from a list.
Answer: You can use something as jQuery Datepicker
if you are already use jQuery then it will be only 1 line:
$( ".datepicker" ).datepicker();

assuming your input field has class datepicker
Answer: If you are looking for a Rails-only-solution, the date_select function from the DateHelper-Module is exactly doing that.
But I agree with @mohamed-ibrahim, that the use of JavaScript would be appropriate in this case.


Use Nlog for CloudwatchLog

Question: I need a detailed/step by step guide for this. I have read the brief guide (example here) and downloaded the sample code, but I still can't figure out how to use Nlog to log to CloudWatch.

As soon as I put in the target in NLog.config, , Intellisense tells me that the name,  type, logGroup, region attributes are not declared
What NuGet packages do I need to install? From what I can tell, Nlog and AWSSDK.CloudWatchLogs only. Am I right?
Do I still need to perform the configuration with code, or is just setting the NLog.config file enough? I get the feeling that I will to do both.

(Edit : 4. Where do I specify the AccessKey/SecretKey/credential, and the logStream? Figured out the stored credential and logStream cannot be changed yet. It always uses the first one)
When I tried to run an example code to write the log, I get the error that the AWSTarget is not found/defined. I have spent over a day on trying to figure this out, and I don't think it is that difficult so I must be doing something wrong. Please help! Thank you.
Answer: I just ran into this issue, and the problem is that some dependencies are missing because they are not specified as dependencies. If you use the programmatic example and dig deeper, you will see some exceptions regarding types that are not available.
You need will the packages:

AWS.Logger.Core
AWSSDK.CloudWatch
AWSSDK.CloudWatchLogs
NLog
NLog.AWS.Logger
Answer: I have no experience with AWS.Logger.Nlog, but the most rules for all these packages are the same.

As soon as I put in the target in NLog.config, , Intellisense tells me that the name, type, logGroup, region attributes are not declared

You can ignore this. Most custom targets don't provide a XSD file.

What NuGet packages do I need to install? From what I can tell, Nlog and AWSSDK.CloudWatchLogs only. Am I right?

As there is no NuGet Package dependency between AWS.Logger.NLog and NLog, I would expect AWS.Logger.NLog and NLog. Because AWS.Logger.NLog is updated recently, I think it works well with NLog 4. To be sure, I would recommend to ask this on their Github repository.

Do I still need to perform the configuration with code, or is just setting the NLog.config file enough? I get the feeling that I will to do both.

In general all NLog targets could be configured by code or (xml) config. You can also combine both, but that could be tricky - that's another topic.

Where do I specify the AccessKey/SecretKey/credential, and the logStream?

That should you as on their Github repository.
Answer: Updated the AWS guide to include:
<code>  <extensions>
    <add assembly="NLog.AWS.Logger" />
  </extensions>
</code>
Important puzzle piece when using NLog on NetCore-platform

Use Nlog for CloudwatchLog


model with markov chain

Question: Suppose to have the following situation:
At a bar at each time unit arrives a certain number of customer with probabilities $p_1,p_2,...,p_n$.
In the bar there are 3 bartenders so 3 customer can be served together.
My idea is to model with a DTMC with states=0,1,2,...

Starting from state i I can go to state i+1,i+2,... with probabilities $p_1,p_2,...,$
Starting from state i (i>2) I can go to state i-3,... with probabilities $1-(p_1
+p_2+...+p_n)$
If i=2 I can go back to state 0 with probabilty $1-(p_1
+p_2+...+p_n)$
If i=1 I can go back to state 0 with probabilty $1-(p_1
+p_2+...+p_n)$

Is this formulation correct?
My doubt is about the probability to come back,  $p_1+p_2+...p_n=1$ I don't know how to express that probability
Answer: Let's introduce $p_0$, the probability that no customer enters the bar during a time unit. So, we have the following probabilities: $p_0,p_1,p_2,..., p_n$. The states of the chain is $\{0,1,2,...\}$ corresponding to the possible number of customers waiting for service at the beginning of a unit after the next group has arrived.
Assuming that during a time unit $3$ customer get served, the state transition matrix will be
$$\begin{bmatrix}
&\color{red}0&\color{red}1&\color{red}2&\color{red}{\cdots}&\color{red}{n-3}&\color{red}{n-2}&\cdots&\\
\color{blue}0&p_0+p_1+p_2+p_3&p_4&p_5&\cdots& p_n&0&\cdots\\
\color{blue}1&p_0+p_1+p_2&p_3&p_4&\cdots&p_{n-1}&p_n\\
\color{blue}2&p_0+p_1&p_2&p_3&\cdots&p_{n-2}&p_{n-1}&\cdots\\
\color{blue}3&p_0&p_1&p_2&\cdots&p_{n-3}&p_{n-2}&\cdots\\
\color{blue}4&0&p_0&p_1&\cdots&p_{n-4}&p_{n-3}&\cdots\\
\color{blue}5&0&0&p_0&\cdots&p_{n-5}&p_{n-4}&\cdots\\
\color{blue}\vdots\\
\color{blue}n&0&0&0&\cdots&p_0&p_1&\cdots\\
\color{blue}\vdots
\end{bmatrix}$$
where the red numbers refer to the next state and the blue numbers refer to the current state.

model with markov chain


Laravel custom websocket handler not working

Question: web.php
use Symfony\Component\Console\Output\NullOutput;
use BeyondCode\LaravelWebSockets\Server\Logger\WebsocketsLogger;

app()->singleton(WebsocketsLogger::class, function () {
    return (new WebsocketsLogger(new NullOutput()))->enable(false);
});

use BeyondCode\LaravelWebSockets\Facades\WebSocketsRouter;

WebSocketsRouter::webSocket('/my-websocket', \App\MyCustomWebSocketHandler::class);

MyCustomWebSocketHandler
<?php

namespace App;

use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface;
use Ratchet\WebSocket\MessageComponentInterface;
use BeyondCode\LaravelWebSockets\WebSockets\WebSocketHandler;

class MyCustomWebSocketHandler extends WebSocketHandler
{

    public function onMessage(ConnectionInterface $connection, MessageInterface $msg)
    {
        // TODO: Implement onMessage() method.
    }
}

Client
let socket = new WebSocket("ws://localhost:6001/app/websocketkey/my-websocket?protocol=7&client=js&version=4.3.1&flash=false");

When trying to run the client connection, it's not getting connected to the custom handler. The default handler is working fine.
The Websocket:serve and artisan:serve are running
referred articles 1 , 2
Any thoughts on this.? Tried with the demo here
Answer: Setting the websocket route as below resolved the issue.
use Symfony\Component\Console\Output\NullOutput;
use BeyondCode\LaravelWebSockets\Server\Logger\WebsocketsLogger;

app()->singleton(WebsocketsLogger::class, function () {
    return (new WebsocketsLogger(new NullOutput()))->enable(false);
});

use BeyondCode\LaravelWebSockets\Facades\WebSocketsRouter;

WebSocketsRouter::webSocket('/app/{appkey}/my-websocket', \App\MyCustomWebSocketHandler::class);


C#/WPF, how to make a window (created with Window.ShowDialog()) title bar blink when clicking its parent window (like MessageBox does)?

Question: I'm trying to create a custom MessageBox by using a WPF Window that is called with ShowDialog().
So far, I've managed to implement everything, except for one thing.
As you know, when you use MessageBox.Show("text"); you cannot set the focus or click the parent window (the one that called the MessageBox). If you do try to click the parent window, the MessageBox will blink briefly in order to alert you that you must close if first.
Windows created with Window.ShowDialog();, however, do not show that behavior. In fact, while you cannot set the focus to the parent window, the child (called with ShowDialog()) will never blink briefly.
My question is, is there any way to implement that in WPF? I've been searching for an answer but I must admit, I am stumped.
Thanks everyone!
Answer: You need to set the Owner of the modal window correctly, e.g. using the following code from within the owning window:
Window win = new SomeModalWindow();
win.Owner = this;
win.ShowDialog();

Answer: You would have to set Owner property of the child Window to the parent Window.  See the MSDN Documentation here.


Django Optional ImageField Not Working

Question: I want to set an optional imagefield in my django models. I set    blank=True,    null=True in the imagefields.After inputting the below codes I input an image in all the imagefield except place_4_view. After clicking on the upload button, I'm getting an error. What I'm I missing?
Models
class Findme(models.Model):
   place_2_view=models.ImageField(upload_to="photos",blank=True,null=True)
   place_3_view=models.ImageField(upload_to="photos",blank=True,null=True)
   place_4_view=models.ImageField (upload_to="photos",blank=True,null=True,help_text='Optional.')

Error when uploading
Request Method: POST
Request URL:    http://127.0.0.1:8000/find/
Django Version: 1.4
Exception Type: MultiValueDictKeyError
Exception Value:    "Key 'place_4_view' not found in <MultiValueDict: {u'place_2_view': [<TemporaryUploadedFile: 2012-05-17-289.jpg (image/jpeg)>], u'place_3_view': [<TemporaryUploadedFile: Crimo.JPG (image/jpeg)>]}>"
Exception Location: C:\Python27\lib\site-packages\django\utils\datastructures.py in __getitem__, line 258
Python Executable:  C:\Python27\python.exe

Views
    def findpic(request):
        extra_data_context={}
           #if there's nothing in the field do nothing.
           if request.method=="POST":
              form=FindmeForm(request.POST, request.FILES)
              if form.is_valid():
                 data=form.cleaned_data
                    newfindmes=Findme(
                        user=request.user,
                        pub_date=datetime.datetime.now(),
                        place_2_view=request.FILES['room_2_view'],
                        place_3_view=request.FILES['room_3_view'],
                        place_4_view=request.FILES['room_4_view'])
                    newfindmes.save()
              extra_data_context.update({'FindmeForm':form})
         else:
             form = FindmeForm()
             extra_data_context.update({'FindmeForm':form})
        extra_data_context.update({'Findmes':Findme.objects.filter(user=request.user)})
        return render_to_response('postme.html',extra_data_context,context_instance=RequestContext(request))

Template
        {% block content %}

        <form enctype="multipart/form-data"  form action="." method="POST">
       {% csrf_token %}

{{ FindmeForm.as_p}}

             <input type="submit" value="Get It"/>
              </form>

           {% for Findme in Findmes.object_list %}

 {{Findme.pub_date|timesince }} ago

     {% if Findme.thumbnail_4 %}
          {% endif %}

 Created By {{ Findme.user }}

        {% endfor %}
        {% endblock %}

Comment: Remember that running `syncdb` doesn't modify existing tables. Check your database against your model.
Comment: you mean I should set it manually?
Comment: Yes, or use some migration application like [`south`](http://south.readthedocs.org/en/latest/index.html)
Comment: In my DB. ImageFields are Null=YES Default= NULL. I even deleted the db and run syncdb again and try uploading, yet I'm getting the above error.
Comment: Update the question with your view and the form you are using.
Comment: I've done that. Check it above.
Comment: You need to add the form that you are using.
Comment: How about adding required=False to the fields and see if that works?
Answer: It appears that you have code that expects the key to be in the form during form submission.
Edit:
Your findPic method is trying to get the field and the field isn't there when it is empty. I would recommend the use of request.FILES.get And specify a default value, or test request.FILES for the presence of the keys, or iterate over the keys themselves. Basically your code needs to be prepared for request.FILES To be empty or not contain all the fields you are trying to access.
See this answer for an example of using request.FILES.get and Files Django Docs for other details on the request.FILES object.
Comment: This really should have been a comment since it doesn't answer anything.
Comment: If I'm to use request.FILES.get, how do I specify default value? Im confused.
Comment: answer updated to include links to an example and to docs on the request.FILES object.

Django Optional ImageField Not Working


Finding appropriate node labels for directed graphs

Question: I am searching for the correct terminology and a solution for the following problem:
Given a directed (hopefully acyclic) graph,
assign for each node a number, s.t. the numbers of a path are decreasing from the start to the end node. The sequences should be consistent no matter which path in the graph is chosen.
Answer: If the graph contains a cycle, then this is impossible, that is, for any numbering there is a path such that the respective numbers won't be decreasing.
If the graph is acyclic, I can suggest three ways:

Perform topological sorting and number the vertices according to the algorithm's output.
Assign a number defined by
$$ n(v) = \sum_{\text{path $P$ that starts at $v$}} \mathrm{length}(P).$$
Define recursively
$$ n(v) = 1+\max\Big(\big\{0\big\} \cup \big\{n(u) \mid (v,u) \in E\big\}\Big).$$

I hope this helps $\ddot\smile$


Javascript convert date string to object

Question: I'm trying to convert a date in string format to a Date object in JavaScript. The date is coming from the openweathermap.org API, which gives the date string in the following format:
'2018-04-28 09:00:00' or 'yyyy-mm-dd hh:mm:ss'
I know that the JavaScript Date class can take other string formats of dates, but this one returns NaN when I try anything with it. How can I convert a date string, like the one above, and convert it easily to a JavaScript object? Thanks!
Comment: Where did it return `NaN`? Which environment?
Comment: React-native project on Windows 10, running app on Android device.
Comment: Because of the variances in parsing of date strings, it is recommended to always manually parse strings as results are inconsistent, especially across different ECMAScript implementations where strings like "2018-04-28 09:00:00" may be parsed to as NaN, UTC or local timezone.
Answer: Since you are getting NaN while directly converting the string to date. You can split the string on spaces, - and : and then pass the value to date constructor and generate the date object.

const str = `2018-04-28 09:00:00`;
const [date, time] = str.split(' ');
const [year, month, day] = date.split('-');
const [hh, mm, sec] = time.split(':');
const dateObj = new Date(year, month - 1, day, hh, mm, sec);
console.log(dateObj);

As pointed out by @RobG, this could also be done using the regex.

const str = `2018-04-28 09:00:00`;
var b = str.split(/\D/);
var date = new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
console.log(date);

const str = `2018-04-28 09:00:00`,
      date = new Date(...(str.split(/\D/).map((v,i)=>i==1?--v:v)));
console.log(date);
Comment: A lot easier to split on non-digits: `var b = str.split(/\D/)` then `new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);` and you're done, and compatible with every implementation ever. ;-)
Comment: Ok, that's working now. Thanks!
Comment: Or if you want to use new stuff and don't care about being inefficient, then `new Date(...(str.split(/\D/).map((v,i)=>i==1?--v:v)))` does the job in less code, but is much less compatible.
Answer: Just try new Date(str)
d = new Date("2018-04-20 09:00:00")
Fri Apr 20 2018 09:00:00 GMT+0800 (Hong Kong Standard Time)
d.getDate()
20

ref: https://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format
Comment: When I do what you suggest and print the result of `d` to the console, it says 'Invalid Date'... Is this date format not recognized by Date?
Comment: That format isn't supported in ECMA-262. Using the built-in parser is not recommended, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results)
Comment: @JohnSeed—parsing of any format other than the one specified in ECMA-262 is implementation dependent. An implementation may decide that is an invalid attempt at the specified format, or it might attempt to parse it to a Date. Both outcomes are consistent with the language specification (e.g. Safari does the former, Chrome the latter, both are based on WebKit).