text:
Q: How to convert Angular code to ES5   $rootScope.$on("$routeChangeStart",
    (event, current, previous, rejection) => {
      if (/#\//.test($window.location.hash)) {
        $location.path($window.location.hash.replace('#', ''));
      }
});

how to convert to ES5?
I want to remove => code because uglify can not work with it ...

A:   $rootScope.$on("$routeChangeStart",
   function(event, current, previous, rejection) {
    if (/#\//.test($window.location.hash)) {
      $location.path($window.location.hash.replace('#', ''));
    }
 });


text:
Q: How to hide method of parent interface in Java? I have 3 classes.
public interface Operation {
    void move();
    void delete();
    void search(String criteria);
}

public abstract class AbstractOperationProcessor implements Operation {
    public void move() {
        // some logic
    }
}

public class DailyMailProcessor extends AbstractOperationProcessor{
    // need to hide this method because I don't want to provide them to customer
    public void delete() {}
    public void search(String criteria) {}
}

What I need is to hide methods delete() and search(String) from API. How can I do it without changing interface Operation and abstract class AbstractOperationProcessor?

A: You cannot. The best you can do is implement stubs that throw something like NotImplementedException and document this fact.
I would use this as an opportunity to examine the definition of the top-level interface.  If you need to hide some of its methods then the real problem may be that it aggregates unrelated functionality.  You may need to split it into two separate interfaces.
Remember, you can "inherit" (i.e. implement) multiple interfaces.

A: As the other answers already stated: You cannot hide a method of a superclass. There is also a good reason that you cannot do this: Polymorphism allows you to pass any object of a subtype where an object of a supertype is needed. In your case, if you have a method
void foo(Operation op){op.delete()}

you can call
foo(new DailyMailProcessor())

As you can see, foo does not know the exact type of op, but because delete is in Operation's interface, the method delete can be called.
If you happen to want to remove some methods from a subtype's interface, you are probably not implementing a behavioral subtype! I suggest you have a look at the Liskov Principle, which is one of the fundamental principles in object oriented programming.
If, what you have is not a behavioral subtype, you are wrongly trying to achieve code reuse by inheritance. You should use composition instead. Favor composition over inheritance (Item 16, Effective Java). The reason to favor composition in your case is obvious: You do not have to throw an UnsupportedOperationException (as mentioned in the other answers) and hereby gain static safety.
Edit: To clarify what I mean when telling you to use composition: Instead of having class DailyMailProcessor extending Operation, give it an member variable of type Operation and forward calls to the methods you want to support to the member variable.
public interface Operation {
    void move();
    void delete();
    void search(String criteria);
}

public class DailyMailProcessor {
    private Operation op;
    public DailyMailProcessor {/*instantiate op*/}
    void move() {op.move();}
}

A: You cannot do that. Every method declared in the interface should be implemented by the class. What you can do is you just implement those methods but do not give any definition to it.

A: Edit:
As suggested in the comments, UnsupportedOperationException might be a better choice.
Original answer:
There is the IllegalStateException just for that. Just make all the methods you don't want to implement throw that. Just do:
public class DailyMailProcessor extends AbstractOperationProcessor {

    public void delete() {
        throw new IllegalStateException();
    }

    public void search(String criteria) {
        // do something useful here
    }
}

A: the best solution that handle your probleme, if, and only if you want to have it in an elegante way, is to use a component system and it would look some this like that:
abstract class Component {
abstract void perform();
}

abstract class Move extends Component {
void perform() { ... }
}

class AbstractOperationProcessor {
List<Component> components;
...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: File locking not aquired in master-slave cluster I´m trying to configure a clúster of ActiveMQ (v.5.12.1) instances in master-slave using a shared file system.
Those instances are running in different servers using this configuration
<persistenceAdapter>
   <kahaDB directory="/sharedDir/data/activemq/kahadb"/>
 </persistenceAdapter>

The problem is that both instances start as master because lock file mechanism does¡t seem to be working.
I´ve made a test with 2 instances in the same server, and with this configuration it works as expected (2nd instance can´t acquire file lock and waits as slave).
We are using NFSv4 and mount properties are like this:
x.x.x.52:/mnt/data on /mnt/nfs type nfs4 (rw,relatime,vers=4.0,rsize=8192,wsize=8192,namlen=255,hard,proto=tcp,port=0,timeo=14,retrans=2,sec=sys,clientaddr=x.x.x.167,local_lock=none,addr=x.x.x.52)
bindfs on /sharedDir type fuse.bindfs (rw,relatime,user_id=0,group_id=0,default_permissions,allow_other)

Thank you


text:
Q: Reversing the contents of an std::list class Print
   {
   public:
       void PrintAll() {}
   private:
    std::list<int> mylist;
   };

I see this example question from a C++ language book.
And I want to print the internal mylist elements.
How can it be done if mylist needs to be reversed, using C++ STL library and using  to output the result.
Thanks you very much!

A: You can use the reverse() method on your list.
mylist.reverse();

will reverse the contents of your list and then you can print the same, using iterators.
list<int>::iterator it;
cout << "mylist contains:";
for (it=mylist.begin(); it!=mylist.end(); ++it)
    cout << " " << *it;

You can wrap all the functionality up in your own member function.

A: std::list<>::reverse()?
That said, if you only need to print the list in reverse, you can simply print it using list's reverse iterators (obtained by std::list<>::rbegin() and std::list<>::rend()) rather than by using list's normal iterators. E.g.:
// given std::list<int> l;
for (std::list<int>::const_reverse_iterator iter(l.rbegin()), iter_end(l.rend());
        iter != iter_end;
        ++iter)
{
    std::cout << *iter << '\n';
}

A: You can also use reverse iterators provided by the container e.g. l.rbegin() and l.rend() and that will iterate through the list backwards.

A: Code example for list::reverse
// list_reverse.cpp
// compile with: /EHsc
#include <list>
#include <iostream>

int main( )
{
   using namespace std;
   list <int> c1;
   list <int>::iterator c1_Iter;

   c1.push_back( 10 );
   c1.push_back( 20 );
   c1.push_back( 30 );

   cout << "c1 =";
   for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ )
      cout << " " << *c1_Iter;
   cout << endl;

   c1.reverse( );
   cout << "Reversed c1 =";
   for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ )
      cout << " " << *c1_Iter;
   cout << endl;
}

And the output will be
c1 = 10 20 30
Reversed c1 = 30 20 10

A: iterator simply point to the current element in the list. So, if we write a for loop going from end to beginning, we can print the list in reverse. in the code given below:
    #include <iostream>
    #include <list>

    using namespace std;

    int main()
    {
       std::list<int> ii;
       ii.push_back(1);
       ii.push_back(2);
       ii.push_back(3);
       ii.push_back(4);
       ii.push_back(5);
       for (std::list<int>::iterator it = (ii.begin()); it != (ii.end()) ; ++it)
       {
           cout << (*it) << " ";
       }
       cout << endl;
       for (std::list<int>::iterator it = (--ii.end()); it != (--ii.begin()) ; it--)
       {
           cout << (*it) << " ";
       }
       return 0;
    }

The first for loop prints out the list from front to back while the second one prints from back to front.


text:
Q: Improving DataTable performance (looping) So I have a function to convert Datatable to NPOI Workbook.
Here's the code :
public static XSSFWorkbook DataTableToExcel(DataTable dt, string sheetName = "Sheet1")
        {
            if (dt.Rows.Count > 0)
            {
                var excel = new XSSFWorkbook();
                var sheet = (XSSFSheet)excel.CreateSheet(sheetName);
                var col = sheet.CreateRow(0);

                //iterate columns
                for(int x = 0; x < dt.Columns.Count; x++)
                {
                    col.CreateCell(x).SetCellValue(dt.Columns[x].ColumnName);
                }

                //iterate row
                for (int r = 0; r < dt.Rows.Count; r++) //SLOW AS HELL
                {
                    var row = sheet.CreateRow(r + 1);

                    for (int c = 0; c < dt.Columns.Count; c++)
                    {
                        value = dt.Rows[r][c].ToString();
                        row.CreateCell(c).SetCellValue(value);
                    }
                }

                return excel;
            }

            return null;
        }

My problem is that the performance is horrible (10.000 rows took around 30 minutes) cause by the loop.
Is there a way to improve the performance?


text:
Q: What does computationally associative mean? K&R's C language has the following sentence:

A compiler's license to treat mathematically associative operators as computationally associative is revoked.

This is in the Appendix C, which tells what's different from before ANSI C. But I don't know how computationally associated is different from mathematically associated. Maybe I guess the mathematically associative is a * b * c = (a * b) * c (left), or a * (b * c) (right).

A: Consider this code:
#include <stdio.h>

int main(void)
{
    double a = 0x1p64;  //  Two the power of 64, 18,446,744,073,709,551,616.
    double b = 1;
    double c = -a;
    printf("%g\n", a+b+c);
}

In the C grammar, a+b+c is equivalent to (a+b)+c, so a and b are added first, and then c is added. In the format commonly used for double, a+b yields 264, not 264+1, because the double format does not have enough precision to represent 264+1, so the result of the addition is the ideal mathematical result rounded to the nearest representable value, which is 264. Then adding c yields zero, so "0" is printed.
If instead we calculated a+c+b, adding a and c would give zero, and then adding b would give one, and "1" would be printed.
Thus, floating-point operations are not generally associative; a+b+c is not the same as a+c+b.
In ordinary mathematics with real numbers, a+b+c is the same as a+c+b; addition of real numbers is associative.
Prior to standardization, some C compilers would treat floating-point expressions as if operators were associative (for those operators whose counterparts in real-number-arithmetic were associative). The C standard does not permit that in implementations that conform to the standard. Conforming compilers must produce results as if the operations were performed in the order specified by the C grammar.
Some compilers may still treat floating-point operators as associative when operating in non-standard modes, which may be selected by flags or switches passed to the compiler. Also, because the C standard allows implementations to perform floating-point arithmetic with more precision than the nominal type (e.g., when computing a+b+c, it can calculate it as if the types were long double instead of double), that can produce results that are the same as if operations were rearranged, so you can still get results that look like operators have been reordered associatively, depending on the C implementation and the flags used.


text: Q: When I type into excel sheet of One work book, it also getting typed into another open workbook I was working on one excel sheet of workbook1, in between i opened another workbook i.e workbook2, after that whatever i am typing in workbook1 is also typed into workbook2 also. I have seen if we select multiplke worksheets in same workbook, then typing into one types in all. But here it is strange, it is happening between different workbooks. How can it be??


text:
Q: Sending wrong paper size to printer We have started a project for printing, however we are completely stuck when it comes to telling the printer what paper size is selected.
Everytime we select the paper size and hit print, the printer preview is showing A4 everytime and not our selected size although if we open the print preferences the correct size is selected.
namespace CPrint
{
    /// <summary>
    /// Логика взаимодействия для ucPrint.xaml
    /// </summary>
    public partial class ucPrint : UserControl
    {
        bool SystemChange = false;
        double? PaperHeight = null;
        double? PaperWidth = null;
        public ucPrint()
        {
            InitializeComponent();
            App.Localization.AddControls(this, new string[]
             {
                    "cHeader", "lPrinter", "lCopies","lLayout", "bPrintSettings","lColorManagement","lPrinterProfile", "lPositionSize", "cCenter", "lTop", "lLeft"
             });
        }

        public static BitmapSource ConvertColorProfile(BitmapSource bitmapSource, ColorContext sourceProfile, ColorContext destinationProfile)
        {
            var bitmapConverted = new ColorConvertedBitmap();
            bitmapConverted.BeginInit();
            bitmapConverted.Source = bitmapSource;
            //bitmapConverted.SourceColorContext = new ColorContext(PixelFormats.Pbgra32);//  bitmapSourceFrame.ColorContexts == null ? sourceProfile : bitmapSourceFrame.ColorContexts[0];
            bitmapConverted.SourceColorContext = sourceProfile;
            bitmapConverted.DestinationColorContext = destinationProfile;
            bitmapConverted.DestinationFormat = PixelFormats.Bgra32;
            bitmapConverted.EndInit();
            return bitmapConverted;
        }

        private void BPrint_Click(object sender, RoutedEventArgs e)
        {
            if (cPrinter.SelectedItem == null) { MessageBox.Show("Printer not set"); return; }
            if (cPaperSize.SelectedItem == null) { MessageBox.Show("Paper size not set"); return; }

            double marging = 30;

            if (App.CurrentTemplateControl != null)
            {
                var img = App.CurrentTemplateControl.GetImage(true);
                if (img == null) return;
                var image = new Image() { Source = img };

                if (cColorProfile != null && cColorProfile.SelectedItem != null && cColorProfile.SelectedIndex > 0)
                {
                    Uri sourceProfileUri = new Uri((cColorProfile.SelectedItem as FileInfo).FullName);
                    image.Source = ConvertColorProfile(image.Source as BitmapSource, new ColorContext(PixelFormats.Pbgra32), new ColorContext(sourceProfileUri));
                }

                if (cMirror.IsChecked == true)
                {
                    var transformGroup = new TransformGroup();
                    transformGroup.Children.Add(new ScaleTransform(-1, 1, img.Width / 2, img.Height / 2));
                    image.RenderTransform = transformGroup;
                }
                PrintDialog printDialog2 = new PrintDialog();
                Size size = (Size)(cPaperSize.SelectedItem as ComboBoxItem).DataContext;
                printDialog2.PrintQueue = new PrintQueue(new PrintServer(), cPrinter.Text);

                //if (printDialog2.ShowDialog() == true)
                //{
                //Size size = new Size(printDialog2.PrintableAreaWidth, printDialog2.PrintableAreaHeight);

                printDialog2.PrintTicket = new PrintTicket()
                {
                    PageMediaSize = new PageMediaSize(size.Width, size.Height)
                };
                //printDialog2.PrintTicket
                Canvas canvas = new Canvas()
                {
                    //Height = PrintContext.ToPx(size.Height),
                    //Width = PrintContext.ToPx(size.Width),
                    Height = size.Height,
                    Width = size.Width,
                    Background = Brushes.White
                };
                canvas.Children.Add(image);

                double scaleW = (size.Width - marging * 2) / img.Width;
                double scaleH = (size.Height - marging * 2) / img.Height;
                if (scaleW < 1 || scaleH < 1)
                {
                    Canvas.SetLeft(image, marging);
                    Canvas.SetTop(image, marging);
                    double scale = scaleW > scaleH ? scaleH : scaleW;
                    var transformGroup = new TransformGroup();
                    transformGroup.Children.Add(new ScaleTransform(scale, scale, 0, 0));
                    image.RenderTransform = transformGroup;
                }
                else if (cCenter.IsChecked == true)
                {
                    Canvas.SetLeft(image, size.Width / 2 - img.Width / 2);
                    Canvas.SetTop(image, size.Height / 2 - img.Height / 2);
                }
                else
                {
                    Canvas.SetLeft(image, marging);
                    Canvas.SetTop(image, marging);
                }
                printDialog2.PrintVisual(canvas, "Print");
                //}
            }

            return;

        }

        private void CPrinter_DropDownOpened(object sender, EventArgs e)
        {
            SystemChange = true;
            var lastPrinterName = cPrinter.Text;
            cPrinter.Items.Clear();
            int index = -1;
            cPrinter.SelectedIndex = index;
            foreach (string strPrinter in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
            {
                index++;
                cPrinter.Items.Add(strPrinter);
                if (strPrinter == lastPrinterName)
                    cPrinter.SelectedIndex = index;
            }
            SystemChange = false;
        }

        private void CPrinter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0 && SystemChange == false)
            {
                var printer = new System.Drawing.Printing.PrinterSettings();
                printer.PrinterName = e.AddedItems[0].ToString();
                var lastPaperName = cPaperSize.Text;
                cPaperSize.Items.Clear();
                int index = -1;
                cPaperSize.SelectedIndex = index;
                foreach (System.Drawing.Printing.PaperSize paper in printer.PaperSizes)
                {
                    index++;
                    cPaperSize.Items.Add(new ComboBoxItem() { Content = paper.PaperName, DataContext = new Size(paper.Width, paper.Height) });
                    if (paper.PaperName == lastPaperName)
                        cPaperSize.SelectedIndex = index;
                }
                Properties.Settings.Default.DefaultDirectPrinter = printer.PrinterName;
                Properties.Settings.Default.Save();
            }
        }

        private void CPaperSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                Properties.Settings.Default.DefaultDirectPaper = ((ComboBoxItem)e.AddedItems[0]).Content.ToString();
                Properties.Settings.Default.Save();
            }
        }

        public void UpdateControls()
        {
            SystemChange = true;

            if (!String.IsNullOrWhiteSpace(Properties.Settings.Default.DefaultDirectPrinter))
            {
                SystemChange = true;
                var lastPrinterName = cPrinter.Text;
                cPrinter.Items.Clear();
                int index = -1;
                cPrinter.SelectedIndex = index;
                foreach (string strPrinter in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
                {
                    index++;
                    cPrinter.Items.Add(strPrinter);
                    if (strPrinter == Properties.Settings.Default.DefaultDirectPrinter)
                        cPrinter.SelectedIndex = index;
                }
                SystemChange = false;

                if (!String.IsNullOrWhiteSpace(Properties.Settings.Default.DefaultDirectPaper))
                {
                    var printer = new System.Drawing.Printing.PrinterSettings();
                    printer.PrinterName = Properties.Settings.Default.DefaultDirectPrinter;
                    string lastPaperName = Properties.Settings.Default.DefaultDirectPaper;
                    cPaperSize.Items.Clear();
                    int indexP = -1;
                    cPaperSize.SelectedIndex = indexP;
                    foreach (System.Drawing.Printing.PaperSize paper in printer.PaperSizes)
                    {
                        indexP++;
                        cPaperSize.Items.Add(new ComboBoxItem() { Content = paper.PaperName, DataContext = new Size(paper.Width, paper.Height) });
                        if (paper.PaperName == lastPaperName)
                            cPaperSize.SelectedIndex = indexP;
                    }
                }
            }

            if (!String.IsNullOrWhiteSpace(Properties.Settings.Default.DefaultDirectColorProfile))
            {
                var lastValue = Properties.Settings.Default.DefaultDirectColorProfile;
                cColorProfile.Items.Clear();
                int index = -1;
                cColorProfile.SelectedIndex = index;
                cColorProfile.Items.Add("");
                index++;
                foreach (var file in App.Icc.items)
                {
                    index++;
                    cColorProfile.Items.Add(file);
                    if (file.FullName == lastValue)
                        cColorProfile.SelectedIndex = index;
                }
            }
            SystemChange = false;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void CColorProfile_DropDownOpened(object sender, EventArgs e)
        {
            var lastValue = cColorProfile.Text;
            cColorProfile.Items.Clear();
            int index = -1;
            cColorProfile.SelectedIndex = index;
            cColorProfile.Items.Add("");
            index++;
            foreach (var file in App.Icc.items)
            {
                index++;
                cColorProfile.Items.Add(file);
                if (file.Name == lastValue)
                    cColorProfile.SelectedIndex = index;
            }
        }

        private void CColorProfile_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!SystemChange)
            {
                Properties.Settings.Default.DefaultDirectColorProfile = (cColorProfile.SelectedItem as FileInfo)?.FullName;
                Properties.Settings.Default.Save();
            }
        }
    }
}

I expect if we select A5, it tells the print driver to print A5,
If we select a custom "user defined" paper size, it tells the printer which size is selected. And not fixing this at A4 everytime
We cant seem to set the paper size outside the print dialog.

A: I believe; following this and this MSDN article; you are going to want to do something along the lines of:
System.Drawing.Printing.PaperSize paperSize = new System.Drawing.Printing.PaperSize("custom", width, height);
PrintDocument printDoc = new PrintDocument();
printDoc.DefaultPageSettings.PaperSize = paperSize;

A: I have walk through your code,
I think some event raise by front end (XAML) on specific use cases that is the overriding the actual value in "Properties.Settings.Default."
It would be better to resolve if you provide a XAML code for this issue.
I can look into it and will give you better solution.
You can share me code here is my skype : shsakariya


text:
Q: whats replace of ThreadAbortException for winRT I am converting .Net code to winRT. I searched but did not find replace of ThreadAbortException that I may write for winRT. Please tell me about this or about some general thread exception.
Thanks

A: Probably the most similar error you can use is OperationCanceledException. This error is thrown by WinRT asynchronous operations when they are aborted and it is supported in all WinRT projections. For more information, take a look at http://msdn.microsoft.com/en-in/library/windows/apps/hh699896.aspx

A: There is no thread abort in winRT. so, you don't need to handle this.


text:
Q: GATE ANNIE Gazetteer lookup word containing colon I want to add a new lookup list to the ANNIE Gazetteer. Some of the words which shall be found contain colons; and a feature in the annotations (which are defined in the new mylookup.list) contain also colons, for example:
mylookup.lst:
Star Wars:Episode I:url=http://example.com

So it shall find the String Star Wars:Episode I and annotate it with url=http://example.com
I already tried to "escape" the colons in my mylookup.lst with \, but it didn't work. Because I also want to use the other default lookup lists (which are all colon-separated) I can't just define an other separator.
So how can I tell the gazetteer to lookup and annotate words that contain colons?

A: As far as I know there is no support for escaping separator characters in .lst files. You have to choose other separator character. I recommend the tab character: \t
In that case you cannot use the default (colon-separated) lookup lists in the same gazetteer PR. But you can use two separate gazetteer PRs in your pipeline. One for the default lookup lists and a second one for the new lists with the different separator.


text:
Q: Swift: BLE 16 bytes to Int I'm getting a byte array like this one:
[60, 2, 0, 0, 0]
In the documentation there is written this:
uint16 -> heartBeatNum;
uint8 -> rawDataFilesNum;
uint8 -> alertNum
uint8 -> fallsNum

I will explain a little about the device so that you understand and then I ask my question.
The bluetooth device sends an object every minute that is called heartbeat. If this is the first time the object is to use the array looks like this:
After first minute:
[1, 0, 0, 0, 0]
After two minute:
[2, 0, 0, 0, 0]
After three minute:
[3, 0, 0, 0, 0]
After for minute:
[4, 0, 0, 0, 0]
...
Now there are more than 12 that have passed and the array is:
[60, 2, 0, 0, 0]
So I try to understand from the documentation the heartbeat count is the first 16 bytes. I can not figure out how to collect the 60's and the 2's to have the exact heartbeat number.
How does this function?
According to my calculation if I do 60 * 12 = 720
So I should have about 700
Can someone enlighten me how to gather the 16 bytes in int?


text:
Q: How to generate a confirmation link to confirm correct data for non-salesforce-users? We have a process in which an external salesperson needs to confirm the amount of his commission. Workflow is something like:

*

*The opportunity has status = won

*A commission is generated

*An email is send with a confirmation link

*The user clicks on the link inside the email

*The commission is updated, setting "Salesperson confirmed commission"-checkbox to true
I tried to find something in the direction of public links / email confirmations but I couldn't find any solution.
Is there any way to do this within salesforce or do we need to use an external system for this?

A: I don't think the link would be possible as all Salesforce pages (other than communities) will require a licence, you could host a landing page externally which could then update Salesforce via an API. The other alternative is you could ask the external user to reply to your email rather than ask them to click a link.

A: You could leverage an approval process for this. You probably don't want it to exist on the Opportunity itself, rather on a related Commission record.
You'd need automation to kick off the approval process when the Oppty entered Closed-Won, but that shouldn't be terribly hard.


text:
Q: How can I mock a file upload in nestjs? I have a method in my controller that accepts a csv file sent as form-data.
import csv = require('csvtojson');

@Post('/create')
@UseInterceptors(FileInterceptor('file'))
async createUsers(@Query() query: RequestDTO, @UploadedFile() file: Express.Multer.File) {
 const createJson = await csv().fromString(file.buffer.toString('utf-8'));
 const response = this.myService.createUsers(query, createJson);
 return response;
}

I just want to be able to mock it using Jest but I am not sure how to go about it.

A: You can simply forge file parameter with the correct properties.
const file: Express.Multer.File = {
  originalname: 'file.csv',
  mimetype: 'text/csv',
  path: 'something',
  buffer: Buffer.from('one,two,three'),
};

In your test file when you call your createUser you can pass it as a second parameter
This could be helpful


text:
Q: Closure issue with callback I'm having a Closure issue with a callback.
every time I call this function I get that tmp equals 1.
and I'm setting it inside the callback..
why is it happening? and how can I solve it?
var tmp = 1;

var getConnection = function() {

    console.log(tmp);

    MongoClient.connect(url, function(err, db) {
        tmp = 2;
    });
};

A: var tmp = 1; // set tmp to 1

var getConnection = function() {

    console.log(tmp); // log current value of tmp

    MongoClient.connect(url, function(err, db) {
        tmp = 2; // set tmp to 2
    });
};

I don't see getConnection() being called, but let's assume you call it immediately after declaration.
What happens in getConnection() is you 1) log current value of tmp, then 2) try to connect to Mongo, and then 3) set the value of tmp to 2.

A: I think some data is missing in order to answer your question.
My guess is that you call getConnection() function in some kind of a loop, e.g.
for (var i = 0; i < l; ++i) {
    getConnection(i);
}

In this case, the serial code (i.e. the loop and the console.log(tmp)) will be executed before all of the callbacks, in your case:
function(err, db) {
    tmp = 2; // set tmp to 2
}

'1' will be always presented, because the value will be updated to '2' only after it was written to the console.

A: MongoClient.connect is an async operation so, if you want to use the updated value of tmp you should do something like:
var tmp = 1; // set tmp to 1

var getConnection = function(callback) {
   var ctx = this; //or whatewever you want the context to be
   console.log(tmp); // log current value of tmp

   MongoClient.connect(url, function(err, db) {
     tmp = 2; // set tmp to 2
     callback.call(ctx, tmp); //you have to choose the context
  });
};

getConnection(function(tmp){
   //do some magic with tmp
})

By the way having tmp as a global variable is not such a good idea, it may be polluted by others and can cause many problems


text:
Q: OpenLDAP 2.4.23 - Debian 6.0 - Import schema - Insufficient access (50) Good day to everybody.
I'm trying to add a new schema inside OpenLDAP. But getting an error:
ldap_add: Insufficient access (50)

root@ldap:/# ldapadd -c -x -D cn=admin,dc=domain,dc=com -W -f  /tmp/test.d/cn\=config/cn\=schema/cn\=\{5\}microsoft.ldif
root@ldap:/# cat /tmp/test.d/cn\=config/cn\=schema/cn\=\{5\}microsoft.ldif
dn: cn=microsoft,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: microsoft
olcAttributeTypes: {0}( 1.2.840.113556.1.4.302 NAME 'sAMAccountType' DESC 'Fss
 ssully qualified name of distinguished Java class or interface' SYNTAX 1.3.6.
 1.4.1.1466.115.121.1.27 SINGLE-VALUE )
olcAttributeTypes: {1}( 1.2.840.113556.1.4.146 NAME 'objectSid' DESC 'Fssssull
 y qualified name of distinguished Java class or interfaced' SYNTAX 1.3.6.1.4.
 1.1466.115.121.1.40 SINGLE-VALUE )
olcAttributeTypes: {2}( 1.2.840.113556.1.4.221 NAME 'sAMAccountName' DESC 'Fds
 sssully qualified name of distinguished Java class or interfaced' SYNTAX 1.3.
 6.1.4.1.1466.115.121.1.15 SINGLE-VALUE )
olcAttributeTypes: {3}( 1.2.840.113556.1.4.1412 NAME 'primaryGroupToken' SYNTA
 X 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
olcAttributeTypes: {4}( 1.2.840.113556.1.2.102 NAME 'memberOf' SYNTAX 1.3.6.1.
 4.1.1466.115.121.1.12 SINGLE-VALUE )
olcAttributeTypes: {5}( 1.2.840.113556.1.4.98 NAME 'primaryGroupID' SYNTAX 1.3
 .6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
olcObjectClasses: {0}( 1.2.840.113556.1.5.6 NAME 'securityPrincipal' DESC 'Cso
 ntainer for a Java object' SUP top AUXILIARY MUST ( objectSid $ sAMAccountNam
 e ) MAY ( primaryGroupToken $ memberOf $ primaryGroupID ) )

I also tried to add the schema by phpldapadmin, but gain the same error.
I'm using the admin user which is specified by default from the begging of the slpad installation. How may I add permissions to this user ?
Best wishes

A: The default access config for cn=config is to only allow via external auth. Try:
ldapadd -c -Y EXTERNAL -H ldapi:/// -f '/tmp/test.d/cn=config/cn=schema/cn={5}microsoft.ldif'


text:
Q: File upload with Selenium WebDriver and FF24 I am facing an issue with the file upload with WebDriver, using Java, on Firefox 24.
And I can NOT use some external program like AutoIT or similar.
I have to upload a file to a section which's HTML code is:
<td>
<input type="file" name="file">
</td>

And what I was using in Eclipse is
pageObject.getTypeFileLocation().sendKeys(textFile);
pageObject.getUploadButton.click();

which does not work; also tried the first answer of this question but neither did the trick.
The test returns 'OK', but I suspected that nothing was being done so added a check to wait for 'Upload complete' text present; But the file is not uploaded, and timeouts after 20 seconds, even when the file to upload is 5KB and takes less than a second when manually uploaded.
 The input=file section contains a button and a 'No File Selected' text that changes to the filepath when a file is selected manually; and this is in what I am basing my idea that the file is not being upload; because the 'No File Selected' remains until the test fails.
I tried this on Chrome and seems to be working fine, and I know that there have been some reworks about input=file in FF since release 23, but mostly pointed to CSS styling, so I don't think it's related.
Also, a question that might sound kind of stupid, but questions are questions: Doesn't the sendKeys() action need a field to input those keys? I feel that the WebDriver is trying to write the path over a button, which can't perform the action as it's only a button.
Any help will be appreciated, and thanks in advance!

A: Solved it!
Don't know if it works for all browsers, but at least it does on FF and Chrome:
Found out that somebody used the FILE type, so reused it and got its absolute path:
protected File *fileName* = new File("*path to file*");
private String textFile = *fileName*.getAbsolutePath();
pageObject.getInput().sendKeys(textFile);

Hope somebody else finds it useful; as it's weird to be answering my own question.


text:
Q: Taking 2 textbox values Insert into SQL Server database I am trying to learn how to take control values and insert them into a db table. For example I have a textbox called NameBox. I want to grab the text from that textbox and add it into a database table.
I am not trying to do it the best way but the simplest so I can wrap by head around the concept. So far I have:
<asp:TextBox ID="NameBox" runat="server"></asp:TextBox>
<asp:TextBox ID="EmailBox" runat="server"></asp:TextBox>

Here is the code-behind.
protected void Button1_Click(object sender, EventArgs e)
{
    string name1 = NameBox.Text;
    string email1 = EmailBox.Text;

    System.Data.SqlClient.SqlConnection sqlConnection1 =
   new System.Data.SqlClient.SqlConnection(@"Data Source=E:\*********.com1.5\**********.com\App_Data\Home.sdf;");

    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.CommandText = "INSERT INTO CustomerList (Name, Email) VALUES (" + name1 + "," + email1 + ")";
    cmd.Connection = sqlConnection1;

    sqlConnection1.Open();
    cmd.ExecuteNonQuery();
    sqlConnection1.Close();
}

Error message I am getting is

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: SQL
  Network Interfaces, error: 26 - Error Locating Server/Instance
  Specified)

I googled the error message and a lot of what i been reading is saying my connection is probably wrong. I tried testing this by using some of the drag and drop controls and I have a repeater working with the same connection string.
Right now I don't even really know if this is right approach. As I am sure you can all relate at one point or another I want to see it work on a very simple level so i can start to play with it and see how it all really works.

A: Your connection string infers you're using SQL Server Compact Edition - in which case you want to use SQLCeCommand and SQLCeConnection instead. Please also look into using parameterised queries instead of concatenating strings together - it's better for performance and security reasons. Please read this link for more background on SQL injection - at the moment you're vulnerable to it.

A: You must use SqlCeConnection in order to create connection
link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlserverce.sqlceconnection%28v=vs.80%29.aspx

A: Just copy paste the connection string you are using for the repeater code, and paste it in the Button1_Click code, where you create a new connection. There might be an extra space, or some capital letter mismatch. And for insertions, I would create a stored procedure in the database, which takes Name and Email parameters, and use the SqlCommand to execute the stored procedure.
CREATE PROCEDURE INSERT_NAME_EMAIL_DATA
    @NAME VARCHAR(100) NULL,
    @EMAIL VARCHAR(100) NULL
AS
BEGIN
      INSERT INTO CustomerList (Name, Email) VALUES (@NAME, @EMAIL)
END

And in your code you can execute the stored procedure by doing:
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(
    new SqlParameter("@NAME", name1));
cmd.Parameters.Add(
    new SqlParameter("@EMAIL", email1));
cmd.Connection = sqlConnection1;

        sqlConnection1.Open();
        cmd.ExecuteNonQuery();
        sqlConnection1.Close();

A: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
For above Error, you have restart your sqlserver instance by going to window of services as following
Press windows + r
type services.msc + enter
find your sqlserver instance and restart it


text:
Q: Unlocking Warcraft 3 reign of chaos campaigns is there a way to unlock campaigns other than finishing human campaign? I cannot play the last mission culling due to some bug (all I see is black screen) so I figured maybe I can just skip it and continue with campaigns... can I? Thanks in advance!

A: You are in luck! Blizzard has been including cheat codes in its games since the original Warcraft: Orcs and Humans.
Among the cheat codes available for Warcraft III is the handy level-select cheat:
The "Motherland" "Race" "Level" cheat is what you're looking for, so to skip to the beginning of the undead campaign, enter any campaign mission, and enter the following in the chat box (accessed with the enter key):

Motherland Undead 1

And you should be well on your way to Deathknight-ing it up with Kel'thuzud.


text:
Q: php - unable to split a string by new lines from database I'm receiving data from a MSSQL database with PHP (using PDO sqlsrv driver).
I need to split the string by new line.
In the DB the string looks like this:

I tried the following with no success:
$text = explode("\n\n",$text);
$text = preg_split("/\n\n/",$text);

Or
$text = explode("\n",$text);
$text = preg_split("/\n/",$text);

When i debug the code and when i print the text to the browser the string appears as one line.

But if i inspect the element in chrome, it is displayed exactly like in the database:

I copied the text from the inspector to a regex tester and the newlines were found successfully! But the "echoed" text was in one line.

A: Try replacing new line character with comma (,) or something other special char.
preg_replace("/((\r?\n)|(\r\n?))/", ',', $input);

Then try to explode like this explode(',', $input);
or
if result set is file go through this post
explode(PHP_EOL, $input);

https://stackoverflow.com/a/29471912/4895810


text:
Q: php get an element's id after submit <input type = 'text' name = 'name_'<?php echo $rownum'?>  id = <?php echo $category_id ?> /> $rownum++;

After submit I iterate through the text fields. While doing that I want to check whether this text's id is in an array. So for that I want to get the id of the text field. How is it possible?

A: IDs are not accessible with the post. Change it and make it easy to handle
<input type = 'text' name = 'name[<?php echo $category_id ?>]'  id = <?php echo $category_id ?> /> $rownum++;

Now subimit it and you have everything you want in $_POST.
This element will be accessible like this
$_POST['name'] will be an array iterate through it
foreach ($_POST['name'] as $key => $value)
{
   echo $key; // $key is the id you want
   echo $value; //$value is the value set for this id
}

A: You would have to specifically pass that value into php.  Once a value is sent out the the browser as HTML php has no more control over it.  So when it gets resubmitted PHP only 'knows' whats handed to it.  In this case it 'know' the name of the input and the value of the input.

A: ids are not submitted with POST data. It's not possible to get their value back.
Use different names that give you the information you need, since only they are submitted.


text:
Q: Stochastic Differential Equation Interpretation of Squared Exponential Kernel As far as I understand, many Gaussian Processes can be either described by their corresponding mean and kernel functions or by a stochastic differential equation (SDE). For my purposes it is sufficient that the predictors $x$ just include time, thus, I will use $t$ instead of $x$. The stochastic differential equation $dX_t = a X_t + bW_t$ where $a, b$ are scalars and $W_t$ the Wiener process leads to the exponential kernel function $k(t,t')= \sigma^2 \exp(\frac{|t-t'|}{l})$ where $l>0$, $\sigma>0$. There is a one to one relationship between the parameters $a,b$ and the parameters $l,\sigma$. By solving the SDE one can even obtain an analytic expression for $X_t$.
My question is: Is there also a SDE interpretation of the squared exponential kernel $$\sigma^2\exp\left(\frac{(t-t')^2}{l}\right)$$ with $l,\sigma>0$, assuming that $t,t'$ are representatives of time, that is $t,t' \in \mathbb{R}_0^+$. If this is the case what is the solution of the SDE, that is, the analytic expression for $X_t?$


text:
Q: Python PyPDF2 counting PDF pages in scanned PDF generates Xref table not Zero indexed I have written a fast script to count the pages in PDF files. However, in some files it cannot be read and it returns an error of Xref table not Zero indexed. Basically when expects an Object Id (5.0) and gets Object Id (4.0) for example. Also I have got with other Object Id like (7.0) and gets Object Id(6.0), etc...
My code is:
from PyPDF2 import PdfFileReader
from pathlib import Path
import os
import math
import logging

numPages=0
workPath = input ('Please introduce your working directory: ')
print ('Your selected path is ' + workPath)
os.chdir (workPath.encode())
logging.basicConfig(filename='errrors.log',
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s')
fout= open('PagesCount.txt', 'w',  encoding="utf-8")
path_files = Path(workPath)
for file in path_files.glob('**/*.pdf'):
    page_Count = 0
    try:
        with open(str(file), "br") as PDF:
            try:
                page_Count = PdfFileReader(PDF).getNumPages()
                numPages = numPages + page_Count
                print ('Pages in ' + str(file) + ': ' + str(page_Count) + ' pages')
                fout.write ('Pages in ' + str(file) + ':\t' + str(page_Count) + ' pages\n')
            except:
                print('File {} cannot be read'.format(str(file)))
                logging.error('File cannot be read:\t {}'.format(str(file)))

    except:
        logging.error('File is not processed: {}'.format(str(file)))

print ('Total number of pages:\t' + str(numPages) + ' pages')
fout.write ('Total number of pages:\t' + str(numPages) + ' pages\n')

So, it happens that I have to count the pages of many scanned PDF files, and a high % of them, about 80% of them go filtered to the errors file due of the mentioned error above. Is there any way to prevent the Xref table not Zero indexed error?
Thank you.

A: I have solved part of the issue. Setting the parameter strict to false, and it allows to open a higher number of files than before
Changing this line from:
    page_Count = PdfFileReader(PDF).getNumPages()
to
    page_Count = PdfFileReader(PDF, strict=False).getNumPages()


text:
Q: How to get currently displayed location on map I'm making an Android app that's based around Maps SDK.
I'm saving locations of multiple markers and want to display them on the map. To make it faster and more lightweight for the Db I've decided to use GeoFire to display only markers that are close to a 'certain location'. (If there are milion markers around the world I don't want to display all of them. Just the ones that are in the viewing area)
I want that 'certain location' to be the middle of the currently displaying area on the map, so that when I move the map to a different location It'll update with markers that are in that area.
What I want to achieve is similar to how Google Maps displays e.g restaurants in an area you're currently displaying on your map and updates real time when you move the map to a different location.
Problem is I don't see any simple option to retrieve the location of a currently displaying area on the map.
I was thinking about creating an invisible marker in the middle of the screen that would move with the map but it seems like a lot of work for such a simple thing.
Is there any easier way I can achieve this?
So long story short: I want to get the location that's currently on the screen. Not the physical location of the phone.
Thanks in advance :)

A: To get camera position you can use:

double mylat = mGoogleMap.getCameraPosition().target.latitude;
double mylon = mGoogleMap.getCameraPosition().target.longitude;


text:
Q: Athena displays special characters as? I have an external table with below DDL
CREATE EXTERNAL TABLE `table_1`(
  `name` string COMMENT 'from deserializer',
  `desc1` string COMMENT 'from deserializer',
  `desc2` string COMMENT 'from deserializer',
  )
ROW FORMAT SERDE
  'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
  'quoteChar'='\"',
  'separatorChar'='|',
  'skip.header.line.count'='1')
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  's3://temp_loc/temp_csv/'
TBLPROPERTIES (
  'classification'='csv',
  'compressionType'='none',
  'typeOfData'='file')

The csv files that this table reads are UTF-16 LE encoded when trying to render the output using Athena the special characters are being displayed as question marks in the output. Is there any way to set encoding in Athena or to fix this.

A: The solution, as Philipp Johannis mentions in a comment, is to set the serialization.encoding table property to "UTF-16LE". As far as I can see LazySimpleSerde uses java.nio.charset.Charset.forName, so any encoding/charset name accepted by Java should work.


text: Q: How to have a text or an image appear on some part of web page on hovering top or bottom half of a sliding image in an image slider? I am just a noob and want to ask that in my centralized image slider, I want that some image or text to appear to the right or some palce in my web page based on top or bottom half of the sliding image being hovered. Please, tell me how to do that ?


text:
Q: Axios API get request with Redux not able to pass in variable in action I'm trying to pass in a variable into an axios request in my action:
export function searchRequest(search){
    return(dispatch)=>{
        console.log('in search', search)
        return axios.get(`http://localhost:4000/reports/${search}`)
                .then(response => {

                    dispatch(searchInfo(response.data))
                })
    }
}

When I console log search, it does not register.
However, when I remove the return dispatch and console log response.data in the .then, I get the desired data, but I'm not able to use dispatch.
The question is, why am I not able to pass in search in this way?
Edit: this is in react native

A: I'm not sure how you connect this function to Redux in React-native but I think it works like you're doing it with regular React.
The searchRequest function return a new function with one variable dispatch. search will be "static" with the value you've passed in when calling searchRequest, so probably null or undefined or some hardcoded value.
You should to this the other way around:
import {connect} from 'react-redux'

const searchRequest = (dispatch) => {
   return async (search) => {
      const response = await axios.get(`http://localhost:4000/reports/${search}`)
      dispatch(searchInfo(response.data))
   }
}

class YourComponent extends Component {
....
  onSearch = (search) => {
     this.props.doSearch(search)
  }
....
}

const mapDispatch = (dispatch) => ({
  doSearch: searchRequest(dispatch)
})

export connect(null, mapDispatch)(YourComponent)

This is how it looks with "normal  web"-React. Maybe in native it looks different. Notice that dispatch is provided as parameter once. Afterwards when calling doSearch the same instance of dispatch is used inside the function.


text:
Q: iOS App Transport Security issue TL; DR:
I have an iOS app connecting to a webservice that does not meet the minimum requirements for the new ATS feature. I have modified my Info.plist to allow an exception so my app can still connect to the webservice. (NSURLSession/NSURLConnection HTTP load failed on iOS 9 ) This works correctly in development, however, the update I just pushed to the store still fails to hit the webservice. I don't know where the disconnect is happening or how to fix this.
===
First off, this is all happening in an emulator, and the same behavior when I deploy directly to my ipad in xcode:
I am trying to connect to a webservice over https in my iOS app. I am now getting this error everytime I try to connect to the webservice:
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)

It is my understanding that this is happening because the new ATS feature is not allowing the connection. I have confirmed this by applying the fix (NSURLSession/NSURLConnection HTTP load failed on iOS 9) to my Info.plist file:
<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>mydomain.com</key>
    <dict>
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <key>NSIncludesSubdomains</key>
      <true/>
      </dict>
  </dict>
</dict>

Once I put that in, it connects to the webservice without issue.
Apparantly, while my server meets the TLS 1.2 requirement, and cipher requirement, it does not meet the signature requirement (https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW35
)
However, I have made an update to my app and pushed to the app store, but the store version of my app is unable to connect to the web service. The very same code builds fine on my local machine and runs on my device when deployed to it from xcode, but the version in the store seems to be ignoring the .plist fix. How can I fix this? This makes no sense to me at all.

A: Try this version of configurations for info.plist:
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>www.example.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
        </dict>
    </dict>
</dict>

EDIT: try specifying NSExceptionRequiresForwardSecrecy to NO as well.

A: Try add the following code to your info.plist
<key>NSAppTransportSecurity</key>
     <dict>
      <key>NSAllowsArbitraryLoads<key><true/>
     </dict>

For more information see the link:apple forum


text:
Q: Integrability of $\frac{k-1}{2(1+|x|^k)}$ Is the following function known to be integrable? It is supposed to be a probability density function, i.e., integrates to one. However, it leaves the online Mathematica integrator stumped:
\begin{equation*}
f(x) = \frac{k-1}{2(1+|x|^k)},\; x \in (-\infty, \infty),\; k \geq 2
\end{equation*}


text:
Q: How to reload javascript without refreshing the page? I have a webpage that links some javascript via  tags. The script is amazon-localiser.js which will change an amazon link to one appropriate for the visitor. e.g. an Amazon.com link will swap to amazon.co.uk for a UK visitor or Amazon.de for a german visitor.It also appends to the link the relevant amazon affiliate link.
When the user lands on the page they click through some options (javascript) however by the time you reach an amazon link the page must be refreshed for the amazon-localiser.js script to work. I have tried using a page refresh in HTML but this sends me back to the very beginning of the questions. How do I reload the javascript without affecting the users location on the site?
The site is www.wfbsir.com, if you select "Scifi" then "Maybe" you will get to an amazon.com link, if you hover over it you will see it links to amazon.com if you refresh the page it will show you the link to your local store with an affiliate link appended.
html
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>What book should I read?</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="manifest" href="/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="app.css" />

        <button class="btn btn-default btn-corner" type="submit" data-bind="click: startOver, visible: queryData().id > 0">Start over</button>

          <button class="btn btn-default btn-lg" type="submit" data-bind="click: $parent.goToTarget, text: text"></button>

        <button class="btn btn-default" type="submit" data-bind="click: stepBack, visible: navHistory().length > 1">Previous Step</button>
                            <button class="btn btn-default" type="submit" data-bind="click: buyBook, visible: navHistory().length > 1">Buy the book</button>

I have tried using jQuery getScript and also window.location.reload(); but neither reload just the javascript, the only thing that I can find to work is F5/Refresh.

A: I noticed that the amazon-localiser.js invokes the function findLocation onload of the page, as you can see below.
if (window.addEventListener) {
    window.addEventListener("load", findLocation, false)
} else {
    window.attachEvent("onload", findLocation)
}

So, a possible solution to your problem, could be to invoke this function again when you need to update your amazon link.
I tried invoking it from the console and it works, so try to invoke findLocation() manually when needed and see if it serves your scope.
Simone

A: You can add dynamically script on the page with some condition, for example:
var script = document.createElement('script');
var src;

if (true) {
  src = 'amazon.co.uk';
} else {
  src = 'amazon.com';
}
script.src = src;
document.head.appendChild(script);

A: As gnllucena told, you can view the question or there is the solution.

*

*Build the loader function:

Put the following code in the document

// place a button for reloading script.

<input type="button" name="reloadNewJs" value="Reload JavaScript" onClick="LoadMyJs('needed_script.js')">


text:
Q: Pass property chain as bracket notation variable I have a function that I want to pass a variable that contains the path to an object's property. This path will change depending on where the function is being called from. I can't figure out how to save the path in a variable.
I need to save data.a.b.c in 'x'.
I need to store the path to access 'c' in 'y' ( I assume using bracket notation)
function
y = [a.b.c]
calculate(data, y)

calculate = function(data, y) {
  x = data[y]
}

A: You can't do what you'd like to do.  A series of 'bracket notation' slices are pure syntax.  But you can pass around functions of paths, like so, with the anonymous function passed to countInDeep:
var deep = {}
deep.a = {}
deep.a.b = {}
deep.a.b.c = {}
deep.a.b.c.count = 42

function countInDeep(func) {
  return func(deep).count
}

console.log(countInDeep(function(x) { return x.a.b.c }))
/* outputs: 42 */


text:
Q: Questions about limits to find a pdf I have a question about the following example (please see image). I fully understand the theory on how to find a pdf from a cdf and everything else, but the only thing I cannot seem to comprehend is how they determine the integral limits. If the support set is given: 0

Am I supposed to treat them as x, y and z variables? I really have no clue how to draw the support set.
Thanks a lot in advance.
Example


text:
Q: Como modificar variable global con parametro recibido de clase interna en Android Tengo una variable GLOBAL  String cadena;
y tengo unos valores recibidos en una clase interna que es el siguiente:
public class MainActivity extends AppCompatActivity {

    RequestQueue queue;

ArrayAdapter<String> adapter;

ArrayList<String> lis;

 String cadena="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text1=(TextView)findViewById(R.id.textView2);

        //text1.setVisibility(View.INVISIBLE);

        lista=(ListView)findViewById(R.id.list_view);

        lis=new ArrayList<String>();

      hacer();

       // Toast.makeText(this,Integer.toString(jsons.size()), Toast.LENGTH_SHORT).show();

       // adapter=new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,lis);

        //lista.setAdapter(adapter);

    }

    public void hacer(){

    queue= Volley.newRequestQueue(this);

        String url="";

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        cadena=Integer.toString(response.length());
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        queue.add(jsonObjectRequest);

        Toast.makeText(this, cadena, Toast.LENGTH_SHORT).show();

    }

}

pero no funciona porque supuestamente no se puede modificar una variable de clase externa en una clase interna. Entonces que puedo hacer para obtener ese response en una variable y usarla en el onCreate ??? Lo que quiero es sacar el response del metodo onResponse y utilizarlo en el onCreate. Pero el metodo "hacer" no me permite guardar el response del metodo onResponse en una variable fuera del metodo y no se porque
Acabo de editar el metodo :
public void hacer(){

    queue= Volley.newRequestQueue(this);

        String url="https://androidfe.herokuapp.com/items";
try{

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
            (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    if(response!=null){
                        cadena="viene con algo";
                    }
                    else{
                        cadena="viene vacio";
                    }

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    text1.setText(error.getMessage());
                }
            });

    queue.add(jsonObjectRequest);

}catch (Exception e){
    Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}

        Toast.makeText(this, cadena, Toast.LENGTH_SHORT).show();

    }

Al final me imprime un Toast nulo, sin nada. No cae en ningun catch ni nada solo imprime nulo

A: He hecho una prueba directa con la petición de tu URL.
El motivo por el que cadena era siempre null es porque la llamada a Volley es asíncrona y el dato no puede ser recuperado en el onCreate.
Vamos a seguir el siguiente procedimiento y verás que sí funciona:

*

*Desde el onCreate llamamos a hacer(), método que lanza la petición Volley

*En hacer() leeremos la respuesta y la concatenaremos en un StringBuilder (es mucho mejor que una simple cadena). Nótese que en la clase hay un nuevo miembro sb. Lo usaremos también para capturar un posible error.

*Desde dentro de hacer(), cuando hayamos terminado, llamaremos a un nuevo método show, que mostrará el resultado de la petición (éxito o error) en el TextView. Nótese que para tener acceso al TextView dentro del método show() éste tiene que ser declarado como miembro de la clase, no dentro del método onCreate. Y lo vamos a inicializar también dentro del método show, que será el dedicado de actualizar el contenido del TextView.

El código quedaría entonces así:
public class MainActivity extends AppCompatActivity {
    RequestQueue queue;
    private StringBuilder sb;
    TextView mTextView;

    //Otras variables ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Otras cosas. RECUERDA no inicializar el textview aquí
        hacer();
    }

    public void hacer() {
        queue = Volley.newRequestQueue(this);
        String url="https://androidfe.herokuapp.com/items";
        sb=new StringBuilder();
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
                Request.Method.GET, url, null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        try {
                            JSONObject json = response.getJSONObject(0);
                            for (int i=0; i < response.length(); i++) {
                                JSONObject mItem = response.getJSONObject(i);
                                sb.append("Código: ");
                                sb.append(mItem.getString("Codigo"));
                                sb.append("\nPrecio: ");
                                sb.append(mItem.getInt("Precio"));
                                sb.append("\nCantidad: ");
                                sb.append(mItem.getString("Cantidad"));
                                sb.append("\nCategoria: ");
                                sb.append(mItem.getString("Categoria"));
                                sb.append("\nCosto: ");
                                sb.append(mItem.getInt("Costo"));
                                sb.append("\nImpuesto: ");
                                sb.append(mItem.getString("Impuesto"));
                                sb.append("\n\n");
                            }
                            show();
                        } catch (JSONException e) {
                            sb.append(e.getMessage());
                            show();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        sb.append("La petición falló. Error: "+error.getMessage());
                        show();
                    }
                }
        );

        queue.add(jsonArrayRequest);
    }

    private void show() {
        mTextView = findViewById(R.id.textView2);
        mTextView.setText(sb.toString());
    }

}

He probado este código en un Activity y me funciona perfectamente. Aquí te dejo una captura de pantalla:

Si tienes algún problema o error lo dices en comentarios. Espero te sirva.


text:
Q: Permissions for Dashboards in Azure Devops to see test results I am setting up the group of people who should see the test results and dashboards in Azure Devops (for external to project users).

*

*I've created another team so they don't see the boards.

*They have the rights to see the test results and this works, they
can see the test runs.

*I've added the Test results dashboard for this new team which works
fine when you are internal user.

However, external users geting the error "FS.WebApi.Exception: TF400898: An Internal Error Occurred." and also no tests data is visible from the dashboard editor. It looks like those external users missing some permissions to see any test data via dashboard but I can't figure out which permissions are missing.

A:
for external to project users

Are the external users here referring to members of different teams in the same project?
One reason I can think of permission is that the team's View analytics permission is set to deny,this may cause the widget content to fail to load. You can also view this case to see if it is the same internal error situation.


text:
Q: How to count number of days in R I have this type of dataframe
DF
ID   DATE_FROM     DATE_TO
1.   01.01.2020    05.01.2020
2.   05.01.2020    11.01.2020
3.   31.01.2020    05.02.2020

We use this format of date in CZE and it means

DD.MM.YYYY

I would like to get this:
DF
ID   DATE_FROM     DATE_TO       NUM.OF.DAY
1.   01.01.2020    05.01.2020    4
2.   05.01.2020    11.01.2020    6
3.   31.01.2020    05.02.2020    5

So I would need to do basic subtraction
I tried this:
 DF %>%
   mutate(DATE_FROM = as.Date(DATE_FROM)) %>%
   mutate(DATE_TO  = as.Date(DATE_TO)) %>%
   mutate(NUM.OF.DAY = DATE_TO - DATE_FROM)

but with no result

A: You need to parse the dates and specify the format in which they are written in order to perform operations between them.
(As a side note, you can use only one mutate statement instead of three)
DF %>%
  mutate(DATE_FROM = as.Date(DATE_FROM, format = "%d.%m.%Y"),
         DATE_TO = as.Date(DATE_TO, format = "%d.%m.%Y"),
         NUM_OF_DAY = as.numeric(DATE_TO - DATE_FROM))

Output
#   ID  DATE_FROM    DATE_TO NUM_OF_DAY
# 1  1 2020-01-01 2020-01-05          4
# 2  2 2020-01-05 2020-01-11          6
# 3  3 2020-01-31 2020-02-05          5

A: Data:
df <- data.frame(
  ID = 1,
  DATE_FROM = as.Date("01.02.2020", "%d.%m.%Y"),
  DATE_TO = as.Date("12.03.2020", "%d.%m.%Y")
)

Solution in base R:
df$NUM.OF.DAY <- as.numeric(df$DATE_TO - df$DATE_FROM)

Result:
df
  ID  DATE_FROM    DATE_TO NUM.OF.DAY
1  1 2020-02-01 2020-03-12         40

A: Another option:
difftime(as.POSIXct('12.03.2020', format = "%d.%m.%Y"),
         as.POSIXct('01.02.2020', format = "%d.%m.%Y")
         )

#Time difference of 40 days


text:
Q: Linear Regression Coefficient Interpretation I have a regression problem: regress y on x1 x2
y: Sales revenue,  x1: is_holiday (dummy variable),  x2: another continuous variable (note that this is just the simplified version)
When interpreting the coefficient of x1, i.e. beta 1, we will say: "when holding all other variables constant, on a holiday, there is beta 1 dollars more revenue compared with a non-holiday.
[1] However, how does regression achieve "holding all other variables constant"? Does it achieve by taking partial derivative when solving First Order Condition of cost function (sum of squared error)?
[2] From the formula of beta 1, can we find any intuitions that the calculation is actually 'holding other variables constant'? I guess it's not observable from the formula
[3] In the dataframe, the regression is not matching holiday sample with non-holiday sample which have the same x2 value, then compare y right? I think such matching is not what regression does. I need to explain the intuition of beta 1, i.e. how "holding other variables constant" is achieved. Hopefully get some explanation in layman terms.
Thanks!

A: The terminology "holding other variables constant" is a bit misleading, I think. I think it's more accurate to state that the coefficient $\beta_{i}$ represents the contribution of the factor $x_{i}$ that's uncorrelated to the other factors. In the following discussion, I'm going to refer to the general case of multiple quantitative variables, as I think that's more what your questions are pointing towards, instead of the two factor case with an indicator variable you use in your example.
In order to illustrate the issue, recall that for simple linear regression the model is $y = \beta_{0} + \beta_{1}x + \varepsilon$, where $\varepsilon$ is the random error term that satisfies the usual regression assumptions. Our estimate is then $\hat{y} = \hat{\beta}_{0} + \hat{\beta}_{1}x_{1}$. In this case, as you seem to be aware, you can show that for the estimated coefficient $\hat{\beta}_{1} = \frac{\text{Cov}(y, x)}{\text{Var}(x)}$.
Now for multiple regression, we have a model of the form $y = \beta_{0} + \beta_{1}x_{1} + \beta_{2}x_{2} + \dots+ \beta_{p}x_{p} + \varepsilon$. The estimate is of the form $\hat{y} = \hat{\beta}_{0} + \hat{\beta}_{1}x_{1} + \hat{\beta}_{2}x_{2} + \dots + \hat{\beta}_{p}x_{p}$. If you try to naively derive the same relationship for your estimated coefficients here as was found with simple linear regression, say for $x_{1}$, you find that
$\frac{\text{Cov}(y, x_{1})}{\text{Var}(x_{1})} = \frac{\text{Cov}(\hat\beta_{0} + \hat\beta_{1}x_{1}+ \hat\beta_{2}x_{2} + \dots+ \hat\beta_{p}x_{p}, x_{1})}{\text{Var}(x_{1})}
 = \frac{\hat\beta_{1}\text{Var}(x_{1}) + \hat\beta_{2}\text{Cov}(x_{2}, x_{1})+ \dots+ \hat\beta_{p}\text{Cov}(x_{p}, x_{1})}{\text{Var}(x_{1})} \color{red}\neq \hat\beta_{1}  $
except in the special case where all the variables $x_{2}, \dots, x_{p}$ are uncorrelated to $x_{1}$.
If we instead perform a transformation of the form (note that I have essentially set $\alpha_{1} = 0$ so that the subscript indices directly correspond, hopefully making things a little easier to understand) $x_{1} = \alpha_{0} + \alpha_{2}x_{2} + \alpha_{3}x_{3} + \dots + \alpha_{p}x_{p} + \tau$, so that $\tau$ is uncorrelated with any of $x_{2}, \dots, x_{p}$, you can perform a similar derivation to that used in simple linear regression to show that $\hat{\beta}_{1} = \frac{\text{Cov}(y, \tau)}{\text{Var}(\tau)}$. To see the relationship between the covariance of $\tau$ and $y$ with $\hat\beta_{1}$,
$\frac{\text{Cov}(y, \tau)}{\text{Var}(\tau)} = \frac{\text{Cov}(\hat\beta_{0} + \hat\beta_{1}x_{1}+ \hat\beta_{2}x_{2} + \dots+ \hat\beta_{p}x_{p}, \tau)}{\text{Var}(\tau)} = \frac{\hat\beta_{1}\text{Cov}(x_{1}, \tau)+ \sum_{i = 2}^{p}\hat\beta_{i}\text{Cov}(x_{i}, \tau)}{\text{Var}(\tau)}$
The sum term in the numerator is equal to $0$ by our assumption that $\tau$ is uncorrelated with any of $x_{2}, \dots, x_{p}$. Substituting our transformation in for $x_{1}$ in our remaining term, we have
$\hat\beta_{1}\text{Cov}(x_{1}, \tau) = \hat\beta_{1}\text{Cov}(\alpha_{0} + \alpha_{2}x_{2} + \alpha_{3}x_{3} + \dots + \alpha_{p}x_{p} + \tau, \tau) = \hat\beta_{1}\text{Var}(\tau)$, where the last equality follows again by $\tau$ being uncorrelated with any of $x_{2}, \dots, x_{p}$. The $\text{Var}(\tau)$ term in the numerator and denominator now cancel, and we are left with $\hat\beta_{1}$, demonstrating that indeed $\hat\beta_{1} = \frac{\text{Cov}(y, \tau)}{\text{Var}(\tau)}$. But by construction, $\tau$ was the part of $x_{1}$ that was uncorrelated with any of the other variables $x_{2}, \dots, x_{p}$. The above argument also shows, mutatis mutandis, the same relationship for the other coefficients $\hat\beta_{2}, \dots, \hat\beta_{p}$.


text:
Q: JavaScript 2D array, if input RegEx match col1 , return col2 I trying to set up a chatbot which when user input match some word, then will response accordingly.
this works
  var input = "i love you";

  if(/.*cute.*/.test(input)) { alert("Aw.... so sweet");}
  if(/.*love.*/.test(input)) { alert("Love you too");}

//result "Love you too"

However, how can I put the data in an array and still make it works?
example:
var queryResponse = [ ["cute","Aw.... so sweet"],
                      ["love","Love you too"] ];

How do I modify this line?
 if(/.*  (what should i insert here?) .*/.test(input)) { alert(So that the response appear here?);}

A: You can do like this:
var regexArray =  [ ["cute","Aw.... so sweet"],["love","Love you too"] ]

    for(var i = 0; i < regexArray.length ; i++){

    let re = new RegExp(`.*${regexArray[i][0]}*.`);

    if(re.test(input){
    alert(regexArray[i][1]);
    break;
     }
    }

A: index of each keys and value should match
var keys=['cute','love'];
var values= ['so cute', 'i love you'];

for(var i = 0; i < keys.length ; i++){

   let re = new RegExp(`.*${keys[i]}*.`);

   if(re.test(input){
        alert(values[i]);
        break;
   }
}

A:

const queryResponseMap = new Map([
  ["cute", "Aw.... so sweet"],
  ["love", "Love you too"]
]);

function getResponse(query) {
  const iterator = queryResponseMap.entries();
  let result = iterator.next();

  while (!result.done) {
    const [key, val] = result.value;

    if (new RegExp(`.*${key}*.`).test(query)) {
      return val;
    }

    result = iterator.next();
  }

  return null;
}

console.log(getResponse("Hi love"));
console.log(getResponse("You're cute"));


text:
Q: Strange video behaviour I have a video made by my mobile phone (Huawei Honor - Android 2.3).
I haven't problems with them some time ago. Unfortunately, I have now and I don't know why.
I'm using Linux Mint 17. When trying to play it with VLC, it crashes:
VLC media player 2.1.6 Rincewind (revision 2.1.6-0-gea01d28)
[0x1c26118] main libvlc: Spouštím přehrávač VLC s výchozím rozhraním.       Přejete-li si spouštět přehrávač VLC bez rozhraní, použijte příkaz 'cvlc'.
Fontconfig warning: FcPattern object size does not accept value "0"
Fontconfig warning: FcPattern object size does not accept value "0"
Fontconfig warning: FcPattern object size does not accept value "0"
Fontconfig warning: FcPattern object size does not accept value "0"
[0x7faa1c001248] main vout display error: Failed to resize display
Unauthorized access to memory (SIGSEGV)

With all other videos, I have, it works fine. Kaffeine media player plays it, but without audio. I have also tried windows machine - it was able to play it, however, was not able to jump within the video.
Information about the video:
General
Complete name                            : VID_20151010_132741.mp4
Format                                   : MPEG-4
Format profile                           : Base Media
Codec ID                                 : isom
File size                                : 6.83 MiB
Duration                                 : 6s 320ms
Overall bit rate mode                    : Constant
Overall bit rate                         : 9 060 Kbps

Video
ID                                       : 2
Format                                   : MPEG-4 Visual
Format profile                           : Simple@L6
Format settings, BVOP                    : Yes
Format settings, QPel                    : No
Format settings, GMC                     : No warppoints
Format settings, Matrix                  : Default (H.263)
Codec ID                                 : 20
Duration                                 : 6s 320ms
Bit rate mode                            : Constant
Bit rate                                 : 8 029 Kbps
Nominal bit rate                         : 256 Kbps
Width                                    : 1 280 pixels
Height                                   : 720 pixels
Display aspect ratio                     : 16:9
Frame rate mode                          : Variable
Frame rate                               : 26.265 fps
Minimum frame rate                       : 26.072 fps
Maximum frame rate                       : 26.463 fps
Color space                              : YUV
Bit depth                                : 8 bits
Scan type                                : Progressive
Compression mode                         : Lossy
Bits/(Pixel*Frame)                       : 0.332
Stream size                              : 6.05 MiB (89%)
Title                                    : VideoHandle
Language                                 : English
mdhd_Duration                            : 6320

Audio
ID                                       : 1
Format                                   : AMR
Format/Info                              : Adaptive Multi-Rate
Format profile                           : Narrow band
Codec ID                                 : samr
Duration                                 : 6s 160ms
Bit rate mode                            : Constant
Bit rate                                 : 5 200 bps
Channel(s)                               : 1 channel
Sampling rate                            : 8 000 Hz
Bit depth                                : 13 bits
Stream size                              : 3.91 KiB (0%)
Title                                    : SoundHandle
Writing library                          :
Language                                 : English

It works fine under VLC 2.2.1 in Arch Linux and the mobile phone.
What can I do? Thanks for your help in advance.


text:
Q: Dúvida em lógica de array em JS Preciso fazer com que o array recebido da função ACONTECE (nessa função eu recebo os horários dos alunos que entraram cedo,atrasado e pontual.) vá para a função ABERTURAS (e aqui eu informo se a aula acontece ou nao, como mostra o enunciado abaixo), ou seja, quero puxar as informações recebidas em ACONTECE, isso é o que o exercício pede:

Escreva as seguintes funções: 1. acontece, que diz se a aula sucederá
  de acordo com o array dos estudantes que entraram. 2. aberturas, que
  utiliza um array com os arrays dos estudantes que entraram nos outros
  dias, e a quantidade mínima de estudantes, e diga quais os dias em que
  as aulas aconteceram e quais não. Por exemplo:

aberturas([alunosDaSegunda, alunosDaTerça, alunosDaQuarta],
[true, false, false]

Esse é o meu código feito até o momento, porém não sei se a lógica está correta, preciso de auxílio para entender.
function acontece(alunos){
  var alunosDaSegunda = []
  var alunosDaTerca = []
  var alunosDaQuarta = []
  for (var i = 0; i < alunos.lenght; i++){
    if(i <= 0){
      return alunos
    }else
      return
  }
}

function aberturas(temAula){
  var alunosDaSegunda = []
  var alunosDaTerca = []
  var alunosDaQuarta = []
  for(var i = 0; i < temAula.lenght; i++ )
    if(temAula > 2 ){
      return temAula
    }else
      return

}

A: Você tem que entender que quando você declara return em uma função, a sua execução é encerrada. Não adianta nada declarar um for e então retornar na primeira interação. yield tem um comportamento mais parecido com o que você está tentando fazer, mas não há necessidade de utiliza-lo nesse caso.
Veja o exemplo:

function acontece(arrAlunos, qtdMinima) {
    var alunosPontuais = 0;
    for (var aluno of arrAlunos) {
        if (aluno <= 0)
            alunosPontuais++;
    }

    return alunosPontuais >= qtdMinima;
}

function aberturas(arrAlunosDias, qtdMinima){
    var arrDiasComAulas = [];
    for (var alunosDia of arrAlunosDias) {
        arrDiasComAulas.push(acontece(alunosDia, qtdMinima));
    }

    return arrDiasComAulas;
}

// 0 = aluno pontual, -1 = aluno adiantado, 1 = aluno atrasado
var arrDiasComAulas = aberturas(
    [
        [0, 0, 0],   //Dia 1
        [-1, 0, -1], //Dia 2
        [1, 1, 1]    //Dia 3
    ], 2 //Mínimo de alunos para contecer uma aula
);

console.log(arrDiasComAulas);


text: Q: Converting a number to Mexican peso letters I have a problem statement, where I need to convert a mexican peso in numeric format(say 213.14) to mexican peso word format (DOSCIENTOS TRECE PESOS 14/100 M.N.) . Is there any library to achieve this in java or javascript.


text:
Q: The action of $SL(2, \mathbb R)$ on $\mathbb R^4$ though Clifford algebra
My question is about the realization of $SL(2, \mathbb R)$ as the group of unit
quaternions in the even-dimensional Clifford algebra corresponding to an anisotropic quadratic form on $\mathbb R^3$ (from the paper ANOSOV FLOWS ON INFRA-HOMOGENEOUS
SPACES by PER TOMTER, page 300), so that $SL(2, \mathbb R)$ can act on $\mathbb R^4$.

Let $V=\mathbb R^3$ and $Q$ be a to-be-determined (?) quadratic form on $V$ free of nonzero integer solutions. The Clifford algebra $\mathcal A$ is defined as the quotient of the tensor algebra
$$\oplus_{n\ge 0} V^{\otimes n}$$
by the two-sided ideal $\langle v\otimes v - Q(v)1 \mid v\in V \rangle$, where $1$ is the unit of $\oplus_{n\ge 0} V^{\otimes n}$.
But I have some difficulty understanding the meaning of "realization of $SL(2, \mathbb R)$ as the group of unit quaternions in the even-dimensional Clifford algebra" in this situation. I guess in order to construct an action of $SL(2, \mathbb R)$ on $\mathbb R^4$ though Clifford algebra, we have to choose $Q$ in such a way (really?) that $\mathcal A$ is a 4-dimensional(or some even-dimensional) real algebra with basis $1,i,j,k$ and embed $SL(2,\mathbb R)$ into $A$ by identifying the matrices in $SL(2,\mathbb R)$ with $a+bi+cj+dk$. My understanding might be wrong, but how is this constructed specifically?
I hope my question is not confusing, but if you know any other ways of defining the action of $SL(2, \mathbb R)$ on $\mathbb R^4$, though Clifford algebra or not, please feel free to share. Thanks!

A: First, there are varying conventions about formation of a Clifford algebra attached to a quadratic form. Some conventions have a sign flipped in comparison to others, so the implications of isotropic/anisotropic are ambiguous.
But that does not affect the facts. :)
Let's take the convention that the Clifford algebra associated to a quadratic form $Q$ is characterized by $v\cdot v=Q(v)$. Thus, the Hamiltonian quaternions appear as the Clifford algebra attached to a negative-definite quadratic form on $\mathbb R^3$, with $i^2=j^2=k^2=-1$.
The opposite sign, giving $i^2=j^2=k^2=1$, gives the ring of two-by-two real matrices, for example taking $i=\pmatrix{1&0\cr0&-1}$, $j=\pmatrix{0&1\cr1&0}$, etc.
In either case, the "unit quaternions" are those with "reduced norm $1$", which means "determinant=1" in matrix models. So this gives $SL_2(\mathbb R)$ in the latter case.
The units $A^\times$ in a quaternion algebra (over $\mathbb R$) $A$ act on $A\approx \mathbb R^4$ in at least two ways. One is by left (or right) multiplication $a\cdot b=ab$. Another is by conjugation $a\cdot b=aba^{-1}$.


text:
Q: Network Configurations I'm using the command nmcli for set the IP of a ubuntu 18.04.5
"nmcli device modify ens33 ipv4.method manual ipv4.address X.X.X.X/X ipv4.gateway X.X.X.X ipv4.dns X.X.X.X"
and the ip changes wihthout problem, but after if I reboot the ubuntu after the IP goes to DHCP (fresh instalation of ubuntu).
with the grahical interface manager I have no problem but the code is for running in a server withtout GUI.

*

*is a server but I use the nmcli to manage the wifi network card saids and passwords. One eth0 and a wan0

A: In a server, without a desktop environment, set your details in the file found in /etc/netplan. Here are some examples:
ls /usr/share/doc/netplan/examples

Most likely, your template is:
network:
  version: 2
  renderer: networkd
  ethernets:
    enp3s0:
      addresses:
        - 10.10.10.2/24
      gateway4: 10.10.10.1
      nameservers:
        search: [mydomain, otherdomain]
        addresses: [10.10.10.1, 1.1.1.1]

Netplan is strict about indentation, spacing, etc., so proofread carefully twice. Follow with:
sudo netplan generate
sudo netplan apply

You should be all set.


text:
Q: Difference in linear model, but not in either main-effects My experiment is a 3 (auditory, vibe, multimodal) x 2 (simple, metro) design. I am defining a linear regression model, using contrast codes (-1,1) to compare means between conditions. I am also looking at main effects using post-hoc t-tests
#contrasts
MetronomeSimple <- c(1,1,1,-1,-1,-1)
AuditoryVibe <- c(1,0,-1,1,0,-1)
AuditoryMultimodal <- c(-1,1,0,-1,1,0)
AuditorySimpleVibeSimple <- c(0,0,0,1,0,-1)
contrasts(entrain_df$trials) <- cbind(MetronomeSimple,
                                      AuditoryVibe,
                                      AuditoryMultimodal,
                                      AuditorySimpleVibeSimple)
#model
ENlinear <- lm(en1 ~ trials, data = entrain_df)
summary(ENlinear)

I am getting some weird findings. I get a significant difference p < 0.01, for the the AuditoryMultimodal contrast. However, when I examine the main effects using post-hoc t-tests I do not find a significant difference in either of the conditions
#model summery
lm(formula = en1 ~ trials, data = entrain_df)

Residuals:
      Min        1Q    Median        3Q       Max
-0.081664 -0.021471 -0.008251  0.017213  0.108259

Coefficients:
                                 Estimate Std. Error
(Intercept)                     0.0686584  0.0028161
trialsMetronomeSimple           0.0084093  0.0028161
trialsAuditoryVibe              0.0176878  0.0051962
trialsAuditoryMultimodal        0.0098270  0.0039958
trialsAuditorySimpleVibeSimple -0.0091532  0.0068751
trials                          0.0001544  0.0069209
                               t value Pr(>|t|)
(Intercept)                     24.381  < 2e-16 ***
trialsMetronomeSimple            2.986 0.003325 **
trialsAuditoryVibe               3.404 0.000862 ***
trialsAuditoryMultimodal         2.459 0.015112 *
trialsAuditorySimpleVibeSimple  -1.331 0.185192
trials                           0.022 0.982233
---
Signif. codes:
0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.03436 on 143 degrees of freedom
  (7 observations deleted due to missingness)
Multiple R-squared:  0.1349,    Adjusted R-squared:  0.1046
F-statistic: 4.458 on 5 and 143 DF,  p-value: 0.0008351

t.test(multiSimple$en1,audSimple$en1, na.action = na.omit)

    Welch Two Sample t-test

data:  multiSimple$en1 and audSimple$en1
t = 1.2224, df = 41.533, p-value = 0.2285
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.007157514  0.029128954
sample estimates:
 mean of x  mean of y
0.06998692 0.05900120

> t.test(multiMetro$en1,audMetro$en1, na.action = na.omit)

    Welch Two Sample t-test

data:  multiMetro$en1 and audMetro$en1
t = 0.19227, df = 46.028, p-value = 0.8484
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.01988436  0.02408416
sample estimates:
 mean of x  mean of y
0.08698381 0.08488391

This does not make sense to me. How can there be a large difference between the conditions but no differences in the main effects? Does anyone have an explanation for this?


text:
Q: Programming Logic - Splitting up Tasks Between Threads Lets say you want 5 threads to process data simultaneous. Also assume, you have 89 tasks to process.
Off the bat you know 89 / 5 = 17 with a remainder of 4. The best way to split up tasks would be to have  4 (the remainder) threads process 18 (17+1) tasks each and then have 1 (# threads - remainder) thread to process 17.
This will eliminate the remainder. Just to verify:
Thread 1: Tasks  1-18  (18 tasks)
Thread 2: Tasks 19-36  (18 tasks)
Thread 3: Tasks 37-54  (18 tasks)
Thread 4: Tasks 55-72  (18 tasks)
Thread 5: Tasks 73-89  (17 tasks)

Giving you a total of 89 tasks completed.
I need a way of getting the start and ending range of each thread mathematically/programmability; where the following should print the exact thing I have listed above:
$NumTasks = 89
$NumThreads = 5
$Remainder = $NumTasks % $NumThreads
$DefaultNumTasksAssigned = floor($NumTasks / $NumThreads)

For $i = 1 To $NumThreads
    if $i <= $Remainder Then
        $NumTasksAssigned = $DefaultNumTasksAssigned + 1
    else
        $NumTasksAssigned = $DefaultNumTasksAssigned
    endif
    $Start = ??????????
    $End = ??????????
    print Thread $i: Tasks $Start-$End ($NumTasksAssigned tasks)
Next

This should also work for any number of $NumTasks.
Note: Please stick to answering the math at hand and avoid suggesting or assuming the situation.

A: Why? Rather then predetermining the scheduling order, stick all of the tasks on a queue, and then have each thread pull them off one by one when they're ready. Then your tasks will basically run "as fast as possible".
If you pre-allocated, then one thread may be doing a particularly long bit of processing and blocking the running of all the tasks stuck behind it. Using the queue, as each task finishes and a thread frees up, it grabs the next task and keeps going.
Think of it like a bank with 1 line per teller vs one line and a lot of tellers. In the former, you might get stuck behind the person depositing coins and counting it out one by one, the latter you get to the next available teller, while Mr. PocketChange counts away.

A: I second Will Hartung 's remark.  You may just feed them one task at a time (or a few tasks at a at a time, depending if there's much overhead, i.e. if individual tasks get typically completed very fast, relative to the cost of starting/recycling threads).  Your subsequent comments effectively explain that your "threads" carry a heavy creation cost, and hence your desire to feed them once with as much work as possible, rather than wasting time creating new "thread" each fed a small amount of work.
Anyway... going to the math question...
If you'd like to assign tasks just once, the following formula, plugged in lieu of the the ?????????  in your logic, should do the trick:
$Start = 1
         + (($i -1) * ($DefaultNumTasksAssigned + 1)
        - (floor($i / ($Remainder + 1)) * ($i - $Remainder))
$End = $Start + $NumTasksAssigned -1

The formula is explained as follow:
        1 is for the fact that your display / logic is one-based not zero-based
       The second term is because we generally add ($DefaultNumTasksAssigned + 1) with each iteration.
        The third term provides a correction for the last few iterations.
             Its first part, (floor($i / ($Remainder + 1)) provides 0 until $i reaches the first thread
       that doesn't receive one extra task, and 1 thereafter.
       The second part express by how much we need to correct.

The formula for $End is easier, the only trick is the minus 1, it is because the Start and End values are inclusive (so for example between 1 an 19 there are 19 tasks not 18)
The following slightly modified piece of logic should also work, it avoids the "fancy" formula by keeping a running tab of the $Start variable, rather than recomputing it each time..
$NumTasks = 89
$NumThreads = 5
$Remainder = $NumTasks % $NumThreads
$DefaultNumTasksAssigned = floor($NumTasks / $NumThreads)
$Start = 1
For $i = 1 To $NumThreads
    if $i <= $Remainder Then    // fixed here!  need <= because $i is one-based
        $NumTasksAssigned = $DefaultNumTasksAssigned + 1
    else
        $NumTasksAssigned = $DefaultNumTasksAssigned
    endif
    $End = $Start + $NumTasksAssigned -1
    print Thread $i: Tasks $Start-$End ($NumTasksAssigned tasks)

    $Start = $Start + $NumTasksAssigned
Next

Here's a Python transcription of the above
>>> def ShowWorkAllocation(NumTasks, NumThreads):
...   Remainder = NumTasks % NumThreads
...   DefaultNumTasksAssigned = math.floor(NumTasks / NumThreads)
...   Start = 1
...   for i in range(1, NumThreads + 1):
...     if i <= Remainder:
...        NumTasksAssigned = DefaultNumTasksAssigned + 1
...     else:
...        NumTasksAssigned = DefaultNumTasksAssigned
...     End = Start + NumTasksAssigned - 1
...     print("Thread ", i, ": Tasks ", Start, "-", End, "(", NumTasksAssigned,")")
...     Start = Start + NumTasksAssigned
...
>>>
>>> ShowWorkAllocation(89, 5)
Thread  1 : Tasks  1 - 18 ( 18 )
Thread  2 : Tasks  19 - 36 ( 18 )
Thread  3 : Tasks  37 - 54 ( 18 )
Thread  4 : Tasks  55 - 72 ( 18 )
Thread  5 : Tasks  73 - 89 ( 17 )

>>> ShowWorkAllocation(11, 5)
Thread  1 : Tasks  1 - 3 ( 3 )
Thread  2 : Tasks  4 - 5 ( 2 )
Thread  3 : Tasks  6 - 7 ( 2 )
Thread  4 : Tasks  8 - 9 ( 2 )
Thread  5 : Tasks  10 - 11 ( 2 )
>>>

>>> ShowWorkAllocation(89, 11)
Thread  1 : Tasks  1 - 9 ( 9 )
Thread  2 : Tasks  10 - 17 ( 8 )
Thread  3 : Tasks  18 - 25 ( 8 )
Thread  4 : Tasks  26 - 33 ( 8 )
Thread  5 : Tasks  34 - 41 ( 8 )
Thread  6 : Tasks  42 - 49 ( 8 )
Thread  7 : Tasks  50 - 57 ( 8 )
Thread  8 : Tasks  58 - 65 ( 8 )
Thread  9 : Tasks  66 - 73 ( 8 )
Thread  10 : Tasks  74 - 81 ( 8 )
Thread  11 : Tasks  82 - 89 ( 8 )
>>>

A: I think you've solved the wrong half of your problem.
It's going to be virtually impossible to precisely determine the time it will take to complete all your tasks, unless all of the following are true:

*

*your tasks are 100% CPU-bound: that is, they use 100% CPU while running and don't need to do any I/O

*none of your tasks have to synchronize with any of your other tasks in any way

*you have exactly as many threads as you have CPUs

*the computer that is running these tasks is not performing any other interesting tasks at the same time

In practice, most of the time, your tasks are I/O-bound rather than CPU-bound: that is, you are waiting for some external resource such as reading from a file, fetching from a database, or communicating with a remote computer.  In that case, you only make things worse by adding more threads, because they're all contending for the same scarce resource.
Finally, unless you have some really weird hardware, it's unlikely you can actually have exactly five threads running simultaneously.  (Usually processor configurations come in multiples of at least two.)  Usually the sweet spot is at about 1 thread per CPU if your tasks are very CPU-bound, about 2 threads per CPU if the tasks spend half their time being CPU-bound and half their time doing IO, etc.
tl;dr: We need to know a lot more about what your tasks and hardware look like before we can advise you on this question.


text:
Q: How to refresh the part below the items of istview/treeview? What I am doing
The tilte of question may be not clear. I will make more description.
When you try to redraw a WC_TREEVIEW contorl, you may need to pay attention to it's parent window message WM_NOTIFY.
It may coding like this:
case WM_NOTIFY: {
    UINT ctrl_id = wParam;
    LPNMHDR pnmh = (LPNMHDR)lParam;
    HWND ctrl_hwnd = pnmh->hwndFrom;
    char class_name[256] = "";
    LRESULT result;

    GetClassName(ctrl_hwnd,class_name,sizeof(class_name));
    if(strstr(class_name,WC_TREEVIEW)) {
        LPNMTREEVIEW item = (LPNMTREEVIEW)pnmh;

        if(item->hdr.code == NM_CUSTOMDRAW) {
            //...Do your item drawing
            return result;
        }
    }
    //....
} break;

The parameter NMTREEVIEW has all the necessary information you need to update the specfic item area.
My Fisrt question is the meaning of structure member NMTVCUSTOMDRAW::nmcd::dwDrawStage.
MSDN say a lot, I have no ideal.
My coding is like this,if not right please correct me. Thank you.

//My drawing of treeview item.
{
    LPNMTVCUSTOMDRAW cust_draw = (LPNMTVCUSTOMDRAW)lParam;
    RECT rect;
    HDC hdc;
    TVHITTESTINFO tv_hit;
    TVITEM tv_item;
    HTREEITEM item;
    char item_text[1024] = "";
    int step_level=cust_draw->iLevel;

    hdc = cust_draw->nmcd.hdc;
    CopyRect(&rect,&(cust_draw->nmcd.rc));
    tv_hit.pt = {(rect.left+rect.right)/2,(rect.top+rect.bottom)/2};

    if(cust_draw->nmcd.dwDrawStage==CDDS_PREPAINT) {
        return CDRF_NOTIFYITEMDRAW;
    }
    else if(cust_draw->nmcd.dwDrawStage == CDDS_ITEMPREPAINT) {
        item = TreeView_HitTest(hwnd,&tv_hit);
        if(item) {
            tv_item.mask = TVIF_TEXT|TVIF_STATE|TVIF_CHILDREN;
            tv_item.hItem = item;
            tv_item.pszText = item_text;
            tv_item.cchTextMax = sizeof(item_text);
            TreeView_GetItem(hwnd,&tv_item);
            MyTreeItemDrawing(hwnd,hdc,rect,step_level,&tv_item);
        }
        return CDRF_SKIPDEFAULT;
    }
    return CDRF_SKIPDEFAULT;
}

What is my problem
All those have been done. Then you will find some ficker when you sizing the holder window.
I make the treeview control auto sizing itself according the size of its container window.
Now if I block the WM_ERASEBKGND return non-zero directly, it will somehow reduce the flicker.
case WM_ERASEBKGND: return 1;
break;

However, if the treeview items do not occupy the whole client zone, the rest part which not been occupied by the treeview items will not refresh correctly.
That is my problem.Treeview refresh its background and items caused the flicker. What should I do to solve this problem?
Right now it's a common issue for me when I redrawing the WC_LISTVIEW control. It also provide WM_DRAWITEM to rewrite the items.
Same flicker problem.

A: The window style WS_CLIPCHILDREN can work.
The container window should apply this style to avoid the double refresh of the control area. In this way you can keep the WM_ERASEBKGND, and no flicker.