text:
Q: RaisePostBackEvent not fired on custum child control I have created tow custom controls to use bootstrap in my C# code. The first one implement a bootstrap dropdown list with this code ;
using System.Web.UI;
using System.Web.UI.WebControls;
using static JDBootStrap.BSTypes;

namespace JDBootStrap.Components
{
    [ToolboxData("<{0}:BSDropDown runat=server></{0}:BSDropDown>")]
    public class BSDropDown : Panel
    {
        public enum OrientationType { Down, Up, Right }

        string _text;
    OrientationType _orientation;
    ControlCollection _controls;
    sizeType _size = sizeType.md;
    bool _useInGroup;
    bool useInList;
    Glyphicon.GlyphiconType? _glyphicon;
    string _style;

    public BSDropDown()
    {
        Controls = new ControlCollection(this);
    }

    public Glyphicon.GlyphiconType? Glyphicon
    {
        get
        {
            return _glyphicon;
        }

        set
        {
            _glyphicon = value;
        }
    }

    #region Properties

    protected override string TagName
    {
        get
        {
            return UseInList ? "li" : "div";
        }
    }

    protected override ControlCollection CreateControlCollection()
    {
        return Controls;
    }

    public string Text
    {
        get
        {
            return _text;
        }

        set
        {
            _text = value;
        }
    }

    public OrientationType Orientation
    {
        get
        {
            return _orientation;
        }

        set
        {
            _orientation = value;
        }
    }

    public bool UseInList
    {
        get
        {
            return useInList;
        }

        set
        {
            useInList = value;
        }
    }

    new public ControlCollection Controls
    {
        get
        {
            return _controls;
        }

        set
        {
            _controls = value;
        }
    }

    public sizeType Size
    {
        get
        {
            return _size;
        }

        set
        {
            _size = value;
        }
    }

    public bool UseInGroup
    {
        get
        {
            return _useInGroup;
        }

        set
        {
            _useInGroup = value;
        }
    }

    #endregion

    public override void RenderBeginTag(HtmlTextWriter writer)
    {
        writer.Write("<" + TagName + " class=\"" + GetOrientationClass());
        if (_orientation == OrientationType.Right) writer.Write(" dropdown-submenu");
        if (!string.IsNullOrEmpty(CssClass)) writer.Write(" " + CssClass);

        if (_useInGroup) writer.Write(" btn-group");
        writer.Write(" btn-" + (UseInGroup ? "group-" : "") + _size.ToString().ToLower());
        writer.Write("\"");
        writer.Write(" name =\"" + UniqueID + "\"");
        writer.Write(" id=\"" + ClientID + "\"");
        writer.Write(">");

        writer.Write(UseInList ? "<a href =\"#\"" : "<button");
        writer.Write(" class=\"");
        writer.Write(_useInGroup ? "btn btn-default " : "");
        writer.Write("dropdown-toggle");
        writer.Write("\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\" aria-expanded=\"false\">");
        if (!string.IsNullOrEmpty(_text)) writer.WriteEncodedText(_text);
        if (_glyphicon != null)
        {
            var g = new Glyphicon((Glyphicon.GlyphiconType)_glyphicon);
            g.RenderControl(writer);
        }
        if (_orientation != OrientationType.Right) writer.Write("");
        writer.Write(UseInList ? "" : "</button>");

        writer.Write("
");
    }

    protected override void Render(HtmlTextWriter writer)
    {
        RenderBeginTag(writer);
        RenderChildren(writer);
        RenderEndTag(writer);
    }
    protected override void RenderChildren(HtmlTextWriter writer)
    {
        foreach (Control ctrl in Controls)
        {
            if (ctrl.GetType() == typeof(BSDropDown)) ((BSDropDown)ctrl).Orientation = OrientationType.Right;
            if (ctrl.GetType() == typeof(BSMenuItem)) ((BSMenuItem)ctrl).SubMenu = true;
            ctrl.RenderControl(writer);
        }
    }

    public override void RenderEndTag(HtmlTextWriter writer)
    {
        writer.Write("
");
        writer.Write("</" + TagName + ">");
    }

    private string GetOrientationClass()
    {
        switch (Orientation)
        {
            case OrientationType.Up:
                return "dropup";
            default:
                return "dropdown";
        }
    }
}

}
the second one is a menuitem like this :
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace JDBootStrap.Components
{
    [ToolboxData("<{0}:BSMenuSeparator runat=server></{0}:BSMenuSeparator>")]
    public class BSMenuSeparator : WebControl
    {
        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write("

");
        }
    }
    [ToolboxData("<{0}:BSMenuHeader runat=server></{0}:BSMenuHeader>")]
    public class BSMenuHeader : WebControl
    {
        private string _title;

        public BSMenuHeader(string title)
        {
            _title = title;
        }

        public string Title
        {
            get
            {
                return _title;
            }

            set
            {
                _title = value;
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write("
");
            if (!string.IsNullOrEmpty(_title)) writer.Write(_title);
            writer.Write("
");
        }
    }
    [ToolboxData("<{0}:BSMenuItem runat=server></{0}:BSMenuItem>")]
    public class BSMenuItem : Panel, IButtonControl, IPostBackEventHandler
    {

        string _text;
        string _navigateUrl;
        bool _active ;
            b

ool _subItem;
        Glyphicon.GlyphiconType? _glyphicon;
        string _value;
        string _title;
        string _commandArgument;
        string _validationGroup;
        string _postBackUrl;
        string _commandName;
        bool _causesValidation;
        static readonly object EventClick = new object();

        public event EventHandler Click
        {
            add
            {
                Events.AddHandler(EventClick, value);
            }
            remove
            {
                Events.RemoveHandler(EventClick, value);
            }
        }

        public event CommandEventHandler Command;

        #region Property
        public BSMenuItem()
        {
        }

        public BSMenuItem(string text)
        {
            _text = text;
        }

        public BSMenuItem(string text, string navigateUrl)
        {
            _text = text;
            _navigateUrl = navigateUrl;
        }

        public string Text
        {
            get
            {
                return _text;
            }

            set
            {
                _text = value;
            }
        }

        public string NavigateUrl
        {
            get
            {
                return _navigateUrl;
            }

            set
            {
                _navigateUrl = value;
            }
        }

        public bool Active
        {
            get
            {
                return _active;
            }

            set
            {
                _active = value;
            }
        }

        public bool SubMenu
        {
            get
            {
                return _subItem;
            }

            set
            {
                _subItem = value;
            }
        }

        public Glyphicon.GlyphiconType? Glyphicon
        {
            get
            {
                return _glyphicon;
            }

            set
            {
                _glyphicon = value;
            }
        }

        public bool CausesValidation
        {
            get
            {
                return _causesValidation;
            }

            set
            {
                _causesValidation = value;
            }
        }

        public string CommandArgument
        {
            get
            {
                return _commandArgument;
            }

            set
            {
                _commandArgument = value;
            }
        }

        public string ValidationGroup
        {
            get
            {
                return _validationGroup;
            }

            set
            {
                _validationGroup = value;
            }
        }

        public string PostBackUrl
        {
            get
            {
                return _postBackUrl;
            }

            set
            {
                _postBackUrl = value;
            }
        }

        public string CommandName
        {
            get
            {
                return _commandName;
            }

            set
            {
                _commandName = value;
            }
        }

        public string Value
        {
            get
            {
                return _value;
            }

            set
            {
                _value = value;
            }
        }

        public string Title
        {
            get
            {
                return _title;
            }

            set
            {
                _title = value;
            }
        }
        #endregion

        protected override void Render(HtmlTextWriter writer)
        {
            if (Controls.Count == 0)
            {
                writer.Write("
");

                if (Glyphicon!=null)
                {
                    var g = new Glyphicon((Glyphicon.GlyphiconType)_glyphicon);
                    g.RenderControl(writer);
                }
                if (!string.IsNullOrEmpty(_text)) writer.WriteEncodedText(_text);
                writer.Write("
");
            }
            else
            {
                var dd = new BSDropDown
                {
                    Text = _text,
                    UseInList = true
                };

                if (SubMenu) dd.Orientation = BSDropDown.OrientationType.Right;
                dd.Controls=Controls;

                dd.RenderControl(writer);

            }
        }

        protected virtual void OnClick(EventArgs e)
        {
            EventHandler handler = (EventHandler)Events[EventClick];
            handler?.Invoke(this, e);
        }
        protected virtual void OnCommand(CommandEventArgs e)
        {
            Command?.Invoke(this, e);
        }

        public void RaisePostBackEvent(string eventArgument)
        {
            OnClick(new EventArgs());
            OnCommand(new CommandEventArgs(CommandName, CommandArgument));
        }
    }

If i use my menu item alone, or as a child of my drop-down control using my aspx page to set them, it work fine. But if i create them programmatically my RaisePostBackEvent is never fired. __EventTarget is well set but nothing happen.
It work only if i set in my aspx page my dropdown and add my child programmatically... (I add my control in Page_init). Thanks for your help.

A: I use an array of control to override Controls of my dropdown list. If i remove this collection and use inherited Controls properties it work.
I was using my own array because my menuitem can change behaviour and become dropdown list if there is child. So i have to move control child from menuitem to a dropdown (list and Controls can't be set).
Now i have to move control like this :
int l = Controls.Count;
for (int a = 0; a < l; a++)
dd.Controls.Add(Controls[0]);
Controls.Clear();

Controls.Add(dd);

where dd is my new dropdown list. Hope it can help someone.


text:
Q: multiple count on derived table I am trying to count total shortlisted and total interested by using a derived table but it's not working.
select  (SELECT COUNT(ID) FROM Dtable WHERE Is_shortlisted=1) AS TOTALSHORLISTED,
        (SELECT COUNT(ID) FROM Dtable WHERE Is_Interested=1) AS TOTALINERESTED
from (
        SELECT  BM.ID,
                BM.Is_Interested,
                BM.Is_shortlisted,
                BM.Business_Masla_Status_ID
        FROM  Business_Maslahal BM
        INNER join Vw_MaslaInfo MI
            on BM.[MaslaHal_ID]=MI.ID and BM.ID=2 AND MI.Masla_status_ID IN(1,2)
) Dtable

A: Actually, you don't even need the derived table:
SELECT  SUM(CASE WHEN Is_shortlisted=1 THEN 1 ELSE 0 END) AS TOTALSHORLISTED,
        SUM(CASE WHEN Is_Interested=1 THEN 1 ELSE 0 END) AS TOTALINERESTED
FROM  Business_Maslahal BM
INNER join Vw_MaslaInfo MI
ON BM.[MaslaHal_ID]=MI.ID
WHERE and BM.ID=2
AND MI.Masla_status_ID IN(1,2)

I've also moved some of the conditions from the ON clause to the WHERE clause. It should have no effect on the results, but it makes the query more readable.

A: Try this way:
select  SUM(CASE WHEN Is_shortlisted=1 THEN 1 ELSE 0 END) AS TOTALSHORLISTED,
        SUM(CASE WHEN Is_Interested=1 THEN 1 ELSE 0 END) AS TOTALINERESTED
from (
    SELECT  BM.ID,
            BM.Is_Interested,
            BM.Is_shortlisted,
            BM.Business_Masla_Status_ID
    FROM  Business_Maslahal BM
    INNER join Vw_MaslaInfo MI
        on BM.[MaslaHal_ID]=MI.ID and BM.ID=2 AND MI.Masla_status_ID IN(1,2)
) Dtable

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set login button go to next applet? How to set the button to go to next applet? The code is like:
if (strp.matches(strp) && stru.matches(stru)) {
    register rg=new register();
    rg.setVisible(true);
    this.setVisible(false);
}
else {
    JOptionPane.showMessageDialog(null,"User name or password are not correct.");
    return;
}

After confirming the password and username, it only shows blank. How to set the applet so that after clicking button it will go to next applet?

A: Please try below...
if (strp.matches(strp) && stru.matches(stru))
{
    Class applet2 = Class.forName("register"); // give complete name of register class including package name
    Applet appletToLoad = (Applet)applet2.newInstance();
    appletToLoad.setStub(this);
    setLayout( new GridLayout(1,0));
    add(appletToLoad);
    appletToLoad.init();
    appletToLoad.start();
}
else
{
     JOptionPane.showMessageDialog(null,"User name or password are not correct.");
     return;
}


text:
Q: Find the arithmetic progression where $a_7 \cdot a_8 = 1326$ and $a_1 \cdot a_{14} = 276$ Find the arithmetic progression where $a_7 \cdot a_8 = 1326$ and $a_1 \cdot a_{14} = 276$
Right now I've only dealt with these problems when I have a sum of two members of the AP so I can use the formula for the sum of the AP. Right now, I don't know how to proceed. Could anyone help?

A: We have $a_n=a_1+(n-1)d$ for all $n\geq 1$. Thus the two pieces of information turn into the equations $a_1(a_1+13d)=276$ and $(a_1+6d)(a_1+7d)=1326$.
By subtracting the first equation from the second, we get $42d^2=1050\Longrightarrow d=\pm 5$. If $d=-5$, the first and second equations both give $a_1=-4,69$. If $d=5$, the first and second equations both give $a_1=4,-69$. So there are four solutions: $(a_1,d)=(-4,-5),(69,-5),(4,5),(-69,5)$.
Note that $(-4,-5)\equiv (-69,5)$ in the sense that they both refer to the sequence $\ldots ,-4,1,5,\ldots $, and $(69,-5)\equiv (4,5)$ in the sense that they both refer to the sequence $\ldots ,-1,4,9,\ldots $.

A: Ross Millikan gave you the correct general approach in the comments.  Given that you're working with rather small numbers, another approach, specific to this question, is to factor $276$ and then look for two factors that differ by a multiple of $13$.  That's because $13$ has to divide $a_{14}-a_1=(a_1+13d)-a_1$.


text:
Q: Impossible to login after crash I am using Fedora 16. I have downloaded MySQL Server and tried to start it; while doing so my Fedora hung. So I shutdown by pressing the power button. When I try to log in next time then this error occurs:
Oh no! Something has gone wrong.A problem has occurred and the system can't recover.Please contact a system administrator

How do I recover my Fedora?

A: reboot into single user mode
press A when you see the grub menu and add a 1 to the end of your kernel args.
from there you will be able to fix anything you need to


text:
Q: Удалить одинаковые элементы массива - Delphi Не удаляются одинаковые элементы двумерного массива
я это делаю так:
    type
      TaXiz = array [0..1,0..1000] of real;
    type
      TaXYiz = array [0..1000,0..1] of real;

    var
      i,v,b,z: Integer;
      aXYiz,aXYizu: TaXYiz;
    ...

  v:=Length(aXYiz)-1;
  i:=0;
  while i<=v do
   begin
    b:=i+1;
    while b<=v do
     begin
      if (aXYiz[b,0]=aXYiz[i,0]) and (aXYiz[b,1]=aXYiz[i,1]) then
      begin
        for z:=b to v-1 do
        begin
          aXYiz[z]:=aXYiz[z+1];
          v:=v-1;
        end;
      end
       else b:=b+1;
     end;
   end;

A: Первое. У Вас неправильная индексация массива - должна быть от нуля до (длина - 1).
Второе. Логика внутри внутреннего while от меня ускользает. Напишите ее словами, потом возьмите листок бумаги и на достаточно простом примере выполните все действия. Убедитесь, что результат соответствует Вашим ожиданиям.
Третье. Не пренебрегайте ключевыми словами begin/end - в цикле for z:=b to v-1 do их явно не хватает.
И четвертое. Термин "удаление" слабо применим к статическому массиву - но это может объясняться логикой кода, не вошедшего в вопрос.


text:
Q: jQuery Selector for Section that Contains Divs I'd like to display all of the fields within the section when the h2 element within that section is clicked. Example: when a user clicks 'Contact Information' the 3 form inputs (fields) below the Contact Information heading are shown.
All of my form fields are hidden with the following css:
div.field {
  display:none;
}

Here's the jQuery that I'm using for that:
$('section > h2').click(function(){
  $('.field').toggle();
});

Here's my HTML:

Contact Information

    // form input

    // form input

    // form input

Address

    // form input

    // form input

    // form input

What happens here is that all of the fields are shown - not just the ones within the same section as the h2 that is being clicked. How can I toggle visibility of only the fields within the same section as the h2 that is being clicked?
Thanks in advance.

A: Go back up to the section, then find all the .field elements within that specific section

$('section > h2').on('click', function(){
  $(this).closest('section').find('.field').toggle();
});
div.field {
  display:none;
}

Contact Information

    form input 1

    form input 2

    form input 3

Address

    form input 4

    form input 5

    form input 6

As long as you keep the HTML just as it is, siblings would work as well
$(this).siblings('.field').toggle()

but it's more specific, and won't work with nested elements

A:

$('section > h2').click(function(){
  $(this).parent().find('.field').toggle();
});
div.field {
  display:none;
}

Contact Information

    // form input

    // form input

     //form input

Address

    // form input

    // form input

    // form input

A: Because your field divs come after the h2 element you can use .nextAll('.field')

$('section > h2').click(function () {
    $(this).nextAll('.field').toggle();
});
div.field {
    display: none;
}

Contact Information

        // form input

      // form input

        // form input

Address

      // form input

    // form input

      // form input


text:
Q: Can I move Delphi TThread.Synchronize() locally to a VCL form to be called from both a main or worker thread? I am using CreateAnonymousThread for a worker task, and when I started with it I used Synchronize within the entire declaration as per documented examples, e.g:
procedure Txxx.RunWorker;
begin
     FExecutionThread := TThread.CreateAnonymousThread(procedure ()
     begin

        TThread.Synchronize (TThread.CurrentThread,
          procedure ()
          begin
            // Here before worker stuff
            NotifyBeforeWorkerStuff;

          end);

        // Do worker stuff

        TThread.Synchronize (TThread.CurrentThread,
          procedure ()
          begin
            // Here after worker stuff
            NotifyAfterWorkerStuff;
          end);
      end);

      FExecutionThread.Start;
    end;
end;

As you see, from within this thread I launch event notifications to various parts of my app including VCL forms (NotifyBeforeWorkerStuff etc).
Later, I saw that I could move Synchronize() more locally to each VCL form close to the point that actually required it for updating (non-safe) VCL controls:
    procedure TSomeVCLForm.ReceiveNotification;
    begin
      TThread.Synchronize (TThread.CurrentThread,
          procedure ()
          begin
            Label1.Caption := GetSomeStringFunction;
          end);
     end;

The worker thread then becomes simpler as long as I live with notifications being from either main or worker threads:
   procedure Txxx.RunWorker;
   begin
     FExecutionThread := TThread.CreateAnonymousThread(procedure ()
       begin

         NotifyBeforeWorkerStuff;

         // Do worker stuff

         NotifyAfterWorkerStuff;

       end);

     FExecutionThread.Start;
   end;

I have several questions about whether this is correct:

*

*My notifications may be from the worker thread but also from the main thread (e.g derived from a button press). So, when 'ReceiveNotification' on a VCL form is called from the main thread, is it allowed to call TThread.Synchronize as above? The the XE8 docs imply not, but checking System.Classes this looks ok and it works fine.

*Within 'ReceiveNotification' when Label1.Caption fetches the string from GetSomeStringFunction, is it correct that there is absolutely no need for locking within that function even when the call is from a worker thread?

Thanks for any advice.

A: The documentation says:

Warning: Do not call Synchronize from within the main thread. This can cause an infinite loop.

I think that documentation is simply wrong. The implementation in XE8 checks whether or not the current thread is the main thread. If it is then the method is executed directly.
No locking is required in ReceiveNotification because the call to GetSomeStringFunction is always performed on the main thread.


text:
Q: Extension of scalars $M_B=B\otimes_A M$ Most textbooks say that the $B$-module structure on $M_B$ (for $A\rightarrow B$ a ring morphism and $M$ an $A$-module) is "defined" by $b'(b\otimes m)=b'b\otimes m$. How is this a proper definition? After all not every element of $M_B$ is of the form $b\otimes m$, isn't it?
Shouldn't the proper definition go as follows: fix $b'\in B$, define $b'\cdot:M_B\rightarrow M_B$ to be induced by the $A$-bilinear map $B\times M\rightarrow M_B$ sending $(b,m)\mapsto b'b\otimes m$.

A: Hint: show that for every $b' \in B$, the map
$$B \times M \to B \otimes_A M$$
given by $(b, m) \mapsto b'b \otimes m$ is $A$-bilinear, and therefore it factors through a map
$$B \otimes_A M \to B\otimes_A M$$
given on simple tensors by $b \otimes m \mapsto b'b\otimes m$. Show that these maps, for all $b' \in B$, give $B \otimes_A M$ the structure of a $B$-module.
(Oops, I just saw that this is exactly what you had in mind. Well, rest assured, you have the right idea.)

A: Tensor products are defined via their universal property. This means that linear maps on tensor products are defined via their corresponding bilinear maps, which makes it possible to define them just on pure tensors (and check bilinearity of course). Thus, your interpretation is correct, but this doesn't mean that the other authors are wrong.
Here is a  abstract-nonsense  method to get the module structure:
An $A$-algebra $B$ is just an $A$-module with a homomorphism $m : B \otimes_A B \to B$ with nice properties (often also including a unit $A \to B$), which are just commutative diagrams. A left $B$-module is just an abelian group $N$ with a homomorphism $\alpha : B \otimes_A N \to N$ with nice properties. Now if $M$ is a left $A$-module and $B$ is an $A$-algebra, then $B \otimes_A M$ becomes an $B$-module via
$$\alpha : B \otimes_A (B \otimes_A M) \cong (B \otimes_A B) \otimes_A M \xrightarrow{m \otimes \mathrm{id}_M} B \otimes_A M.$$
(This method has the advantage to be applicable in more abstract situations, too, where no elements are available anymore.)


text:
Q: {How/why} {could I have missed/did I miss} watching this movie till now? How/why could I have missed watching this movie till now?
OR
How/why did I miss watching this movie till now?
I'm confused about how to use this sentence. I did research on these sentences but I became confused a lot. Could anyone explain how to frame this sentence?
Thank you.

A: I would go with: "How could I have missed watching this movie until now?"
It is basically a shorter way of saying "How is it that I could have missed watching this movie until now?"
The word "why" is typically used when asking for a reason, but your sentence implies "how could this happen?", so I think "How" is a better fit.


text:
Q: Download .pdf file from web with puppeteer How can I download .pdf file from web with puppeteer? The site that I am using need cookies that must be imported before accessing.
I have already tried this:
const puppeteer = require('puppeteer');
(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('http://www.africau.edu/images/default/sample.pdf');
  await page.setCookie({
    "domain": "africau.edu",
    "hostOnly": false,
    "httpOnly": false,
    "name": "test",
    "path": "/",
    "sameSite": "unspecified",
    "secure": false,
    "session": true,
    "value": "testvalue",
    "id": 1
});
  await page.pdf({ path: 'sample.pdf', format: 'A4' });

  await browser.close();
})();

Error that I get:
C:\Users\Khaniini\project\node_modules\puppeteer\lib\cjs\puppeteer\common\FrameManager.js:194
                    ? new Error(`${response.errorText} at ${url}`)
                      ^

Error: net::ERR_ABORTED at http://www.africau.edu/images/default/sample.pdf
    at navigate (C:\Users\Khaniini\project\node_modules\puppeteer\lib\cjs\puppeteer\common\FrameManager.js:194:23)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async FrameManager.navigateFrame (C:\Users\Khaniini\project\node_modules\puppeteer\lib\cjs\puppeteer\common\FrameManager.js:170:21)
    at async Frame.goto (C:\Users\Khaniini\project\node_modules\puppeteer\lib\cjs\puppeteer\common\FrameManager.js:589:16)
    at async Page.goto (C:\Users\Khaniini\project\node_modules\puppeteer\lib\cjs\puppeteer\common\Page.js:1089:16)
    at async C:\Users\Khaniini\project\index.js:15:3

Thank you very much for your help!


text:
Q: How to make the merge query to do insert once in SQL Server I have a merge query, in which when the merge search condition is not matched the insert position id column we are generating uniquely based on the table name. For that we use a separate function for generation.
But the select statement in the merge query is executing once. So the same id is getting inserted in the table.
 declare @tenantid uniqueidentifier,
 @upid uniqueidentifier,
 @endDate datetime ,
 @pid nvarchar(14)

declare @emp table
(
    Action nvarchar(50),
    PositionId nvarchar(14),
    ReferenceId nvarchar(14)
)

set @endDate = '9999-12-31 00:00:00.000'
set @upid = 'B00D76D1-E0EF-4614-8F2C-77E01D37BFE8'
set @tenantid= 'CEA19256-7C40-40A2-A7A9-0DD5122904D6'

insert into @emp
select Action,PositionId, ReferenceId
from
(
merge hr.Position as position
using (select PositionId,CreatedBy,TenantId from upl.Employee where UploadId= @upid   and TenantId = @TenantId ) as uplEmpl
on position.ReferenceId= uplEmpl.PositionId and position.TenantId= uplEmpl.TenantId
when matched
  then update set position.LastUpdatedBy =  uplEmpl.CreatedBy,position.LastUpdatedDate= GetDate()
when not matched then
 insert   (PositionId,ReferenceId,StartDate,EndDate,CreatedBy,CreatedDate,LastUpdatedBy,LastUpdatedDa  te,TenantId)
  values((select   mst.getNextNumber('Position',null,null,@TenantId)),uplEmpl.PositionId,GetDate(),@endDate,up      lEmpl.CreatedBy,GetDate(),uplEmpl.CreatedBy,GetDate(),@tenantid)
  output $action,Inserted.PositionId,Inserted.ReferenceId)
  as changes(Action,PositionId,ReferenceId)

select * from @emp

Can anyone suggest how to make the function to execute every time when we call the insert statement in merge query

A: You are assuming the following order of events:

*

*Generate ID

*Insert

*Generate ID

*Insert

*...

But the SQL Standard says that first all values to write a calculated, then all writes are made:

*

*Generate ID

*Generate ID

*...

*Insert

*Insert

*...

Combined with the fact that functions cannot change data you cannot use this approach. Your ID generator function can only ever return the same value because it cannot record that a certain ID has been used. No matter what getNextNumber contains, it is not allowed to write.
Honestly, I'm a little out of good ideas here. Here is one that would work, though:
Insert dummy IDs, output the changes into a table variable and after the MERGE statement loop through that table to UPDATE the dummy values to use real values. Here, you can invoke side-effecting procedures. You can't do that as part of the MERGE.
Or, abandon MERGE and use a loop/cursor to do the writes. You can still perform most work as part of the cursor query and only apply the writes in a loop. A MERGE translates to a full outer join (in your case a left join is enough). You'd need to write that up yourself.


text:
Q: Group by column and add columns to count for occurences of values I have the following code:
import numpy as np
from random import randrange

groups = [randrange(1,8) for x in range(50)]
df = pd.DataFrame(groups,columns = ["group"])
df["dummy1"] = pd.Series(np.random.randint(20,size = len(df)))
df["dummy2"] = pd.Series(np.random.randint(20,size = len(df)))

Grouping the data is obvious, let's say like this:
groups = df.groupby("group").agg({"dummy1":[np.sum,np.mean]})

However i want to count the occurences of specific values in df["dummy1"] for example. And in the groups i want to have a column that shows the count for each value. For example like this:
I want to have something like this:
      dummy1            count_1 count_3
         sum       mean
group
1        128   9.846154       2       1
2         70  10.000000       4       3
3         89  12.714286       2       3
4         65   8.125000       4       4
5         93  15.500000       4       3
6         69  11.500000       3       1
7         31  10.333333       4       2

Is there any easy way to do this? I tried a solution of just adding new columns that show if the df["dummy1"] value is for example 1 and then use a sum on the column while aggregating the groups. However, this is insanely slow for even my dataset with around 100k entries.

A: You can try value_counts with groupby and then join with your groupby().agg():
groups = df.groupby("group")

(groups.agg({"dummy1":[np.sum,np.mean]})
   .join(groups['dummy1'].value_counts().to_frame('count').unstack())
)


text:
Q: How to remove/uninstall this "PASS BROW" application in Windows 10 / Google Chrome? I had a friend use my PC and suddenly, I was having to climb over his "account" when it's my PC. He had deleted the icon pic that was associated with my username, etc., so I was just trying to go back, through Google Chrome (He was using Firefox, I think).
Anyway, this "PASS BROW" app popped up, and I began to fill it in, though I don't know why.  I was tired and angry by now.  Then, I cut the machine off over night, try to get back online, and this prompt tells me I used the wrong password and my browser will now be closed for security and safety reasons.
How can I get this 'PASS BROW' off of my desktop? Its a terrible application. I am not computer savvy, obviously, and this has had me locked out of my Google for days now.
I tried uninstalling Chrome, then reinstalling but the same issue comes back.


text:
Q: retry where script/program left off in python remembering variable value I would like my script to re-try where it left off when an error occurs.  I am using selenium to download multiple reports.  Once in a while a report will not load correctly.  I want the script, on error, to remember where it was and re-try to pull the report. (I need the script to remember the value of x).
Here is some code that might help...(I desperately need help)
import time
import os
import glob
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import MoveTargetOutOfBoundsException
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException

for x in range(1, 51):
    while True:
        try:
            fp = webdriver.FirefoxProfile('C:/Users//Documents/FirefoxProfile')
            browser = webdriver.Firefox(fp)
            browser.get('https://reportlocation/')

            time.sleep(8)

            browser.find_element_by_id("ctl00_PlaceHolderMain_login_UserName").clear()
            browser.find_element_by_id("ctl00_PlaceHolderMain_login_UserName").send_keys("ytb971")
            browser.find_element_by_id("ctl00_PlaceHolderMain_login_password").clear()
            browser.find_element_by_id("ctl00_PlaceHolderMain_login_password").send_keys("Fender25")
            browser.find_element_by_id("ctl00_PlaceHolderMain_login_login").click()

#gets user to reporting front end

            ReportMgr= browser.find_element_by_partial_link_text('Report Manager')
            ReportMgr.click()

            time.sleep(5)

            CustomReport= browser.find_element_by_partial_link_text('Custom Report')
            CustomReport.click()

            time.sleep(5)

            ProgramManagement= browser.find_element_by_partial_link_text('Program Management')
            ProgramManagement.click()
            ProgramManagement= browser.find_element_by_partial_link_text('Program Management').send_keys(Keys.ARROW_LEFT)

#pulls reports

            browser.find_element_by_partial_link_text('Program Management').click()
            time.sleep(10)
            browser.find_element_by_partial_link_text('Program Management').send_keys(Keys.ARROW_DOWN * x, Keys.ENTER, Keys.ENTER)
            time.sleep(30)
            browser.find_element_by_css_selector("#ctl00_PlaceHolderMain_ReportViewer1_HtmlOutputReportResults2_CSVButton_ImageAnchor > img").click()
            time.sleep(10)
            browser.find_element_by_partial_link_text('Program Management').click()
            time.sleep(10)
            browser.quit()

            except:
                continue
            else:
                break

A: What you do here is iterate over 50 values of x, and as soon as one access fails, you recursively start iterating over all 50 values again. The repeat logic should rather look like this:
for x in range(1, 51):
    while True:  # or some condition to put a bound on retries
        try:
            ...
        except:
            continue
        else:
            break
therest()

This way, you catch each exception still inside the loop over the 50 values, and you perform retries within your running iteration so remembering the current value of x becomes a non-issue. Note the use of else with the try statement: the else clause is executed if no exception occurred; this is when you want to stop retrying with the current value of x.

A: You could write the current value of x to a file in the current directory, and then remove the file when the script is done.  When the script starts up, if the file is still there, then you know that there was an error because the file wasn't removed.  So, read the file to get x and start from there.
But overall, a better solution would be to structure your program so that the while True loop is above the for x in range loop, so breaking out of one report will naturally proceed on to the next report, instead of skipping all the remaining ones.


text:
Q: Best way to play wav files in the browser? I have no choice but to play wav files directly in the browser (serverside encoding to mp3 isn't an option, unfortunately.)
What's the best way to do this? I'd really like to take advantage of the HTML 5 audio tag but my target audience includes many, many teens using IE6. As far as I'm aware flash isn't an option, but speedy playback really is critical.
Thanks.

A: It's been a few years since the last answer. Embed tag was good but I had an issue trying to trigger it to play in JavaScript. New audio tag works well is most browsers.

<audio src="cat9.wav" preload></audio>

You can trigger it manually with audioElement.play()

A: <audio controls="controls"><source src="http://blablabla.com/hghghgh/my%20file.wav" type="audio/x-wav" /></audio>

Due to unfixed bug (issue from 2012 year?) sometimes Chromium-like browsers cannot play .wav from redirected URLs because they "think" that file size is zero. But .mp3 is OK.
Opera 12.14 and Firefox play from < audio >
tag normally in the same case (redirected URL).
I tried JPlayer's 2.9.* lib in Drupal 7 with 3 players, but not successful (was black inactive rectangle 300*14 pixels for each player).

A: Nowadays, the best way is probably just to use the HTML5 <audio> tag.  In the past, you might have done it like this:
Background:
<embed src="bgsound.wav" hidden="true" autostart="true" loop="1">

On Click:
Play Sound


text:
Q: Laravel Excel::store file empty after stored I uploaded this excel file: myExceldocument.xlsx
After uploading I want to store in a folder.
I used this method:
$uploadedFile = $request->file('files')[0]->getClientOriginalName(); //it worked

Excel::store(new DeductionsImport, $uploadedFile, 'documents');

'documents' is related to filesystem.
The excel file is correctly filed in my folder called 'documents'.
The problem is when I open it, the excel file is empty!
Do you know why ?
My goal is only upload an excel document and store in folder.

A: Excel::store is for storing exports, not saving uploaded files.
If you are simply trying to save your myExceldocument.xlsx to your documents folder, the request object has a simple method for it.
// Where 'files' is the name of the upload field in HTML.

$request->file('files')->store('documents');

A: Another example:
$fileNameToStore = $request->file('files')[0]
Storage::disk('documents')->put($fileNameToStore, fopen($file, 'r+'));

work but is not the best solution because folder is filed with '' :
$file->storeAs('',$file->getClientOriginalName(),'documents');


text:
Q: Sending SMS through gateway not working I am trying to send the messages through "email to sms" gateway for that i have the following code:
<?php
require 'mailer/PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();                            // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com';             // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                     // Enable SMTP authentication
$mail->Username = '<my-email>@gmail.com';          // SMTP username
$mail->Password = '<password>'; // SMTP password
$mail->SMTPSecure = 'tls';                  // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                          // TCP port to connect to

$mail->setFrom('<my-email>@gmail.com', 'abhishek');
$mail->addAddress('<mob-no>@bplmobile.com');   // Add a recipient

$mail->isHTML(true);  // Set email format to HTML

$bodyContent = 'Hello world';
$mail->Subject = 'Demo Subject';
$mail->Body    = $bodyContent;

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}
?>

I have got the gateway from here. I have tried all the gateways in the link, but the message doesn't seems to be deliver.

A: Email to SMS gateways are a thing of past. Today none of the providers provide email address based on number. Best solution is to use a sms gateway like twilio.


text:
Q: Find value for $x$ at a known $y$ on a line So, I have 2 points of a line $(x_1, y_1), (x_2, y_2)$ and I need to find the value of $X$ for a point on the line at a given $Y$.
Any idea how i could do that?

A: It's simple when you have an equation (in $x$ and $y$ terms) by putting value of $y$ you can get $x$ and vice versa.
How to get equation?
When you have two points in a straight line  say $(x_1,y_1)$ and $(x_2,y_2)$ we can simply make an equation with these two points in $x$ and $y$ terms.
$$y - y_1 = m (x - x_1) $$
Where $$m = \frac{y_2 - y_1} {x_2 - x_1}$$
$m$ is a slope of line.

A: $$
x = x_1 + \frac{y - y_1}{y_2 - y_1} (x_2 - x_1)
$$
This will fail if $y_2 = y_1$, but for that situation, either there's no solution or infinitely many, so you couldn't expect a single formula to work.


text:
Q: How to stack (overlap) legend items in ggplot2 I was wondering if it is possible to "stack" the items of the legend on a ggplot2 map (or any package that allows to produce the same result).
For spatial (sf, etc.) objects there is at least one package, mapsf, that produces the desired output, but I would like to produce this type of legend also for non-spatial objects (dataframes/tibble, etc.).
See here a reprex:
# A regular plot with ggplot2

library(ggplot2)

# A plot
ggplot(mtcars, aes(wt, mpg)) +
  geom_point(aes(size = drat))

# A map with the circles of the legend "stacked" (overlapping points)

# Need to conver to sf
mtcars_sf <- sf::st_as_sf(mtcars, coords = c("wt", "mpg"))

library(mapsf)

# See the legend on the top-right corner (blue arrow)
mf_map(x = mtcars_sf)
mf_map(x = mtcars_sf, var = "drat", type = "prop",
       inches = .2)

A: As Allan said, there is (to my knowledge) no general way to do this. But you can hack this together for your custom graph. Thomas Pedersen's awesome packages ggforce and patchwork are your friend.
I am essentially faking a legend. The challenge is to get the right dimensions between main plot and legend, and to stitch the legend in a reasonable way to the main plot. This is achieved by using carefully chosen radii on geom_ellipse, setting the coordinate ratio accordingly, and adjusting the coordinate limits from both plots. More comments in the code.
library(ggplot2)
library(ggforce)
library(patchwork)

## we cannot just use geom_point,
## because the size of the circles need to correspond to the legend later
## you will need to play around with this constant
r_constant <- 25
mtcars$r <- mtcars$drat / r_constant
## this is to make the points round  - it will have an effect on the panel dimension
ellipse_fac <- .1
p <-
  ggplot(mtcars) +
  geom_ellipse(aes(x0 = wt, y0 = mpg, a = r, b = r / ellipse_fac, angle = 0), fill = "darkred") +
  theme(legend.position = "none") +
  coord_equal(ellipse_fac)

## for the legend, chose rounded values from the radius range
unique_r <- unique(plyr::round_any(mtcars$r, .1))
y_circles <- floor(min(mtcars$mpg))
## I'm sorting the radii decreasingly, so that the circles overlap correctly
circles <- data.frame(x = 0, r = sort(unique_r, decreasing = TRUE))
## the segment / label poistion is also arbitrary
x_lab <- max(circles$r) + .1
y_seg <- y_circles + 2 * circles$r / ellipse_fac

p_leg <-
  ggplot(circles) +
  geom_ellipse(aes(x0 = x, y0 = y_circles + r / ellipse_fac, a = r, b = r / ellipse_fac, angle = 0), fill = "darkred", alpha = .5) +
  geom_segment(aes(x = x, xend = x_lab, y = y_seg, yend = y_seg)) +
  geom_text(aes(x = x_lab, y = y_seg, label = r), hjust = 0) +
  ## you need to set the ylimits similar to the main plot for control of legend position
  coord_equal(ratio = ellipse_fac, ylim = range(mtcars$mpg), clip = "off") +
  theme_void() +
  ## also need to set a margin
  theme(plot.margin = margin(r = .2, unit = "in"))

p + p_leg

I've added an alpha just for aesthetic reasons


text:
Q: How do I get months and years between start date and end date I'm looking for the solution for while, but i didn't get what i except.
Case : Start Date : 10/17/2017 and End Date: 02/23/2018
      From these date range I want to get months and years in a array format like following
      array 1
      - 2017
         -10
         -11
         -12
      array 2
      - 2018
         -01
         -02

Please let me know your suggestions. Thanks in advance.

A: I was intrigued so I wrote it anyway - might as well post it. Moment.js is huge overkill here.

var obj = {}, start=new Date("10/17/2017"), end=new Date("02/23/2018");
for (var i=start.getTime(), n = end.getTime(); i<=n;) { // we update i later
  var d=new Date(i), year = d.getFullYear(), month=d.getMonth()+1;
  if (!obj[year]) obj[year] = [month]; // initialise array
  else obj[year].push(month); // add to array
  d.setMonth(month); // next month
  i = d.getTime();   // here instead of in the for statement
}
console.log(obj);


text:
Q: Understanding C malloc and sbrk() I am trying to understand the difference between malloc and sbrk in C and how they relate to each other.  From what I understand malloc and sbrk are pretty much the same thing but I read that malloc uses sbrk in allocating memory.  This is really confusing can someone explain it to me?
For example in this program does malloc call sbrk? if so does it simply call sbrk each time it gets called, so for this example 10 times?
int main(int argc, char **argv) {
        int i;
        void *start_pos, *finish_pos;
        void *res[10];
        start_pos = sbrk(0);
        for (i = 0; i < 10; i++) {
                res[i] = malloc(10);
        }
        finish_pos = sbrk(0);
        return 0;
}

Thank you,

A: sbrk requests more memory from the operating system.  It is a pretty low-level function and not very flexible.
malloc uses sbrk, but is more flexible.  Generally, malloc will ask sbrk for large chunks of memory and then dole out pieces of those large chunks.  So most calls to malloc will not result in calls to sbrk.

A: malloc uses sbrk--a system call used to change the data segment
K&R C has an appendix which walks through the implementation of malloc, free using the sbrk sys call.


text:
Q: PHP function to increment variable by 1 each time script is executed Is it possible to increment a variable or array by 1 each time the script is executed.
An example would be, I execute the script and it sets a variable to $increment = '1';
I then close the script and come back 30 min later to execute the script again.
This time the variable needs to be $increment = '2';
The script will be run from cron every 30 minutes for a total of 8 times.
After the 8th execution the variable would need to be rewound back to $increment = '1';
Is this possible through session? Can session be setup for the cli sapi ?
Or would it be easier to output a text file with the next increment number and just pull the value from the text file?
All help is appreciated.

A: You will have to persist the value of the variable to a non-volatile source between calls to the script.  Furthermore, you'll have to consider race conditions if (as is often the case) the script can be called at almost the same time.
The best bet for this, is to store your variable in a database that maintains transactional safety.  Even most cheap webhosters offer some form of database that will meet this requirement ... the specifics depend on your particular setup.

A: Store the counter value in database and on execution of the script update counter with + 1
Example script
$conn = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

if($query = $conn->query("YOU ACTION QUERY HERE"))
{
    // Here you call your actions of script

    /* Increment the counter field here. */
    $conn->query("UPDATE table SET counter = counter + 1");
}

$conn->close();

Note Its simple logic to increment variable by 1 each time script is executed.


text:
Q: Flask debug depends on tkinter, sometimes When I try to import non-standard modules into my Flask app with debug mode on and run it locally, the Flask server crashes with an ImportError for _tkinter. If I remove the import for the non-standard module, or turn off debug mode, everything works as expected.
Examples
The following runs fine, and "Hello, World" can be seen at localhost:5000
from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, World"

if __name__ == '__main__':
    app.run(debug=True)

If I add the following line at the top of the file
import dateparser

I get the following Traceback when I run the file:
flask@ubuntu:~/tkerr$ python app.py
   * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
   * Restarting with stat
  Traceback (most recent call last):
    File "app.py", line 10, in <module>
      app.run(debug=True)
    File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 772, in run
      run_simple(host, port, self, **options)
    File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 622, in run_simple
      reloader_type)
    File "/usr/local/lib/python2.7/dist-packages/werkzeug/_reloader.py", line 269, in run_with_reloader
      reloader.run()
    File "/usr/local/lib/python2.7/dist-packages/werkzeug/_reloader.py", line 159, in run
      for filename in chain(_iter_module_files(), self.extra_files):
    File "/usr/local/lib/python2.7/dist-packages/werkzeug/_reloader.py", line 70, in _iter_module_files
      for package_path in getattr(module, '__path__', ()):
    File "/usr/lib/python2.7/dist-packages/six.py", line 116, in __getattr__
      _module = self._resolve()
    File "/usr/lib/python2.7/dist-packages/six.py", line 105, in _resolve
      return _import_module(self.mod)
    File "/usr/lib/python2.7/dist-packages/six.py", line 76, in _import_module
      __import__(name)
    File "/usr/lib/python2.7/lib-tk/tkCommonDialog.py", line 11, in <module>
      from Tkinter import *
    File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 42, in <module>
      raise ImportError, str(msg) + ', please install the python-tk package'
  ImportError: No module named _tkinter, please install the python-tk package

For confirmation, with debug mode turned off everything runs as expected, even if I use the dateparser module. For example, the following shows "2015-01-01 00:00:00"
import dateparser
from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
    return str(dateparser.parse("1 jan"))

if __name__ == '__main__':
    app.run()

Importing any standard Python modules, such as
import json

works fine. But any other modules installed through pip cause the same issue.
If I run (as prompted by the error)
sudo apt-get install python-tk

Then the Traceback is replaced with an ImportError for _winreg
flask@ubuntu:~/tkerr$ python app.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
Traceback (most recent call last):
  File "app.py", line 11, in <module>
    app.run(debug=True)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 772, in run
    run_simple(host, port, self, **options)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 622, in run_simple
    reloader_type)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/_reloader.py", line 269, in run_with_reloader
    reloader.run()
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/_reloader.py", line 159, in run
    for filename in chain(_iter_module_files(), self.extra_files):
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/_reloader.py", line 70, in _iter_module_files
    for package_path in getattr(module, '__path__', ()):
  File "/usr/lib/python2.7/dist-packages/six.py", line 116, in __getattr__
    _module = self._resolve()
  File "/usr/lib/python2.7/dist-packages/six.py", line 105, in _resolve
    return _import_module(self.mod)
  File "/usr/lib/python2.7/dist-packages/six.py", line 76, in _import_module
    __import__(name)
ImportError: No module named _winreg

Details
Python 2.7.7; Ubuntu 14.04 (VMWare VM); Flask/Werkzeug 0.10.1
A solution would be appreciated, but more so I'd love to gain insight into what could cause Flask to require tkinter, considering it displays all debug output from within the web browser.
edit Add output from pip freeze
Flask==0.10.1
Jinja2==2.7.3
MarkupSafe==0.23
PAM==0.4.2
Pillow==2.3.0
PyMySQL==0.6.6
PyYAML==3.11
Twisted-Core==13.2.0
Twisted-Web==13.2.0
Werkzeug==0.10.1
adium-theme-ubuntu==0.3.4
apt-xapian-index==0.45
argparse==1.2.1
beautifulsoup4==4.4.1
ccsm==0.9.11.3
chardet==2.0.1
colorama==0.2.5
command-not-found==0.3
compizconfig-python==0.9.11.3
dateparser==0.3.0
debtagshw==0.1
defer==1.0.6
dirspec==13.10
duplicity==0.6.23
feedparser==5.1.3
html5lib==0.999
httplib2==0.8
itsdangerous==0.24
lockfile==0.8
lxml==3.3.3
oauthlib==0.6.1
oneconf==0.3.7
pexpect==3.1
piston-mini-client==0.7.5
pyOpenSSL==0.13
pycrypto==2.6.1
pycups==1.9.66
pycurl==7.19.3
pygobject==3.12.0
pyserial==2.6
pysmbc==1.0.14.1
python-apt==0.9.3.5
python-dateutil==2.4.2
python-debian==0.1.21-nmu2ubuntu2
pyxdg==0.25
reporter==0.1.2
reportlab==3.0
requests==2.2.1
sessioninstaller==0.0.0
six==1.5.2
software-center-aptd-plugins==0.0.0
system-service==0.1.6
unity-lens-photos==1.0
urllib3==1.7.1
virtualenv==1.11.4
wsgiref==0.1.2
xdiagnose==3.6.3build2
youtube-dl==2014.02.17
zope.interface==4.0.5

A: I just tried running the following code on my Windows 10 machine and it worked fine for me.
Flask-Test.py
import dateparser
from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
    return str(dateparser.parse("1 jan"))

if __name__ == '__main__':
    app.run(debug=True)

I think there may be an issue with the python environment that you're currently working in. Perhaps try creating a virtual environment to operate out of using virtualenv to make sure that your environment is setup correctly.
If you would like to following along with the steps that I took to setup up a virtual environment to test the code, see below. The commands used might be slightly different when running from Ubuntu.
pip install virtualenv

Navigate to the folder where you have your test code saved and create the Virtual Environment using the following command
virtualenv env

Activate the virtual environment by navigating to the 'activate' file. In my case it was located at
.\venv\Scripts\activate

Download Flask and dateparser using pip
pip install Flask
pip install dateparser

Finally, activate the test file through the virtual environment
python .\Flasky-Test.py

Navigating to localhost returned a value of 2015-01-01 00:00:00 for me ok.
Edit
I just tried running your list of packages and managed to replicate the error that you were receiving. I believe the problem might be with the version of six that you are using. Try running
pip install six --upgrade

And let me know if that fixes the problem for you - it did for me.


text:
Q: Regex for git commit (SHA1) inside or not a markdown link I want to parse a line having the word Commits (case insensitive) followed by a colon, a possible space and either two commits hash separated by three dots or the same included in a markdown link.
For example, for the following lines:
commits:56af25a...d3fead4
Commits: [56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4)

I want to get:
56af25a...d3fead4
[56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4)

So I tested the basic expression /^commits:[ ]{0,}(.*)/i, it works but I get anything behind commits:, not just two commits.
I also tested /^commits:[ ]*([\[.*?\]\(]?\b[0-9a-f]{5,40}\b\.\.\.\b[0-9a-f]{5,40}\b[\)]?)/i but I only get the two commits, e.g.:
56af25a...d3fead4
[56af25a...d3fead4

Is it possible to achieve what I want with one regex, or is it better to have two different regex?
I only want the value after commits: if :

*

*It's two commit hashes separated by three dots: 56af25a...d3fead4

*The same thing, but as a markdown link text: [56af25a...d3fead4](anything in here)
It have to fail if there is anything before or after.
So typically the following string are bad:
Commits: [56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4) Commits:
Commits: test[56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4)
Commits: test [56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4)

A: ^commits:[ ]{0,}(?:([a-z0-9A-Z]+\.{3}[a-z0-9A-Z]+)|(\[[a-z0-9A-Z]+\.{3}[a-z0-9A-Z]+\]\(https?:\/\/\S+\)))$

Simply try this.See demo.
https://regex101.com/r/eS7gD7/9


text:
Q: Does anyone have a good java BitBuffer? I was working on a school assignment (doing Hoffman encoding) and I need some sort of bitbuffer to use to put all the bits in.  While I did find several things doing a google, most of the stuff was garbage - didn't compile, referenced other libraries I didn't have, etc.  Does anyone have an actual good bitbuffer class out there?  All that I really even want to do is read and write bits one at a time.  If nobody has a good one, is there some existing data structure that would be good for holding that sort of data efficently that I could use to write one myself?

A: I faced same problem when solving Huffman code implementation, I used this library and tested it, it works..
BitOutputStream
    import java.io.*;

/**
 * Write bits-at-a-time where the number of bits is between 1 and 32.
 * Client programs must call flush or
 * close when finished writing or not all bits will be written.
 * This class is intended to be used with BitInputStream to
 * facilitate reading and writing data in a bits-at-a-time manner.
 *

 * Updated for version 2.0 to extend java.io.OutputStream
 *

 * Any exceptions generated are rethrown as RuntimeException objects
 * so client code does not have to catch or rethrow them.
 *

 * @author Owen Astrachan
 * @version 1.0, July 2000
 * @version 2.0, October 2004
 * @version 2.1, March 2010, Fixed >> to >>> bug in writeBits
 */

public class BitOutputStream extends OutputStream
{

    private OutputStream  myOutput;
    private int           myBuffer;
    private int           myBitsToGo;

    private static final int bmask[] = {
        0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff,
        0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
        0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,
        0x7fffff,0xffffff,0x1ffffff,0x3ffffff,0x7ffffff,
        0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff
    };

    private static final int BITS_PER_BYTE = 8;

    /**
     * Required by OutputStream subclasses, write the low
     * 8-bits to the underlying outputstream
     */
    public void write(int b) throws IOException {
        myOutput.write(b);
    }

    /**
     * Create a stream that writes-through to the OutputStream object
     * passed as a parameter.
     * @param out is the output stream to which bits are written
     */
    public BitOutputStream(OutputStream out){
        myOutput = out;
        initialize();
    }

    private void initialize(){
        myBuffer = 0;
        myBitsToGo = BITS_PER_BYTE;
    }
    /**
     * Construct a bit-at-a-time output stream with specified file
     * name.
     * @param filename is the name of the file being written
     * @throws RuntimeException if opening file fails for either FileNotFound
     * or for Security exceptoins
     */
    public BitOutputStream(String filename)
    {
        try{
            myOutput = new BufferedOutputStream(new FileOutputStream(filename));
        }
        catch (FileNotFoundException fnf){
            throw new RuntimeException("could not create " + filename + " " + fnf);
        }
        catch(SecurityException se){
            throw new RuntimeException("security exception on write " + se);
        }
        initialize();
    }

    /**
     * Flushes bits not yet written, must be called by client
     * programs if close isn't called.
     * @throws RuntimeException if there's a problem writing bits
     */
    public void flush()
    {
        if (myBitsToGo != BITS_PER_BYTE) {
            try{
                write( (myBuffer << myBitsToGo) );
            }
            catch (java.io.IOException ioe){
                throw new RuntimeException("error writing bits on flush " + ioe);
            }
            myBuffer = 0;
            myBitsToGo = BITS_PER_BYTE;
        }

        try{
            myOutput.flush();
        }
        catch (java.io.IOException ioe){
            throw new RuntimeException("error on flush " + ioe);
        }
    }

    /**
     * Releases system resources associated with file and
     * flushes bits not yet written. Either this function
     * or flush must be called or not all bits will be written
     * @throws RuntimeException if close fails
     */
    public void close()
    {
        flush();
        try{
            myOutput.close();
        }
        catch (IOException ioe){
            throw new RuntimeException("error closing BitOutputStream " + ioe);
        }
    }

    /**
     * Write specified number of bits from value to a file.
     * @param howManyBits is number of bits to write (1-32)
     * @param value is source of bits, rightmost bits are written
     * @throws RuntimeException if there's an I/O problem writing bits
     */

    public void writeBits(int howManyBits, int value)
    {
        value &= bmask[howManyBits];  // only right most bits valid

        while (howManyBits >= myBitsToGo){
            myBuffer = (myBuffer << myBitsToGo) |
                       (value >>> (howManyBits - myBitsToGo));
            try{
                write(myBuffer);
            }
            catch (java.io.IOException ioe){
                throw new RuntimeException("error writing bits " + ioe);
            }

            value &= bmask[howManyBits - myBitsToGo];
            howManyBits -= myBitsToGo;
            myBitsToGo = BITS_PER_BYTE;
            myBuffer = 0;
        }

        if (howManyBits > 0) {
            myBuffer = (myBuffer << howManyBits) | value;
            myBitsToGo -= howManyBits;
        }
    }
}

BitInputStream
import java.io.*;

/**
 * Reads bits-at-a-time where the number of bits is between 1 and 32.
 * Updated for version 2.0 to extend java.io.InputStream. This class
 * can be used together with BitOutputStream to facilitate
 * reading and writing data several bits-at-a-time. BitInputStream objects
 * that are constructed from a File support reset(). However,
 * if constructed from an InputStream an object cannot be reset.
 *

 * Any exceptions generated are rethrown as RuntimeException objects
 * so client code does not have to catch or rethrow them. (Unless the extension
 * of InputStream requires throwing as another type of exception, e.g.,
 * as with method read.
 *

 * @author Owen Astrachan
 * @version 1.0, July 2000
 * @version 2.0, October 2004
 */

public class BitInputStream extends InputStream
{
    private InputStream     myInput;
    private int             myBitCount;
    private int             myBuffer;
    private File            myFile;

    private static final int bmask[] = {
        0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff,
        0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
        0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,
        0x7fffff,0xffffff,0x1ffffff,0x3ffffff,0x7ffffff,
        0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff
    };

    private static final int BITS_PER_BYTE = 8;
    /**
     * Construct a bit-at-a-time input stream from a file whose
     * name is supplied.
     * @param filename is the name of the file that will be read.
     * @throws RuntimeException if filename cannot be opened.
     */
    public BitInputStream(String filename)
    {
        this(new File(filename));
    }

    /**
     * Construct a bit-at-a-time input stream from file.
     * @param file is the File that is the source of the input
     * @throws RuntimeExceptoin if file cannot be opened.
     */
    public BitInputStream(File file)
    {
        myFile = file;
        try {
            reset();
        } catch (IOException e) {
            throw new RuntimeException("could not open file for reading bits "+e);
        }

    }

    /**
     * Open a bit-at-a-time stream that reads from supplied InputStream. If this
     * constructor is used the BitInputStream is not reset-able.
     * @param in is the stream from which bits are read.
     */
    public BitInputStream(InputStream in){
        myInput = in;
        myFile = null;
    }

    /**
     * Return true if the stream has been initialized from a File and
     * is thus reset-able. If constructed from an InputStream it is not reset-able.
     * @return true if stream can be reset (it has been constructed appropriately from a File).
     */
    public boolean markSupported(){
        return myFile != null;
    }

    /**
     * Reset stream to beginning. The implementation creates a new
     * stream.
     * @throws IOException if not reset-able (e.g., constructed from InputStream).
     */

    public void reset() throws IOException
    {
        if (! markSupported()){
            throw new IOException("not resettable");
        }
        try{
            close();
            myInput = new BufferedInputStream(new FileInputStream(myFile));
        }
        catch (FileNotFoundException fnf){
            System.err.println("error opening " + myFile.getName() + " " + fnf);
        }
        myBuffer = myBitCount = 0;
    }

    /**
     * Closes the input stream.
     * @throws RuntimeException if the close fails
     */

    public void close()
    {
        try{
            if (myInput != null) {
                myInput.close();
            }
        }
        catch (java.io.IOException ioe){
           throw new RuntimeException("error closing bit stream " + ioe);
        }
    }

    /**
     * Returns the number of bits requested as rightmost bits in
     * returned value, returns -1 if not enough bits available to
     * satisfy the request.
     *
     * @param howManyBits is the number of bits to read and return
     * @return the value read, only rightmost howManyBits
     * are valid, returns -1 if not enough bits left
     */

    public int readBits(int howManyBits) throws IOException
    {
        int retval = 0;
        if (myInput == null){
            return -1;
        }

        while (howManyBits > myBitCount){
            retval |= ( myBuffer << (howManyBits - myBitCount) );
            howManyBits -= myBitCount;
            try{
                if ( (myBuffer = myInput.read()) == -1) {
                    return -1;
                }
            }
            catch (IOException ioe) {
                throw new IOException("bitreading trouble "+ioe);
            }
            myBitCount = BITS_PER_BYTE;
        }

        if (howManyBits > 0){
            retval |= myBuffer >> (myBitCount - howManyBits);
            myBuffer &= bmask[myBitCount - howManyBits];
            myBitCount -= howManyBits;
        }
        return retval;
    }

    /**
     * Required by classes extending InputStream, returns
     * the next byte from this stream as an int value.
     * @return the next byte from this stream
     */
    public int read() throws IOException {
        return readBits(8);
    }
}

A: Look here for a bitbuffer example
http://www.javadocexamples.com/java_source/com/sun/java/help/search/BitBuffer.java.html

A: A Queue makes a good buffer (FIFO) in general. A bit can be represented using a boolean. The Queue implementation in the Java library is generic, so you could instantiate your bit buffer like this:
Queue<Boolean> bbuff = new Queue<Boolean>();
Boolean imabit = false;

You enqueue/buffer bits like this:
bbuff.add(imabit);

And you dequeue/read(and delete) the next bits like this:
Boolean dequeuedbit = bbuff.remove();


text:
Q: How to set screen resolution for ipad 3 Hey All i m bit new to ipad -3 designing. Can any one guide me how to set media queries for ipad-3.thanx in advance

A: The new iPad has the same width and height as the first and second iPad so you just need to apply the same media queries:
@media all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait) {
  .ipad-portrait { color: red; } /* your css rules for ipad portrait */
}

@media all and (device-width: 768px) and (device-height: 1024px) and (orientation:landscape) {
  .ipad-landscape { color: blue; } /* your css rules for ipad landscape */
}

A:      @media screen and (device-aspect-ratio: 3/4) {

          // your styles here
     }


text:
Q: What the part of speech of some phrases of the sentence What the part of speech of the word "open" in the next sentence:

He had only time to back away before the thick wooden doors swung open, hinges protesting loudly.

What the meaning of the second part of the sentence "hindges protesting loudly"?

A:
Hinges protesting loudly

This means that the hinges were stiff or rusted, so there was some friction or resistance when the door was opening that created some noise.

A: The second part of the sentence, "hinges protesting loudly," is figurative.
The author is personifying the hinges in order to draw a connection between the sound the hinges are making and the sound that people make while protesting. Suspense is built in this way (by using a combination of lengthy syntax and powerful imagery).
Basically, it is just a fancy way of saying the door's hinges were creaking loudly.

A: "Open" is an adjective functioning as an optional predicative adjunct.
"Swung open" entails that the door swung and it became open. "Hinges protesting loudly" means that the hinges were stiff and noisy as a result of being old and/or inadequately lubricated. –
BillJ


text:
Q: Elastic opposite query I'm using elastic search for classic queries LIKE "search all documents with G4 in name and LG in manfucaturer". This is ok. But what if I have a lot of documents and database with lot of search terms and I need to know which documents match some specific multicolumn terms. For example:
Documents:
[
    {
     "id": 5787,
     "name": "Smartphone G4",
     "manufacturer": "LG",
     "description": "The revolutionary LG G4 design can only be described as forward thinking—with a classic touch."
    },
    {
     "id": 68779,
     "name": "Smartphone S6",
     "manufacturer": "Samsung",
     "description": "The Samsung Galaxy S6 is powerful to use and beautiful to behold."
    }
]

...
Terms:
[
   {
     "id": "587",
     "name": "G4",
     "manufacturer": "LG",
     "description": "classic touch"
    },
    {
     "id": "364",
     "manufacturer": "Samsung",
     "description": "galaxy s6"
    }
]

...
Result:
{
  "587": [5787],
  "364": [68779]
}

OR:
{
  "5787": [587],
  "68779": [364]
}

I need list of documents and list of terms which corresponds them (or oposite). In small amount of terms, it should be possible to apply all rules one by one and save matching documents. But I have milions of documents and thousands of terms. So, it is not possible to aply them one by one. Is it possible in another way?

A: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-percolate.html is exactly what I wanted. It can store your queries and execute them against documents.


text:
Q: Show multiple Ajax html response The $('.my-button').click(function(e) function is supposed to show the output of the display.php, which just contains some mysql query and the output in html.
It works so far, but as I am looping the button itself for each post, the function only works for the first button. I need to make the script understand, that for each button it should only show the results for that button. But how to insert some individual ID to the $(".responsecontainer").html(response);? I tried with $(".responsecontainer" + id).html(response); getting "id" before via parameters, but it seems that this id must be hardcoded.
Here is the full code:
$(document).ready(function() {
$('.my-button').click(function(e) {
  $.ajax({    //create an ajax request to display.php
    type: "GET",
    url: "display.php",
    dataType: "html",   //expect html to be returned
    success: function(response){
        $(".responsecontainer").html(response);
        //alert(response);
    }

And this is the button and DIV to show results:
<input type="button" class="my-button" value="'.$plus.'" />

Noting that $plus is always unique.

A: *

*Use data-attributes to store the related DIV's id.

*When a button is clicked get the data-attribute, i.e: data-target-id.

*With that id you can execute a selector as follow: #div_1 and insert the received HTML.

*DON'T use value to target your DIV, the button's value is the text for your buttons, just imagine if your button texts are filled using a kind of i18n translation.

$(document).ready(function() {
  $('.my-button').click(function(e) {
      var targetId = $(this).data('target-id');
      /*$.ajax({ //create an ajax request to display.php
          type: "GET",
          url: "display.php",
          dataType: "html", //expect html to be returned
          success: function(response) {*/
            $(`#${targetId}`).html(`Response = ${targetId}`);
          /*});
      });*/
  });
});

<input type="button" data-target-id='div_1' class="my-button" value="Click me!" />

<input type="button" data-target-id='div_2' class="my-button" value="Click me!" />

<input type="button" data-target-id='div_3' class="my-button" value="Click me!" />

A: Since the value of the button and the id of the div are the same ($plus) just capture the button's value and use that to tell you which div to update:
$('.my-button').click(function(e){
    e.preventDefault();
    var buttonVal = $(this).val(); // the value of the button which should match the id of the container to be updated
    var response = 'button ' + buttonVal + ' clicked';
    $('#' + buttonVal).html(response);

})

Here is a an example.
Assuming the button is a sibling of the div (as stated in comments) the code becomes this, with no id needed for the div:
$('.my-button').click(function(e){
    e.preventDefault();
    var buttonVal = $(this).val(); // just using this to get something to display
    var response = 'button ' + buttonVal + ' clicked'; // same here
    $(this).next('div').html(response);

})

Here is that example.


text:
Q: Import BACPAC into an _existing_ database Is there a way to import a BACPAC file into an existing (empty) database? It looks like the PowerShell commands allow me to create new target databases only...
Is there a trick?

A: Yes you can import BACPAC file to an existing db but it should be absolutely empty.
Use below command, run it from cmd or powershell. Note : location of sqlpackage.exe could be different on your machine.
/tdn: is target database name here, which could be a pre-existing db but totaly empty. It's a good practice to create db before hand for larger db imports. SQL package.exe does make a new db for you if your db does not exists but then it caps its maximum size to 32gb unless specified otherwise.
c:\"Program Files"\"Microsoft SQL Server"\150\DAC\bin\sqlpackage.exe
    /a:Import
    /sf:"bacpac file path"
    /tsn:"targetsqlserver.database.windows.net"
    /tdn:target_database_name
    /tu:username
/tp:password

A: It is not possible to import or restore a bacpac to an existing Azure SQL Database. It will always create a new database.
Drop the existing database and rename the database resulting from the imported bacpac, or drop the database and import the bacpac using as database name the name of the dropped database.


text:
Q: Is there any way I can read environment name in .Net core 3.1 console app? I have a .Net core 3.1 Worker service but whenever I am running it I am getting environment name as "Production" and it's taking appsettings.json as its file to read configs from. I want to deploy this service to Windows server where I have added ASPNETCORE_ENVIRONMENT variable as "SIT" (Test environment) but still it uses appsettings.json and not appsettings.SIT.json.
I had same issue with my API project but there is used dotnet cli to publish and it made environment entry in web.config which worked for me. This is a console app.
Command which I used for api:
dotnet publish /p:Configuration=Release /p:EnvironmentName=SIT

Find below the code which i used to read environment name.
public static string CURRENT_DIR = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

    static void Main(string[] args)
    {

        var builder = new ConfigurationBuilder();
        BuildConfig(builder);
        CreateHostBuilder(args).Build().Run();

    }

static void BuildConfig(IConfigurationBuilder builder)
        {
            builder.SetBasePath(CURRENT_DIR)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{ Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
                .AddEnvironmentVariables();
        }

   public static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
        .UseWindowsService()
    .ConfigureServices((hostContext, services) =>
    {
        IConfiguration Configuration = hostContext.Configuration;

        var collection = new ServiceCollection();
        collection.AddOptions();
        collection.Configure<AppOptions>(Configuration.GetSection("AppOptions"));

        services.AddHttpContextAccessor();
        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
        var env = serviceProvider.GetRequiredService<IHostEnvironment>();
        ConfigureLogging(env);


text:
Q: Complex projective manifold with an antiholomorphic involution Let $M$ be a complex projective manifold with an antiholomorphic involution. Can $M$ be defined by equations with real coefficients then?

A: Corrected. As Robert Bryant points out, it is not enough to show that the manifold can be realised as a submanifold of $\mathbb CP^n$ invariant under some anti-holomorphic involution of $\mathbb CP^n$. For this reason the answer is extended.

Let $\sigma: M\to M$ be the anti-holomorphic involution. Take a very ample divisor $D$ on $M$, and consider the linear system $|D+\sigma(D)|=\mathbb P_{\mathbb C}^n$. It is invariant under $\sigma$ and $\sigma$ induces on it an anti-holomorphic involution. Now, we have the embedding $M\to \mathbb P_{\mathbb C}^{n *}$ that is invariant under the induced action of $\sigma$.

However, being invariant under an anti-holomorphic involution of $\mathbb CP^n$ doesn't mean being defined by equations with real coefficients (as Robert points out).
So to answer the question, we need to solve additionally the following exercise:
Exercise. Suppose we have $\mathbb CP^n$ with an anti-holomorphic involution $\sigma$. Find an embedding $\mathbb CP^n\to \mathbb CP^N$, such that the image is invariant under the real involution of $\mathbb CP^N$ and the real involution induces $\sigma$ on $\mathbb CP^n$.
Solution. Let us show first how to do this for $\mathbb CP^1$ with the antipodal involution (the example proposed by Robert). Here we can embed it in $\mathbb CP^2$ with equation $x^2+y^2+z^2=0$.
As for general case we note the following. On an even-dimensional space each anti-holomoprhic involution is conjugate to the usual complex conjugation $(z_1:\ldots :z_{2n+1})\to (\bar z_1:\ldots :\bar z_{2n+1})$. So we don't need to do anything if $n=2m$. On the other hand, on odd dimensional projective spaces there is one more type of anti-holomorphic involutions, namely $$(z_1:\ldots: z_m:z_{m+1}:\ldots: z_{2m}\to (-\bar z_{m+1}:\ldots: -\bar z_{2m}: -\bar z_1:\ldots: -\bar z_m ).$$
So we just need to take some Segre embedding of $\mathbb CP^{2m-1}$ into an even dimensional projective space. For this we need to find $k$ such that ${2m+k-1}\choose{k}$ $-1$ is even. This can always be done.


text:
Q: Webpage view source has body content as 'please wait' and selenium is unable to load any elements I've a webpage where if I use inspect element (or inspect frame), I get only 'Please wait, this page is loading...' even though the chrome page is completely loaded (and the frame is also loaded completely). I've clicked on Inspect element after the page load and when querying in 'console', I get the html elements (see in screenshot).
While checking in selenium with below code, the returned list value is empty (because the page source has only 'please wait...' message???) even though the console returns the elements.
Is there a work around? I know I'm missing something but have spent about 2hrs already. So, reaching out to you guys.
Inspect Element (Ctrl+Shift+I)

View Source (Ctrl+U)
<!DOCTYPE HTML>

<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="UTF-8">
<meta name="viewport"
    content="width=device-width, initial-scale=1, maximum-scale=10, user-scalable=yes">

Please wait, this page is loading...

Selenium Script
List<WebElement> tiles = driver.findElements( By.className("swiftux-tiles"));

System.out.println("Tiles value "+ tiles);

[Update for @Dev]
Code
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class testSelenium {

    public static void main(String[] args) throws Exception {
        String url = "";
        System.setProperty("webdriver.chrome.driver", "\\Desktop\\Mathes\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get(url);
        String currentURL = driver.getCurrentUrl();
        System.out.println(currentURL);
        driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
        System.out.println("Page Source: \n "+driver.getPageSource());
        List<WebElement> tiles = driver.findElements( By.className("swiftux-tiles"));
        System.out.println("Tiles List"+ tiles);
    }
}

Console Output
Starting ChromeDriver 2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9) on port 14929
Only local connections are allowed.
May 02, 2017 5:42:23 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
May 02, 2017 5:42:26 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS

Page Source:
 <!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=10, user-scalable=yes" />

<title>CITI Workflow Management</title>

Please wait, this page is loading...

Tiles List[]

Update for Kushal


text:
Q: Highlighting selected div with JavaScript I would like to know how to use jquery or JavaScript to apply a onclick event that highlights the selected div and highlights the others..
I have a dynamic row of names the user can click to view selected messages, When the user clicks the selected name the name will be highlighted with a border... Is there a simple way to achieve this sort of event without having to go through the following.

function swapme(foo) {
  buttons = new Array();
  buttons = document.getElementsByTagName('a');
  for (i = 0; i < buttons.length; i++) {
    if (buttons[i].className === 'active') buttons[i].className = 'inactive';
  }
  document.getElementById('button' + foo).className = 'active';
}
.inactive {
  background: #666;
  border: 1px solid #000;
  color: #FFF;
  padding: 12px
}

.active {
  background: #0F0;
  border: 1px solid #F00;
  color: #F00;
  padding: 12px
}

    1
    2
    3
    4
    5

If there is a simple work around please advise, as in maybe a toggle event or a on change.
also possibly without having to go through an array loop..

A: Try this:

let links = document.querySelectorAll('a');
   for (var i = 0; i < links.length; i++) {
    links[i].addEventListener('click', activateClass);
   }
function activateClass(e) {
for (var i = 0; i < links.length; i++) {
    links[i].classList.remove('active');
   }
    e.target.classList.add('active');
}
.active { background:#0F0 ; border:1px solid #F00 ; color:#F00 ; padding:12px }

    1
    2
    3

A: You can remove the loop by usingdocument.querySelectorAll().
You can implement something like the following:

*

*when clicking on one of the names

*get the current active

*remove the active class from the current active

*add active class to the clicked element

This way you don't need to iterate over all buttons.
Note that you can use addEventHandler to add all handlers at once instead of an onclick in the html. This should make the code less coupled and easier to maintain.

function swapme(event) {
  // Get current active element(s)
  document.querySelectorAll('.active')
    // Remove active class
    .forEach(e => e.className = 'inactive');
  // And add the active class to the event target.
  event.target.className = 'active';
  // Prevent default link hanlding
  event.preventDefault();
}

document.querySelectorAll('#container > a')
  .forEach(button => button.addEventListener('click', swapme));
.inactive {
  background: #666;
  border: 1px solid #000;
  color: #FFF;
  padding: 12px
}

.active {
  background: #0F0;
  border: 1px solid #F00;
  color: #F00;
  padding: 12px
}

    1
    2
    3
    4
    5


text:
Q: Running MVC application under Cassini I am trying to run Asp.Net MVC applications using Cassini but when i launch my application, all I get is directory listing and not the results of my default controller/action.
What I am I missing?
I need to mention that WebForms apps are running fine.

A: Do you have any good reason for using standalone cassini ? I am not quite sure how "registration" of MVC stuff (route handlers, httphandler.. ) works with it - maybe it knows only about handlers for webforms. Do you know about the new IIS Express ? very lightweight and powerfull, full compatibility with IIS, maybe you could try it instead.


text:
Q: disadvantage of dividing fortran code into subroutines and its effect on speed? I have a Big FEM code. I have divided it into subroutines so it could further be sectioned and changed. My question is: why speed got slow.

*

*Speed got slower when i divided code into subroutines

*It got further slower when number of arguments were decreased (rearanged inside subroutine with extremely small computation).

Can somebody help me with some suggestions, how to optimize a fortran program when it is divided into subroutine. especially when that subroutine is called in a big loop.

A: When a large monolithic code is divided into several parts, each of which is called perhaps millions of times, the overhead cost of calling each subroutine or function is in general, non-negligible (regardless of the specific programming language used), unless the compiler(linker) can automatically in-line those functions. I suspect this lack of in-lining by the compiler is the source of significant slowdown that you observed in your codes. With regards to your question number 2, I could not understand it. Perhaps a minimal working example code would be helpful, as @VladimirF and @HighPerformanceMark suggested.

A: Identifying the cause can be difficult, as can identifying the occurrence of this type of problem.
I suspect that the cacheing of code can improve performance, so that if related routines are spread throughout memory, there "may" be a performance penalty.
Identifying cache related delays is difficult to achieve.
If this is an explanation, then changing the order of routines being added while linking could show some change. Examples of this possible approach are including ddotp near equation reduction and daxpy near equation back substitution could be effective.
Effectively this approach is to link inner loop routines near the calling routine. When developing code, this is often the case.
You have not indicated your approach to linking order; alphabetical would be a bad approach based on this assumption.
FEM code is better described as polylithic, so this approach should be available. I have experimented with multiple versions of high usage utility routines, placing them in the code, such as duplicate equation solvers for Eigen subspace iteration or direct integration solutions, where inner loops are a high proportion of the solution time.
Experimenting with processors with different memory speed/bandwidth or cache size could provide an interesting comparison.
However, cacheing strategies for memory management to partition arrays should be more productive than experimenting with linking order.
Another issue relates to if the compiler optimises routine calls or if it inlines some trivial routines. You have not indicated your compile options or compiler to identify if this is a possibility.
I hope this answer provides some possible areas to investigate further, while providing no definite explanation for your problem.


text:
Q: Getting an "Enumeration values 'x', 'y' and 'z' not handled in switch" message when, in fact, these enumerations are being handled. What's going on? I have an enumeration defined as such:
//ModelClass.h
typedef enum { Automatic, Manual, Off } MyModes;

Later, in a ViewController, I have a switch statement within a method that switches on a variable of my enumeration type.  My switch statement looks as follows:
//MyViewController.m
#import "ModelClass.h"

-(void) dryer:(MyClass *)m didChangeMode:(MyModes) newMode
{

    //Code within an instance method, utilizing the above enumeration
    switch (newMode) //newMode is an instance of MyMode enum.
    {
    case Automatic:
        //Some code...
        break;
    case Off:
        //Some code...
        break;
    case Manual:
        //Some code...
        break;
    }
}

The above switch statement was copy/pasted from my code and all I did was replace the functional code with the //Some code... comments.
XCode keeps giving me a warning at the switch (newMode) line stating "Enumeration values 'Automatic', 'Manual', and 'Off' not handled in switch".
Furthermore, at each case statement, I'm getting an error stating "Expression is not an integer constant expression", even though it should be since it's an enumeration.
How can I fix this?  The odd thing is that I have another enumeration in the ModelClass header (consisting of 4 enumerated items) defined on the following line after MyModes enumeration and, in my view controller, I have another method that is doing the exact same type of switch/case operation.  I am not getting a single warning or error on that method, using that enumerator.
What could be going on?
EDIT
I put the method declaration within the code snippet.  The newMode variable is a parameter to the method.  Furthermore, the aforementioned, other enumerator that is working correctly is also being passed into the other method as a parameter.

A: With the help of both Keith and Micheal in the comments above, I have been able to solve this problem.  At Keith's suggestion, I am answering my own question.
This problem was my own fault because I had defined a few buttons within my ViewController, each respectively named Automatic, Manual and Off. The compiler assumed I was referencing my UIButtons and not the enum type because those were local-scope variables.
Renaming the enumerated values and updating the code fixed this bug.  In my case, I redefined my enumeration as such:
typedef enum { AutoMode, ManualMode, OffMode } MyModes;


text:
Q: How to exit a function without returning a value Suppose I have a function that returns a certain value when it satisfies a given condition and does not return any value when the condition is not satisfied.
e.g.
fun foo(n)= if n< 100000 then n else (something like exit function. We have it in other programming languages. Do we have something like that here?)
I initially wanted to write () but it says mismatch in two conditions of if or something.
Becoming more explicit, I want to write a function that takes a number, any number and combines to a list if it is valid integer and disregards it if it is not integer.

A: In SML a function always has to return a value¹. One way to represent a function that may or may not have a useful result would be using the OPTION type. Using OPTION your function would return SOME value if it has something useful to return, or NONE if it does not.
For your particular use-case another alternative would be to take the list as a second argument and then either return the result prepended to the list or the list unchanged.
¹ In fact I'm not aware of any language where a non-void function is allowed to not return a value (without invoking undefined behavior). In some languages you can return null in place of a proper return value, but in most languages that isn't allowed for functions with return type int. Either way SML doesn't have a null value.

A: fun foo n = if n < 1000000 then SOME n else NONE

beware that you can't use foo n directly as an integer but you have to use isSome and valOf or pattern matching to know in which case you are.
May be it would be better to pass your list as an argument and to append the value to it.
fun foo (n: int, xs: int list) =
   if n < 1000000 then n :: xs else xs


text:
Q: unicode-math gobbling up glyphs from other package I would like Times New Roman as my default font for text and mathematics, and after having tried out several I've found TeX Gyre to have the best coverage. But by using unicode-math for the mathematics, it seems to cause the lilyglyphs package not to display its symbols.
The documentation for the latter requires fontspec to be loaded which, if called with the no-math option, produces an error.
Compiling the below MWE using lualatex.
\documentclass{article}

\usepackage{unicode-math}
\usepackage{fontspec}
\usepackage{lilyglyphs}

\setmainfont{Tex Gyre Termes}
\setmathfont{TeX Gyre Termes Math}

\begin{document}
  6
  \sharp{} %from lilyglyphs
  $\widehat{6}$
\end{document}

The MWE includes the Times New Roman numeral but no lilyglyph. The \widehat is also wonky:

Commenting out unicode-math and \setmathfont shows the lilyglyph correctly and the widehat is correct too, but the numeral is no longer Times New Roman (of course):

My desired output is the second picture but with both numerals in Times New Roman. Is this possible?

A: The accent position seems to be just a feature in the font (you see same position without lilygyphs) I shifted it a bit here (actually it is shifted too far I think).
The \sharp goes as unicode-math delays all its definitions until begin document and TeX Gyre Termes Math does not have the character, you can re-instate the lilyglyphs version.

\documentclass{article}

\usepackage{lilyglyphs}
\let\zzzsharp\sharp
\AtBeginDocument{\let\sharp\zzzsharp}
\usepackage{unicode-math}

\setmainfont{Tex Gyre Termes}
\setmathfont{TeX Gyre Termes Math}

\begin{document}

  6
  \sharp{} %from lilyglyphs
  $\mkern-1mu \widehat{\mkern1mu6}$
\end{document}


text: Q: Pandas dataframe plot has "None, None" on the legend. How to get rid of them? see attached picture. When I generate pandas dataframe plot, I see "None, None" on the legend. How to get rid of them?enter image description here


text:
Q: Ever any performance different between Java >> and >>> right shift operators? Is there ever reason to think the >> (signed) and >>> (unsigned) right bit-shift operators in Java would perform differently? I can't detect any difference on my machine.
This is purely an academic question; it's never going to be the bottleneck I'm sure. I know: it's best to write what you mean foremost; use >> for division by 2, for example.
I assume it comes down to which architectures have which operations implemented as an instruction.

A: No.
Your compiler will translate these to bytecode and the JVM will interpret the bytecode for your architecture. I think it is safe to assume that your architecture has an instruction set which includes both operations be done in few clock cycles.
Anyway, there is a difference in the behavior of these operators, so it isn't like you can just interchange them.


text:
Q: Force DecimalFormat to throw ParseException if not all the string is parseable I want to configure my DecimalFormat instance so that it fails to parse a string if not all the string is parsable.
If I run the below code, the output I get is:

I could parse the string, and the result is: 2000

However I would like it to throw an exception because it contains non-digits: MMM
public static void main(String[] args) {
    try {
        DecimalFormat df = new DecimalFormat();
        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        symbols.setDecimalSeparator(',');
        symbols.setGroupingSeparator('.');
        df.setDecimalFormatSymbols(symbols);
        Number n = df.parse("2.000.MMM,77");
        System.out.println("I could parse the string, and the result is: " + n);
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
}

A: You could add yourself a little utility method like this:
    private static Number parse(DecimalFormat df, String input) throws ParseException {
        final ParsePosition position = new ParsePosition(0);
        final Number result = df.parse(input, position);

        if (position.getErrorIndex() != -1) {
            throw new ParseException("could not parse input='" + input + "'", position.getErrorIndex());
        } else if (position.getIndex() < input.length()) {
            throw new ParseException("input='" + input + "' wasnt processed completely", position.getIndex());
        }

        return result;
    }

It will throw an exception if the input wasnt processed completely
You could also extend DecimalFormat and add the above method like so:
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.ParsePosition;

public class ThrowingDecimalFormat extends DecimalFormat {

    public Number parseSafe(String input) throws ParseException {
        final ParsePosition position = new ParsePosition(0);
        final Number result = parse(input, position);

        if (position.getErrorIndex() != -1) {
            throw new ParseException("could not parse input='" + input + "'", position.getErrorIndex());
        } else if (position.getIndex() < input.length()) {
            throw new ParseException("input='" + input + "' wasnt processed completely", position.getIndex());
        }

        return result;
    }
}