text:
Q: cannot convert 'UIBarButtonItemStyle' to 'UIBarButtonSystemItem' in argument passing I am trying to add subview contains uipickerview and Done button using the following code
    pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0,744, 768, 216)];
    mytab = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 700, 768, 44)];

    pickerView.alpha=0.0;
    mytab.alpha=0.0;

    pickerView.showsSelectionIndicator = YES;
    pickerView.dataSource = self;
    pickerView.delegate = self;

    [self.view addSubview:pickerView];
    [self.view bringSubviewToFront:pickerView];

    mytab.tintColor=[UIColor blackColor];

    UIBarButtonItem * bt1=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonItemStylePlain target:self action:@selector(_cancel)];
    UIBarButtonItem * flx=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];

    NSArray *arr=[[NSArray alloc] initWithObjects:flx,bt1,nil];
    [mytab setItems:arr];
    [self.view addSubview:mytab];

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    pickerView.alpha=1.0;
    mytab.alpha=1.0;
    [UIView commitAnimations];

    [pickerView release];
    [mytab release];
    [bt1 release];
    [flx release];
    [arr release];

it raise the following error
cannot convert 'UIBarButtonItemStyle' to 'UIBarButtonSystemItem' in argument passing
aany suggestion to solve that

A: typedef enum {
    UIBarButtonSystemItemDone,
    UIBarButtonSystemItemCancel,
    UIBarButtonSystemItemEdit,
    UIBarButtonSystemItemSave,
    UIBarButtonSystemItemAdd,
    UIBarButtonSystemItemFlexibleSpace,
    UIBarButtonSystemItemFixedSpace,
    UIBarButtonSystemItemCompose,
    UIBarButtonSystemItemReply,
    UIBarButtonSystemItemAction,
    UIBarButtonSystemItemOrganize,
    UIBarButtonSystemItemBookmarks,
    UIBarButtonSystemItemSearch,
    UIBarButtonSystemItemRefresh,
    UIBarButtonSystemItemStop,
    UIBarButtonSystemItemCamera,
    UIBarButtonSystemItemTrash,
    UIBarButtonSystemItemPlay,
    UIBarButtonSystemItemPause,
    UIBarButtonSystemItemRewind,
    UIBarButtonSystemItemFastForward,
#if __IPHONE_3_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED
    UIBarButtonSystemItemUndo,
    UIBarButtonSystemItemRedo,
#endif
#if __IPHONE_4_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED
    UIBarButtonSystemItemPageCurl,
#endif
} UIBarButtonSystemItem;

UIBarButtonItemStylePlain is not available for UIBarButtonSystemItem. It is available for UIBarButtonItemStyle
typedef enum {
    UIBarButtonItemStylePlain,    // shows glow when pressed
    UIBarButtonItemStyleBordered,
    UIBarButtonItemStyleDone,
} UIBarButtonItemStyle;

you can try - (id)initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action; for your button

A: UIBarButtonItemStylePlain is not a Button's System Item Style. Changing it for any of the following:
typedef enum {
UIBarButtonSystemItemDone,
UIBarButtonSystemItemCancel,
UIBarButtonSystemItemEdit,
UIBarButtonSystemItemSave,
UIBarButtonSystemItemAdd,
UIBarButtonSystemItemFlexibleSpace,
UIBarButtonSystemItemFixedSpace,
UIBarButtonSystemItemCompose,
UIBarButtonSystemItemReply,
UIBarButtonSystemItemAction,
UIBarButtonSystemItemOrganize,
UIBarButtonSystemItemBookmarks,
UIBarButtonSystemItemSearch,
UIBarButtonSystemItemRefresh,
UIBarButtonSystemItemStop,
UIBarButtonSystemItemCamera,
UIBarButtonSystemItemTrash,
UIBarButtonSystemItemPlay,
UIBarButtonSystemItemPause,
UIBarButtonSystemItemRewind,
UIBarButtonSystemItemFastForward,
UIBarButtonSystemItemUndo,        // iOS 3.0 and later
UIBarButtonSystemItemRedo,        // iOS 3.0 and later
UIBarButtonSystemItemPageCurl,    // iOS 4.0 and later
} UIBarButtonSystemItem;

in the line: UIBarButtonItem * bt1=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonItemStylePlain target:self action:@selector(_cancel)];
should make it work.
I hope it helps
Cheers


text:
Q: Error Thrown When Toggling 'Quick Edit' on a List or Library For some reason users are getting the following popup/error when toggling 'Quick Edit' on a list or library.

This site says...
Assertion Failed: Edit manager is still in Editing state, but focus is on the grid's input element!
Break into debugger?

No errors are showing in Chrome's developer tools console. However it is showing the following messages... (I'm not sure if they are related.)
[Violation] Added synchronous DOM mutation listener to a 'DOMSubtreeModified' event. Consider using MutationObserver to make the page more responsive.

[Violation] 'click' handler took 34811ms

[Violation] Forced reflow while executing JavaScript took 35ms
[Violation] Forced reflow while executing JavaScript took 38ms

We are running SharePoint 2013

redpajama_set_name: RedPajamaStackExchange


text:
Q: AJAX Update panel swallows exceptions and its strange behaviour I've got just caught with strange behavior of AJAX update panel. The first think made me embarrassed is that I have noticed that  when I throw exception during async postback, it is swallowed by enviroment.
Since it's first time when I faced to such issue, I started to make experiments - trying either to throw different types of exceptions, or to throw same exceptions outside updatePanel (e.g at Page_Init event). The conclusion is that when exception is thrown within async postback, the environment swallows it,  and page renders as if nothing happened (it is the inacceptible point ). But when I throw the exception within normal page life-cycle, exception forwards in usual way and page fails as expected  (I hope to be right with my deductions)
The question is  what should I do to enable exception throwing
(BTW, while I'd been writing this message, I was noticed that due to business-logic changes there is no longer need to throw above-mentioned exception, but I am interested anyway why it happens)
The second issue with updatePanel is that when I set it {up.Visible=false;} at Page_Load, then at the some method set it  {up.Visible=true; up.Update() } - it still unrenderred. I have set breakpoints at both places; .visible is set to true when page renders, but anyway it still be invisible.I do not see any obvious reason why.
Thanks.

A: To enable asp.net error screens when errors are thrown in update panel code, you need to set in your ScriptManager:
EnablePartialRendering="false"


text:
Q: Несколько BackgroundWorker не возвращают вычисляемые значения полностью при большом объёме данных Я создаю программу для чтения и редактирования файлов. Она читает файл, затем преобразуя его в последовательность нулей и единиц.
Из-за того, что я рассчитывал на обработку больших объёмов данных, то преобразование файла я доверил 16ти BackgroundWorker. Однако я столкнулся с такой проблемой, что если размер файла превышает 2 килобайта, то небольшая часть данных теряется. Я не знаю, с чем это связано, так что выложил этот вопрос сюда.
В общем, сначала файл считывается и заносится в массивы по 1\16 части в каждый
, кроме последнего, в него заносятся все оставшиеся символы.При необходимости (размер файла превышает 32768 байтов) файл делится на части по 32768 символов по такому же принципу:
    void ShowFileOpenDialog(object sender, EventArgs e)
    {
        if (DialogResult.OK == FileOpenDialog.ShowDialog()) {
            using (StreamReader streamReader = new StreamReader(FileOpenDialog.FileName, Encoding.UTF8))
            {
                RawCommonFile = streamReader.ReadToEnd();
            }
            MessageBox.Show(Convert.ToString(RawCommonFile.Length));
            if(RawCommonFile.Length >= 16) {
                FilePart = 1;
                if (RawCommonFile.Length > 32768) { FullCommonFile = RawCommonFile.Substring(0,32768);AllFileParts = (int)Math.Floor((double)RawCommonFile.Length / 32768);}
                else { FullCommonFile = RawCommonFile; AllFileParts = 1; }
            FileReadProgressBar.Maximum = RawCommonFile.Length;
            MessageBox.Show(Convert.ToString(RawCommonFile.Length));
            CommonFile[0] = FullCommonFile.Substring(0, Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length) / 16)));
            CommonFile[1] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[2] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 2))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[3] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 3))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[4] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 4))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[5] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 5))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[6] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 6))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[7] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 7))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[8] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 8))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[9] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 9))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[10] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 10))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[11] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 11))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[12] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 12))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[13] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 13))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[14] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 14))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[15] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 15))), FullCommonFile.Length - Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 15))));
            BinaryFile[0] = "";
            BinaryFile[1] = "";
            BinaryFile[2] = "";
            BinaryFile[3] = "";
            BinaryFile[4] = "";
            BinaryFile[5] = "";
            BinaryFile[6] = "";
            BinaryFile[7] = "";
            BinaryFile[8] = "";
            BinaryFile[9] = "";
            BinaryFile[10] = "";
            BinaryFile[11] = "";
            BinaryFile[12] = "";
            BinaryFile[13] = "";
            BinaryFile[14] = "";
            BinaryFile[15] = "";
            CharProgress = 0;
            FileBox.Text = "";
            FileReader.RunWorkerAsync();
            FileReader2.RunWorkerAsync();
            FileReader3.RunWorkerAsync();
            FileReader4.RunWorkerAsync();
            FileReader5.RunWorkerAsync();
            FileReader6.RunWorkerAsync();
            FileReader7.RunWorkerAsync();
            FileReader8.RunWorkerAsync();
            FileReader9.RunWorkerAsync();
            FileReader10.RunWorkerAsync();
            FileReader11.RunWorkerAsync();
            FileReader12.RunWorkerAsync();
            FileReader13.RunWorkerAsync();
            FileReader14.RunWorkerAsync();
            FileReader15.RunWorkerAsync();
            FileReader16.RunWorkerAsync();
            MainMenu.Enabled = false;
            FileBox.Enabled = false;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            ProgressPanel.Visible = true;
        }
    }
}

Затем все BackgroundWorker начинают работать:
    void OpenFileAsync(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach (char sb in CommonFile[0]) {
            BinaryFile[0] += Convert.ToString(sb, 2).PadLeft(8, '0');
                if (CharProgress % 8 == 0) { FileReadProgressBar.Value += 8;FileReadProgressLabel.Text = "Reading char " + Convert.ToString(FileReadProgressBar.Value) + " of " + Convert.ToString(FileReadProgressBar.Maximum);
                }
                CharProgress++;
        }
    }

    void FileOpened(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync2(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach (char sb in CommonFile[1]) {
                BinaryFile[1] += Convert.ToString(sb, 2).PadLeft(8, '0');
                CharProgress++;
        }
    }

    void FileOpened2(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync3(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach (char sb in CommonFile[2]) {
                BinaryFile[2] += Convert.ToString(sb, 2).PadLeft(8, '0');
                CharProgress++;
            }
    }

    void FileOpened3(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync4(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach(char sb in CommonFile[3]) {
                BinaryFile[3] += Convert.ToString(sb, 2).PadLeft(8, '0');
                CharProgress++;
        }
    }

    void FileOpened4(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync5(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach(char sb in CommonFile[4]) {
            BinaryFile[4] += Convert.ToString(sb, 2).PadLeft(8, '0');
            CharProgress++;
        }
    }

    void FileOpened5(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync6(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach (char sb in CommonFile[5]) {
            BinaryFile[5] += Convert.ToString(sb, 2).PadLeft(8, '0');
            CharProgress++;
        }
    }

    void FileOpened6(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync7(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach (char sb in CommonFile[6]) {
            BinaryFile[6] += Convert.ToString(sb, 2).PadLeft(8, '0');
            CharProgress++;
        }
    }

    void FileOpened7(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync8(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach (char sb in CommonFile[7]) {
            BinaryFile[7] += Convert.ToString(sb, 2).PadLeft(8, '0');
            CharProgress++;
        }
    }

    void FileOpened8(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync9(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach (char sb in CommonFile[8]) {
            BinaryFile[8] += Convert.ToString(sb, 2).PadLeft(8, '0');
            CharProgress++;
        }
    }

    void FileOpened9(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync10(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach(char sb in CommonFile[9]) {
            BinaryFile[9] += Convert.ToString(sb, 2).PadLeft(8, '0');
            CharProgress++;
        }
    }

    void FileOpened10(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync11(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach(char sb in CommonFile[10]) {
            BinaryFile[10] += Convert.ToString(sb, 2).PadLeft(8, '0');
            CharProgress++;
        }
    }

    void FileOpened11(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync12(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach (char sb in CommonFile[11]) {
            BinaryFile[11] += Convert.ToString(sb, 2).PadLeft(8, '0');
            CharProgress++;
        }
    }

    void FileOpened12(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync13(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach (char sb in CommonFile[12]) {
            BinaryFile[12] += Convert.ToString(sb, 2).PadLeft(8, '0');
            CharProgress++;
        }
    }

    void FileOpened13(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync14(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach (char sb in CommonFile[13]) {
            BinaryFile[13] += Convert.ToString(sb, 2).PadLeft(8, '0');
            CharProgress++;
        }
    }

    void FileOpened14(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync15(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach (char sb in CommonFile[14]) {
            BinaryFile[14] += Convert.ToString(sb, 2).PadLeft(8, '0');
            CharProgress++;
        }
    }

    void FileOpened15(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        JoinBinary();
    }

    void OpenFileAsync16(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        foreach (char sb in CommonFile[15]) {
            BinaryFile[15] += Convert.ToString(sb, 2).PadLeft(8, '0');
            CharProgress++;
        }
    }

Далее при завершении работы каждого BackgroundWorker специальная переменная увеличивается до тех пор, пока не становится равна количеству всех потоков, а далее весь код добавляется в текстовое поле FileBox:
    void JoinBinary()
    {
        ReadPartsCount++;
        if (ReadPartsCount == 16) {
            MessageBox.Show("char progress : " + Convert.ToString(CharProgress) + " of " + Convert.ToString(CommonFile[0].Length + CommonFile[1].Length + CommonFile[2].Length + CommonFile[3].Length + CommonFile[4].Length + CommonFile[5].Length + CommonFile[6].Length + CommonFile[7].Length + CommonFile[8].Length + CommonFile[9].Length + CommonFile[10].Length + CommonFile[11].Length + CommonFile[12].Length + CommonFile[13].Length + CommonFile[14].Length + CommonFile[15].Length));
            MainMenu.Enabled = true;
            FileBox.Enabled = true;
            this.FormBorderStyle = FormBorderStyle.Sizable;
            FileBox.Text = BinaryFile[0];
            FileBox.Text += BinaryFile[1];
            FileBox.Text += BinaryFile[2];
            FileBox.Text += BinaryFile[3];
            FileBox.Text += BinaryFile[4];
            FileBox.Text += BinaryFile[5];
            FileBox.Text += BinaryFile[6];
            FileBox.Text += BinaryFile[7];
            FileBox.Text += BinaryFile[8];
            FileBox.Text += BinaryFile[9];
            FileBox.Text += BinaryFile[10];
            FileBox.Text += BinaryFile[11];
            FileBox.Text += BinaryFile[12];
            FileBox.Text += BinaryFile[13];
            FileBox.Text += BinaryFile[14];
            FileBox.Text += BinaryFile[15];
            if (FilePart != AllFileParts) {
            FilePart++;
                if (FilePart + 1 != AllFileParts) {
                FullCommonFile = RawCommonFile.Substring((FilePart - 1) * 32768,32768);}
            else {FullCommonFile = RawCommonFile.Substring((FilePart - 1) * 32768,RawCommonFile.Length - ((FilePart - 1) * 32768));
            }
            BinaryFile[0] = "";
            BinaryFile[1] = "";
            BinaryFile[2] = "";
            BinaryFile[3] = "";
            BinaryFile[4] = "";
            BinaryFile[5] = "";
            BinaryFile[6] = "";
            BinaryFile[7] = "";
            BinaryFile[8] = "";
            BinaryFile[9] = "";
            BinaryFile[10] = "";
            BinaryFile[11] = "";
            BinaryFile[12] = "";
            BinaryFile[13] = "";
            BinaryFile[14] = "";
            BinaryFile[15] = "";
            CommonFile[0] = FullCommonFile.Substring(0,Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length) / 16)));
            CommonFile[1] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[2] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 2))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[3] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 3))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[4] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 4))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[5] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 5))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[6] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 6))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[7] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 7))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[8] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 8))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[9] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 9))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[10] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 10))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[11] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 11))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[12] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 12))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[13] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 13))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[14] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 14))), Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16))));
            CommonFile[15] = FullCommonFile.Substring(Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 15))), FullCommonFile.Length - Convert.ToInt32(Math.Floor(Convert.ToDouble(FullCommonFile.Length / 16 * 15))));
            CharProgress = 0;
            FileReader.RunWorkerAsync();
            FileReader2.RunWorkerAsync();
            FileReader3.RunWorkerAsync();
            FileReader4.RunWorkerAsync();
            FileReader5.RunWorkerAsync();
            FileReader6.RunWorkerAsync();
            FileReader7.RunWorkerAsync();
            FileReader8.RunWorkerAsync();
            FileReader9.RunWorkerAsync();
            FileReader10.RunWorkerAsync();
            FileReader11.RunWorkerAsync();
            FileReader12.RunWorkerAsync();
            FileReader13.RunWorkerAsync();
            FileReader14.RunWorkerAsync();
            FileReader15.RunWorkerAsync();
            FileReader16.RunWorkerAsync();
            }
            else{
                ProgressPanel.Visible = false;
            }
            ReadPartsCount = 0;
            }
    }

MessageBox.Show("char progress : " + Convert.ToString(CharProgress) + " of " + Convert.ToString(CommonFile[0].Length + CommonFile[1].Length + CommonFile[2].Length + CommonFile[3].Length + CommonFile[4].Length + CommonFile[5].Length + CommonFile[6].Length + CommonFile[7].Length + CommonFile[8].Length + CommonFile[9].Length + CommonFile[10].Length + CommonFile[11].Length + CommonFile[12].Length + CommonFile[13].Length + CommonFile[14].Length + CommonFile[15].Length));

Я использовал для отладки. В маленьких файлах символы присутствовали все, в больших же их немного не хватало.


text:
Q: gst multifilesink of datestamped files every 5 minutes I've searched and found some relevant threads but I'm just a bit too new to bash to comprehend so I figured I post my explicit problem. I've got a raspberry pi with a camera taking a picture every 5 minutes. It names the file $DATE.jpg where DATE=$(date +"%m-%d-%Y_%H%M"). So at 1:35PM the filename would be 07-28-2018_1335.jpg. After each day I'm wanting to make a gst script to combine them all for the day into an avi and then flush out the directory. So far I have:
DATE=$(date +"%m-%d-%Y")
TAIL=%04d
NAME=$(echo ${DATE}_${TAIL})
gst-launch-1.0 multifilesrc location=/home/pi/usbdrive/archive/$NAME.jpg index=0 caps="image/jpeg,framerate=5/1" ! jpegdec ! omxh264enc ! avimux ! filesink location=/home/pi/usbdrive/video-archive/$DATE.avi

If I have it set to take a picture every minute, it seems to work for 60 frames as last 2 digits resets to 00 on a new hour. Can't figure out how to tell it to take every file based on every 5 digits while also resetting after 55 or every digit while resetting at 59. Any help help would be appreciated! Thanks!

A: multifilesrc is to read file sequences. Your sequence is way to complex. A sequence is expected not to have any gaps and increases by 1. Create files with real sequences as names instead of hour and minutes.


text:
Q: Postgres COUNT instances and put in "buckets" I have a big table with row that each have a location id (location_id). Down the location_id column there are multiple instances of the same value. What I want to do is count how many times each value appears and then place that value into a "bucket"
I tried this, but ended up with everything in the "500+" bucket.
SELECT
 CASE WHEN count(location_id) > 1 AND count(location_id) <= 25 THEN '1-25'
 WHEN count(location_id) > 25 AND count(location_id) <= 500 THEN '26-500'
 WHEN count(location_id) > 500  THEN '500+'
 ELSE 'nothing'
 end as bucket,
 count(*) as Column1
FROM myTable

What am I doing wrong here?

A: You want two levels of aggregation:
SELECT (CASE WHEN cnt <= 25 THEN '1-25'
             WHEN cnt <= 500 THEN '26-500'
             ELSE '500+'
        END) as bucket, COUNT(*) as numlocations, SUM(cnt) as numTotal
FROM (SELECT location_id, count(*) as cnt
      FROM myTable
      GROUP BY location_id
     ) l
GROUP BY bucket
ORDER BY MIN(cnt);

A: Try this:-
    Select
     CASE WHEN #_cnt >= 1 AND #_cnt<= 25 THEN '1-25'
     WHEN #_cnt > 25 AND #_cnt <= 500 THEN '26-500'
     WHEN #_cnt > 500  THEN '500+'
     ELSE 'nothing'
     end as bucket,
   count(*) as column1
    from
    (
    Select location_id, count(*) as #_cnt
    from
    myTable
    group by location_id
    ) a
group by bucket

Thanks:-)


text:
Q: SetInterval javascript escribí este código para unos tótem para mostrar imágenes y logre que todo funcione menos el botón para pausar la reproducción automática...
    btnPlay.addEventListener('click', function(){
    setInterval(function(){
        Next();
    }, 5000);
});

Ese es el botón de play, y el botón de pausa no tiene nada escrito, intenté varias cosas pero no me han funcionado
Si alguien me puede ayudar lo agradecería mucho!

A: Solo necesitas crear una variable global para poder controlar el intervalo y cancelarlo cuando presiones el botón "Pausa" con clearInterval()
// Crear variable global, fuera de funciones
let timer;

// En la función play asignas el intervalo a la variable
btnPlay.addEventListener('click', function(){
    timer = setInterval(function() {
        Next();
    }, 5000);
});

// En la función de pausa cancelas el intervalo
btnPause.addEventListener('click', function() {
    clearInterval(timer);
});

Sería buena idea cancelar el temporizador antes de iniciarlo, por si se hacen varios clics en el botón Play, para evitar que haya dos o más:
btnPlay.addEventListener('click', function(){
    clearInterval(timer);
    timer = setInterval(function() {
        Next();
    }, 5000);
});

Aunque también podrías habilitar y deshabilitar los botones de acuerdo al estado "en reproducción" o "en pausa", pero eso ya es otro tema.

A: La función setInterval devuelve un identificador único que puede usarse para detener la llamada continua de la función usando clearInterval(identificador).
En tu caso específico, para detenerlo, guarda el identificador en una variable fuera de las funciones, y modifícalo con los botones Play y Pause. Te adjunto un ejemplo:

let interval;
const btnPlay = document.getElementById('play')
const btnPause = document.getElementById('pause')

btnPlay.addEventListener('click', function(){
    if(!interval)
      interval = setInterval(changeColor, 100);
});

btnPause.addEventListener('click', function(){
    if(interval)
      clearInterval(interval);
    interval = null
});

function changeColor(){
  const p = document.querySelector('p')
  p.style.color = p.style.color == 'red' ? 'blue': 'red';
}
<button id="play">Play</button>
<button id="pause">Pause</button>

Prueba

Alternativamente usando un solo botón:

let interval;
const btnPlay = document.getElementById('play')

btnPlay.addEventListener('click', function(){
    if(!interval){
      interval = setInterval(changeColor, 100);
      btnPlay.innerHTML = "Pause"
      }else{
        clearInterval(interval);
        interval = null
        btnPlay.innerHTML = "Play"
      }
});

function changeColor(){
  const p = document.querySelector('p')
  p.style.color = p.style.color == 'red' ? 'blue': 'red';
}
<button id="play">Play</button>

Prueba


text:
Q: Page renders IE6, IE8 but not IE7? I have constructed this page: http://www.letstalkmarketing.co.uk/print
It works fine in IE6 and IE8 but doesn't seem to render anything below the red help and advice block in IE7.
I cannot see what is wrong and frankly without Firebug (Firebug Lite just doesn't really cut it) I am struggling to figure it out.
Thank you for any help you can offer.

A: IE7 and position:relative never were very happy bedfellows. Where you have
.info_boxes {
    position: relative;
    top: -20px;
}

You would probably do better with
.info_boxes {
    position: static;
    margin-top: -20px;
}

Alternatively, you could add a width. e.g.
.info_boxes {
    width: 630px;
}

You can map this into a ie7 only stylesheet in a similar way as you've already done with iframe_ie6.css, but specifying the IE version in the conditional comment.


text:
Q: Is it grammatically wrong if we say 'I have been unable too' and 'I have not been able either'? So, If the context is like this:
Person 1: Hey, due to a black out in my region, I have not been able to turn on my TV. So, I missed some parts of the show.
Person 2: What a coincidence! I have not been able to either.
I was wondering if putting either at the end of the sentence caused any grammatical error.

A: Adding either is not an error at all. However, Person 2 would be more likely to say "I haven't either" without any need to repeat be able to.


text:
Q: In which include file EPERM (returned by pthread_mutex_unlock) error code is declared? Can anyone give me the right direction for this, as I am not able to find the declaration of EPERM in either pthread.h or errno.h (on openSUSE Linux). I found this in asm-generic/errno-base.h but is this the right one? Why its not in errno.h? Thanks

A: It's the right one. And it's in errno.h, though through a long chain of includes. For example on my linux development box errno.h includes bits/errno.h which includes linux/errno.h which includes asm/errno.h which includes a specific version of asm-*/errno.h, e.g. asm-i386/errno.h, which includes asm-generic/errno.h containing the #define for EPERM.


text:
Q: 16.75 How to convert to floating point representation? 16.75 convert to base 2 floating point representation.
Need help on formula, Thanks.

A: Note $16.75=2^4+2^{-1}+2^{-2}$ so in base $2$ we have $10000.11=1000011\cdot2^{-2}$

A: $16=2^4$ and $0.75=3/4=3\times 2^{-2}$. Therefore $16.75_{10}=10000.11_2.\;$ Or do you want to have  IEEE floating point format (for single, double)?
The IEEE double is computed as: sign bit $= 0,\;$ exponent $4+1023,\;$ significand including high bit =$100001100000000\dots$. Omitting the leading significand bit and combining the parts give
0 10000000011 0000110000000000000000000000000000000000000000000000

written in 4-bit blocks
0100 0000 0011 0000 1100 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000

or as hexadecimal
4030C00000000000


text:
Q: User gets instantly disconnected after connection successful on a chrooted SSH I configured a jail with Chroot in SSH following this tutorial.
I found another question on StackOverflow dealing with the same problem, however the answers didn't work for me either.
The auth.log file contains the following:
Mar 16 18:36:06 *** sshd[30509]: Accepted password for thenewone from x.x.x.x port 49583 ssh2
Mar 16 18:36:06 *** sshd[30509]: pam_unix(sshd:session): session opened for user thenewone by (uid=0)
Mar 16 18:36:07 *** sshd[30509]: lastlog_openseek: Couldn't stat /var/log/lastlog: No such file or directory
Mar 16 18:36:07 *** sshd[30509]: lastlog_openseek: Couldn't stat /var/log/lastlog: No such file or directory
Mar 16 18:36:07 *** sshd[30509]: pam_unix(sshd:session): session closed for user thenewone

My sshd_config file contains the following:
Match User thenewone
    ChrootDirectory         /home/thenewone
    AllowTcpForwarding      no
    X11Forwarding           no

My /home/thenewone directory is owned by root:root and contains the chrooted system (all files but /home/thenewone/home/thenewone owned by root:root)
I don't understand why the connection is successful then simply close.

A: Problem found: some binaries dependencies were missing, even for the shell associated with the chrooted account...
Shell failed to load --> disconnection!
If you are experiencing the same trouble as mine, use ldd <binary> to find all needed dependencies in the chroot jail


text:
Q: How to create custom relations using KBPAnnotator? Is it possible to somehow define and use custom rule patterns for KBPAnnotator? If I not wrong the annotator reads rules from files located by the following path edu/stanford/nlp/models/kbp/tokensregex and these rule types are hardcoded in the RelationType interface.

A: Unfortunately, this is not as easy as it is with many of the other CoreNLP components. The KBP relation annotator evolved primarily as a way to share Stanford's system for the TAC-KBP slot filling shared task, and is therefore very much tuned to that task.
You can likely adapt the Tokensregex part of the classifier to use your own pattern definitions, but this is not yet supported out-of-the-box.


text:
Q: How can I add coreIdentity to existing DB I have problem with adding Microsoft.AspNetCore.Identity.EntityFrameworkCore to my project. I have created db already (code-first) and now i need to add some tables, that are necessary to create login and register system.
i've tried to do some tutorials how to do it, but i have always the same error. Probably i forgot about smth easy.
I have 2 controllers, Home and Account. Home is doing operations on products and products lists. Account have to let me register users and let them login.
 public class AccountController : Controller
    {
        private readonly UserManager<IdentityUser> userManager;
        private readonly SignInManager<IdentityUser> signInManager;

        public AccountController(UserManager<IdentityUser> userManager,
                                  SignInManager<IdentityUser> signInManager)
        {
            this.userManager = userManager;
            this.signInManager = signInManager;
        }
        [HttpGet]
        public IActionResult Register()
        {

            return View();

        }
        [HttpPost]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new IdentityUser { UserName = model.Email, Email = model.Email };
                var result = await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await signInManager.SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Main_menu", "Home");
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }

            }

            return View();
        }
    }

and my Context(I'm creating there 3 table, but db have much more becouse of IdentityDbContext)
 public class ProductContext : IdentityDbContext
    {

        public Microsoft.EntityFrameworkCore.DbSet<Product> Products { get; set; }
        public Microsoft.EntityFrameworkCore.DbSet<List> Lists { get; set; }

        public Microsoft.EntityFrameworkCore.DbSet<ProductList> ProductLists { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);

                optionsBuilder.UseSqlite("Data Source=database.db");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<ProductList>()
                .HasKey(pl => new { pl.ProductId, pl.ListId });

            modelBuilder.Entity<ProductList>()
                .HasOne(pl => pl.Product)
                .WithMany(p => p.ProductList)
                .HasForeignKey(pl => pl.ProductId)
                .OnDelete(DeleteBehavior.Cascade);

            modelBuilder.Entity<ProductList>()
                .HasOne(pl => pl.List)
                .WithMany(l => l.ProductList)
                .HasForeignKey(pl => pl.ListId)
                .OnDelete(DeleteBehavior.Cascade);
        }
    }

and my View:
@model RegisterViewModel
@{
    ViewData["Title"] = "Register";
}

Rejestracja

        <form method="post">

                <input asp-for="Email" class="form-control" />

                Haslo:
                <input asp-for="Password" class="form-control" />

                Powtorz Haslo:
                <input asp-for="ConfirmPassword" class="form-control" />

            <button type="submit" class="btn btn-primary">Zarejestruj</button>

        </form>

And startup:
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            var contentRoot = configuration.GetValue<string>(WebHostDefaults.ContentRootKey);
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {

            services.AddIdentity<IdentityUser, IdentityRole>()
                    .AddEntityFrameworkStores<ProductContext>();
            services.Configure<CookiePolicyOptions>(options =>
            {

                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

When i want to move to this view i have:
InvalidOperationException: Unable to resolve service for type 'PracaInz.Models.ProductContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore9[Microsoft.AspNetCore.Identity.IdentityUser,Microsoft.AspNetCore.Identity.IdentityRole,PracaInz.Models.ProductContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim1[System.String],Microsoft.AspNetCore.Identity.IdentityUserRole1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken1[System.String],Microsoft.AspNetCore.Identity.IdentityRoleClaim1[System.String]]'.
Is it possible to add Microsoft.AspNetCore.Identity.EntityFrameworkCore to code-first database?
In whole project i have more views and i can move between it. The error appears only when im trying to use Microsoft.AspNetCore.Identity.EntityFrameworkCore.
The error concerns Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore.
The tables are empty.
When i dont have HttpPost Register method, i can move to the view. The problem is when im adding HttpPost method.

A: need to add
services.AddEntityFrameworkSqlite().AddDbContext<ApplicationDbContext>();

and delete
services.AddIdentity<IdentityUser, IdentityRole>()
                    .AddEntityFrameworkStores<ProductContext>();

in startup.
the error was about bad startup configuration.
Was sending too much things.
ApplicationDbContext:
 public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
        public Microsoft.EntityFrameworkCore.DbSet<Product> Products { get; set; }
        public Microsoft.EntityFrameworkCore.DbSet<List> Lists { get; set; }

        public Microsoft.EntityFrameworkCore.DbSet<ProductList> ProductLists { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);

             optionsBuilder.UseSqlite("Data Source=assistant.db");

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<ProductList>()
                .HasKey(pl => new { pl.ProductId, pl.ListId });

            modelBuilder.Entity<ProductList>()
                .HasOne(pl => pl.Product)
                .WithMany(p => p.ProductList)
                .HasForeignKey(pl => pl.ProductId)
                .OnDelete(DeleteBehavior.Cascade);

            modelBuilder.Entity<ProductList>()
                .HasOne(pl => pl.List)
                .WithMany(l => l.ProductList)
                .HasForeignKey(pl => pl.ListId)
                .OnDelete(DeleteBehavior.Cascade);
        }
    }


text:
Q: Extracting data from table on web page I am trying to extract data from a table on a web page with beautiful soup. I want to get the data inside the cells for each row.
I am new to python have tried the following snippet, but it's not working:
import urllib.request
fname = r"C:\Python34\page.htm"
HtmlFile = open(fname, 'r', encoding='utf-8')
source_code = HtmlFile.read()
from bs4 import BeautifulSoup
soup = BeautifulSoup(source_code, 'html.parser')
table = soup.find( "table", {"title":"geoip-demo-results-tbody"} )
rows=list()
for row in table.findAll("tr"):
   rows.append(row)
for tr in rows:
    cols = tr.findAll('td')
    p = col[0].string.strip()
    d = col[1].string.strip()
    print(p)
    print(d)

EDIT:Im getting this error
Traceback (most recent call last): File "C:\Python34\scrip.py", line 14, in  d = cols[1].text.strip()
IndexError: list index out of range" for the row
84.78.229.78ESSantander,Cantabria,Cantabria,Spain,Europe3900143.4647,-3.8044Orange EspanaOrange Espana
this is the html file which generated the above error www.pastebin.com/tQ3Cp5Wj thanks

A: fname = r"F:\Vikas\jobs\temp\page.htm"
HtmlFile = open(fname, 'r', encoding='utf-8')
source_code = HtmlFile.read()
from bs4 import BeautifulSoup
soup = BeautifulSoup(source_code, 'html.parser')

table = soup.find('tbody', id='geoip-demo-results-tbody')
rows = table.find_all('tr')
for tr in rows:
    cols = tr.find_all('td')
    p = cols[0].text.strip()
    d = cols[1].text.strip()
    print(p)
    print(d)


text:
Q: Am I properly using delegation? If not, how should I be doing this? So I have taken the plunge into Objective-C programming for iOS development. I have a little app that I am working on, nothing special, but something to help teach me the ropes. The problem I am having is as follows:
Currently, I have two classes. The first being
ViewController

and the second being one that I created myself called
UserDecision

The View controller shows what is on screen, and UserDecisions currently takes the information from buttons pressed on screen, and performs the proper logic on it while working with my model class. My issue is, that I have an update UI method in UserDecision which needs to update the button properties (text, visibility, etc.) in ViewController if certain events take place. Because of this, I can't user an instance of ViewController because I won't be able to access the buttons on screen. So for this I created a delegate system:
@protocol updateUIDelegate <NSObject>

-(void)hideAll;
-(void)makeBackVisible;
-(void)updateOutput:(NSString *)output;
-(void)updateChoices:(NSString *)choices;
-(void)updateTrueButton:(NSString *)trueString;
-(void)updateFalseButton:(NSString *)falseString;
-(void)removeChoiceFromArray;

@end

The above protocol is defined in UserDecision.h, and then I assigned my ViewController as my delegate:
@interface ViewController : UIViewController <updateUIDelegate>;

And then I flush out said methods in my ViewController.m:
#pragma - updateUIDelegates -

//Called when the last screen is displayed
-(void)hideAll{
    [_trueButton setHidden:true];
    [_falseButton setHidden:true];
    [_choicesText setHidden:true];
    [_backButton setHidden:true];
    [_resetButton setHidden:false];
}

//Makes back button visible
-(void)makeBackVisible{
    [_backButton setHidden:false];
}

//Updates the text on the false button
-(void)updateFalseButton:(NSString *)falseString{
    [_falseButton setTitle:falseString forState:UIControlStateNormal];
}

//Updates the text on the true button
-(void)updateTrueButton:(NSString *)trueString{
    [_trueButton setTitle:trueString forState:UIControlStateNormal];
}

//Updates the output text box
-(void)updateOutput:(NSString *)output{
    [_outputText setText:output];
}

//Updates the choices textbox
-(void)updateChoices:(NSString *)choices{
    if(!choicesArray){
        choicesArray = [[NSMutableArray alloc] initWithCapacity:4];
    }
    //If this is the first button press, add string to array and display
    if([_choicesText.text isEqualToString:@""]){
        [choicesArray addObject:choices];
        _choicesText.text = [NSString stringWithFormat:@"%@", choices];
    }
    //Otherwise, add the new string to the array, and print the array
    //using a comma as a way to concatinate the string and get rid of
    //the ugly look of printing out an array.
    else{
        [choicesArray addObject:choices];
        [_choicesText setText:[NSString stringWithFormat:@"%@",[choicesArray componentsJoinedByString:@", "]]];
    }
}

//Removes the last choice from the array
-(void)removeChoiceFromArray{
    [choicesArray removeLastObject];
    [_choicesText setText:[NSString stringWithFormat:@"%@", [choicesArray componentsJoinedByString:@","]]];

}

This allows me to call theses methods by sending them as a message to self.delegate in my UserDecision class when needed.
This is my current setup. My issue has become that I want to create a modal seque view that pops up at the end (after a user presses a button to bring up the view), and which can be dismissed afterward. The problem I have is that this view, from the reading and research I have done online, can only be dismissed through delegation, unless I want things to get nasty. Now, I tried to implement this information in my class, but then I read that a class can only be a delegate to one other class. And since my ViewController(which is my main window) is already a delegate of my UserDecision class, I can't make it a delegate of the new View I have created, and thus can't dismiss the view. So, I am here to ask for your help. How can I go about solving this issue?
Also, for more of my code, should you want to have a look, here is a link to my gitHub: https://github.com/Aghassi/Xcode/tree/master/Bubble%20Tea%20Choice/Bubble%20Tea%20Choice

A:
I read that a class can only be a delegate to one other class. And
  since my ViewController(which is my main window) is already a delegate
  of my UserDecision class, I can't make it a delegate of the new View I
  have created

I don't believe that's true. You can make ViewController implement many different protocols, therefore being delegates to different classes/objects.
For example: (UITableViewDelegate and UITextViewDelegate can both be implemented on the same ViewController for 2 separate objects (UITextView and UITableView).
As for using delegation to close modal windows, another option is to use blocks as well.

A: It is possible for a viewController to dismiss itself. Just hook up a dismiss button to a function that calls something like:
[self.presentingViewController dismissViewControllerAnimated:YES];

or
[self.navigationController popViewControllerAnimated:YES];

Dismissal can be done with a delegate pattern but it is not required for everything.

A: You viewController class can be a delegate of multiple objects so it should be able to dismiss the modal view.  The only issue is if its a delegate of multiple objects of the same class you may need to check which object is calling it.
Look at the tableView delegate methods as an example, the tableView calls them passing itself as the first parameter.
To dismiss a custom modal view you would define a different protocol anyway so there would be no problem with calling the same method.
See example below:
@protocol OSImageViewControllerProtocol <NSObject>

- (void)dismissImageViewer;

@end

@implementation OSImageViewController

- (void)loadView
{   //LOG(@"loadView called");
    scrollView = [[ImageScrollView alloc] init];

    scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    UITapGestureRecognizer *doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollViewDoubleTapped:)];
    doubleTapRecognizer.numberOfTapsRequired = 2;
    doubleTapRecognizer.numberOfTouchesRequired = 1;
    [scrollView addGestureRecognizer:doubleTapRecognizer];

    self.view = scrollView;
}

- (BOOL)prefersStatusBarHidden {
    return NO;
}

- (void)scrollViewDoubleTapped:(UITapGestureRecognizer*)recognizer {
    //LOG(@"scrollViewDoubleTapped called");
    [self.delegate dismissImageViewer];
}

@end

@implementation ViewController

-(void)browseImage:(UIImage*)image
{

    OSImageViewController *_imageViewerController = [[OSImageViewController alloc] init];
    UIImage *img = [[UIImage alloc] initWithData:UIImagePNGRepresentation(image)];

    _imageViewerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imageViewerController.modalPresentationStyle = UIModalPresentationFullScreen;
    _imageViewerController.delegate = self;
    [self presentViewController:_imageViewerController animated:YES completion:^(void){
        [_imageViewerController setImage:img];

    }];

}
- (void)dismissImageViewer {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end

A: I believe you want to display a modal view from your ViewController.
Let the the modal view be managed by say ViewController2. In ViewController2.h declare a protocol of ViewController2
@protocol viewController2Delegate

-(void)dismissViewController2;

@end

Now make ViewController implement this protocol
@interface ViewController : UIViewController <updateUIDelegate,viewController2Delegate>

Add the method to the ViewController.m
-(void)dismissViewController2
{
     [self dismissViewControllerAnimated:YES completion:nil];
}

Now whenever you push a modal view(managed by ViewController2) from ViewController you set the delegate to self. Your ViewController.m code might look like this
ViewController2 *objViewController2 = [[ViewController2 alloc]init];
objViewController2.delegate = self;
[self presentViewController:objViewController2 animated:YES completion:nil];

Hope this solves your problem

A: COMMUNICATION PATTERNS
Delegation is one of the communication patterns that more or less loosely coupled objects use to communicate each other. iOS Framework provides the following patterns: KVO, Notification, Delegation, Block, Target-Action.
In general, there are cases where the choice comes down to a matter of taste. However, there are many cases that are pretty clear cut.
It's also important to note that the use of each of this patterns results in a certain level of coupling among objects involved into the communication process.
Let's focus now on Delegation, Block, Target-Action.
DELEGATION
Level of coupling (proportional to the level of mutual ignorance) : loose
It allows us to customize an object's behaviour (decoration) and to be notified about certain events (callback). In this case, the coupling is pretty loose, because the sender only knows that its delegate conforms to a certain protocol.
Since a delegate protocol can define arbitrary methods, you can model the communication exactly to your needs. You can hand over payloads in the form of method arguments, and the delegate can even respond in terms of the delegate method's return value. Delegation is a very flexible and straightforward way to establish some sort of blind communication between two object that should be loosely coupled for design reason. Let's think to the communication mechanism between a tableview and its dataSource delegate.
Conversely, if two objects are that tightly coupled to each other that one cannot function without the other, there's no need to define a delegate protocol (use composition instead). In these cases, the objects can know of the other's type and talk to each other directly. Two modern examples of this are UICollectionViewLayout and NSURLSessionConfiguration.
TARGET-ACTION
Level of coupling : very loose
Target-Action is the typical pattern used to send messages in response to user-interface events. Both UIControl on iOS and NSControl/NSCell on the Mac have support for this pattern. Target-Action establishes a very loose coupling between the sender and the recipient of the message. The recipient of the message doesn't know about the sender, and even the sender doesn't have to know up front what the recipient will be. In case the target is nil, the action will goes up the responder chain until it finds an object that responds to it. On iOS, each control can even be associated with multiple target-action pairs.
A limitation of target-action-based communication is that the messages sent cannot carry any custom payloads. On the Mac action methods always receive the sender as first argument. On iOS they optionally receive the sender and the event that triggered the action as arguments. But beyond that, there is no way to have a control send other objects with the action message.
BLOCK
Blocks are usually used to pass to an object a behaviour to be executed before its lifecycle end. Besides, they can also substitute delegates with a caveat relevant to the potential creation of retain cycle.
self.tableView.didSelectRowAtIndexPath = ^(NSIndexPath *indexPath) {
    ...
    [self.tableView reloadData];
    ...
}

In this case the sender retain the table view whose selection block retain the sender so we'd better use delegation pattern.
An example in which block communication shines:
self.operationQueue = [[NSOperationQueue alloc] init]
Operation *operation = [[Operation alloc] init];
operation.completionBlock = ^{
    [self finishedOperation]
}
[operationQueue addOperation:operation];

There's a retain cycle in the above code as well, but once the queue removes the operation, the retain cycle is broken.
Blocks are a very good fit if a message we call has to send back a one-off response that is specific to this method call, because then we can break potential retain cycles. Additionally, if it helps readability to have the code processing the message together with the message call, it's hard to argue against the use of blocks. Along these lines, a very common use case of blocks are completion handlers, error handlers, and the like.
A CHART HELPING US TO MAKE THE RIGHT CHOICE

source: objc.io
In your specific case, I'd use the target-action communication pattern to dismiss the presented modal view controller.
For example,
 ModalViewController *modalViewController = [[ModalViewController alloc] init];
 [self presentViewController:modalViewController animated:YES completion:^{
    [modalViewController.closeButton addTarget:self action:@selector(dismissModalViewControllerAnimated:)
                              forControlEvents:UIControlEventTouchUpInside];
}];


text:
Q: Reading numbers using PyTesseract I am trying to read numbers from images and cannot find a way to get it to work consistently (not all images have numbers). These are the images:

(here is the link to the album in case the images are not working)
This is the command I'm using to run tesseract on the images: pytesseract.image_to_string(image, timeout=2, config='--psm 13 --oem 3 -c tessedit_char_whitelist=0123456789'). I have tried multiple configurations, but this seems to work best.
As far as preprocessing goes, this works the best:
    gray = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2GRAY)
    gray = cv2.bilateralFilter(gray, 11, 17, 17)
    im_bw = cv2.threshold(gray, thresh, 255, cv2.THRESH_BINARY_INV)[1]

This works for all images except the 3rd one. To solve the problem of lines in the 3rd image, i tried getting the edges with cv2.Canny and a pretty large threshold which works, but when drawing them back, even though it gets more than 95% of each number's edges, tesseract does not read them correctly.
I have also tried resizing the image, using cv2.morphologyEx, blurring it etc. I cannot find a way to get it to work for each case.
Thank you.

A: cv2.resize has consistently worked for me with INTER_CUBIC interpolation.
Adding this last step to pre-processing would most likely solve your problem.
im_bw_scaled = cv2.resize(im_bw, (0, 0), fx=4, fy=4, interpolation=cv2.INTER_CUBIC)
You could play around with the scale. I have used '4' above.
EDIT:
The following code worked with your images very well, even special characters. Please try it out with the rest of your dataset. Scaling, OTSU and erosion was the best combination.
import cv2
import numpy
import pytesseract

pytesseract.pytesseract.tesseract_cmd = "<path to tesseract.exe>"

# Page segmentation mode, PSM was changed to 6 since each page is a single uniform text block.
custom_config = r'--psm 6 --oem 3 -c tessedit_char_whitelist=0123456789'

# load the image as grayscale
img = cv2.imread("5.png",cv2.IMREAD_GRAYSCALE)

# Change all pixels to black, if they aren't white already (since all characters were white)
img[img != 255] = 0

# Scale it 10x
scaled = cv2.resize(img, (0,0), fx=10, fy=10, interpolation = cv2.INTER_CUBIC)

# Retained your bilateral filter
filtered = cv2.bilateralFilter(scaled, 11, 17, 17)

# Thresholded OTSU method
thresh = cv2.threshold(filtered, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

# Erode the image to bulk it up for tesseract
kernel = numpy.ones((5,5),numpy.uint8)
eroded = cv2.erode(thresh, kernel, iterations = 2)

pre_processed = eroded

# Feed the pre-processed image to tesseract and print the output.
ocr_text = pytesseract.image_to_string(pre_processed, config=custom_config)
if len(ocr_text) != 0:
    print(ocr_text)
else: print("No string detected")


text:
Q: Get Podio Item via the SDK using ID from database and not from Podio I wrote an app that pushes items into Podio.
Now I need to update the Items in Podio, but we need a way to get the Item by using our data (eg. a Order Number or Product ID), because we have no way of tracking the ItemId that is given on Submit.
Is this possible?

A: Podio API is returning item_id of newly created item in response, so it should be fairly easy to save that item_id together with your data (e.g. Order Number or Product ID).
Create item documentation is here, have a look on Response section
https://developers.podio.com/doc/items/add-new-item-22362
Sample on Ruby:
content = {'title'=> 'sample item title'}
item = Podio::Item.create(app_id, 'fields' => content)
puts "item.item_id: #{item.item_id}"

Output:
> item.item_id: 9202803167

Once item_id is saved, you can use as much as you need to get item back from Podio API.


text:
Q: Can i get rotation from this matrix algorithm Can i get rotation(yaw , pitch,roll) from this matrix algorithm ?
thanks
matrix[0][0] = cos(pitch)*cos(yaw);
matrix[0][2] = cos(pitch)*sin(yaw);
matrix[0][1] = sin(pitch);
matrix[0][3] = 0;
matrix[1][0] = -cos(roll)*sin(pitch)*cos(yaw)+sin(roll)*sin(yaw);
matrix[1][1] = cos(roll)*cos(pitch);
matrix[1][2] = -cos(roll)*sin(pitch)*sin(yaw)-sin(roll)*cos(yaw);
matrix[1][3] = 0;
matrix[2][0] = -sin(roll)*sin(pitch)*cos(yaw)-cos(roll)*sin(yaw);
matrix[2][1] = sin(roll)*cos(pitch);
matrix[2][2] = cos(roll)*cos(yaw)-sin(roll)*sin(pitch)*sin(yaw);
matrix[2][3] = 0;
matrix[3][0] = 0;
matrix[3][1] = 0;
matrix[3][2] = 0;
matrix[3][3] = 1;

edit : i used this code but it not working :
D3DXMATRIX matrix2 = D3DXMATRIX(matrix);
yaw   = atan2(matrix2._13, matrix2._11);
pitch = asin(matrix2._12);
roll  = atan2(matrix2._32, matrix2._22);

Edit 3:
this is my old function , it works but not 100%
VECTOR getAnglefromMatrix(float* m)
{
    float pitch, yaw, roll;

    D3DXMATRIX matrix = D3DXMATRIX(m);

    if (matrix._11 == 1.0f)
    {
        yaw = todegree(atan2f(matrix._13, matrix._34));
        pitch = 0;
        roll = 0;
    }
    else if (matrix._11 == -1.0f)
    {
        yaw = todegree(atan2f(matrix._13, matrix._34));
        pitch = 0;
        roll = 0;
    }
    else
    {

        yaw = todegree(atan2(-matrix._31,matrix._11));
        pitch = todegree(asin(matrix._21));
        roll = todegree(atan2(-matrix._23,matrix._22));
    }

    return vector3d(yaw,pitch,roll);
}

i did something wrong ?

A: We can go through the entries and find some that are nice for back-calculations:
matrix[0][0] = cos(pitch)*cos(yaw);
matrix[0][2] = cos(pitch)*sin(yaw);

This gives us:
yaw = atan2(matrix[0][2], matrix[0][0])

For the pitch:
matrix[0][1] = sin(pitch);

This gives us:
pitch = asin(matrix[0][1])  //this assumes pitch is between -pi/2 and +pi/2

Then
matrix[1][1] = cos(roll)*cos(pitch);
matrix[2][1] = sin(roll)*cos(pitch);

This gives us:
roll = atan2(matrix[2][1], matrix[1][1])

I omitted the cases where the arguments to atan2 become zero. I am confident you can figure them out. In these cases, the Euler angles are not uniquely defined.


text:
Q: Sort string data based on characters and its length Can I get any easy way in java where I could arrange the alphabets in order where
a < aa < aaa < aaaa
a < b < ab < ba < aba

String.compareTo method will arrange data in the below format. Hence will not serve my purpose
a < aa < aaa < b < ab < ba
Kindly help!!!

A: You can do it by using a Comparator
Check this:
import java.util.Comparator;
public class SComparator implements Comparator<String> {

    @Override
    public int compare(String s1, String s2) {
        if(s1.length() != s2.length()){
            return s1.length() - s2.length();
        }
        return s1.compareTo(s2);
    }

}

Then, you can use it like this:
ArrayList<String> L = new ArrayList<String>();
// ...
Collections.sort(L, new SComparator());

A: You could use the comparator that compares the string length and use compareTo together
        public int compare( String o1, String o2 )
        {
            if( o1.length() > o2.length() )
            {
                return 1;
            }
            else if( o1.length() < o2.length() )
            {
                return -1;
            }
            return o1.compareTo( o2 );
        }

A: You can solve this question through sorting as well.
String[] words = {"going", "went", "go", "how", "jam"};
Arrays.sort(arr);

Output:
go < going < how < jam < went


text:
Q: Possible range of correlation between two random variables I was given this question in a job interview and I wasn't sure how to answer it.
Suppose you have two random variables, $X,Y$.
Let us say that $X=1$ with probability $50\%$ and $0$ otherwise,
$Y=1$ with probability of $30\%$ and $0$ otherwise.
The first question was what is the range of probabilities for the event $X=1 ,Y=1$? The answer to that would be from $0\%$ to $30\%$, so this is not the focus of my question
The second question, which I was unsure of, is the following - what is the range of the correlation between both variables? The standard formula for correlation seemed quite unhelpful, especially since the question wasn't phrased like that with 0 and 1 (it was framed in the sense that $X$ or $Y$ occurred or did not occur)

A: Since $P(X=1,Y=1)\leq \min \{P(X=1),P(Y=1)\}=0.3,$ we have $$P(X=1,Y=1)\in [0,0.3].$$ Further, since $X\sim Bern(0.5),Y\sim Bern(0.3),$ we know $E[XY]=P(X=1,Y=1)$ and
$$E[X]=0.5,E[Y]=0.3,Var(X)=0.5(1-0.5)=0.25,Var(Y)=0.3(1-0.3)=0.21.$$
Thus, $$\text{Corr(X,Y)}=\frac{E[XY]-E[X]E[Y]}{\sqrt{Var(x)Var(Y)}}=\frac{E[XY]-(0.5)(0.3)}{\sqrt{(0.25)(0.21)}}\\
\in \left[\frac{0-(0.5)(0.3)}{\sqrt{(0.25)(0.21)}},\frac{0.3-(0.5)(0.3)}{\sqrt{(0.25)(0.21)}}\right]\approx \left[-0.65,+0.65\right].$$

To see a concrete example where any value of this range can be realized, flip two coins in succession. The first coin is fair. If the first coin lands heads, the second coin that is used will be weighted with probability $p$ of landing heads. If the first coin lands tails, the second coin that is used will be weighted with probability $0.6-p$ of landing heads. Let $X,Y$ be indicators for coin 1, coin 2 respectively landing heads. This setup meets the assumptions of the problem, and since $0.6-p\geq 0\implies p\in [0,0.6],$ we have $$P(X=1,Y=1)=0.5p\in [0,0.3].$$

A: Visualisation:
Take a line segment of length $1$.   Mark $0.50$ as the event $X=1$.  Place aside it another line segment of length $0.30$ to mark the event $Y=1$.  Slide it along the first segment to identify the possible range of the joint event's probability.
At a minimum, there is no overlap.  At a maximum, there is complete overlap (of the longer segment over the shorter).
Thus: $~0\leqslant\mathsf P(X{=}1,Y{=}1)\leqslant 0.30$

The formula for correlation is: $$\begin{align}\mathsf{Corr}(X,Y)&=\dfrac{\mathsf{Cov}(X,Y)}{~\sqrt{\raise{2ex}~{\mathsf{Var}(X)~\mathsf{Var}(Y)}~}~}\\[2ex]&=\dfrac{\mathsf E(XY)-\mathsf E(X)\,\mathsf E(Y)}{~\sqrt{\big(\mathsf E(X^2)-\mathsf E(X)^2\big)\,\big(\mathsf E(Y^2)-\mathsf E(Y)^2\big)~}~}\\[2ex]~\end{align}$$
Where $$\begin{align}\mathsf {E}(X)&=1~\mathsf P(X{=}1)+0~\mathsf P(X{=}0)\\ &=\mathsf P(X{=}1)\\\text{et cetera}\end{align}$$


text:
Q: Anchor to another page going to wrong element in mobile I have a dropdown menu where each option send the user to an element in another page. It is working perfectly for desktop, but in mobile it works fine only for the first time.
Example:  if in mobile the user select for example
"Galway", the user will be sent to the page 2 and where galway element is, if after that the user go back to the main page and select "Dublin", the user will be sent to the page 2, but where the galway element is, instead of dublin. Even the url will be showing galway, and it will be always galway it doesn't matter what I try to select unless I clean the browser cache.
In the page 1

        Dublin

        Galway

        Cork City

In the page 2

Blackrock

Dr Cliona Fergey

Dental Options Cork

Blackrock Hall Primary Care Centre

Skehard Road

Blackrock

And the other elements with different ids

A: The answer was copied from https://stackoverflow.com/a/22643441/3238940
Opera, IE, Chrome and Firefox will carry over the anchor to the new page. However, Safari loses the anchor on the redirect.
So what if you add / just before the ID Tag?
Old URL Path:

http://www.example.com/my-example-article-url-is-like.php#articlebottom

New URL Path:

http://www.example.com/my-example-article-url-is-like.php/#articlebottom

Another solution is that you'd have to delete both "www." from the domain and add a forward slash before the anchor tag in the URL/pathname before Safari would respond properly. Firefox doesn't seem to care, and I haven't gotten to testing on IE yet.
***Hope this might help other's without much trouble.***


text:
Q: Qt static linking problem: undefined reference to C++ std library I am using a Qt static library. I compiled the static version of Qt5.15.1. I wrote my program which links to the Qt static library.
When I compile it, it shows the error:
undefined reference to std::pmr::get_default_resource()

which is from the C++ std library memory_resource header.
The following is the minimal reproducible example:
OS: archlinux
c++ compiler: gcc10
c++ standard: c++17

main.cpp
////main.cpp
#include <QWidget>
#include <QApplication>

int main(int argc, char* argv)
{
    QApplication app;
    QWidget w;
    w.show();
    return app.exec();
}

CMakeLists.txt
////CMakeLists.txt
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(test LANGUAGES CXX)

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

find_package(Qt5 COMPONENTS Widgets REQUIRED)
include_directories(${Qt5Widgets_INCLUDE_DIRS)
add_executable(test ./main.cpp)
target_link_libraries(test Qt5::Widgets)

The linking error while compiling:
[  3%] Automatic MOC and UIC for target w
[  3%] Built target w_autogen
[ 50%] Built target w
[ 53%] Automatic MOC and UIC for target test
[ 53%] Built target test_autogen
[ 57%] Linking CXX executable ../bin/test
/usr/bin/ld: /opt/qt_5_15_1_static/lib/libQt5FontDatabaseSupport.a(qfontconfigdatabase.o): in function `QFontconfigDatabase::fallbacksForFamily(QString const&, QFont::Style, QFont::StyleHint, QChar::Script) const':
qfontconfigdatabase.cpp:(.text._ZNK19QFontconfigDatabase18fallbacksForFamilyERK7QStringN5QFont5StyleENS3_9StyleHintEN5QChar6ScriptE+0x1f3): undefined reference to `std::pmr::get_default_resource()'
/usr/bin/ld: qfontconfigdatabase.cpp:(.text._ZNK19QFontconfigDatabase18fallbacksForFamilyERK7QStringN5QFont5StyleENS3_9StyleHintEN5QChar6ScriptE+0x1fa): undefined reference to `vtable for std::pmr::monotonic_buffer_resource'
/usr/bin/ld: qfontconfigdatabase.cpp:(.text._ZNK19QFontconfigDatabase18fallbacksForFamilyERK7QStringN5QFont5StyleENS3_9StyleHintEN5QChar6ScriptE+0x443): undefined reference to `std::pmr::monotonic_buffer_resource::~monotonic_buffer_resource()'
/usr/bin/ld: /opt/qt_5_15_1_static/lib/libQt5Core.a(qstringlist.o): in function `QtPrivate::QStringList_removeDuplicates(QStringList*)':
qstringlist.cpp:(.text._ZN9QtPrivate28QStringList_removeDuplicatesEP11QStringList+0x3c): undefined reference to `std::pmr::get_default_resource()'
/usr/bin/ld: qstringlist.cpp:(.text._ZN9QtPrivate28QStringList_removeDuplicatesEP11QStringList+0x57): undefined reference to `vtable for std::pmr::monotonic_buffer_resource'
/usr/bin/ld: qstringlist.cpp:(.text._ZN9QtPrivate28QStringList_removeDuplicatesEP11QStringList+0x486): undefined reference to `std::pmr::monotonic_buffer_resource::~monotonic_buffer_resource()'
/usr/bin/ld: qstringlist.cpp:(.text._ZN9QtPrivate28QStringList_removeDuplicatesEP11QStringList+0x4c1): undefined reference to `std::pmr::monotonic_buffer_resource::~monotonic_buffer_resource()'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/test.dir/build.make:398: ../bin/test] Error 1
make[1]: *** [CMakeFiles/Makefile2:137: CMakeFiles/test.dir/all] Error 2
make: *** [Makefile:104: all] Error 2

The error shows the Qt static library cannot find the reference to memory_resource in the std library. How could this happen? I have built Qt static library without any problem.
The reason why I have to use static Qt library is that CUDA requires static linking.
update
I have enabled c++17 in CMakeLists.txt
In my project, it is a little different.
My project structure is as below:
.
|--include
|--src
|   |--mainwindow
|   |      |--mainwindow.h
|   |      |--mainwindow.cpp
|   |      |--CMakeLists.txt
|   |
|   |--other
|
|--main.cpp
|--CMakeLists.txt

I add mainwindow as a static library, which inherits QWidget class. and main.cpp links mainwindow.
After I add cxx17 standard, the problem still occurs.
I am not sure whether it is the problem of mainwindow subdirectory.
update
I have updated my CMakeLists.txt
//CMakeLists.txt
project(my_proj LANGUAGES CXX C)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
set(CMAKE_CXX_EXTENSIONS OFF)

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

find_package(Qt5 ... ...)
...
...

However, it still doesn't works...
UPDATE
I have updated my CMakeLists.txt by adding
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libstdc++ -static-libgcc -static")

It links targets to static stdlibc++ and stdlibc;
It works for linking stdlib.
Now I have another problem. Since my project is static linking, it need to link to 3rd party shared libs, for example, third_party_lib.so.
It shows another error:
/usr/bin/ld: attempted static link of dynamic object '/usr/local/lib/librealsense2.so.2.30.0'

How about link my static libs to a 3rd party shared library?

A: It's unclear whether or not C++17 was enabled when you built the test executable. At least, I don't see it in your CMake file. You can enable it for that CMake target using the following:
set_target_properties(test PROPERTIES
    CXX_STANDARD 17
    CXX_STANDARD_REQUIRED ON
    CXX_EXTENSIONS OFF
)

The undefined references (such as std::pmr::get_default_resource) are C++17 features, so adding this to your CMake file may resolve the issue.

You could also try setting the C++17 standard globally for your entire CMake project using the following:
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

A: Another way to set c++17 besides explicitly setting its properties is to use target_compile_features
Like the following:
target_compile_features(test PUBLIC cxx_std_17)
Here is the list of features

A: I don't know the cause (didn't investigate deeply), but with C++17 you need to link your code with QtXML component.
CMakeLists.txt:
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(test LANGUAGES CXX)

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

find_package(Qt5 COMPONENTS Widgets Xml REQUIRED)

#include_directories(${Qt5Widgets_INCLUDE_DIRS)

add_executable(test ./main.cpp)

target_link_libraries(test Qt5::Widgets Qt5::Xml)


text:
Q: onClick add parameter to url I am trying to insert a youtube video with a custom thumbnail to my website. Therefore I found this code, which I am using.

It works so far, but the autoplay makes the video play behind the cover image. So I've tried to add the autoplay parameter onClick, so it changes to true as the cover hides.
I have tried to use

But this isn't working. To be honest, I have no background in JS and do not know what I am doing. Could anybody please help me with this? Just adding a URL parameter to a given Link onClick.
thank you.

A: I think you are not doing things the right way.
when you change the url of the iframe, the iframe will reload, not just start to play.
try this:

this will show the iframe and change the url the same time.


text:
Q: Threading emails by subject We're parsing an email inbox signed up to a mailing list (Mailman) that does nothing except sit there and capture emails from other users on the mailing list. This is going to be PHP connecting to an email box, grabbing new emails and putting them into a MySQL database for use as a web archive that's searchable.
I noticed that many of the subjects have RE: FW: FWD in front of them (obviously), but wondered if I didn't need to manually strip these out to get a grouping by subject when outputting database results to the web page.
Maybe there's a PHP/Mail or PEAR class that will automatically handle message grouping/threading that I'm not aware of. Thanks for your help!

A: The proper way to thread them is not by subject, but rather by the Message-ID and References headers.  The References header will contain a comma-delimited string of all the previously related Messgage-ID headers.  By using these, the actual content of the subject line becomes less relevant since it can get modified and mangled.  In other cases, you might get many separate threads with subjects like "Need help please" that should not be threaded together.

A: You probably want to look into the References and In-Reply-To email headers. These give you information about which email the current email is in reply to.
There's a good algorithm for threading email based on this information here: http://www.jwz.org/doc/threading.html


text:
Q: Bad Memory Allocation when trying to use a SLL of an array I have created a SLL that is filled with array objects of size [2].  The goal is to use a SLL to save a list of usernames and passwords.  I have a list of names in a file.  I am able to read the list and write the last names to a new file.  However, when I make the objects in the SLL all arrays and try to save a corresponding password with a username, I get a bad allocation error when trying to access the arrays.
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted (core dumped)

Here is my main.cpp
LinkedList* listOfNames = new LinkedList[2]();

void readFile(std::string newFile){
    ifstream inFile(newFile);
    std::string firstWord;

    while(inFile >> firstWord)
    {
        listOfNames[0].InsertAtHead(firstWord);
        listOfNames[1].InsertAtHead("password");
        inFile.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    inFile.close();
}

void writeFile(std::string outFilename)
{
    Node *temp = new Node[2];
    temp = listOfNames->getHead();
    ofstream outFile(outFilename);

    while(temp != NULL)
    {
        outFile << temp[0].GetValue() << "        "   << temp[1].GetValue() << std::endl;
        temp = temp->GetNext();
    }
    outFile.close();
}

If I comment out the line where I try to access the 2 items in an array, then it runs fine.
outFile << temp[0].GetValue() << "        "   << temp[1].GetValue() << std::endl

I know that I have a memory allocation issue, but I don't know how to fix it.
Below are my LinkedList.cpp and Node.cpp.  They are last because they may be uneccesary.
Node::Node()
{
    this->value = "";
    this->next = nullptr;
}

Node::Node(std::string value)
{
    this->value = value;
    this->next = nullptr;
}

std::string Node::GetValue()
{
    return this->value;
}

void Node::SetNext(Node* next)
{
    this->next = next;
}

Node* Node::GetNext()
{
    return this->next;
}

LinkedList::LinkedList()
{
    this->head = nullptr;
    this->tail = nullptr;
    this->size = 0;
}

void LinkedList::InsertAtHead(std::string value)
{
    Node* newNode = new Node(value);
    newNode->SetNext(this->head);
    this->head = newNode;
    if(this->tail == nullptr)
    {
        this->tail = newNode;
    }
    this->size++;
}

void LinkedList::Print()
{
    Node* currentNode = this->head;
    while(currentNode != nullptr)
    {
        std::cout << currentNode->GetValue() << std::endl;
        currentNode = currentNode->GetNext();
    }

}

Node* LinkedList::getHead()
{
    return this-> head;
}

Node.hpp
class Node
{
    private:
        std::string value;
        Node* next;
    public:
        Node();
        Node(std::string value);
        std::string GetValue();
        void SetNext(Node* next);
        Node* GetNext();

};

linked_list.hpp
class LinkedList
{
    private:
        Node* head;
        Node* tail;
        int size;
    public:
        LinkedList();
        void InsertAtHead(std::string value);
        void Print();
        Node* getHead();

};

#endif

A: I solved my issue.  I was trying to access objects that were never created.  I am not that good with a debugger, but I was able to use small samples to test my output.  I ended up changing my node class to accept 2 values.  This way I don't have to create an array.  I can use an SLL and have each node hold 2 values.  This keeps me from trying to mix pointers with nonpointers.  Thank you for the insight!


text:
Q: How to solve the problem of overlap in absolute position element On medium devices the hello 2 which is the second column is made to go below Hello1.
The section 2 doesn't move as a relative positioned element should and so it gets overlapped by Hello2.
I do not want to use background-image url and want to solve this issue using the image src.
The section 2 should start from where the content of the second col-md-6 ends
Is it possible.

<!DOCTYPE html>

 <title></title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Hello1

Hello1

Hello1

Hello1

Hello1

Hello1

Hello2

Hello2

Hello2

Hello2

Hello2

Hello2

Hello2

This is section 2


text:
Q: time complexity issue when checking the connectivity between nodes in R igraph I'd like to see which first degree nodes are connected to which second degree nodes for every node in a given graph. Suppose I generate a graph with 1000 nodes.
library(igraph)
g <- erdos.renyi.game(1000, 0.2)

When I calculate the set of adjacent nodes and second degree nodes for every node in the graph, there's no issue.
The code runs pretty quick independent from the size of the network. Once I add an if statement to check if two nodes are connected as:
for(j in adjacent){
      for(k in secondDegreNodes){
             if(  are.connected(g, j, k) ){

             }
         }
      }

My code takes forever. What is the exact complexity issue that I am facing? Is there a better way to conduct this operation?
There is something odd definetely happening. Even the following code block does not converge though it's the simplest operation.
g <- erdos.renyi.game(1000, 0.3)
A <- as_adjacency_matrix(g)
from<- 1
to <- nrow(A)
for(i in from:to){
  for(j in i:to){
    if(A[i,j] == 1){
      #do nothing
    }

  }
}

EDIT: I believe there could be some issues with igraph package. I generated the graph in R igraph and coded everything in Java language, and it worked. As I expected, there is no complexity issue with the algorithm. However, I have no idea what is wrong with igraph.

A: In the example that you give, indexing matrix A repeatedly in a for-loop is rather inefficient. In this particular instance it is due to A being of class dgCMatrix from package Matrix.
When you compare the performance before and after converting A to another class, you will notice the difference. With N = 300 nodes, the duration of the for-loop decreases from 23.5 seconds to 0.1 seconds on my machine once I convert to the standard matrix class. There are moreover (N^2 + N) / 2 comparisons to be made. The squared term means going from 300 nodes to 3 x 300 = 900 nodes will roughly increase the computing time ninefold (at the very least).
If you further Rprofile the code, you will see that when subsetting an object of class dgCMatrix (i.e. A[i, j]) a number of further R functions are called, whereas the function [ is implemented straight in C for the basic matrix class. In addition, dgCMatrix is from the S4 object system. That means i.a. that finding the right method to use for [ is a little more costly than usual.
Finally, if you rely on R, you will be much better of (in general) using vectorised operations. These will typically avoid a deep call stack of further (inefficient) R functions and will often be implemented in C. With the adjacency matrix, you can quickly find second degree nodes by inspecting A_2 = A %*% A which will be very fast also (or I suspect especially so) for an object of class dgCMatrix.

Timing:
library(igraph)

N <- 300
g <- erdos.renyi.game(N, 0.3)
A <- as_adjacency_matrix(g)
from<- 1
to <- nrow(A)

class(A)
# [1] "dgCMatrix"
# attr(,"package")
# [1] "Matrix"

# run through matrix via for loop
# 23.5 seconds
system.time({
  for(i in from:to){
    for(j in i:to){
      if(A[i,j] == 1) {}
    }
  }
})

# change class
A <- as.matrix(A)

class(A)
# [1] "matrix"

# run for loop again
# 0.097 seconds
system.time({
  for(i in from:to){
    for(j in i:to){
      if(A[i,j] == 1) {}
    }
  }
})


text:
Q: $\int{({\sin{x}})^{101}\cdot \sin{99x}}\ dx$
Integrate,
$$ \int{({\sin{x}})^{101}\cdot \sin({99x}})\ dx $$

I have seen this Question and tried to proceed the same way but it doesn't work.
I also tried writing this as,
$$ \int{({\sin{x}})^{99}\cdot \sin({99x}}) - (\cos{x})^2 ({\sin{x}})^{99}\cdot \sin({99x}) $$
I was able to solve the first term using,
$$\sin{99x}=\sin({100x})\cos({x})-cos({100x})\sin({x})$$
But the second term is giving me problem. How should I proceed?


text:
Q: How to enable SideMenu to work with ViewController functions | Swift/Xcode I'm using a pod called "SideMenu" which creates a menu using a tableView. The menu is embedded in my ViewController, but it doesn't have access to the ViewController's functions. When I tap on a row in the menu, I want it to segue to the proper screen. Unfortunately, the segues originate from the ViewController and not the Menu. I obviously can't use a Delegate since I never segue to the tableView - it's embedded. How can I solve this issue?
class ViewController: UIViewController, UINavigationControllerDelegate {
    var menu: SideMenuNavigationController?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Setup the menu
        setupMenu()
    }

    func setupMenu() {
        menu = SideMenuNavigationController(rootViewController: MenuListController())
        menu?.setNavigationBarHidden(true, animated: false)
        menu?.presentationStyle = .menuDissolveIn
        SideMenuManager.default.rightMenuNavigationController = menu
        SideMenuManager.default.addPanGestureToPresent(toView: self.view)
    }

    func showProfile() {
        performSegue(withIdentifier: "profileSegue", sender: self)
    }

    func showHelp() {
        performSegue(withIdentifier: "helpSegue", sender: self)
    }

    func showSettings() {
        performSegue(withIdentifier: "settingsSegue", sender: self)
    }

    func showPreferences() {
        performSegue(withIdentifier: "preferencesSegue", sender: self)
    }

}

class MenuListController: UITableViewController {

    var items = ["Profile", "Help", "Settings", "Preferences", "Log Out"]
    var darkColor = UIColor(red: 33/255.0, green: 33/255.0, blue: 33/255.0, alpha: 1)

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.backgroundColor = darkColor
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        var content = cell.defaultContentConfiguration()
        content.text = items[indexPath.row]
        content.textProperties.color = .white
        cell.contentConfiguration = content
        cell.backgroundColor = darkColor
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        if indexPath.row == 0 {
            // Profile
        } else if indexPath.row == 1 {
            // Help
        } else if indexPath.row == 2 {
            // Settings
        } else if indexPath.row == 3 {
            // Preferences
        } else if indexPath.row == 4 {
            // Log Out
            logOut()
        }

    }

}

I couldn't find the answer in the GitHub documentation for the pod. Here is the link anyway:
SideMenu

A: You can navigate like this also.
 func openSettings(){
        let storyBoard = UIStoryboard(name: "ReplaceStoryBoardName", bundle: nil)
        let childVc = storyBoard.instantiateViewController(withIdentifier: "ReplaceYourIdentifierFromStoryBoard") as? YourViewControllerName
childVc.anyData = self.Data // or whatever data you want to sent you can inject it here.

        self.navigationController?.pushViewController(childVc, animated: true)
    }

There are some others way like NotificationCenter You can post the notification from Sidemenu View Controller Then Observe it on your ViewController in which you have embeded the SideMenu


text:
Q: Trying to get div on same line with
* using flexbox I am trying to arrange an image next to some text. I was able to accomplish this with font awesome icons and text, but two images I was unable to get an icon for, so I am using images. I can't seem to get them side by side. What am I missing? Here is the code:

     <FontAwesomeIcon
       icon={'question-circle'}
       className='question-circle'
     />
     Help

      <FontAwesomeIcon
        icon={'map-marker-alt'}
        className='map-marker-alt'
      />
      Where to Buy/Rent

Safety

EN

And my CSS:
.lower-nav__link {
  margin-bottom: 15px;
}

.lower-nav-ul {
  margin-top: 0px;
  display: flex;
  justify-content: flex-start;
  flex-direction: column;
  padding-left: 15px;
  padding-top: 15px;
}

I've tried so many different things and just took it all back to where it looks best. Any help would be appreciated. Thanks!

A: a div is not a valid child of a ul (only li's can be children of ul's). You need to put your content into an li and use display: flex on the li to space them. the display: flex styling only applies to the immediate children of the element it is applied to

A: Flex property applying on a container element. In your case li so move your div inside the li .

A: I believe the issue is that the second
 element closes too early. The
 that contains the  is after the closing
 tag, so the style rules that apply to both the
 and
 will not apply to it. Does moving that
 inside the
 tags solve the issue?


text:
Q: Multilingual Python script I recently created a Python script and am now considering making it multilingual.
However, I already have all the text written in English and all in that particular script.
So I didn't write down the sentences in any external file and apply variables, but wrote the sentences right into the script.
Now the question: How can I translate the script for another language?
Do I have to replace all the existing sentences with variables? Or is there an API for this?
If I have to replace the sentences with variables, should I use JSON or xml as external language file?

A: There are different libraries to handle translations of software/scripts, which is called internationalization (i18n). Depending on the library common formats are JSON, gettext, YAML or XML. As an example there is https://pypi.org/project/python-i18n/.
Yes, you basically import the translation function of an i18n-library and provide your text as a parameter. If you also have variables, insert them properly in your text to place them somewhere different depending on the grammar of the language.


text:
Q: Business Rule - Specified cast is not valid I have searched for the answer to this question, and just can't seem to find it for my situation, or I just haven't grasped it yet.  I am working on a business rule for my company's business software and am receiving the "Specified cast is not valid" error.  I know it has to do with the char variable and/or a null, I just can't figure out how to fix it or why I'm getting the error (it's probably simple).
Below is the code for the rule.  It is supposed to compare the unit_price to price1, both fields in a table, and replace unit_price with price1 if price1 is higher, and it is to do this for every row in the table.
I had the code working until I tried to add Class4.  Class4 specifies items with locked prices.  This was to be used to prevent changing prices of items with locked prices.  Class4 is a char[8] field in the table, and has two values, LOCKED and null.  This is where my issues began.
I have removed references to the program for legal purposes.
Forgive me if my code is messy or completely inefficient or incorrect.  I'm fairly new to c# and have been guessing for the most part.
    public class PriceCheck : program.Extensions.BusinessRule.Rule
    {
        decimal Unit = 0m;
        decimal Price1 = 0m;
        String Class4;
        DataTable datatable1;
        Boolean bDebugMode = true;
        int TriggerRow;

        public override RuleResult Execute()
        {
            RuleResult result = new RuleResult();
            result.Success = true;

            if (bDebugMode) MessageBox.Show("Starting PriceCheck"); //MessageBox for debugging purposes, shows that PriceCheck has begun

            try
            {
                if (this.Session.MultiRow)
                {
                    datatable1 = this.Data.Set.Tables["Table"]; //Set table information will be pulled from and sent to
                    TriggerRow = this.Data.TriggerRow;

                    foreach (DataRow row in (InternalDataCollectionBase)datatable1.Rows) //Begin loop for all rows in datatable1
                    {
                        Unit = DataRowExtensions.Field<Decimal>(row, "unit_price"); //Retrieve Unit Price from current row
                        Price1 = DataRowExtensions.Field<Decimal>(row, "inv_mast_price1"); //Retrieve Price1 from current row
                        Class4 = Convert.ToString(DataRowExtensions.Field<Char?>(row, "class_id4")); //Retrives Class4 from current row
                        if (bDebugMode) MessageBox.Show("Unit Price " + Unit + "\n" + "Price 1 " + Price1 + "\n" + "Class 4" + Class4, "Debug", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); //MessageBox for debugging, shows values in Unit, List, and Class4

                        if (Class4 == "LOCKED")
                        {
                            if (bDebugMode) MessageBox.Show("Class 4 Locked" + "\n" + "Unit Price will remain the same!" + "\n" + "Unit Price " + Unit, "Class 4 Locked", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                        else
                        {
                            if (Unit > 0) //if unit is null(0), the rule will fail, this is here to prevent that...might change to item Id, depending on if any items have 0 Unit Price and Price 1
                            {
                                if (bDebugMode) MessageBox.Show("Unit > 0", "Unit Check", MessageBoxButtons.OK, MessageBoxIcon.Information); //MessageBox for debugging, shows that this if statement has been reached

                                if (Unit < Price1) //beginning of calculations
                                {
                                    if (bDebugMode) MessageBox.Show("Price 1 " + Price1, "Debug", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); //Shows Price1 before putting it into the unit_price field
                                    DataRowExtensions.SetField<Decimal>(row, "unit_price", Price1); //assigns Price1 to the unit_price field
                                }
                                else
                                {
                                    if (bDebugMode) MessageBox.Show("Unit Price" + Unit, "Debug", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); //Shows Unit Price before assigning it to the unit_price field
                                    DataRowExtensions.SetField<string>(row, "unit_price", Convert.ToString(Unit)); //assigns Unit to the unit_price field
                                }
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = ex.Message;
            }
            if (bDebugMode) MessageBox.Show("Ending Price Check"); //MessageBox for debugging, shows the end of the calculations before result is returned
            return result;
        }
        public override string GetDescription()
        {
            return "Checks prices to keep Unit Price above minimum.";
        }
        public override string GetName()
        {
            return "Price Check";
        }
    }
 }