How to evaluate a for-comprehension to the last successful step in the chain?

Question: Consider the following composition
for {
  v1 <- transform1(v)
  v2 <- transform2(v1)
  v3 <- transformThatErrors(v2)
  v4 <- transfrom4(v3)
} yield { v4 }

Is there a monad M that would allow for the above to evaluate to M(v2)?
I am trying to model a situation where the program should apply the full chain of transformations until the first transformation that fails, in which case the chain evaluates to the last successful transformation. In the worst case, the whole chain represents identity(v).
Monads like Either and Option do not fit this requirement because on an error they evaluate the whole chain to an error, while it is required for the chain to always evaluate to success. In other words, I would like the program to try to do as much as it can, but if it cannot do anything, that is fine too.
Comment: I don't think you can do this with the for comprehension syntax. I think you may be able to use `Either[T, T]`, ie. pass the failure value as the error.
Comment: I have a messy solution involving a combination of `Tuple2`, `Either`, `foldLeft`, pattern matching, and early `return`, however I was wondering if cat/scalaz provide out of the box solution.
Comment: It may help to include that code/the best parts of it. I've not seen it, but could be that there is!
Answer: The Either monad does exactly what you want. Nothing in the interface of Either forces you to use different types for Left and Right case. In particular, the Left type parameter can be the same as the Right type parameter, they both can equal to something like Result (or "PartialSuccess"?), where you define what constitutes a Result.
Thus, you simply declare all your transformN functions to have return type
def transformN(previousStep: Result): Either[Result, Result] = ???

and in the very end, you fold it into a single result:
val res: Result = (for {
  v1 <- transform1(v)
  v2 <- transform2(v1)
  v3 <- transformThatErrors(v2)
  v4 <- transfrom4(v3)
} yield v4).fold(
  partialRes => partialRes,
  completeRes => completeRes
)

or even just
.fold(identity, identity)

As soon as the first transformation fails, the Either will package the partial result as a Left, and return it, without applying any further transformations. If every single transformation step succeeds, the very final result will be returned as Right. No matter at which point the transformation stops, the final fold will extract the (partial) result out of it.
If I understand it correctly, every other monad M you could possibly come up with, would be essentially the same as Either[Result, Result] with some special getResult method that is equivalent to .fold(identity, identity), so there is no need to multiply entities unnecessarily.
Comment: `.merge` instead of `.fold(identity,identity)` makes it even shorter.
Comment: @MarioGalic oh, indeed! Never heard of it. Cool!


Unknown nullpointer error?

Question: I have this for loop in my onCreateView for one of my fragments.
for(int i = 0; i<digitalIOModeSwitchArray.length;i++){
            digitalIOModeSwitchArray[i].setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // TODO Auto-generated method stub

                }
            });
        }

Which produces the following logcat error:
    03-03 08:08:50.236: E/AndroidRuntime(7350): FATAL EXCEPTION: main
03-03 08:08:50.236: E/AndroidRuntime(7350): java.lang.NullPointerException
03-03 08:08:50.236: E/AndroidRuntime(7350):     at com.example.ioiorun.digitalFragment.onCreateView(digitalFragment.java:231)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.View.measure(View.java:15264)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.View.measure(View.java:15264)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.View.measure(View.java:15264)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2163)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.View.measure(View.java:15264)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2131)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1242)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1435)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1127)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4650)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:747)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.Choreographer.doCallbacks(Choreographer.java:567)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.Choreographer.doFrame(Choreographer.java:536)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:733)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.os.Handler.handleCallback(Handler.java:615)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.os.Looper.loop(Looper.java:153)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at android.app.ActivityThread.main(ActivityThread.java:4987)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at java.lang.reflect.Method.invokeNative(Native Method)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at java.lang.reflect.Method.invoke(Method.java:511)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
03-03 08:08:50.236: E/AndroidRuntime(7350):     at dalvik.system.NativeStart.main(Native Method)
03-03 08:10:00.758: E/Trace(7429): error opening trace file: No such file or directory (2)

My digitalIOModeSwitchArray is just an array which holds a bunch of Switch views.
I am not sure why this for loop is causing an immediate app crash; when I comment out the loop the application works fine and dandy. The fragmentactivity is just an activity with tabs that switches a page of fragments.
How the array is instantiated:
Switch[] digitalIOModeSwitchArray = { digitalIO0Mode, digitalIO1Mode,
        digitalIO2Mode, digitalIO3Mode, digitalIO4Mode, digitalIO5Mode,
        digitalIO6Mode, digitalIO7Mode, digitalIO8Mode, digitalIO9Mode };

Beginning of the file:
public class digitalFragment extends Fragment {
// Declare all the UI Variables
TableLayout centralDigitalTable;
View digitalfragmentview;

Switch digitalIO0Mode;
Switch digitalIO1Mode;
Switch digitalIO2Mode;
Switch digitalIO3Mode;
Switch digitalIO4Mode;
Switch digitalIO5Mode;
Switch digitalIO6Mode;
Switch digitalIO7Mode;
Switch digitalIO8Mode;
Switch digitalIO9Mode;

Here is the entire chunk of code:
public class digitalFragment extends Fragment {
    // Declare all the UI Variables
    TableLayout centralDigitalTable;
    View digitalfragmentview;

    Switch digitalIO0Mode;
    Switch digitalIO1Mode;
    Switch digitalIO2Mode;
    Switch digitalIO3Mode;
    Switch digitalIO4Mode;
    Switch digitalIO5Mode;
    Switch digitalIO6Mode;
    Switch digitalIO7Mode;
    Switch digitalIO8Mode;
    Switch digitalIO9Mode;

    Switch digitalIO0Power;
    Switch digitalIO1Power;
    Switch digitalIO2Power;
    Switch digitalIO3Power;
    Switch digitalIO4Power;
    Switch digitalIO5Power;
    Switch digitalIO6Power;
    Switch digitalIO7Power;
    Switch digitalIO8Power;
    Switch digitalIO9Power;

    Switch digitalInput0Power;
    Switch digitalInput1Power;
    Switch digitalInput2Power;
    Switch digitalInput3Power;
    Switch digitalInput4Power;

    TextView digitalIO0VoltageText;
    TextView digitalIO1VoltageText;
    TextView digitalIO2VoltageText;
    TextView digitalIO3VoltageText;
    TextView digitalIO4VoltageText;
    TextView digitalIO5VoltageText;
    TextView digitalIO6VoltageText;
    TextView digitalIO7VoltageText;
    TextView digitalIO8VoltageText;
    TextView digitalIO9VoltageText;

    TextView digitalInput0VoltageText;
    TextView digitalInput1VoltageText;
    TextView digitalInput2VoltageText;
    TextView digitalInput3VoltageText;
    TextView digitalInput4VoltageText;

    ProgressBar digitalIO0VoltageProgress;
    ProgressBar digitalIO1VoltageProgress;
    ProgressBar digitalIO2VoltageProgress;
    ProgressBar digitalIO3VoltageProgress;
    ProgressBar digitalIO4VoltageProgress;
    ProgressBar digitalIO5VoltageProgress;
    ProgressBar digitalIO6VoltageProgress;
    ProgressBar digitalIO7VoltageProgress;
    ProgressBar digitalIO8VoltageProgress;
    ProgressBar digitalIO9VoltageProgress;

    ProgressBar digitalInput0VoltageProgress;
    ProgressBar digitalInput1VoltageProgress;
    ProgressBar digitalInput2VoltageProgress;
    ProgressBar digitalInput3VoltageProgress;
    ProgressBar digitalInput4VoltageProgress;

    // Place UI into arrays for easier management.
    // TextViews
    TextView[] digitalIOVoltageTextArray = { digitalIO0VoltageText,
            digitalIO1VoltageText, digitalIO2VoltageText,
            digitalIO3VoltageText, digitalIO4VoltageText,
            digitalIO5VoltageText, digitalIO6VoltageText,
            digitalIO7VoltageText, digitalIO8VoltageText, digitalIO9VoltageText };

    TextView[] digitalInputVoltageTextArray = { digitalInput0VoltageText,
            digitalInput1VoltageText, digitalInput2VoltageText,
            digitalInput3VoltageText, digitalInput4VoltageText };
    // Switches

    Switch[] digitalIOPowerSwitchArray = { digitalIO0Power, digitalIO1Power,
            digitalIO2Power, digitalIO3Power, digitalIO4Power, digitalIO5Power,
            digitalIO6Power, digitalIO7Power, digitalIO8Power, digitalIO9Power };

    Switch[] digitalInputPowerSwitchArray = { digitalInput0Power,
            digitalInput1Power, digitalInput2Power, digitalInput3Power,
            digitalInput4Power };

    Switch[] digitalIOModeSwitchArray = { digitalIO0Mode, digitalIO1Mode,
            digitalIO2Mode, digitalIO3Mode, digitalIO4Mode, digitalIO5Mode,
            digitalIO6Mode, digitalIO7Mode, digitalIO8Mode, digitalIO9Mode };
    // progress bars

    ProgressBar[] digitalIOVoltageProgressArray = { digitalIO0VoltageProgress,
            digitalIO1VoltageProgress, digitalIO2VoltageProgress,
            digitalIO3VoltageProgress, digitalIO4VoltageProgress,
            digitalIO5VoltageProgress, digitalIO6VoltageProgress,
            digitalIO7VoltageProgress, digitalIO8VoltageProgress,
            digitalIO9VoltageProgress };

    ProgressBar[] digitalInputVoltageProgressArray = {
            digitalInput0VoltageProgress, digitalInput1VoltageProgress,
            digitalInput2VoltageProgress, digitalInput3VoltageProgress,
            digitalInput4VoltageProgress };
    Context superContext;

    public View onCreateView(LayoutInflater viewInflation, ViewGroup container,
            Bundle SavedInstantState) {
        superContext = getActivity().getApplicationContext();
        digitalfragmentview = viewInflation.inflate(
                R.layout.digitalfragment_page, container, false);

        digitalIO0Mode = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio0mode);
        digitalIO1Mode = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio1mode);
        digitalIO2Mode = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio2mode);
        digitalIO3Mode = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio3mode);
        digitalIO4Mode = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio4mode);
        digitalIO5Mode = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio5mode);
        digitalIO6Mode = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio6mode);
        digitalIO7Mode = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio7mode);
        digitalIO8Mode = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio8mode);
        digitalIO9Mode = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio9mode);

        digitalIO0Power = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio0power);
        digitalIO1Power = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio1power);
        digitalIO2Power = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio2power);
        digitalIO3Power = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio3power);
        digitalIO4Power = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio4power);
        digitalIO5Power = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio5power);
        digitalIO6Power = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio6power);
        digitalIO7Power = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio7power);
        digitalIO8Power = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio8power);
        digitalIO9Power = (Switch) digitalfragmentview
                .findViewById(R.id.digitalio9power);

        digitalIO0VoltageProgress = (ProgressBar) digitalfragmentview
                .findViewById(R.id.digitalio0voltage);
        digitalIO1VoltageProgress = (ProgressBar) digitalfragmentview
                .findViewById(R.id.digitalio0voltage);
        digitalIO2VoltageProgress = (ProgressBar) digitalfragmentview
                .findViewById(R.id.digitalio0voltage);
        digitalIO3VoltageProgress = (ProgressBar) digitalfragmentview
                .findViewById(R.id.digitalio0voltage);
        digitalIO4VoltageProgress = (ProgressBar) digitalfragmentview
                .findViewById(R.id.digitalio0voltage);
        digitalIO5VoltageProgress = (ProgressBar) digitalfragmentview
                .findViewById(R.id.digitalio0voltage);
        digitalIO6VoltageProgress = (ProgressBar) digitalfragmentview
                .findViewById(R.id.digitalio0voltage);
        digitalIO7VoltageProgress = (ProgressBar) digitalfragmentview
                .findViewById(R.id.digitalio0voltage);
        digitalIO8VoltageProgress = (ProgressBar) digitalfragmentview
                .findViewById(R.id.digitalio0voltage);
        digitalIO9VoltageProgress = (ProgressBar) digitalfragmentview
                .findViewById(R.id.digitalio0voltage);

        digitalIO0VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalio0voltagetext);
        digitalIO1VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalio1voltagetext);
        digitalIO2VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalio2voltagetext);
        digitalIO3VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalio3voltagetext);
        digitalIO4VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalio4voltagetext);
        digitalIO5VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalio5voltagetext);
        digitalIO6VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalio6voltagetext);
        digitalIO7VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalio7voltagetext);
        digitalIO8VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalio8voltagetext);
        digitalIO9VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalio9voltagetext);

        digitalInput0VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalinput0voltagetext);
        digitalInput1VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalinput1voltagetext);
        digitalInput2VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalinput2voltagetext);
        digitalInput3VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalinput3voltagetext);
        digitalInput4VoltageText = (TextView) digitalfragmentview
                .findViewById(R.id.digitalinput4voltagetext);

        centralDigitalTable = (TableLayout) digitalfragmentview
                .findViewById(R.id.digitalTable);

        //sets the listener for the mode switches
        for(int i = 0; i<digitalIOModeSwitchArray.length;i++){
            digitalIOModeSwitchArray[i].setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // TODO Auto-generated method stub

                }
            });
        }

        return digitalfragmentview;
    }

The problem was as Eltabo had stated and his solution was viable for a fix.
Comment: Where/how is that `Array` initialized?
Comment: It is initialized in the class header right after I initialize all the switches. and I immediately input all of the switches.
Comment: what is line number 231?
Comment: for(int i = 0; i<digitalIOModeSwitchArray.length;i++){
   digitalIOModeSwitchArray[i].setOnCheckedChangeListener(new OnCheckedChangeListener() { that is line 231
Comment: Is the line number in the stack trace this: `for(int i = 0; i<digitalIOModeSwitchArray.length;i++){` or this: `digitalIOModeSwitchArray[i].setOnCheckedChangeListener(`? Please post  how (and when) you instantiate the array.
Comment: your switches are null, as far as the code you posted goes.
Comment: digitalIOModeSwitchArray[i] this is giving you null pointer exception.It seems that you just have the switch references. Have you created those objects??
Comment: check out the latest edit
Answer: A simple example of what is happening you:
package snippet;

public class MainExample {

    public static void main(String[] args) throws Exception {

        MainExample s = null; //A variable containing null

        MainExample[] ss = {s}; //An array containing, the object referenced by your variable, errr... null

        s = new MainExample(); //The varible references a new object

        System.out.println(ss[0]); //The array still contains null
    }
}

To avoid this issue, you can make these changes:
package snippet;

public class MainExample {

    public static void main(String[] args) throws Exception {

        MainExample s = null;

        MainExample[] ss = null;

        s = new MainExample();

        ss = new MainExample[]{s};

        System.out.println(ss[0]);
    }
}

Hope it helps.
Comment: Should I create my arrays after I do my findViewById stuff in onCreateView?

Unknown nullpointer error?


Remover texto DevExtreme

Question: Como posso remover o texto e deixar a penas a caixa de texto do meu formulário ?
Preciso remover o texto Ban nome:, preciso que fique apenas a caixa de texto(css ainda não está pronto)

@(Html.DevExtreme().Form<AgenciaViewModel>()
                .ID("formularioCadastro")
                .ShowValidationSummary(false)
                .Items(items =>
                {
                    items.AddGroup()
                    .Items(groupItems =>
                    {
                        groupItems.AddSimpleFor(m => m.Ban_codigo).CssClass("txtBanUf")
                        .Editor(e => e.NumberBox().OnKeyPress("key_press").Width("70px"));

                        groupItems.AddSimpleFor(m => m.Ban_Nome)
                        .Editor(e => e.NumberBox().ReadOnly(true).ID("txtBanName").OnKeyPress("key_press").Width("200px"));

Qual propriedade posso usar para isso?
Creio eu que esses texto vem da ViewModel, o Nº do Banco vem, então o Ban Nome deve vim também
ViewModel usada:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace SoftluxWebCore.ViewModels.Tabelas.Financeiro
{
public class AgenciaViewModel
{
    public int? Bcx_codigo { get; set; }
    public int? mun_codigo { get; set; }

    public string Bcx_Nome { get; set; }

    public string Ban_Nome { get; set; }

    [Display(Name = "Nº do Banco")]
    [Required(ErrorMessage = "Informe o número do Banco")]
    [MaxLength(4, ErrorMessage = "Esse número é maior que 4 caracteres")]
    public string Ban_codigo { get; set; }

    [Display(Name = "Nº da Agência")]
    [Required(ErrorMessage = "Informe a agência do Banco")]
    [MaxLength(10, ErrorMessage = "Essa agência é maior que 10 caracteres")]
    public string Bcx_agencia { get; set; }

    [Display(Name = "Dígito")]
    [MaxLength(5, ErrorMessage = "Essa agência é maior que 5 caracteres")]
    public string Bcx_DigitoAgencia { get; set; }

    [Display(Name = "Endereço")]
    [MaxLength(45, ErrorMessage = "Esse endereço é maior que 45 caracteres")]
    public string Bcx_endereco { get; set; }

    [Display(Name = "Número")]
    [MaxLength(10, ErrorMessage = "Esse número é maior que 10 caracteres")]
    public string Bcx_numero { get; set; }

    [Display(Name = "Bairro")]
    [MaxLength(30, ErrorMessage = "Essa agência é maior que 30 caracteres")]
    public string Bcx_bairro { get; set; }

    [Display(Name = "Cidade")]
    [MaxLength(30, ErrorMessage = "Essa cidade é maior que 35 caracteres")]
    public string Bcx_cidade { get; set; }

    [Display(Name = "UF")]
    [MaxLength(2, ErrorMessage = "Essa UF é maior que 2 caracteres")]
    public string Bcx_uf { get; set; }

    [Display(Name = "Cep")]
    [MaxLength(10, ErrorMessage = "Esse cep é maior que 10 caracteres")]
    public string Bcx_cep { get; set; }

    [Display(Name = "Telefone")]
    [MaxLength(15, ErrorMessage = "Esse telefone é maior que 15 caracteres")]
    public string Bcx_telefone { get; set; }

    [Display(Name = "Fax")]
    [MaxLength(15, ErrorMessage = "Esse fax é maior que 15 caracteres")]
    public string Bcx_fax { get; set; }

    [Display(Name = "Site")]
    [MaxLength(100, ErrorMessage = "Esse site é maior que 100 caracteres")]
    public string Bcx_Pagina { get; set; }

    [Display(Name = "Contato")]
    [MaxLength(25, ErrorMessage = "Esse nome é maior que 25 caracteres")]
    public string Bcx_Contato { get; set; }

    public string Con_tpcadastro { get; set; }
    public int? Con_codigo { get; set; }

    [Display(Name = "Nome")]
    public string Con_nome { get; set; }

    [Display(Name = "Vinculo")]
    public string Con_vinculo { get; set; }

    [Display(Name = "Fone")]
    public string Con_fone { get; set; }

    [Display(Name = "FAX")]
    public string Con_fax { get; set; }

    [Display(Name = "Celular")]
    public string Con_celular { get; set; }

    [Display(Name = "Email")]
    public string Con_email { get; set; }

    [Display(Name = "Código de Criação")]
    public Nullable<int> usr_cod_criacao { get; set; }

    [Display(Name = "Data de Criação")]
    public Nullable<System.DateTime> usr_dt_hr_criacao { get; set; }

    [Display(Name = "Código de Alteração")]
    public Nullable<int> usr_cod_alteracao { get; set; }

    [Display(Name = "Data de Alteração")]
    public Nullable<System.DateTime> usr_dt_hr_alteracao { get; set; }

    [Display(Name = "Ativo")]
    public bool Bcx_situacao { get; set; }

    [Display(Name = "Código da Empresa")]
    public Nullable<int> Emp_codigo { get; set; }

}
}

Comment: De onde vem essa informação?
Comment: Creio que da ViewModel, vou editar a publicação
Comment: Eu tive a ideia de adicionar a propriedade display a ViewModel e passar valor vazio, porém ele ficará exibindo apenas " : ", pois exibe por padrão
Comment: Na verdade está faltando o DisplayName no     `public string Ban_Nome { get; set; }`
Comment: Mesmo que eu acrescente [Display(Name = " ")] ao campo, ele me traz " : " automaticamente
Comment: Mas alterando para `[Display(Name="Nome do Banco)]` ele funciona não?
Comment: Funciona, mas a minha intenção é que fique em branco, consegui resolver, vou posta solução
Answer: Consegui resolver através de css
    .txtBanName > label
    {
         display: none !important;
    }

E mudei de id para class:
groupItems.AddSimpleFor(m => m.Ban_Nome).class("txtBanName")
                    .Editor(e => e.NumberBox().ReadOnly(true).OnKeyPress("key_press").Width("200px"));

Remover texto DevExtreme


Is a promise object part of the browser api or is it javascript specific

Question: I understand that a promise is an object. Question is, where does this object belong to or where is it created? I understand the XMR object is a browser object but is the promise object also a browser object? or is it a javascript object.
Comment: What is "XMR"? Have you read the [documentation](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#specifications)? It tells you which specification Promises are part of.
Comment: As of the relatively modern versions of the language, they're part of JavaScript.
Answer: As of ES6 (ES2015), promises are built into the Javascript specification and implementations to that spec. Before that, there were separate (outside of the language itself) implementations.
By XMR, I'm guessing you meant to say XHR (XML Http Request) which has always just been a separate implementation in the browser, not part of the Javascript specification - sometimes referred to as a "host object" or "host implementation".


Npm start not works for me

Question: While install owasp jUice shop when i enter npm start it doesn't work for me i tried lots of methods but it stuck..
Error: The module '/home/kali/Downloads/juice-shop_9.3.1/node_mpdules/libxmljs2/build/xmljs.node'

Was compiles against a
different node.js version using NODE_MODULE_VERSIONB64.
This version of Node.js
requires NODE_MODULE_VERSIONB 93.

I tried to recompiling and reinstalling
When i again install npm install it says
Unsupported engine i tries lots of ways but nothing works for me
I'm doing it in my kali machine
Answer: You need to recompile the binaries for your new Node version with npm rebuild.

Npm start not works for me


How to overlay Canvas with a Canvas dynamically?

Question: i have a canvas dynamically written with no id assigned to it. How can i overlay image on the first canvas (out of multiple canvas) via JS ?
<canvas  width="240" height="297">

<canvas id = "image_to_Overlay" width = "800" height = "500"></canvas>

Answer: In order to get the 1st canvas of the DOM using plain javascript you can use the good old function document.getElementsByTagName(). Then do what you want with it.
Probably it would be safer matching even on other attributes - such as class name - just to avoid getting the wrong canvas (jquery selectors would work great).
BTW the following should work

    <canvas  width="240" height="297"></canvas>

    <canvas id = "image_to_Overlay" width = "800" height = "500"></canvas>

Comment: Thank you. I dont see the image drawing on the canvas.
var image = new Image();
image.src = "https://i.imgur.com/ITWfejd.png";

//you can get the 1st canvas of the DOM accessing the array of canvas
var canvas = document.getElementsByTagName("canvas")[0];

//then draw on it as needed
var context = canvas.getContext('2d');
context.drawImage(image,1000,1000);
Comment: That's because `image.src='...'` returns immediately: the image download is asynchronous.
If you call it early, then you have to wait for the image to be available, i.e. using  an event listener, like `image.onload=...`
It really depends on your logic.
See https://stackoverflow.com/questions/2691301/async-or-sync-when-we-set-the-src-property-of-the-image-object
Comment: I've expanded the example with full html document and `onload` function. Again, you can move it where needed depending on your specific needs. Keep in mind that
1) the image src must be set after the onload event listener function has been attached
2) the canvas should be available at that time.
Comment: My requirement is to put the image of glass on top of the below chart , which is not working http://bl.ocks.org/MohamedZaki/326752ae3c1beed530242417fc6b20bb
Comment: Should I see a canvas on that document? I see only svg
Comment: Project is available here https://github.com/SAP/openui5-charting-custom-controls . The renderer function in /webapp/control/C3JSControl.js has the canvas to be used.


Need to find the formula for the elements of a unitary matrix $U$.

Question:
Let $A = \left[\begin{matrix} a & b \\ 0 & c \end{matrix} \right] \in \mathbb C^{2\times 2}$. Find a unitary $U$ such that $U^HAU = \left[\begin{matrix} c & b \\ 0 & a \end{matrix}\right]$.

NOTE: we have dealt with the cases when $b=0$ or $a = c$. Now we solve for the case when $b \ne 0 \wedge a \ne c$.
Let $U= (u_c, u_a)$ where the $u_{c,a}$'s are the unit length right and left eigenvectors of $A$, respectively. Then $u_c \perp a_a$ and $U$ is unitary. We have
$$
U^HAU = \left[\begin{matrix} u_c^HAu_c & u_c^HAu_a \\ u_a^HAu_c & u_a^HAu_a\end{matrix}\right] = \left[\begin{matrix} cu_c^Hu_c & u_c^HAu_a \\ au_a^Hu_c & au_a^Hu_a\end{matrix}\right] = \left[\begin{matrix} c & b \\ 0 & a\end{matrix}\right].
$$
How does one then find that
$$
U = \frac 1{\sqrt{1 + \left| \frac{a-c}a\right|^2}}\left[\begin{matrix} 1 & \frac{a-c}b \\ -\frac{a-c}b & 1\end{matrix}\right]
$$
Any help is appreciated! Thanks!
Comment: Note that the $U$ you describe is only unitary if $(a-c)/b$ is a real number, which need not be the case.
Answer: You're on the right track. To find $u_c$, note that
$$
(A - c I)u_c = 0 \implies \pmatrix{a-c&b\\0&0}u_c = 0.
$$
With that, we can conclude that $u_c$ a multiple (in particular a unit vector in the direction of) $(b,-(a-c))$. From there, note that $u_a$ must be a unit vector that is orthogonal to $u_c$. Putting it all together, we find that
$$
u_c = \frac{e^{i\theta_c}}{\sqrt{1 + |\frac{a-c}{a}|^2}}\left(1, -\frac{a-c}{b}\right), \quad
u_a = \frac{e^{i\theta_a}}{\sqrt{1 + |\frac{a-c}{a}|^2}}\left(\frac{\bar a-\bar c}{\bar b},1\right)
$$
for some real numbers $\theta_a,\theta_c$. Choosing $\theta_a = \theta_c = 0$ leads to a solution close to that which you presented.
Comment: Can you show how you got the formulas for $u_c, u_a$?


Exchange 2019 To replace Exchange 2013 in Hybrid Environment

Question: After the recent Exchange Vulnerabilities were announced, we disconnected our Exchange 2013 server in our hybrid configuration and investigated any impact. There was none, but it has been decided that we should no longer use this one and replace it with a new Exchange 2019 server. Something we were planning to do anyway.
With Exchange 2019 installed on the new server, when we run the Hybrid Configuration Wizard, we get an error HCW8045 - No TLS Certificate Name specified. We use a multi-domain certificate for Exchange as we did on our old server. We have found 1 post on Reddit with no replies and no other mention of this error that we can find.
Anyone seen this before, know what it could be?
Answer: Here is a link about the requirements of certificate in a hybrid environment, please check if it's helpful to you: Certificate requirements for a hybrid deployment


How to find the subdifferential of $|x|$?

Question: I want to compute the subdifferential of $ f $ on $ \mathbb{R} \setminus \{ 0 \} $ when $ f(x) = |x| $. How do I do this?
Answer: On $\mathbb{R}^*$, $f$ is differentiable so $\partial f(x)=\{f'(x)\}$ with $f'(x)$ the differential of $f$ at $x$.
You can also see Subdifferential of a finite dimensional function.


Value Textarea não funciona React

Question: Olá, estou tentando "popular" um textarea com um valor, mas quando tento editar o campo e ele não permite. Já tentei utilizar a propriedade "defaultValue" mas o campo fica vazio. Segue partes do codigo:
class TaskForm extends React.Component {

    constructor(props) {
        super(props);

        this.apis = new APIs();
        this.state = {
            taskEdit: [],
            title: '',
            description: '',
            project: '',
            service: '',
            date: moment(),
        };

    }

    componentDidMount() {
        this.setState({ isLoading: true });

        this.apis.editTask(this.props.location.state.id)//usar isso aqui
            .then(taskEdit => {

                return this.setState({
                    taskEdit: taskEdit ? taskEdit : {},
                    isLoading: false
                });
            });

    }

    handleChange(event) {
        this.setState({[event.target.name]: event.target.value});
    }

    render() {
        const { taskEdit } = this.state;
        const { history } = this.props;

        return (
            <Layout history={history} styleName='container'>

                {taskEdit.title}
                {taskEdit.description}

{this.state.id}

                    <form onSubmit={this.handleSubmit}>

Edit Task

                            Title:
                            <input defaultValue={taskEdit.title} type="text" size="100" className='title' name='title' onChange={this.handleChange}/>

                            Description:
                            <textarea value={taskEdit.description} type="text" className='description' name='description' onChange={this.handleChange}/>

                    </form>

            </Layout>
        );
    }
}

export default TaskForm;

Fica assim:

Alguém tem alguma dica?
Comment: Não sei se tem a ver mas.... *`` não suporta o value atributo.*
Answer: Olá, a função que vai lidar com a alteração do textarea deve ser iniciada no constructor, exemplo:
...
    this.state = {
      taskEdit: [],
      title: '',
      description: '',
      project: '',
      service: '',
      date: moment(),
    };

    this.handleChange = this.handleChange.bind(this);
  }
...

Isso acontece por uma questão de escopo das funções em JavaScript.
Seu método handlerChange precisa acessar o this do componente criado e usando o método bind no constructor nós conseguimos resolver este problema dizendo através do bind que o this da função é o mesmo do constructor.
Answer: O problema é como você está fazendo, código sem necessidade e variaveis com mesmo nome fazendo coisas diferentes, para simplificar eu montei um exemplo minimo:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      t1: 'a',
      t2: 'b'
    };
    this.handlerOnChange =
      this.handlerOnChange.bind(this);
  }
  handlerOnChange(e) {
    const {name, value} = e.target;
    this.setState({[name]: value});
  }
  render() {
    const {t1, t2} = this.state;
    return (

        <input type="text" name="t1" value={t1} onChange={this.handlerOnChange} /> {t1}

        <textarea name="t2" value={t2} onChange={this.handlerOnChange}/> {t2}

    )
  }
}
ReactDOM.render(<App/>,document.getElementById('root'));

Percebe que tanto o input e o textarea compartilham do mesmo método de alteração e nesse caso não pode esquecer de colocar o mesmo nome das tags html com os da variáveis do javascript.

Value Textarea não funciona React


synchronized method that use a public static HashTable from other class. How can I make this method thread safe?

Question: suppose I have a synchronized method that use a public static HashTable from other class. How can I make this method thread safe ? for my understanding any other thread can change this HashTable as it in other class and not in the class that holds the key (the class of the synchronized method) , doesn't it ?
Comment: `Hashtable` is already synchronized.
Comment: Use a synchronized collections such as ConcurrentHashMap/HashSet
Answer: Your understanding about the HashTable is not correct. HashTable is Synchronized and thread safe.
Look into the source code of HashTable. All the public methods are synchronized.
public synchronized V put(K key, V value) {

public synchronized V get(Object key) {
public synchronized boolean contains(Object value) {

Comment: thank you . And if the map is in the same class of the synchronized method and the map is private , can I use HashMap instead ? no other thread can change it when used by the synchronized method ?
Comment: HashMap is not synchronized. If you want to synchronize you can use

`Collections.synchronizedMap(map);` and  do the stuff inside synchronized block. Refer this : http://java67.blogspot.in/2015/02/how-to-synchronize-hashmap-in-java-with.html
Comment: Collections.synchronizedMap makes method calls atomic, it does not make it fully threadsafe and still you need the synchronization block. I would prefer `ConcurrentHashMap`for thread safe operations.
Comment: this is not my qwestion . if the map is in the **same** class of the synchronized method and the map is **private** , can I use HashMap instead ? no other thread can change it when used by the **synchronized method** ?
Comment: If you are using the map internally only in synchronized block ,then you can!. Make sure you doesn't provide the way to access the map outside.
Answer: If you want to use your HashMap inside your synchronized method, it can work but only if all threads use the same instance of the class that contains both the method and the HashMap, for more clarity take a look at the example bellow :
Code Snippet
public class SynchronizedCounter {
    private int c = 0;

    public synchronized void increment() {
        c++;
    }
}

Now if all the threads use the same instance of SynchronizedCounter, we make sure only one thread is running the increment() method at time, but if each thread is instantiating his own SynchronizedCounter instance then the method won't be thread safe.
Oracle's official description here.
Comment: but c is not static and it is private in your example .. so what is the problem?it is thread safe , no ?
Comment: and if it was static public we have to use Atomic Integer , no ?
Comment: Event if your HashMap is static this won't change the behavior of synchronized method, if your threads use the same instance of the class that contains your HashMap, then the synchronized method will allow only one thread to run the function at time, however, if they use different instances then the method won't block the other threads,  regardless of whether your HashMap is static or not.
Comment: No cause the HashMap is static, so it will be the same of all instances.
Comment: yes I mean if it is not static ..so if it is static it is important to use same instanace and if not it is not important
Comment: Not really, cause if all the threads are using the same HashMap instance, and the HashMap is not static you still have to use same instance of the class containing the HashMap.


Expressão regular strsplit

Question: Como atribuir a E.R. para separar o nome da cidade ?
cid <- c(cidade1..SP.Brasil,cidade2...SP.Brasil,cidade3..SPDF.Brasil,cidade4...SPDF.Brasil)

No sublime por exemplo, isto funciona:
\\.{3}[A-Z]{4}|\\.{3}[A-Z]{2}|\\.{2}[A-Z]{4}|\\.{2}[A-Z]{2}

Mas não consigo atribuir a uma variável no rstudio.
pattern <- ".{3}[A-Z]{4}|.{3}[A-Z]{2}|.{2}[A-Z]{4}|.{2}[A-Z]{2}"
pattern <- "\.{3}[A-Z]{4}|\.{3}[A-Z]{2}|\.{2}[A-Z]{4}|\.{2}[A-Z]{2}"
pattern <- "\\.{3}[A-Z]{4}|\\.{3}[A-Z]{2}|\\.{2}[A-Z]{4}|\\.{2}[A-Z]{2}"
pattern <- regex(".{3}[A-Z]{4}|.{3}[A-Z]{2}|.{2}[A-Z]{4}|.{2}[A-Z]{2}")
pattern <- regex("\.{3}[A-Z]{4}|\.{3}[A-Z]{2}|\.{2}[A-Z]{4}|\.{2}[A-Z]{2}")
pattern <- regex("\\.{3}[A-Z]{4}|\\.{3}[A-Z]{2}|\\.{2}[A-Z]{4}|\\.{2}[A-Z]{2}")

c <- strsplit(cid, pattern, fixed = TRUE)

Comment: Você quer pegar somente o trecho `SP` ou `SPDF`?
Comment: Quero pegar só os nomes das cidades.
troquei o fixed para FALSE e funcionou, mas agora tenho uma lista :
"cidade1"   ".Brasil"
"cidade2"   ".Brasil"
...
Answer: Eu resolvi o problema sem regex.
cid  <-  c("cidade1..SP.Brasil", "cidade2...SP.Brasil", "cidade3..SPDF.Brasil",
"cidade4...SPDF.Brasil")

primeiro <- function(x){
  return(x[[1]])
}

unlist(lapply(strsplit(cid, split="..", fixed=TRUE), FUN=primeiro))
[1] "cidade1" "cidade2" "cidade3" "cidade4"

Eu utilizei a sequência de caracteres ".." como separador das strings originais. Entretanto, o comando strsplit vai te dar como output uma lista com 4 elementos, onde cada elemento é um vetor de duas posições. Como a cidade está sempre a primeira posição deste vetor, eu criei uma função chamada primeiro, que vai retornar apenas o primeiro elemento de cada um destes vetores do resultado.
Os comandos lapply e as.vector são utilizados, respectivamente, para aplicar a função primeiro em cada elemento da lista criada pelo strsplit e organizar o resultado final do algoritmo em um vetor.

Expressão regular strsplit


Dynamically populate one select based on another

Question: I'm new to Drupal and well aware this question has been asked before, but I couldn't find a situation similar to mine, or maybe I didn't understand it.
I have three content types:

Team with fields Team Name.
Game with fields Team 1 and Team 2, an entity reference to the Team content.
Vid content type which has a select box for games (entity reference) which I'm able to populate.

On selection of game, the teams (Team 1 and Team 2) should be populated in the select box of another field say Pass.
One game can have two teams, several teams exist and each team can be involved in different games.
I've tried the hierarchical select module, conditional select, entity reference limit option, creating views and populating the entity reference, and tried Rules as well, but either I couldn't work through it or couldn't find the right setup.
Can someone point me in the right direction to solve this problem?
Answer: Try conditional_fields
Update multiple fields with ajax callback in form


how to execute first php function than javascript function onclicking/submiting a submit button

Question: i have this input field:
<input type="submit"  name="rregjistro" value="Rregjistro Tani Te Dhenat" onclick="openmodal()" >

I want first to execute POST script in PHP and than to open a modal popup using a javascript function.
Can you please help me!
Thanks in advance!
Comment: consider using ajax
Comment: Run Ajax query. Then in callback - open popup.
Answer: It is not possible to click using PHP because form submission is the action on the client's side, i.e in your browser. Events in the browser like this can be  executed by javascript or other client language.
<form ... >
<input type="submit"  name="rregjistro" value="Rregjistro" />

</form>

Answer: You would still need to start with a javascript function first.
In jquery that would be something like that:
function open() {
  $.post('http://url', $('#form').serialize(), function() {
    alert('popup goes here');
  })
)


How would I know if I'm good in logic?

Question: I've always been interested in logic, but unfortunately my school contains no logicians. What are some good logic puzzles/books and how would I know if logic is right for me?
Also, what can I do with logic? Is it strictly academic? Can I do math with it?
Comment: Mathematical logic is not about puzzles. It's not "logical thinking" as many people may think it would be. Looking at puzzles is absolutely no indication to whether or not you are going to be good in logic.
Answer: There are several questions here, but maybe I can answer the ones in the last paragraph.  Different occupations use logic in different amounts.
Probably mathematical logicians use it the most, other mathematicians, somewhat less, and some other professionals such as lawyers use it even less, but still more than the average person.  Here I am talking about informal logical reasoning, which is a mode of thinking that helps with many things in life.
Mathematical logic and formal logic, by contrast, are academic subjects (although of course they do have some relation with the layman's notion of logic.)
Being a mathematical logician is quite different from just practicing logical thinking.  Mathematical logic is a big field of mathematics that includes set theory, model theory, recursion theory, and proof theory.  Formal logic underlies all of these fields, but once you learn it, you can proceed to reason informally almost as much of the time as you can in other areas of math.
In short, logic isn't only about logical reasoning, just as math isn't only about numerical calculation.  Probably the only way to know if you like mathematical logic is to be introduced to some of its subject matter (perhaps someone else will answer with some suggested reading for you.)
Answer: You may try to read some of the Raymond Smullyan puzzle books. He is professional logician and he popularizes logic. He wrote his puzzle books which concern many different topics of logic. One I especially like is "To Mock a Mockingbird" it is about combinatory logic. Another author you may try is Ian Steward. He also writes puzzle books but they are quite different. Personally I prefer Smullyan. I think his books are more educative. Both authors write books that are suitable for layman.

How would I know if I'm good in logic?


For a cdf, $F(F^{-1}(u)) \geq u$ and $F^{-1}(F(x)) \leq x$. When does strict inequality apply?

Question: For the cdf of a random variable X, we have:
$F(F^{-1}(u)) \geq u$ and $F^{-1}(F(x)) \leq x$, for $u \in [0,1]$ and $x \in \mathbb{R}$.
Note that $F^{-1} = Q_F = \inf \{x: F(x) \geq u\}$ is the corresponding quantile function.
My question is: when do we have strict inequality ?
For the first inequality, would it be when we have a discontinuous cdf with a jump, and our $u^*$ is located within the jump ?
That is, our cdf jumps from $u_1$ to $u_2$ at $x_0$ and our $u^* \in (u_1,u_2)$.
Thus, $F^{-1}(u^*) = x_0 \Rightarrow F(F^{-1}(u^*)) = F(x_0) = u_2 > u^*$.
For the second inequality, would it be for a constant region in the cdf from, say, $x_1$ to $x_2$ with our $x^* \in (x_1,x_2)$ ?
So $F(x^*) = u \Rightarrow F^{-1}(F(x^*)) = F^{-1}(u) = x_1 < x^*$.
Answer: That looks correct.
To summarize, if the CDF is invertible, then your identities hold with equality. If it is not invertible, it is either because it is not injective or not surjective.
If it is not injective (e.g. it is constant over some interval), it doesn't have a left inverse so that $F^{-1}\circ F(x)\leq x$ should generally not hold with equality for some $x\in \mathbb{R}.$
If it is not surjective (e.g. it has jump discontinuities or atoms), it doesn't have a right inverse so that $F\circ F^{-1}(u)\geq u$ should generally not hold with equality for some $u\in [0,1].$
Comment: Nothing to do with continuity (a CDF is always right continuous).  We say a function $f$ is left-invertible when there is some function $g$ such that $g\circ f$ is the identity map. Similar for right inverse.  A function is invertible when it is both left and right invertible.
Comment: As for their connections with injectivity/surjectivity, you can check out proofs here:http://www.cs.cornell.edu/courses/cs2800/2015fa/lectures/lec06-proofs.html
Comment: thank you, this is perfect. Can you clarify what you mean by left/right inverse? Does that just mean that the cdf is not left or right continuous?


How to force Sequential Javascript Execution?

Question: I've only found rather complicated answers involving classes, event handlers and callbacks (which seem to me to be a somewhat sledgehammer approach). I think callbacks may be useful but I cant seem to apply these in the simplest context. See this example:

    Call my function

In this, the second function completes before the first function; what is the simplest way (or is there one?) to force the second function to delay execution until the first function is complete?
---Edit---
So that was a rubbish example but thanks to David Hedlund I see with this new example that it is indeed synchronous (along with crashing my browser in the test process!):

  Call my function

As my ACTUAL issue was with jQuery and IE I will have to post a separate question about that if I can't get anywhere myself!
Comment: Hope this will helpful https://github.com/dineshkani24/queuecall
Comment: Well I am glad its just not me who is struggling with this. I started to use nodejs for the processing of logs files. Everything about that processing dictates sequential operation, but I have spent so much time trying to force the required sequenes. I find with promises and all of the chaining of "then this" "then that" that we end up with unreadable code.
Answer: Well, setTimeout, per its definition, will not hold up the thread. This is desirable, because if it did, it'd freeze the entire UI for the time it was waiting. if you really need to use setTimeout, then you should be using callback functions:
function myfunction() {
    longfunctionfirst(shortfunctionsecond);
}

function longfunctionfirst(callback) {
    setTimeout(function() {
        alert('first function finished');
        if(typeof callback == 'function')
            callback();
    }, 3000);
};

function shortfunctionsecond() {
    setTimeout('alert("second function finished");', 200);
};

If you are not using setTimeout, but are just having functions that execute for very long, and were using setTimeout to simulate that, then your functions would actually be synchronous, and you would not have this problem at all. It should be noted, though, that AJAX requests are asynchronous, and will, just as setTimeout, not hold up the UI thread until it has finished. With AJAX, as with setTimeout, you'll have to work with callbacks.
Comment: Also, I should note that AJAX requests are *generally* asynchronous, but can be made to be synchronous.
Comment: @SukanyaPai: No, this answer was written 10 years ago to explain a specific pattern of passing callbacks. In your code, `shortfunctionsecond` would be called first, as you're calling it, and not just passing it as a parameter. The result of `shortfunctionsecond(thirdFunction)` will be passed to `longfunctionfirst`. An up to date answer that handles the complexity you introduce would be to use [Promises](https://developers.google.com/web/fundamentals/primers/promises)
Comment: @Justin: yes, that's a valid point, thanks for the remark. if the real case scenario of issue is indeed ajax-related, synchronous callbacks could be the solution
Comment: (altho the async-with-callback approach probably still gives greater control and readability of the execution flow)
Comment: He didn't ask for AJAX in the question
Comment: @Chris: you're right about that, i only briefly touched on AJAX in my response, in the event that it was actually an AJAX issue he was dealing with in his real world example, but was just using setTimeout for a stripped down way to reproduce the issue. There are absolutely no grounds for *assuming* that that is the case, but you'll notice in my answer, I don't make that assumption, and I don't focus on AJAX.
Comment: Thanks David. I was looking in the wrong place and used a bad example - thanks for clearing that up and expanding my javascript knowledge.
Comment: Don't get mr wrong your solution is very elogant and spot on, it's just sometimes Ajax seems to confused with boring old JavaScript
Comment: @DavidHedlund Is your solution valid for 2 functions alone? how do I make sure 3rd function is called after second? Is it like longfunctionfirst(shortfunctionsecond(thirdFunction));
Answer: I am back to this questions after all this time because it took me that long to find what I think is a clean solution :
The only way to force a javascript sequential execution that I know of is to use promises.
There are exhaustive explications of promises at : Promises/A and Promises/A+
The only library implementing promises I know is jquery so here is how I would solve the question using jquery promises :

    Call my function

By implementing a promise and chaining the functions with .then() you ensure that the second function will be executed only after the first one has executed
It is the command d.resolve() in longfunctionfirst() that give the signal to start the next function.
Technically the shortfunctionsecond() does not need to create a deferred and return a promise, but I fell in love with promises and tend to implement everything with promises, sorry.
Comment: Hi All, I am always surprised that this old tread still attract attention. Yes you are right, now ES6 and an increasing number of frameworks implement promises. This is old stuff, but it drove me up the wall 5 years ago and was the hardest lesson I ever learned in computing. Simply put I was stuck in a Von Newmann sequential understanding of computing and could not grasp the beauty of event driven development embraced by Javascript.
Comment: Promises actually are part of the current (2015) ECMAscript draft: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-objects
Comment: People still reading this old answer ? Thanks, yes Javascript moves on, just waiting for the 2015 draft to catch up with all the browsers out there :-)
Answer: I am an old hand at programming and came back recently to my old passion and am struggling to fit in this Object oriented, event driven bright new world and while i see the advantages of the non sequential behavior of Javascript there are time where it really get in the way of simplicity and reusability.
A simple example I have worked on was to take a photo (Mobile phone programmed in javascript, HTML, phonegap, ...), resize it and upload it on a web site.
The ideal sequence is :

Take a photo
Load the photo in an img element
Resize the picture (Using Pixastic)
Upload it to a web site
Inform the user on success failure

All this would be a very simple sequential program if we would have each step returning control to the next one when it is finished, but in reality :

Take a photo is async, so the program attempt to load it in the img element before it exist
Load the photo is async so the resize picture start before the img is fully loaded
Resize is async so Upload to the web site start before the Picture is completely resized
Upload to the web site is asyn so the program continue before the photo is completely uploaded.

And btw 4 of the 5 steps involve callback functions.
My solution thus is to nest each step in the previous one and use .onload and other similar stratagems, It look something like this :
takeAPhoto(takeaphotocallback(photo) {
  photo.onload = function () {
    resizePhoto(photo, resizePhotoCallback(photo) {
      uploadPhoto(photo, uploadPhotoCallback(status) {
        informUserOnOutcome();
      });
    });
  };
  loadPhoto(photo);
});

(I hope I did not make too many mistakes bringing the code to it's essential the real thing is just too distracting)
This is I believe a perfect example where async is no good and sync is good, because contrary to Ui event handling we must have each step finish before the next is executed, but the code is a Russian doll construction, it is confusing and unreadable, the code reusability is difficult to achieve because of all the nesting it is simply difficult to bring to the inner function all the parameters needed without passing them to each container in turn or using evil global variables, and I would have loved that the result of all this code would give me a return code, but the first container will be finished well before the return code will be available.
Now to go back to Tom initial question, what would be the smart, easy to read, easy to reuse solution to what would have been a very simple program 15 years ago using let say C and a dumb electronic board ?
The requirement is in fact so simple that I have the impression that I must be missing a fundamental understanding of Javsascript and modern programming, Surely technology is meant to fuel productivity right  ?.
Thanks for your patience
Raymond the Dinosaur ;-)
Comment: I have experienced the same difficulties with phonegap. I have a code full of nested callback functions, which is hard to read. At some point I was wishing I had implemented the app natively. I was working on an audio recorder and synchronizing recorded data with the server. I tried to simplify my code with requirejs and backbone. This helped a little to pull things apart and organizing the code in modules, but I still need to nest callbacks...
Answer: In your example, the first function does actually complete before the second function is started. setTimeout does not hold execution of the function until the timeout is reached, it will simply start a timer in the background and execute your alert statement after the specified time.
There is no native way of doing a "sleep" in JavaScript. You could write a loop that checks for the time, but that will put a lot of strain on the client. You could also do the Synchronous AJAX call, as emacsian described, but that will put extra load on your server. Your best bet is really to avoid this, which should be simple enough for most cases once you understand how setTimeout works.
Answer: If you don't insist on using pure Javascript, you can build a sequential code in Livescript and it looks pretty good. You might want to take a look at this example:
# application
do
    i = 3
    console.log td!, "start"
    <- :lo(op) ->
        console.log td!, "hi #{i}"
        i--
        <- wait-for \something
        if i is 0
            return op! # break
        lo(op)
    <- sleep 1500ms
    <- :lo(op) ->
        console.log td!, "hello #{i}"
        i++
        if i is 3
            return op! # break
        <- sleep 1000ms
        lo(op)
    <- sleep 0
    console.log td!, "heyy"

do
    a = 8
    <- :lo(op) ->
        console.log td!, "this runs in parallel!", a
        a--
        go \something
        if a is 0
            return op! # break
        <- sleep 500ms
        lo(op)

Output:
0ms : start
2ms : hi 3
3ms : this runs in parallel! 8
3ms : hi 2
505ms : this runs in parallel! 7
505ms : hi 1
1007ms : this runs in parallel! 6
1508ms : this runs in parallel! 5
2009ms : this runs in parallel! 4
2509ms : hello 0
2509ms : this runs in parallel! 3
3010ms : this runs in parallel! 2
3509ms : hello 1
3510ms : this runs in parallel! 1
4511ms : hello 2
4511ms : heyy

Answer: I had the same problem, this is my solution:

var functionsToCall = new Array();

function f1() {
    $.ajax({
        type:"POST",
        url: "/some/url",
        success: function(data) {
            doSomethingWith(data);
            //When done, call the next function..
            callAFunction("parameter");
        }
    });
}

function f2() {
    /*...*/
    callAFunction("parameter2");
}
function f3() {
    /*...*/
    callAFunction("parameter3");
}
function f4() {
    /*...*/
    callAFunction("parameter4");
}
function f5() {
    /*...*/
    callAFunction("parameter5");
}
function f6() {
    /*...*/
    callAFunction("parameter6");
}
function f7() {
    /*...*/
    callAFunction("parameter7");
}
function f8() {
    /*...*/
    callAFunction("parameter8");
}
function f9() {
    /*...*/
    callAFunction("parameter9");
}

function callAllFunctionsSy(params) {
 functionsToCall.push(f1);
 functionsToCall.push(f2);
 functionsToCall.push(f3);
 functionsToCall.push(f4);
 functionsToCall.push(f5);
 functionsToCall.push(f6);
 functionsToCall.push(f7);
 functionsToCall.push(f8);
 functionsToCall.push(f9);
 functionsToCall.reverse();
 callAFunction(params);
}

function callAFunction(params) {
 if (functionsToCall.length > 0) {
  var f=functionsToCall.pop();
  f(params);
 }
}
Answer: In javascript, there is no way, to make the code wait. I've had this problem and the way I did it was do a synchronous SJAX call to the server, and the server actually executes sleep or does some activity before returning and the whole time, the js waits.
Eg of Sync AJAX: http://www.hunlock.com/blogs/Snippets:_Synchronous_AJAX
Comment: SJAX is typically a sign of bad design and I would encourage novices to avoid it until they understand its implications.
Answer: I tried the callback way and could not get this to work, what you have to understand is that values are still atomic even though execution is not. For example:
alert('1'); <--- these two functions will be executed at the same time
alert('2'); <--- these two functions will be executed at the same time
but doing like this will force us to know the order of execution:
loop=2;
total=0;
for(i=0;i<loop;i++) {
           total+=1;
           if(total == loop)
                      alert('2');
           else
                      alert('1');
}

Answer: Another way to look at this is to daisy chain from one function to another.
Have an array of functions that is global to all your called functions, say:
arrf: [ f_final
       ,f
       ,another_f
       ,f_again ],

Then setup an array of integers to the particular 'f''s you want to run, e.g
var runorder = [1,3,2,0];

Then call an initial function with 'runorder' as a parameter, e.g.
    f_start(runorder);
Then at the end of each function, just pop the index to the next 'f' to execute off the runorder array and execute it, still passing 'runorder' as a parameter but with the array reduced by one.
var nextf = runorder.shift();
arrf[nextf].call(runorder);

Obviously this terminates in a function, say at index 0, that does not chain onto another function.
This is completely deterministic, avoiding 'timers'.
Answer: Put your code in a string, iterate, eval, setTimeout and recursion to continue with the remaining lines. No doubt I'll refine this or just throw it out if it doesn't hit the mark. My intention is to use it to simulate really, really basic user testing.
The recursion and setTimeout make it sequential.
Thoughts?
var line_pos = 0;
var string =`
    console.log('123');
    console.log('line pos is '+ line_pos);
SLEEP
    console.log('waited');
    console.log('line pos is '+ line_pos);
SLEEP
SLEEP
    console.log('Did i finish?');
`;

var lines = string.split("\n");
var r = function(line_pos){
    for (i = p; i < lines.length; i++) {
        if(lines[i] == 'SLEEP'){
            setTimeout(function(){r(line_pos+1)},1500);
            return;
        }
        eval (lines[line_pos]);
    }
    console.log('COMPLETED READING LINES');
    return;
}
console.log('STARTED READING LINES');
r.call(this,line_pos);

OUTPUT
STARTED READING LINES
123
124
1 p is 0
undefined
waited
p is 5
125
Did i finish?
COMPLETED READING LINES


Google Api Java client list root folder children

Question: So, in Google Play Services, it's
final DriveFolder rootFolder = Drive.DriveApi.getRootFolder(mGoogleApiClient);

To get root folder and then you can use parents feature.
In REST API, to list root children you had to add 'root' in parents to a query parameter.
But there is no search query feature in Google Api Java client, or is it just that I haven't found it?
I can't use Drive.Children.list(String) because I have to find out the root folder id first.
Comment: the root folders id is root I believe so you shouldn't have to find it.
Answer: As DalmTo said in the comment above, the ID of the root folder is always "root". Additionally, the querying functionality you are looking for is in Drive.Files.list(), which has a q parameter for specifying a query.


How to show that $\sum\limits_{k=1}^{n-1}\frac{k!k^{n-k}}{n!}$ is asymptotically $\sqrt{\frac{\pi n}{2}}$?

Question: According to "Concrete Mathematics" on page 434, elementary asymptotic methods show that $\displaystyle \sum_{k=1}^{n-1}\frac{k! \; k^{n-k}}{n!}$ is asymptotically  $\sqrt{\frac{\pi n}{2}}$. Does anybody see how to show this?
Comment: I think you can find this somewhere in Flajolet and Sedgewick, Analytic Combinatorics. (At least I'm sure they quote the result; I'm not sure if they derive it, but if they don't derive it they give a source that does.) This book is available online. But I don't have time to track down the reference more precisely, so this comment may be of little help as it's an 800-page book.
Comment: In the second edition, it's on page 448.
Answer: The sum can asymptotically be replaced by an integral
$$\sum_{k=1}^{n-1}\frac{k! \; k^{n-k}}{n!} \sim \int_1^n dk\, \frac{k! k^{n-k}}{n!}.$$
The integral can be approximated by its saddle point (which here coincides with a boundary). For that first use Stirling
$$k! k^{n-k} \sim k^n e^{-k} = e^{-k +n \log k}.$$
The maximum of $-k+n \log k$ is attained at $k=n$ such that we can expand the integrand around this value and obtain
$$\frac{k! \; k^{n-k}}{n!} \approx e^{-(k-n)^2/2n}$$
up to second order in the exponent. Thereby
$$\sum_{k=1}^{n-1}\frac{k! \; k^{n-k}}{n!} \sim \int_1^n dk\, \frac{k! k^{n-k}}{n!}
\sim \int_{-\infty}^n dk\,  e^{- (k-n)^2/2n}  = \sqrt{\frac{n \pi}{2}}. $$
Edit: as an answer to the comment of Didier Piau I try to be a bit more rigorous.
To estimate the integrand, we expand the exponent around the saddle point. This amounts to finding the maximum of $$\log \left[\frac{k! \; k^{n-k}}{n!} \right]
\sim (n-k) \log k + k (\log k -1) - n (\log n -1).$$
Taking the derivative with respect to $k$ yields
$(n-k)/k$ with the maximum at $n= k$. Expanding around this maximum to second order in $k-n$, we obtain
$$\log \left[\frac{k! \; k^{n-k}}{n!} \right] \sim -\frac{(k-n)^2}{2n}.$$
What Didier Piau observed is a subdominant linear term ($i/2n$ in his comment). This leads to a shift in the position of the maximum but the curvature stays the same. In fact, the first nonvanishing term around the maximum is always second order as the linear term vanishes by definition. To make this more explicit, we have to include the next term in the Stirling expansion
$$\log \left[\frac{k! \; k^{n-k}}{n!} \right]
\sim (n-k) \log k + k (\log k -1) + \frac{1}{2} \log k - n (\log n -1) - \frac{1}{2} \log n.$$ The maximum is now obtained at $k^*= (2n -1)/2$ (exactly due to the shift noted by Didier Piau). Expanding to second order around this point yields
$$\log \left[\frac{k! \; k^{n-k}}{n!} \right] \sim- \frac{(k - k^*)^2}{2n+1}.$$ The shifts of order 1 in the position of the maximum and in the curvature do not affect the result in leading order.
Comment: @Fabian OK, once again: 1) Euler-Maclaurin has a rest term, which one must control. This is (not trivial and) not done here. 2) The function $x\mapsto\Gamma(x+1)x^{n-x}$ is maximum where its derivative is zero. To compute this derivative and to solve for the point where it is zero is (a difficult task and) not done here. 3) Bender-Orszag is excellent but its invocation cannot replace solving 1) and 2). In view of this, I wonder how high is your confidence in the value $\sqrt{\pi/2}$ of the constant. Sorry, life is hard...
Comment: @PeterR: Often mathematicians will use "elementary" to mean "does not use complex analysis".  As you can see, "elementary" does not mean "easy."
Comment: +1 Some related explanation here: http://en.wikipedia.org/wiki/Laplace%27s_method
Comment: To me, the part with the $\approx$ sign is a little too light on the side of rigor... For example, $k=n-i$ with $i\ge1$ fixed yields $1-(i^2+i)/(2n)+o(1/n)$ on the LHS and $\exp(-i^2/2n)=1-i^2/(2n)+o(1/n)$ on the RHS.
Comment: Thanks for the edit. Unfortunately, I do not understand this shift thing: the maximum is exactly at $k=n$, and not anywhere else. Somewhat related to this, I still do not get whether you are extending the sequence of ratios indexed by $k$ to a function defined on the real numbers or not, and if you are, how you are doing it. Call me obdurate if you wish but as far as I am concerned, there is still way to go before I can consider this is a proof. :-)
Comment: @Fabian One last point: the sentence in your post which asserts that I *observed a subdominant linear term* (whatever that means) is misleading and does not correspond to what I wrote.
Comment: It would be of course interesting to find the next term in the asymptotic expansion...
Comment: @leonbloy: thank you for the link. This will help people to understand the answer...
Comment: @Didier Piau: the linear term $i/2n$ leads to a shift in the position of the maximum but the curvature remains the same (see the edited answer). The sum is dominated by the upper boundary. All what we need to know is the width of the peak in leading order in $n$.
Comment: @Didier Piau: it is not intended as a proof. The maximum of the sum is at $k=n$, the maximum of the integral not. To go from the sum to the integral you can apply Euler–Maclaurin (of course you have to convince yourself that the integral is more important than the other terms).
Comment: @Fabian Your proposal is not a proof per se, I have no problem with that. To go in the direction of a more assured result, you could precise what is the function you integrate and to which you suggest to apply Euler-Maclaurin, if I read you correctly. Note that Euler-Maclaurin applies to the integral of a function independent on the bound $n$ of the integral while your function depends on $n$.
Comment: @Didier Piau: $n$ is fixed (but large) -- then you apply Euler-Maclaurin for the sum over $k$ which becomes an integral... The function which I integrate is $\Gamma(k+1) k^{n-k}/\Gamma(n+1)$. An excellent (more rigorous) overview of the method can be found in Bender, Orszag: Advanced mathematical methods for scientists and engineers especially chapter 6.7.
Comment: Thanks for all the help. I was expecting something simpler when they said " elementary asymptotic methods", but this will certainly do.
Comment: I agree with Didier Piau that there are some gaps in this argument (although I do think it captures the essence of what is going on).  I've posted as a separate answer Knuth's own derivation.
Answer: I don't think the accepted answer is sufficiently rigorous, so I dug up Knuth's derivation in The Art of Computer Programming, Vol. 1 (3rd ed.), Section 184.108.40.206, pp. 119-120.  Here's a summary of his argument.
Use Stirling's approximation on $k!$ to get
$$\sum_{k=0}^n \frac{k^{n-k} k!}{n!} = \frac{\sqrt{2\pi}}{n!}\sum_{k=0}^n k^{n+1/2} e^{-k}\left(1 + O(k^{-1})\right).$$
Then, use the Euler-Maclaurin formula to obtain
$$\sum_{k=0}^n k^{n+1/2}e^{-k} = \int_0^n x^{n+1/2} e^{-x} dx + \frac{1}{2} n^{n+1/2}e^{-n} + \frac{1}{24}n^{n-1/2}e^{-n} - R,$$
where $R$ is the remainder term and can be shown to be $O(n^n e^{-n})$.
Since the integral is an incomplete gamma function, we have
$$\sum_{k=0}^n k^{n+1/2}e^{-k} = \gamma \left(n+\frac{3}{2},n\right) + O(n^{n+1/2}e^{-n}).$$
In a two-page analysis earlier in the section, Knuth shows that for large values of $x$ and fixed $y$, $$\frac{\gamma (x+1,x+y)}{\Gamma(x+1)} = \frac{1}{2} + O\left(\frac{y}{\sqrt{x}}\right).$$
Putting this all together yields
$$\sum_{k=0}^n \frac{k^{n-k} k!}{n!} = \frac{\sqrt{2\pi}}{\Gamma(n+1)} \left[\Gamma\left(n+\frac{3}{2}\right)\left(\frac{1}{2} + O\left(\frac{1}{\sqrt{n}}\right)\right) + O\left(\Gamma\left(n+\frac{1}{2}\right)\right)\right].$$
Since, for fixed $a$ and $b$ (see, for instance, here), $$\frac{\Gamma(n+a)}{\Gamma(n+b)} = n^{a-b}\left(1 + O(n^{-1})\right),$$
we finally get
$$\sum_{k=0}^n \frac{k^{n-k} k!}{n!} =\sqrt{ \frac{\pi n}{2}} + O(1).$$
Knuth says, "Our derivations... use only simple techniques of elementary calculus."  So perhaps this is what is meant by "elementary asymptotic methods" in Concrete Mathematics, rather than "this derivation is easy." :)

Knuth also describes more advanced techniques whereby you can get the more precise estimate
$$\sum_{k=0}^n \frac{k^{n-k} k!}{n!} = \sqrt{ \frac{\pi n}{2}} - \frac{2}{3} + \frac{11}{24} \sqrt{\frac{\pi}{2n}} + \frac{4}{135n} - \frac{71}{1152} \sqrt{\frac{\pi}{2n^3}} + O(n^{-2}).$$
Comment: Is the more advanced technique also from 'The Art of Computer Programming'?
Comment: @sigma.z.1980: I don't have my copy with me now.  I think he does describe the techniques, but he doesn't go into the detail that he does with the first-order estimate.


How does the Sin and Cos scale on a slide rule work and what is the formula for it?

Question: As I described in this question, I am trying to make a printable slide rule (similar to the slide rule provided in this SciAm article). I have made most of the parts of it but I can't make the Sin and the Cos scales. Although it looks very easy when I use a slide rule, but for some reason now I can't make them work. I tried various formulas but it didn't work.
From the original answer, I got the formula for the main log scale:
$$f(x,y)=(\log x)\cdot y$$
(where $f$ is the distance where the ticks have to be made, $x,y$ are integers and $y$ is fixed.)
But what is the formula for the $\sin$ and $\cos$ scales?
I searched on google but I didn't get any result.
If I diectly apply $\sin$, then I get this:
Answer: Usually the $S$ scale is exactly the sine of the $C$ scale , where the argument is taken in degrees.  Say the length of the rule is $\ell $. Each point on the $C$ scale at distance $x$ from the index is marked with the number  $10^{2x/\ell }$.
Then each point on $S$ is marked with $$\sin\left (\frac\pi{180} 10^{2x/\ell}\right).$$
To use it, you have some argument on the $C$ scale of which you need to find the sine. You zero the scale (aligning the index marks) and match the cursor to the argument on the $C$ scale.
 Then you read the sine off of the corresponding value on the $S$ scale.
(To solve the reverse problem, "where on the $S$ scale should I place the label $s$?, you must invert this function: place label $s$ at distance $\frac\ell2\log\left (\frac {180}\pi\sin^{-1} s \right)$.)

Addendum: I think the foregoing would work well, but when I inspected an actual slide rule, I found that it was constructed differently: The $S$ scale, not the $A$ scale, is the argument.  I don't know if my memory was completely at fault or if different slide rules worked in different ways.   On the example slide rule I looked at, the argument (in degrees) is marked on the $S$ scale, for arguments between $\sin^{-1}\frac1{10}\approx 5.73^\circ$ and $\sin^{-1} 1 = 90^\circ$, and then the sines of these arguments are in the corresponding positions on the $D$ scale, which runs from $\frac1{10}$ to $1$.  For this slide rule, the rule is that each point at position $x$ is marked with the two labels  $\frac{180}\pi\sin^{-1}10^{(x/\ell)-1}$ and $90-\frac{180}\pi\sin^{-1}10^{(x/\ell)-1}$.
The picture below shows that the sine of $10^\circ10' $ (on the $S$ scale) is $0.1765 $ (on the $D$ scale).
Comment: "The picture below shows that the sine of $10.1^circ$ (on the $S$ scale) is $0.17537$ (on the $D$ scale)." Not quite. The photo shows that the sine of $10^\circ 10'$, or $10.17^\circ$ (note there are six, not ten, primary divisions between each degree on the $S$ scale), is about $0.1767$ (You seem to have misread the $D$ scale by one mark.)
Comment: Thanks. I just forgot that computers work in radians.
Comment: Since the $C$ scale goes from 1 to 100, you conveniently get the $S$ scale from (almost) 0 to (a little more than) 1, and the important values close to 0 are well-represented.
Comment: Should the last formula not be $\frac{\ell}{2}\log(\sin^{-1}(\frac{s\cdot180}{\pi}))$?
Comment: No, of course not. The labels are sines of various angles, so are between $-1$ and $1$.   $\sin^{-1} x$ is defined only for $-1\le x\le 1$.  $\sin^{-1} \frac{180}\pi s$ is not even well-defined for labels in the range $-1$ to $1$.
Comment: @Steve You are absolutely right, thanks.


Use of a function when importing a feed

Question: I have a Feed which imports data from a CSV file. I import data of products, namely title, price, category, etc. However, in order to provide a friendly URL, I send a customized field, which is in different languages and completely verbose, for example: Shoes for female scientists. I want to use this description as part of the clean friendly URL, so I would need to use some function like pathauto_cleanstring(). However, the update takes ages to complete. Is there a faster way, for example directly on import?
This code is executed on a call to mymodule_cronapi via Elysia Cron, and through curl PHP function:
   $results = db_query('SELECT nid, title FROM node WHERE type= :product', array(":product" => "product") );
    foreach($results as $row){
        $node = node_load($row->nid);
        $node_wrapper = entity_metadata_wrapper('node', $node);
        $node_wrapper->field_product_url->set(pathauto_cleanstring($row->title));
        $node_wrapper->save();
    } // foreach

Answer: You should be able to use Feeds Tamper to create your URLs based on values in your CSV: https://www.drupal.org/project/feeds_tamper
Comment: But I don't see nowhere in the GUI where I can choose *pathauto_cleanstring* or equivalent, which is what I need. URLencode or URLdecode won't do the trick, and the raw regular pattern probably won't either.

Use of a function when importing a feed


Regex for containing x AND not containing y without lookarounds

Question: I'm trying to write a simple regex for a string that contains a dot (.) AND doesn't contain @.
I managed to do this like this:
(^(?!.*@).*\..*$)

and it works!
But I'm getting an error:
'Value "/(^(?!.*@).*\..*$)" must be a valid regular expression. Details: invalid or unsupported Perl syntax.'

I've searched and found out that the issue is with the negation part - "?!".
Trying to change the expression to work with ^ but with no luck.
Would appriciate your help, thanks.
Comment: Try `^[^@.]*[.][^@]*$`
Comment: How can it be working if you're getting an error?
Comment: @Barmar what I meant by that is that the Regex itself is correct but our system doesn't support it's syntax
Comment: What is "your system"? The question is tagged `javascript` and `perl`, both of them should support this.
Comment: @Barmar The error said "invalid or unsupported Perl syntax". The info I've given in the question is what I know, and the answer I got from Wiktor is what I needed. Thank you.
Comment: What that means is that it's perl syntax that isn't supported by your regular expression library. You should tag the question with the language you're using.
Comment: @Barmar this is the first time I've posted a question so I wasn't aware of how the tags should work. Anyway someone removed already the irrelevant tags :)
Answer: You can use a regex that does not rely on lookarounds:
^[^@.]*\.[^@]*$

Or, if you have trouble with finding the right amount of escaping backslashes:
^[^@.]*[.][^@]*$

Details:

^ - start of string
[^@.]* - zero or more chars other than a . and @
\. / [.] - a mere dot char
[^@]* - zero or more chars other than a @ char
$ - end of string.
Comment: Why do you need `[^@.]*` instead of `[^@]*`?
Comment: @Barmar To reduce backtracking.


How to display unicode for "micron" or lower case "Mu" in a CEdit?

Question: How to display unicode for "micron" or lower case "Mu" in a CEdit?
thx
CEdit *ed = new CEdit();
ed->Create(WS_VISIBLE | WS_BORDER, CRect(200,100,300,120), this, 10);

CString s;
s.Format("%c", xx); //<--- how to do unicode here?
ed->SetWindowText(s);

I think the unicodes:
micron 0x00b5
squared 0x00b2
cubed 0x00b3
degree 0x00b0

Answer: If you're using the UNICODE project setting, this is trivial:
s.Format("%c", 0x3BC);

The CString will contain wide (UTF-16) characters which can hold most common Unicode characters in a single location; the only problem will come with Unicode code points over U+FFFF.


partial directory listing

Question: Is it possible to get a partial directory listing?
In Python, I have a process that tries to get os.listdir of a directory containing >100,000 of files and it takes forever.  I'd like to be able, let's say, to get a listing of the first 1,000 files quickly.
How can I achieve this?
Comment: This might be of use: http://www.olark.com/spw/2011/08/you-can-list-a-directory-with-8-million-files-but-not-with-ls/
Comment: Next time, I would suggesting adding more subdirectories into your file set (i.e. instead of `/bigdir/00001.txt` .... `/bigdir/99999.txt`  have `/bigdir/subdir0/0001.txt` .... `/bigdir/subdir9/9999.txt`). It would make things easier (and perhaps a bit faster). Having hundred of thousands entries in a single directory is usually not a good idea.
Comment: @BasileStarynkevitch - hindsight is truly a wonderful thing ;) - doesn't really solve the OP's current problem though, and this may not be of his own doing.
Answer: I found a solution that gives me a random order of the files :) (At least I can't see a pattern)
First I found this post in the python maillist. There are 3 files attached that you have to copy to your disk (opendir.pyx, setup.py, test.py). Next you need the python package Pyrex to compile the file opendir.pyx from the post. I had problems installing Pyrex and found that I had to install python-dev via apt-get. Next I installed the opendir package from the three above downloaded files with python setup.py install. The file test.py contains examples how to use it.
Next I was interested in how much faster this solution will be than using os.listdir and I created 200000 files with the following small shellscript .
for((i=0; i<200000; i++))
do
    touch $i
done

The following script is my benchmark running in the directory where I just created the files:
from opendir import opendir
from timeit import Timer
import os

def list_first_fast(i):
    d=opendir(".")
    filenames=[]
    for _ in range(i):
        name = d.read()
        if not name:
            break
        filenames.append(name)
    return filenames

def list_first_slow(i):
    return os.listdir(".")[:i]

if __name__ == '__main__':
    t1 = Timer("list_first_fast(100)", "from __main__ import list_first_fast")
    t2 = Timer("list_first_slow(100)", "from __main__ import list_first_slow")
    print "With opendir: ", t1.repeat(5, 100)
    print "With os.list: ", t2.repeat(5, 100)

The output on my system is:
With opendir:  [0.045053958892822266, 0.04376697540283203, 0.0437769889831543, 0.04387712478637695, 0.04404592514038086]
With os.list:  [9.50291895866394, 9.567682027816772, 9.865844964981079, 13.486984968185425, 9.51977801322937]

As you can see I got a speedup of a factor of 200 when returning a list with 100 filenames out of the 200000, thats pretty nice :).
I hope this is the goal you are trying to achieve.
Comment: +1: interesting but I'd rather have a more standard solution.

partial directory listing


Deck of cards index/array error

Question: I'm trying to create a deck of cards that shuffles itself and then outputs the cards in random order. I am running into the error ArrayIndexOutOfBoundsException for the lines
return ranks[rank] + " of " + suits[suit];

and
System.out.println( C.toString() );

What am I doing wrong? It outputs the deck size, and then occasionally outputs a card or two before showing the error code. Thanks in advance.
import java.util.Random;
import java.util.ArrayList;

public class Deck
    {
    private ArrayList<Card> cards;

    Deck()
        {
        cards = new ArrayList<Card>();
        for (int a=0; a<=3; a++)
            {
            for (int b=0; b<=12; b++)
                {
                cards.add( new Card(a,b) );
                }
            }
        }

    public static void main(String[] args)
        {
        Deck deck = new Deck();
        Card C;

        System.out.println( deck.getTotalCards() );

        while (deck.getTotalCards() != 0)
            {
            C = deck.drawFromDeck();
            System.out.println( C.toString() );
            }
        }

    public class Card
        {
        private int rank,
                    suit;

        private String[] suits = {"Hearts", "Spades", "Diamonds", "Clubs"};
        private String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

        Card(int rank, int suit)
            {
            this.rank=rank;
            this.suit=suit;
            }

        public @Override String toString()
            {
            return ranks[rank] + " of " + suits[suit];
            }

        public int getRank()
            {
            return rank;
            }

        public int getSuit()
            {
            return suit;
            }
        }

    public Card drawFromDeck()
        {
        Random generator = new Random();
        int index = generator.nextInt( cards.size() );
        return cards.remove(index);
        }

    public int getTotalCards()
        {
        return cards.size();
        }
    }

Answer: Everything there is good but you initialize the cards backwards.
Your Card constructor is (rank, suit) and your Deck constructor is creating them (suit, rank).
Just flip the order of the args in your Deck constructor on line 15
cards.add( new Card(a, b) );

should be
cards.add( new Card(b, a) );

Since a ranges from 0 to 3, a is the suit, and should be the second argument in the constructor.

Deck of cards index/array error


How to deal with discontinuous points when proving that step functions are dense in $PC[a,b]$

Question: This question is a follow-up to my previous question: How does one prove that a space is dense in another under some norm?
I figured out a way to solve (part of) the exercise.
Given some function $f\in PC[a,b]$, my argument relies on the continuity of $f$ to prove that there exists some sequence $f_N\subset S[a,b]$ such that $$\lim_{N\to \infty} d(f,f_N)=\lim_{N\to\infty} ||f-f_N||_\infty=\lim_{N\to\infty}\sup_{x\ \in\ [a,b]} |f(x)-f_N(x)|=0 $$
However, the exercise that I am trying to solve asks for a proof that $S[a,b]$ is dense in $PC[a,b]$, the space of all bounded piecewise continuous functions on $[a,b]$. My assumption of continuity seems to be at tension with the fact that $f$ should be allowed to be discontinuous at finitely many points.
I was wondering what the standard procedure is for dealing with the finitely many points where $f\in PC[a,b]$ may be discontinuous. One possibility I considered can be described as "starting a new step in the step function at each of the finitely many $x_j$ where one encounters discontinuity of $f(x)$", but this is clearly not rigorous enough.
Update: After some discussion with T.A.E., he suggested that it should be possible to add some $s\in S[a,b]$ to any piecewise continuous function to reduce the problem to the continuous case, which I solved already. However, I am unclear how to make this argument precise (doesn't a step function just 'shift the discontinuity'?). Any suggestions or alternatives are more than welcome.
Comment: There's a problem with the formulation because in order to discuss $S[a,b]$ being dense *in* $C[a,b]$, you would have to have $S[a,b]\subseteq C[a,b]$, which you don't have. I assume there is some larger space $X$ with $S[a,b]\subseteq X$ and $C[a,b]\subseteq X$ where $C[a,b]\subseteq S[a,b]^{c}$. What is that larger space $X$?
Comment: @T.A.E. Thank you for your reply. Your suggestion certainly sounds reasonable. However, if you have a look at problem 8a of this problem set: http://math.uga.edu/~clayton/courses/608/608_1.pdf, does this not seem to contradict what you said? Feel free to point out any blatant errors of mine, I am quite new to analysis.
Comment: @T.A.E. The exercise I am trying to solve calls for a proof that $S[a,b]$ is dense in $PC[a,b]$. I just thought I'd proven that $S[a,b]$ is dense in $C[a,b]$ because I assumed that $f$ is continuous on $[a,b]$ in my proof. This may be wrong.
Comment: @T.A.E. I rewrote part of my question so that this confusion about $C[a,b]$ does not arise. Is the question sensible in this form? And would you happen to know an answer to it?
Comment: Now the formulation can make sense because it could make sense that $S[a,b]\subseteq PC[a,b]$. The problem with piecewise continuous functions is that $f(x-0)$, $f(x+0)$ and $f(x)$ are not necessarily related. So it's convenient to settle on a convention where $f(x-0)=f(x)$ or $f(x)=f(x+0)$ or $f(x)=\frac{1}{2}(f(x-0)+f(x+0))$. The problem is that every point counts in a sup norm. But the normalization is irrelevant if you are you using an $L^{\infty}$ essential sup norm. Are you using the essential sup norm?
Comment: @T.A.E. In the book that I am using, $PC[a,b]$ is defined as 'the family of bounded piecewise continuous functions on $[a,b]$ which are continuous from the right and for which the limit from the left exists everywhere and is equal to the limit from the right everywhere except for finitely many points'. Does this help in formulating a way to complete the proof?
Comment: You can use a max norm if all the functions in $S[a,b]$ and in $PC[a,b]$ have limits $f(x+0)$, $f(x-0)$ where possible, and satisfy $f(x)=f(x+0)$ where possible. Then, for $p \in PC[a,b]$ there should exist $s \in S[a,b]$ so that $p-s$ is continuous on $[a,b]$, which reduces the approximation problem to one of finding $s \in S[a,b]$ to approximate $f \in C[a,b]$.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/15611/discussion-between-danu-and-t-a-e).
Answer: Let's assume that the functions in $PC[a,b]$ and in $S[a,b]$ are normalized so that
$$
            f(x+0)=f(x),\;\;\; a \le x < b.
$$
All of the functions are required to be continuous at $a$ using this normalization. But these funtions may be discontinuous at $b$. If $y \in (a,b]$ is a point of discontinuity of $f \in PC[a,b]$, then
$$
          s(x) = f(y-0)\chi_{[a,y)}(x)+f(y)\chi_{[y,b]}(x)
$$
is a normalized function in $S[a,b]$ with $y$ as the only point of discontinuity; furthermore, $s(y+0)=f(y)=f(y+0)$ and $s(y-0)=f(y-0)$. Therefore $f-s$ is a normalized function in $PC[a,b]$ that is continuous at $y$; $f-s$ has the same jumps and discontinuities as $f$ in $[a,b]\setminus\{y\}$. Continuing by finite induction, you obtain $s \in S[a,b]$ such that $g=f-s$ is continuous. Because $g$ is continuous, then it is uniformly continuous, and, for every $\epsilon > 0$, you can find points $a=x_{0} < x_{1} < \cdots < x_{n}=b$ such that
$$
    s_{\epsilon}(x) = \sum_{j=1}^{n-1}c_{j}\chi_{[x_{j-1},x_{j})}(x)+c_{n}\chi_{[x_{n-1},x_{n}]}(x)
$$
satisfies $|s_{\epsilon}(x)-g(x)| < \epsilon$ for all $x \in [a,b]$. It follows that $|f-s-s_{\epsilon}| < \epsilon$ on $[a,b]$.
Comment: Beautiful. Of course, 'shift the discontinuity' to $a$!


Dirichlet characters and quadratic fields

Question: Let $\chi$ be a Dirichlet character. This is,
$$\chi: (\mathbb{Z}/m\mathbb{Z})^* \to S^1$$
I'm trying to understand the relation between those characters and fiel extensions.
For example, the principal (trivial) character $\chi_0$ mod $1$ is naturally associated to $\mathbb{Q}$, in the sense that $L(s,\chi_0)=\zeta(s)$.
In particular I'm interested in the following. Let $K$ be a quadratic extensions. We know that:
$$\zeta_K(s)=\zeta(s)L(s,\chi_K)$$
Let's call quadratic characters to those who appear that way. There should be a bijection between quadratic characters and quadratic extensions (right?).

Are all non-principal characters quadratic?

But perhaps the most natural question is,

Given a Dirichlet character $\chi$, how do we get a field extension
  $K$ from it? Is $K$ quadratic always? Is this process unique?

Thanks for any information. I'd appreciate references also.
Comment: The correspondence between quadratic fields and quadratic Dirichlet characters, that is, those characters such that $\chi(n)=\pm 1$ for $n$ coprime to the conductor of $\chi$, is the Quadratic Reciprocity Law.
Comment: Notice also that $L(s,\chi_0)\neq \zeta(s)$.
Comment: @ÁngelValencia Thanks, but what about the rest of characters?
Comment: @PITTALUGA I ment mod 1.
Comment: In general, Dirichlet characters are associated to characters of abelian extensions of $\Bbb Q$ via Class Field Theory. Check the relation, for example, at Bump et. al., _An Introduction to the Langlands Program_, Thm 5.2, p. 13. The book _Cyclotomic Fields_ by L. Washington is more explicit.
Comment: The phrase "fundamental discriminant" is also associated to your observed correspondence between quadratic extensions and quadratic characters.
Answer: This is probably not a complete answer to your question but here it is anyways.
Usually, one calls a Dirichlet character $\chi$ quadratic, if it has order 2 in the dual of $(\mathbb{Z}/m\mathbb{Z})^\ast$, i.e. if $\chi^2 = 1$ and $\chi$ is not principal. Notice that every qudratic character takes only the values $\pm 1$ and $-1$ at least once. Equivalently, a quadratic characater is a real and non-principal character.
Next, call an integer $D$ a quadratic discriminant, if it arises as the discriminant of a quadratic number field. Equivalently, $D$ is a quadratic discrimant, if $D$ is $\neq 1$, square-free and $D \equiv 1 \mod{4}$ or if $D  = 4d$ for some square-free integer $d \equiv 2$ or $3 \mod 4$.
Attached to every quadratic discriminant $D$ is a special quadratic character, called the Kronecker symbol, sometimes denoted by $\chi_D(n)$ or $\left( \frac{D}{n} \right)$ where $n$ is the argument. One can define it by requiring:

$\chi_D$ is completely multiplicative.
$\chi_D(0) = 0$ and $\chi_D(1) = 1$.
For every odd prime $p$, $\chi_D(p)$ is equal to the Legendre symbol mod $p$.
$\chi_D(2) = \begin{cases}0 & \text{ if } D \equiv 2  \pmod{2}\\ 1 &\text{ if } D \equiv 1 \pmod{8}\\ -1 &\text{ if } D \equiv 5 \pmod{8} \end{cases}$.
$\chi_D(-1) = \begin{cases}1 & \text{ if } D > 0 \\ -1 & \text{ if } D < 0 \end{cases}$.

One has then the following Theorem, whose proof uses a lot of the theory of Dirichlet characters and Gauss' quadratic reciprocity law.
Theorem. For every quadratic discrimant $D$, the Kronecker symbol $\chi_D$ defines a primitive quadratic character mod $|D|$. Conversely, every primitve quadratic character is given by a Kronecker symbol and hence every quadratic character is induced by some Kronecker symbol.
In my opinion, Montgomery's and Vaughan's ''Multiplicative number theory'' or Davenport's classical ''Multiplicative number theory'' is a good reference for this.
Furthermore, the following formula holds for quadratic fields $K$:
$$\zeta_K(s) = \zeta(s)L(s, \chi_D).$$
In your notation $\chi_D = \chi_K$.
The answer to your first question is no with both your and 'my' defintion of quadratic.
Comment: Thanks, that helps a lot! I'll go through it more carefully, and give a look to the books you reference.


Hi..I have issue when I clicked on Upload file button, file uploading window not get open but its sometimes works,How I solved it?

Question: I am using Selenium Webdriver with Java.I have issue when I clicked on Upload file button, file uploading window not get open but its sometimes works,How I solved it?
Answer: Do not click on file upload rather just use send keys..
WebElement upload = driver.findElement(By.id("myfile"));
upload.sendKeys("c:\\darkbulb.jpg");

UPDATE:
From the information shared you cannot use send keys as it works only for <input type="file">. So you must use Autoit,
1.Download and Install Autoit tool from http://www.autoitscript.com/site/autoit/
2.Open Programs -> Autoit tool -> Script Editor.
3.Paste the following code in Autoit editor and save it as "filename.exe" (eg: fileUpload.exe)
Then compile and build the file to make it exe. (Tools → Compile). Following is the code for autoit:
WinWaitActive("File Upload"); Name of the file upload window pop-up(Windows Popup Name: File Upload)
Send("c:\logo.jpg"); File name (absolute path preferred)
Send("{ENTER}")

Then Compile and Build from Tools menu
Use the below Java code to call autoit file
Java Code:
driver.findElement(By.className("qq-upload-button-selector qq-upload-button")).click; // open the Upload window using selenium
Thread.sleep("20000"); // wait for page load
Runtime.getRuntime().exec("C:\\Documents and Settings\\new.exe"); // Give  path where the exe is saved.

Comment: Hi, these syntax cant working for me Because there is only upload button that have to click & then window for file upload is open. Its working fine in Chrome & Fife Fox browser only issue in IE. Please give Solution.
Comment: @Swapnil If its a browse file button you can use `sendKeys`... have you tried the above command? what error u get ?
Comment: Yeah I tried, after executing these command whole page get refresh and file is not getting Uploaded.
Comment: @Swapnil can you confirm if the HTML code is `` ? because the above script would work only if so...
Comment: hi... Upload Button HTML code is
Comment: @Swapnil I've updated my answer... this would work... you must use Aotoit for this task... let me know if you face any difficulty...