Document has been modified or corrupted since signed! (data)

Question: I'm working in HCL Notes application. I have developed a summary view to show calculated figures to the user. Then the user clicks one of the action buttons and I open a detailed view, but for that view I setup Selection Formula on the fly so that it shows the records filtered specific to that button conditions. It was working almost fine for a few days, but now most of the time it shows some previously shown (filtered) data no matter what button the user has clicked. Means it doesn't set the Selection Formula of the view and shows the view with the old formula and it won't get back to normal condition even if they restart Notes application.
When the user is stuck in this particular condition, and they peep through the status bar it shows this message:
Document has been modified or corrupted since signed! (data).
The necessary code-snippet is as below:
*Set dtlView = db.GetView("Report_Dtl")
dtlView.SelectionFormula =formula
Call dtlView.Refresh()*
where formula is the dynamically built formula. Looks like the line
dtlView.SelectionFormula =formula
is unable to update the selection formula and then the line below generates the above error message:
Call uidb.OpenView(dtlView.Name,,False, False)
Please help!
Thanks
Answer: For "on the fly" modification of the view selection formula your user need "Designer"- access to the database, and that is never a good idea. The help document to the function you are using is explicitly stating that this is not a good idea (emphasise of mine):

This is not a good way to display a selected set of documents for a specific user. When you use this property to change the view selection, it applies to all users of the view.
There are problems with using this method to make a view display a new selection of documents for an end user:
Do not give end-users Designer access to an application.
If it is a shared view, users will interfere with each other's searches.
The Notes® client caches design information, and there's no way to tell it to update its cache (except for outlines). Exiting and re-entering the application usually works, but it's hard to programmatically ensure the user exited the application entirely.

In addition the modification of the view selection formula can break the signature of the design element and then other errors occur.
Better use another approach:

Use a Folder for every user and put the selected documents in there (after doing a NotesDatabase.Search with the formula
Use a separate view for every user and let a server agent manipulate its selection formula with a user that has access.

For having a separate view / folder for every user you could use "Shared, Private on first use"- views (they are not easy to maintain), or any process that generates them and is able to assign every view to the users they belong to... in both cases this needs some effort, but at least it will work.
Comment: Sorry for being too much late in responding, in fact I have provided my user with some work around by providing a 'clone' of the same view when the original view fails because of the mentioned issue. This somehow gives them some 'relief' at least, though i have to change the code a bit to point to the other view if this condition is reported to occur.
Comment: There's only one user for this view but the problem is that I have to provide filter  based on the selected row and column. For each column I have provided an action button at the top, so I can make a separate view for each column. That makes it quite simple to get rid of "Document has been modified or corrupted...", BUT, I also have to provide (dynamic) filter on the plot size (determined by the selected row). There are about 14 various plot sizes. So If I choose to build views for each scenario, I have to build 14 (rows) * 9 (columns)  = 126 separate views which is not a good solution.
Comment: Still: You continue to produce problems that arise from your broken design... redesign your feature to use a folder and you will not need hundreds of views to handle this...


Powershell find the name of a user that created the account

Question: I would like to filter for a  username based on the account that was created
For example email@example.com is the username
Currently I have the following code
Get-WinEvent  -FilterHashtable @{logname='security';id=624;firstname.lastname@example.com'}

The notes I'm working from say that account creation is Event IDs 624, 626
However I'm unable to return the above filter successfully
How is it possible to filter for a username associated with an account that was created ?
I have also tried the following which shows me account creation date but not the user who created it .
Get-EventLog  -FilterHashtable | Where-Object { $_.EventID -eq 4720 }:

Thanks
Comment: I rolled back your question to edit 2, since you removed a big chunk of your question. Even if something doesn't work it is nice to see what you have tried. Future readers might see this and say that "yes, this is exactly what I did" and know that they are reading a question related to their issue.
Answer: 624 is the ID for the "user account was created" event prior to Windows Vista, 4720 is the ID for the same event in Windows Vista and newer. According to this article you should be able to extract the information who created the new account from the event message:
Subject:
          Security ID:             TESTLAB\Santosh
          Account Name:            Santosh
          Account Domain:          TESTLAB
          Logon ID:                0x8190601

New Account:
          Security ID:             TESTLAB\Random
          Account Name:            Random
          Account Domain:          TESTLAB

Attributes:
          SAM Account Name:        Random
          Display Name:            Random
          User Principal Name:     firstname.lastname@example.com
...
Something like this should work:
$upn = 'email@example.com'

Get-WinEvent -FilterHashtable @{LogName='Security';Id=4720} |
  Where-Object { $_.Message -match "user principal name:\s+$upn" } |
  Select-Oject -Expand Message |
  Select-String '(?<=subject:\s+security id:\s+\S+\s+account name:\s+)\S+' |
  Select-Object -Expand Matches |
  Select-Object -Expand Value

Comment: @NivekDefend Working _how_? While this answer may have provided the crucial pointer, it would still be helpful to see a complete solution, especially since you've removed your solution attempt from your question.
Comment: @mklement0 I think I can help with that ;)


how to implement Speech To Text using python houndify?

Question: I am new to houndify,i have been creating STT(Speech To Text) process.i have an idea to create it using python.I choosed houndify python 2.7 SDK.I have got the client id and client key of houndify service.So how can i proceed to Speech To Text conversion?.Please solve it in step by step process?
Answer: The Python SDK contains two sample scripts that show how to send voice queries to Houndify: sample_stdin.py and sample_wave.py. Regardless of the source of audio, the steps are following:

initialize houndify.StreamingHoundClient object with clientID, clientKey and some userID (can be "test_user" during development, but ideally should correspond to your enduser)
extend houndify.HoundListener class
pass the instance of your listener to StreamingHoundClient object's start() method
read audio chunks (8/16 kHz mono 16-bit little-endian PCM samples) in a loop and feed it into client: client.fill(samples)
call client.finish() after streaming is done

You can find more details about the SDK (including information about setting request info fields) here:
https://docs.houndify.com/sdks/docs/python .
Here's a simple script that reads audio from stdin and just prints partial transcripts, final response or error message:
import sys
import houndify

class MyListener(houndify.HoundListener):

  def onPartialTranscript(self, transcript):
    print "Partial transcript: " + transcript

  def onFinalResponse(self, response):
    print "Final response: " + str(response)

  def onError(self, err):
    print "Error: " + str(err)

client = houndify.StreamingHoundClient(<CLIENT_ID>, <CLIENT_KEY>, "test_user", sampleRate = 8000)

BUFFER_SIZE = 512

client.start(MyListener())

while True:
  samples = sys.stdin.read(BUFFER_SIZE)
  if len(samples) == 0: break

  finished = client.fill(samples)
  if finished: break

client.finish()


Getting width of LinearLayout in my getView method

Question: I want to get the width of a LinearLayout element in my getView method of my custom adapter. My getView method looks like this:
@Override
    public View getView(int position, View v, ViewGroup parent) {
        View mView = v;

        if (mView == null) {

            LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            mView = vi.inflate(R.layout.levelselector_item, null);

        }
if (mView != null) {
...
LinearLayout ln = (LinearLayout) mView.findViewById(R.id.lineScore);
            LinearLayout lnTotal = (LinearLayout) mView.findViewById(R.id.lineScoreTotal);
int widthTotal = lnTotal.getWidth()/2;
                ln.getLayoutParams().height = 3;
                ln.getLayoutParams().width = widthTotal;
                ln.requestLayout();
                ln.setBackgroundColor(Color.parseColor("#eef05e"));

}
        return mView;
    }

The problem my widthTotal doesn't seem to have a value. If I click on an item of the gridview and hit the back button, then I suddenly see a yellow bar. If I enter ln.getLayoutParams().width = 20; he also shows a yellow short bar. I just don't know when or where I can get the width of the LinearLayout...
Answer: It looks like you are trying to set the dimensions of the lineScore view to be 3 pixels high and half the width of the lineScoreTotal view. Unfortunately, you can't do it like this—the getView code is executed before the view is attached to the activity's view hierarchy, so there is no size defined for anything.
One approach is to define your own custom view and override onMeasure as suggested in this thread. This is perhaps the cleanest way.
Another is to try to query the parent view for its dimensions; account for padding, etc.; and then construct appropriate width and height measure specs and lay out mView before trying to query for the dimensions.
Another is to create a layout that divides up the total width into the desired proportions. Since you haven't posted your layout, I can't suggest anything specific. If the container for the row is a vertical LinearLayout, for instance, you could do something like this::
<LinearLayout
     android:orientation="vertical"
     . . . >
     . . .
    <LinearLayout
         android:orientation="horizontal"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content">

         <View
              android:layout_width="0dp"
              android:layout_height="3dp"
              android:layout_weight="25" />
         <View
              android:layout_width="0dp"
              android:layout_height="3dp"
              android:layout_weight="50"
              android:background="#eef05e" />
         <View
              android:layout_width="0dp"
              android:layout_height="3dp"
              android:layout_weight="25" />
    </LinearLayout>
    . . .
</LinearLayout>

This is not particularly efficient (using three extra views), but it lets you do everything in XML. If you are targeting API level 14 or above, you can also use the Space view to provide spacing.
EDIT
Here's code that outlines what I mean by "query the parent view...":
int availW = parent.getWidth() - parent.getPaddingLeft() - parent.getPaddingRight();
int widthSpec = MeasureSpec.makeMeasureSpec(availW, MeasureSpec.AT_MOST);
// similar for height
mView.measure(widthSpec, heightSpec);
mView.layout(0, 0, mView.getMeasuredWidth(), mView.getMeasuredHeight());
// now you can query the width of `mView`

I have not tested this, so I can't warrant that it will work, but this is the idea.
Comment: What do you mean exact with query the parent view for its dimensions? What I do know, is that the width of the linearlayout = mView.getWidth - (2*20dp), but I dont know if I can go from dp to px? Maybe that is also a solution (or maybe you ment that? :))
Comment: @JackCommonw - I was referring to the third argument passed to `getView`. This is the view that will become the parent to the view that `getView` returns.
Comment: I'm sorry, but I still don't know what you mean by "querying the parent view for its dimensions" and to layout the mView with proper width and height specs... can you explain a little bit more about this? Do you think my solution above could work?
Comment: I tried this:

    int test = mView.getWidth();
    Resources r = C.getResources();
    float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
    int submit = (test - (2*(int)px))/2;
But then I get an error. I'll try your method
Comment: @JackCommonw - The easiest thing is to define your own custom view that lays itself out appropriately (or, better yet, just draws appropriately).
Comment: Ok, is it possible to pass a variable width to this custom view then? Its just my first app and never made a custom view before.. Maybe you know a good tutorial on this? Thanks!
Answer: Instead of setting the dimensions in code you can do it in XML. You can use LinearLayout weight property to get "half" parent width. e.g.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:weightSum="2" >

    <View
        android:layout_width="0dp"
        android:layout_height="3dp"
        android:layout_weight="1"
        android:background="#eef05e" />

</LinearLayout>

Comment: I assume you know what percentage or fraction of parent width you need. Define the weightSum on the parent, to say 100. And set the weight of the child in code after you inflate the XML, to that percentage value.
Comment: The width is dynamic... Not in my example but it will be based on the width of the LL
Comment: you mean width need not be half of the parent width? In that case you can set the weight in code.
Comment: No I just divided it by 2 in this example, but actually it will be (anothervalue / the totalwidth which I need to retrieve ) * 100.. I can't get it to work... still not
Comment: Well what does the parent exactly tell me? I know that comparing to the eventual view of the item in the gridview, the width of the bar (the linearlayout I am using right now) will be starting from the left (left margin = 20dp) and can have a maximum until it reaches a margin to the right of 20dp.
Answer: I don't think you can get the width of the view before you set the layout(R.layout.levelselector_item ) on the screen. It should return 0.
Comment: How do you mean? The R.layout.levelselector_item is called: if (mView == null) {

   LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
     Context.LAYOUT_INFLATER_SERVICE);
   mView = vi.inflate(R.layout.levelselector_item, null);

  }
Or maybe there is another way to go around this problem.. ?
Answer: I got it to work properly. For those who might be interested:
I first set my border around my gridview to an amount which is controlable by adding to my gridview in xml:
android:listSelector="@null"
android:layout_margin="5dp"

Then I used a combination of Ted Hopp's and Sameer's solution: Since I know what the padding of my elements is; 5dp around the gridview, 2dp between the elements and 15dp in an element. I also have 3 items each row, this makes my code look like:
int parentW = parent.getWidth() - parent.getPaddingLeft() - parent.getPaddingRight();
                Resources r = C.getResources();
                float pxPaddingBetweenItem = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, r.getDisplayMetrics());
                float pxPaddingInItem = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, r.getDisplayMetrics());

                int totalBarWidth = (parentW - (int)(2*pxPaddingBetweenItem)  - (int)(6*pxPaddingInItem))/3;

And this takes me exactly where I want to be :)
Thanks!


Suitable ladder for reaching stair well above corner stairs

Question: I want to hang a picture in our stairwell above the stairs, but the stairs curve directly beneath the stairwell where I want to hang the picture. What is the best way to reach the wall above the stairwell?
Comment: Second - is that smoke detector on the right-hand side doing anything useful there?   It would probably be better on the ceiling right over the top landing (ie, above photographer's head)
Comment: **Move those detectors!**  (Sorry @Criggie I think it needed to be said with a little less subtlety.)
Comment: Just for everyone's peace of mind... one of the detectors is a wall mounted CO detector. The other is a faulty smoke detector which has a replacement on the ceiling but has been gathering dust on that shelf for the past 6 months.
Comment: @tone thank you for clarifying - we have a good+bad habit of noticing things in photos :)
Comment: Aside - use more than one hook, and make them solid.  This stairwell is probably the main egress and you don't want things falling down in a quake or fire.
Answer:
The stair blocks the feet of the ladder, so they can't slip towards the back.
Comment: +1 I don't know why, but there's a soft spot in my heart for crude MS paint sketches that elegantly and perfectly answer a question.  @SolarMike Fuzzy slippers, towels, puffy socks, etc, also work well for wrapping the ladder feet against the wall.
Comment: And it may be worth having a board at to top of the ladder so it does not poke holes in the wall.
Comment: A bonus answer: They make ladders that fold in the middle and can be used as platforms with the ends at different heights. One of those, if tall enough could be used for this situation and could also be used to make a work platform to hang (or paint) something high on the side walls of the stair case. Used one years ago to help my mom hang a large mirror over the stairs (wall on one side, open on the other).
Comment: With ladders should always have someone to watch and maybe stabilize the ladder, even if it looks perfectly safe.
Comment: @TonE an internet search for "multi-position ladder" netted a variety of results. Big-blue and Big-orange seem to both carry a single Werner ladder with 3 hinges so it will fold into a flat work platform. The online giant carries a wide variety of no-name versions in a multitude of lengths and of unknown quality. As a note: A search for "folding ladder" will give you so many results you're not interested in, it's not worth the effort.
Comment: @J... the legs of old jeans for me, doubled over  (jeans make good rags if you cut round the rivets so once worn out they end up in the garage anyway)
Comment: Thanks all. @FreeMan - can you add a link to this kind of ladder? I think this is what I had at the back of my mind when I asked the question - I only have a step ladder so will need to buy a new ladder for this job - might as well get something versatile.
Comment: Of course, on more than one occasion, I've also used two standard A-frame ladders and a 2x12 to make temporary scaffolding.
Comment: I've done exactly the same (as well as painting) using this approach, despite having a3-way  ladder that's supposed to be good for use on stairs
Comment: It may be worth investing in life insurance as well!
Answer: The accepted answer qualifies as "simplest" for sure.  For those of us who view the hardware store as our "toy store,"  Get one of those combo/multiposition ladders.  Extend one side a notch or two more than the other so that all the feet sit solidly on one stair or another.   In fact, some models even allow you to extend one of the feet on each side so you can set the ladder "sideways" on a staircase.
This gives you an excuse to buy one of these ladders because they're very cool and handy to use in all sorts of situations.
Comment: TBH, I thought that they were the dumbest thing in the world when my wife insisted that we get one. Then I needed to work above some stairs and discovered that they're _genius_! We now own two and they do make good scaffold bases, too. Only drawback - all that AL is _heavy_.
Comment: @FreeMan - I do agree that the ladders are a lot heavier, but I find mine easier to move despite the weight because it's so compact. I just put my full shoulder in the 2nd rung hole from the top, lift with my legs, and use the same hand to help stabilize & shift. This leaves a hand free for doors / tailgates and the compact size is easier to avoid obstacles. IMHO, of course... but I sure do love mine!
Comment: Yes, those multi-position ladders are surprisingly heavy.  I actually got rid of mine and went back to single-position extension ladders, as they're a lot easier to carry around.
Comment: Little Giant ladders are an absolute godsend for changing lightbulbs above stairwells. Truly a must for that kind of situation. They are lovely in all kinds of other situations too but that's the one use case where I really saw their point.


How can I match the wall color after dent fixing?

Question: I used to have a couple of small dents in one of my walls (the walls are plastered brick if that matters). I covered them and the wall is now smooth. However the main issue I have right now is the paint. Is there any way to paint the fixed areas without painting the whole wall and without having a noticeable difference between the old wall color and these fixed patches?
First I thought about trying to match the original color but there are 2 problems with that:

I didn't paint the wall in the first place and finding the exact color will be impossible.
I assume that since the wall paint is fairly old, even if I find the exact color, it is still going to be different from fresh paint.

Any ideas?
Answer: Your best shot at that would have been to take a large enough chip from the damaged portion of the wall before it was repaired, take it to a paint store to have it computer color matched. There would have been only a chance it would been an exact match still.
Your next best bet if it is close enough, is to paint the wall corner to corner, at least it would not be the whole room.
Comment: Exactly what I do with drywall. I use a utility knife to cut a 1" square of paper out, peeling it away from the gyp inside. Hit the hole with a bit of mud and head to the store.


Most Efficient Food/Speed movement in strip mines

Question: In a strip mine (2 high, 1 wide):
The quickest method of movement is sprinting and spamming jump in the tunnel.
But what is the most efficient method as jumping and sprinting uses a LOT of hunger very quickly?
Keeping in mind that one does not have infinite food and wants to preserve it;
from my knowledge one should always jump and sprint after eating food, due to the saturation where one loses no hunger no matter what. However after this is it more efficient to just walk OR just sprint OR sprint and jump ( or some other sneaky method :P)
Comment: "Efficient" in what way?
Answer: Not sure if this is what you are looking for, but I will base my answer off of 2 things.

How much faster is jumping while sprinting?
https://minecraft.wiki/w/Hunger

So if you want efficient, there are 2 answers both can be found in the 2 links above.
for #1, Most efficient speed, sprint-jumping travels faster even taking time to eat, so this could be considered more speed efficient.
for #2, Most efficient hunger, by itself walking (or sneaking after 1.9) would be the most efficient, besides choosing something that does not take up food (i.e. minecart tracks everywhere).
If this doesn't answer your question, then you have to decide whether you want to sacrifice speed for hunger or the other way around.  If you want to make your hunger last longer, then walk everywhere.  That's the simple answer.
Walking to me is the best way to go, with an occasional sprint if i get impatient.  I would suggest just making shortcuts to reduce time, such as messing with minecarts and pits with water at the bottom to speed up the time it takes to travel up/down.  Stairs would also make it more efficient to walk up, since you won't have to jump.
So if you want to use less hunger, then either decide to invest some time to make something like a minecart system to take you up and down the shaft, then walk/sprint the rest of the way.  You can also do the same above ground, including the use of a waterway + boat to save hunger.
You can also mess with redstone, which would be more time consuming than a minecart system and still save time/hunger later.  Also you could get a saddle and ride an animal down there (if you can even fit), but just another option that saves hunger.  Obviously a horse or pig may not work well, but it does save hunger.


What is Google Authenticator's app style called and where can I get more visual resources?

Question: I love the UI of the Google Authenticator, and I am currently in the design phase of my Team Fortress 2 Server Status application. I am looking to have each server as a "card" much like Authenticator has and a sparkline for the number of players across the day.
What is Google Authenticator's UI style and where can I get more resources on staying consistent to the style here?
Answer: Google utilizes the FlatUI trend, then the "cards" mechanism is something they brought in with Google NOW and are rolling out across their platform to distinguish content on their dashboard like applications.
Comment: My God this is absolutely perfect! Are there any Android libraries (my app is Android) to leverage anything Google has already existing so I don't have to write them from scratch?
Comment: Found it: https://github.com/eluleci/FlatUI
Comment: There you go! Kindly mark as answered ;)


WinForms User Control has ComboBox that causes ToolStripDropDown to auto-close

Question: I have a custom WinForms user control that looks like a combobox but instead opens a ToolStripDropDown that contains another custom user control, called NumericFilterPanel, that has a checkbox, a combobox, and a textbox.

The problem is that when the user click-selects an option for the combobox embedded in the dropdown control, it causes the parent dropdown to hide.
I have set ToolStripDropDown.AutoClose = false, which fixes the original problem, but now I am having difficulty detecting all the situations where the dropdown loses focus, such as when the user clicks on the parent form or switches programs. Sometimes the dropdown remains visible and topmost.
Is there a way to either keep AutoClose = true and prevent the embedded combobox from closing the parent dropdown, or is there a way to always detect when the dropdown has lost focus so I can manually close it?
  using System;
  using System.Drawing;
  using System.Windows.Forms;

  namespace mviWinControls
  {
    public partial class NumericRangeDropDown : UserControl
    {
      private const int ARROW_HEIGHT = 4;
      private Brush arrowBrush = new SolidBrush(Color.FromArgb(77, 97, 133));

      private ToolStripDropDown _dropdown;
      private ToolStripControlHost _host;
      private NumericFilterPanel _filter;

      public NumericRangeDropDown()
      {
        InitializeComponent();

        _filter = new NumericFilterPanel();
        _filter.DropDown = this;

        _host = new ToolStripControlHost(_filter);
        _host.Margin = Padding.Empty;
        _host.Padding = Padding.Empty;

        _dropdown = new ToolStripDropDown();
        _dropdown.Margin = Padding.Empty;
        _dropdown.Padding = Padding.Empty;
        _dropdown.AutoClose = false;  // Use this because panel has a combobox.  https://social.msdn.microsoft.com/Forums/windows/en-US/dd95b982-820e-4807-8a1f-79c74acab3f8/two-problems-toolstripdropdown?forum=winforms
        _dropdown.Items.Add(_host);
        _dropdown.Leave += new System.EventHandler(this.DropDown_Leave);

        this.Leave += new System.EventHandler(this.DropDown_Leave);
      }

      ///
      /// Clean up any resources being used.
      ///
      /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
      protected override void Dispose(bool disposing)
      {
        if (disposing)
        {
          if (components != null) components.Dispose();
          if (_dropdown != null) _dropdown.Dispose();
        }
        base.Dispose(disposing);
      }

      public override string Text
      {
        get
        {
          return base.Text;
        }
        set
        {
          base.Text = value;
          _filter.SetValue(value);
        }
      }

      protected override void OnPaint(PaintEventArgs e)
      {
        //base.OnPaint(e);
        TextBox _txtDraw = new TextBox();

        _txtDraw.Width = this.Width;

        using (Bitmap bmp = new Bitmap(_txtDraw.Width, _txtDraw.Height))
        {
          _txtDraw.DrawToBitmap(bmp, new Rectangle(0, 0, _txtDraw.Width, _txtDraw.Height));
          e.Graphics.DrawImage(bmp, 0, 0);
        }

        StringFormat format = new StringFormat();
        format.Alignment = StringAlignment.Near;
        format.FormatFlags = StringFormatFlags.NoWrap;
        format.LineAlignment = StringAlignment.Center;

        using (Brush b = new SolidBrush(this.ForeColor))
          e.Graphics.DrawString(this.Text, this.Font, b, this.DisplayRectangle, format);

        Point[] arrowPoints = new Point[] { new Point(this.Width - ARROW_HEIGHT * 3 - 2, (this.Height - ARROW_HEIGHT) / 2),
                                            new Point(this.Width - ARROW_HEIGHT + 1 - 2, (this.Height - ARROW_HEIGHT) / 2),
                                            new Point(this.Width - ARROW_HEIGHT * 2 - 2, this.Height - (this.Height - ARROW_HEIGHT) / 2) };

        e.Graphics.FillPolygon(arrowBrush, arrowPoints );

      }

      private void DropDown_Leave(object sender, EventArgs e)
      {
        HideDropDown();
        this.Text = _filter.SummaryText();
      }

      private void NumericRangeDropDown_Click(object sender, EventArgs e)
      {
        if (_dropdown.Visible)
          HideDropDown();
        else
          ShowDropDown();
      }

      public void ShowDropDown()
      {
        _dropdown.Show(this, new Point(0, this.Height), ToolStripDropDownDirection.Default);
        _dropdown.BringToFront();
        //_dropdown.Focus();
        _filter.Select();
        _filter.Focus();
      }

      public void HideDropDown()
      {
        _dropdown.Close();
        this.Invalidate();
      }

    }
  }

Comment: I wish I could find an answer to this same question
Comment: Nvm, found a workable solution. Check my answer below.
Answer: Here's a combobox that can automatically disable and enable the AutoClose property on the host control for you.
Source(I modified it for a combobox versus the DatePicker in their example): http://www.queasy.me/programming/questions/13919634/tool+strip+toolstripdropdownbutton+close+and+lose+window+focus
public partial class CComboBox : ComboBox
{
    private bool savedAutoClose;

    public CComboBox()
    {
        InitializeComponent();
    }

    protected override void OnDropDownClosed(EventArgs e)
    {
        if (this.Parent != null)
        {
            var dropDownHost = this.Parent.Parent as ToolStripDropDown; // recursive instead?
            if (dropDownHost != null)
                dropDownHost.AutoClose = savedAutoClose; // restore the parent's AutoClose preference
        }

        base.OnDropDownClosed(e);
    }

    protected override void OnDropDown(EventArgs e)
    {
        if (this.Parent != null)
        {
            var dropDownHost = this.Parent.Parent as ToolStripDropDown; // recursive instead?
            if (dropDownHost != null)
            {
                savedAutoClose = dropDownHost.AutoClose;
                // ensure that our parent doesn't close while the calendar is open
                dropDownHost.AutoClose = false;
            }
        }
        base.OnDropDown(e);
    }
}

Comment: Thanks, this code solves it! I just had to change the type of the parent class to match my NumericRangeDropDown class and add a property to get/set the _dropdown object's AutoClose.
Answer: Having taken a good look at the source code, the bug (and it is a bug) lies in the fact that ToolStripManager, which sets up a message filter to catch mouse-clicks outside the active ToolStrip, checks if the click is within the bounds of a child window.
The problem is that it uses activeToolStrip.ClientRectangle to verify this, and does not check child windows of the window that was clicked. In the case of a ComboBox, the drop-down is a separate child window which floats above everything, and can actually be out of the bounds of the main combo window if the drop-down is large.
The relevant line is:
if (!activeToolStrip.ClientRectangle.Contains(pt.x, pt.y)) {

I have found another solution to temporarily disable the automatic close while the dropdown is open.
Ideally, you are supposed to use a ToolStripComboBox within a ToolStrip rather than just a bare ComboBox. However if you would like to just us a bare one, you can add events to call the relevant private methods to suspend and resume the message filter.
static class ToolStripComboBoxFilter
{
    private static Action SuspendMenuMode = (Action) typeof(ToolStripManager)
        .GetNestedType("ModalMenuFilter", BindingFlags.NonPublic)
        .GetMethod(nameof(SuspendMenuMode), BindingFlags.NonPublic | BindingFlags.Static)
        .CreateDelegate(typeof(Action));

    private static Action ResumeMenuMode = (Action)typeof(ToolStripManager)
        .GetNestedType("ModalMenuFilter", BindingFlags.NonPublic)
        .GetMethod(nameof(ResumeMenuMode), BindingFlags.NonPublic | BindingFlags.Static)
        .CreateDelegate(typeof(Action));

    public static void AddToolStripFilterEvents(this ComboBox combo)
    {
        combo.DropDown += OnDropDown;
        combo.DropDownClosed += OnDropDownClosed;
    }

    private static void OnDropDown(object sender, EventArgs e)
    {
        SuspendMenuMode();
    }

    private static void OnDropDownClosed(object sender, EventArgs e)
    {
        ResumeMenuMode();
    }
}

You can use it like this
myComboBox.AddToolStripFilterEvents();


Declaring type after it is parsed as a JSON file Swift

Question: Right now I have a JSON output that I got from Pearson's API:
Optional(<__NSCFArray 0x7f9b7601a910>(
{
    datasets =     (
        laad3,
        dictionary
    );
    headword = theoretically;
    id = cs1tNTvYvg;
    "part_of_speech" = adverb;
    senses =     (
                {
            definition = "used to say that something could happen, but it is extremely unlikely";
            examples =             (
                                {
                    text = "It\U2019s theoretically possible for everyone in the class to get 100%.";
                }
            );
        }
    );
    url = "/v2/dictionaries/entries/cs1tNTvYvg";
},
{
    datasets =     (
        laad3,
        dictionary
    );
    headword = theoretical;
    id = cs1tNTpDbZ;
    "part_of_speech" = adjective;
    senses =     (
                {
            definition = "relating to or based on ideas, especially scientific ideas, rather than practical work or experience";
            examples =             (
                                {
                    text = "theoretical research";
                }
            );
        }
    );
    url = "/v2/dictionaries/entries/cs1tNTpDbZ";
})

And assume that the output above is stored to:
let results = parsedResult!["results"]

XCode says that there is an ambiguous use of subscript and after Googling it seems that I have to cast the type of results to continue. What would I have to cast the type of results to e.g. [[String:String]]?
Side note: Does anyone know why Xcode complains that there is an ambiguous use of subscript when selecting the run target to be on my iPhone6 with iOS 9.3, but not while running in the simulator (also on iPhone6 with iOS9.3)?
Answer: I don't understand the deeper cause of this problem. But since XCode 7.3 (or rather with Swift 2.2), the compiler now complains about ambiguous use of subscript when using NSDictionary.
To avoid the error, cast NSDictionary instances to [String: AnyObject] and NSArray instances to [AnyObject].


PM2 is starting my app in fork mode instead of cluster mode

Question: I'm starting my PM2 (v 3.2.1) app like so:
pm2 start server.js --name app -i max --log-date-format 'LLLL'

The problem is that this is starting two PM2 processes, but one is constantly getting the EADDRINUSE error.
My server.js script is as follows:
const server = require('./build/bundle.server.js')

server.listen(8081, function () {
  console.log(`Listening at http://localhost:${server.address().port}`)
})

I've tried deleting all PM2 apps prior to running pm2 start with pm2 stop all and pm2 delete all but the processes still start in fork mode instead of cluster mode.
How can I get my PM2 processes to use cluster mode?
Answer: This is a bug in PM2 v 3.2.1 - upgrading to the latest version solved the issue.


Does cold galvanizing compound restore the rust protection of a galvanized duct?

Question: The house is a ranch built on slab on grade with a newer furnace in a downflow configuration with A/C. The in-floor clay tile supply lines are in good shape and clean.
The original 60 year old in-floor supply plenum (30in x 22in) shows corrosion.  The plenum is directly below the A-Coil & subject to condensate.
I have wire brushed the surface rust and treated it with The Must for Rust. I am looking at various cold galvanizing compounds (GRC/Rustoleum) to apply to the bare metal to restore the zinc protection. Access to the plenum (which is much larger than the 14in x 19in cabinet housing the A-Coil) is tight so this will be a challenge.
My concern is that since there are mixed metals in close proximity, a zinc coating may be important to protect the noble metal of the A-Coil by sacrificing itself to the eventual rusting process. Or does this even apply given that plenums are now sometimes fabricated with duct board?
I am wondering if I can just reline the bottom with a thin rubber mat cut to size that will conform itself to the metal isolating it from moisture from possible condensate from above?
Answer: The zinc coating on the galvanized duct work is not in any way required to control corrosion of the A-coil.  Isolating the unit from the duct work is commonly done in the trade to provide vibration isolation.
However, sandwiching corrosion under a sheet of rubber that is not fully adhered may not be a good idea.  Moisture may become trapped between the two layers.  Also, it is generally not acceptable to place flammable materials such as rubber inside of duct work.  You would likely be better off painting or cold galvanizing the duct after applying your phosphotizing chemical.  If the condensate drain on the new fan-coil is correctly installed and kept clear, very little condensate should reach the duct.


I am using agora Client API in my web, but it's not returning a list of users list

Question: I am following this link to integrate Agora Chat SDK using Client API
https://docs.agora.io/en/agora-chat/client-api/messages/retrieve-messages?platform=web
but it's not returning a list. I have created 2 users and all is working fine like both users can chat but we refresh the page the agora isn't returning a chat list.
Comment: @thefallen the above issue is fixed by agora support basically they have suggested to add toLowerCase() with username while connection opening, and now it's working fine.
Comment: Can you add some code what have you done and tried so far?
Answer: There is a small tip in doc:
Retrieve a list of conversations from the server
As I know, they intend to be compatible with mixed upper-case issues
Answer: Issue is resolved now after contact agora support they told me to add toLowerCase() with the user in open connection call E.g.
<code>WebIM.conn.open(
{
      user: username.toLowerCase(),
      agoraToken: token,
});
</code>
Comment: mark then as correct!


check_box_tag is only passing the last check box value to params

Question: I have a form_builder for my @organization object where I have inserted a check_box_tag:
form_for @organization do |f|
  f.text_field :name
  City.all.each do |city|
    check_box_tag(:cities, city.id)
  end
  f.submit
end

City and Organization don't have a relationship.
How should I write the code such as all checked boxes' values are passed to params?
Comment: have you use activeadmin and/or decorators? =)
Comment: Sorry, but cannot see how that would improve my understanding of the `check_box_tag`...
Comment: if you think that we should not know the details, solve the problem by yourself
Comment: Learn more about check_box_tag [here](http://apidock.com/rails/ActionView/Helpers/FormTagHelper/check_box_tag)
Answer: Fetch the cities from the Controller/Model itself:
@cities = City.all

Then, you could use:
  <% @cities.each do |city| %>
    <%= check_box_tag 'city_ids[]', city.id -%>
  <% end %>

Refer: http://apidock.com/rails/ActionView/Helpers/FormTagHelper/check_box_tag
Hope it helps :)
Comment: wow GENIUS! the brackets did it. thank you, thank you, thank you.
Answer: Take a look at collection_check_boxes.
f.collection_check_boxes :city_ids, City.all, :id, :name


Bash script to convert multiple image sequences to video files

Question: I'm trying to make a script to take multiple series of image sequences within subdirectories of the present working directory and send them through ffmpeg to create video files in the present working directory named after the directories. It's complicated by the fact that the image sequence names vary, as does the starting number of the sequences, but the real problem is I'm new to bash scripting. Here is an example of the files:
directoryFirstRender01
     renderOne0032.png
     renderOne0033.png
     renderOne0034.png
directoryFourthRender01
     renderFour4253.png
     renderFour4254.png
     renderFour4255.png
directoryFifthRender01
     renderFiveTwo1367.png
     renderFiveTwo1368.png
     renderFiveTwo1369.png

Here is a rough outline of the script that has several problems that I know about and probably many more that I don't. The reason I don't know how many problems it has is because I've gotten stuck getting and parsing the filenames, and without that working I can't test the rest:
#!/bin/bash

for DIR in (ls -d */); do
    1STFILE=(ls $dir/ | sort -n | head -1)
    STARTNO=${1STFILE:(-8):4}
    IMGSEQ=${1STFILE%????.*}
    EXTEN=${1STFILE*.}
    ffmpeg -start_number $STARTNO -i $IMGSEQ%04d.$EXTEN $DIR.mkv
done

My current main problems that I know about are these:

I don't know how to get the filename of just the first file in the directories. ls dir/ | sort -n | head -1 works in the terminal, but not in a script.
The substring extraction for getting the first number of the first file would only work on image sequences of 4 digits. Is there a way to make it accept renderSix00001.png-renderSix99999.png and renderSeven001.png-renderSeven999.png too? That's also a problem with the line getting $IMGSEQ, and the %04d in the ffmpeg line would need to be changed somehow.
I think I'm going to have trouble with the $IMGSEQ variable mixing with the %04d in the ffmpeg input filename without brackets, but I haven't gotten that far yet. What syntax do I use there $IMGSEQ(%04d).$EXTEN or $IMGSEQ {%04d}.$EXTEN maybe? (Stuff like this is why it sucks to be jumping in the deep end of scripting)
(minor problem: 1. I know using ls in for DIR in (ls -d */) is frowned upon, but I don't know how else to filter out any files in the present working directory and just work on the directories.)

I'm sure the script looks like a complete mess. Any overall guidance to get the whole thing working would be very welcome, but if no one has the patience to walk me through the whole thing if I can just get some help getting and parsing the filenames maybe I can fix the rest myself. Thank you.
UPDATE 1: (After applying Ron's suggestions)
Thank you again Ron! This is the near-final script:
#!/bin/bash

for DIR in $(ls -d */)
do
    FIRSTFILE=$(ls $DIR | sort -n | head -1)
    STARTNO=$(echo $FIRSTFILE | grep -Eo "[0-9]+")
    DIGITNO=${#STARTNO}
    IMGSEQ=${FIRSTFILE%????.*}
    EXTEN=${FIRSTFILE#*.}
    OUTPUT=${DIR%/}
    ffmpeg -start_number $STARTNO -i "$DIR$IMGSEQ"%0"$DIGITNO"d".$EXTEN" $OUTPUT.mkv
done

Since thanks to Ron the $STARTNO variable will now accept multiple digit lengths, I'm using the length parameter expansion in the $DIGITNO line to get the number to use in the %04d part to make it %03d or %05d as needed so that will work too. I'm hoping the liberal use of " to separate the %04d from the surrounding variables isn't considered bad form (if it was, what is the right way?). The ONLY missing part of the script (I think!) is how to make $IMGSEQ accept multiple digit lengths. I have no ideas for that right now. If anyone knows, I would appreciate knowing, but maybe I can find it combing through parameter expansion documentation, as if I haven't had more than enough of that for one lifetime. :)
UPDATE 2: (Success!)
Figured it out! (How to get IMGSEQ to accept names involving multiple digit lengths that is) Working based on Ron's suggestion for $STARTNO using (echo $FIRSTFILE | grep -Eo "[0-9]+") I came up with
IMGSEQ=$(echo ${FIRSTFILE%.*} | grep -iEo "[a-z]+")

${FIRSTFILE%.*} takes the first file and strips off the extension.
grep is pattern searching
The -i part of -iEo is to make grep accept uppercase and lowercase pattern matches.
The -E part of -iEo is to (quoting from man grep) "Interpret PATTERN as an extended regular expression." Whatever that means.
The -o part of -iEo is to only print the matching pattern.
[a-z] is to match the pattern of any letter of the alphabet
+ tells grep that the previous alphabet pattern should be matched "one or more times" (so do it over and over to get all the letters).

A limitation of that is that it wouldn't handle filenames with special characters like - or _, but I can live with that for now.
So here is the semi-final script!
#!/bin/bash

for DIR in $(ls -d */)
do
    FIRSTFILE=$(ls $DIR | sort -n | head -1)
    STARTNO=$(echo $FIRSTFILE | grep -Eo "[0-9]+")
    DIGITNO=${#STARTNO}
    IMGSEQ=$(echo ${FIRSTFILE%.*} | grep -iEo "[a-z]+")
    EXTEN=${FIRSTFILE#*.}
    OUTPUT=${DIR%/}
    ffmpeg -n -start_number $STARTNO -i "$DIR$IMGSEQ"%0"$DIGITNO"d".$EXTEN" $OUTPUT.mkv
done

So run in a directory with some directories named like my example directories above (except I added one with an image sequence padded with more than 4 zeros to make sure that worked too), this script will run the following ffmpeg lines one after the other:
ffmpeg -n -start_number 0032 -i directoryFirstRender01/renderOne%04d.png directoryFirstRender01.mkv
ffmpeg -n -start_number 4253 -i directoryFourthRender01/renderFour%04d.png directoryFourthRender01.mkv
ffmpeg -n -start_number 01367 -i directoryFifthRender01/renderFiveTwo%05d.png directoryFifthRender01.mkv

Freakin' perfect! Thanks so much again for your help Ron! I definitely would not have been able to finish without your help.
Answer:
I don't know how to get the filename of just the first file in the
  directories. ls dir/ | sort -n | head -1 works in the terminal, but
  not in a script.

You may want to re-write:
for DIR in (ls -d */); do
    1STFILE=(ls $dir/ | sort -n | head -1)

as
for DIR in (ls -d */)
do
    1STFILE=$(ls $DIR | sort -n | head -1)

Is there a way to make it accept renderSix00001.png-renderSix99999.png
  and renderSeven001.png-renderSeven999.png too?

If you've followed the above then:
STARTNO=$(echo $1STFILE | grep -Eo "[0-9]+")

should get all the numbers in the filename.

What syntax do I use there $IMGSEQ(%04d).$EXTEN or $IMGSEQ {%04d}.$EXTEN maybe?

Put that thing inside "" so:
ffmpeg -start_number $STARTNO -i "$IMGSEQ%4d.$EXTEN" "$DIR.mkv"

Now, if you use just "$IMGSEQ%4d.$EXTEN" you are going to hit a problem (try it to see what it is!). So make it "$DIR$IMGSEQ%4d.$EXTEN"
If you use "$DIR.mkv" it is going to create a hidden file .mkv which is not what you want. One not-so-cool way I thought is to store only the name of directory by stripping the suffix / in a variable:
OUTPUT=$(echo $DIR | sed 's/\/$//')

and use this in ffmpeg as in:
ffmpeg -start_number $STARTNO -i "$DIR$IMGSEQ%4d.$EXTEN" "$OUTPUT.mkv"

Comment: Thank you so much for the detailed answer Ron! I'm getting a `syntax error near unexpected token ('` for the new line `for DIR in (ls -d */)
do`. I'm going to tinker for a while with that and hopefully once I get that worked out I can try your other suggestions. Thank you again!
Comment: Figured out that first syntax error. It needed to be `for DIR in $(ls -d */)
do`. I was missing the $.
Comment: Amazing Ron! You're a lifesaver! I used your suggestions and it seems to be working almost perfectly! `STARTNO=$(echo $FIRSTFILE | grep -Eo "[0-9]+")` works great for getting the file number regardless of it's length.  I'd love to ask you how that works exactly, but from reading the grep man page about the -E being an "extended regular expression" it sounds like something that couldn't be explained to a noob quickly. I'll need to read up on it on my own time.
Comment: `echo "ffmpeg -start_number $STARTNO -i "$DIR$IMGSEQ%04d.$EXTEN" -vcodec ffv1 $VIDNAME.mkv"` Right! Thank you for pointing out the $DIR$IMGSEQ mistake. One of several stupid mistakes I knew I was making. Without the $DIR on the beginning there it would be looking for the image files in the present working directory, which the image file would not be in.
Comment: (Note: I did change `$1STFILE` to `$FIRSTFILE` because I've heard some scripts have a problem with leading numbers in variables.)
Comment: Thanks for pointing out the $DIR.mkv problem. The parameter expansion `OUTPUT=${DIR%/}` seems to work. Is that more or less of a good method than `OUTPUT=$(echo $DIR | sed 's/\/$//')`?
Comment: In the home stretch! The only thing left to fix is `$IMGSEQ` to accept multiple digit lengths. I posted an update in the main question below "EDIT." (I hope I'm doing this right; I'm not sure how Ask Ubuntu likes us to handle updating our questions.)


CSS absolute positioning is not moving to parent, the parent is relative

Question: I am trying to absolutely position sideways text inside a div that there are multiple occurences of.
Each child has position: absolute; ,
and each parent has position: relative;
<code>    .parent{
    width: 24%;
    display: inline-block;
    float: left;
    border-left: 1px solid #FFA500;
    position: relative;
    }

    .child{
    display: inline-block;
    line-height: 1.5;
    height: 5%;
    position: absolute;
    top: 0px;
    right: 0px;
    transform: translate(0px, 100%) rotate(90deg);
    overflow: hidden;
    float: right;
}
</code>
Of of the children go to the same exact place on the page, which seems to be the first childs parent.
The structure is
<code>Parent
    child
close
close
</code>
for all 4 divs.
Can anyone please help?
Comment: Please post a complete code example.
Answer: In your css, if your parent has no content other than the absolute position child div, then the parent has a 0 height declaration - so you have to set the height of the parent div in pixels in order to give it a place in the DOM.
Answer: Your height: 5% on the .child may be what is throwing it off (it was for me).  That, or there could be other css that is overriding something for you.  Fiddle here: https://jsfiddle.net/tagb3yja/
<code>.parent{
  width: 24%;
  display: inline-block;
  float: left;
  border-left: 1px solid #FFA500;
  position: relative;
  background: yellow;
}

.child{
  position: absolute;
  display: inline-block;
  line-height: 1.5;
  top: 0px;
  right: 0px;
  transform: translate(0px, 100%) rotate(90deg);
  overflow: hidden;
  float: right;
  background: silver;
}
</code>


State of Checkbox remains same

Question: $('#SaveCheckbox').attr('checked') != true

Intending to check the value of CheckBox by the above means , as found the solution , but its giving false always , either i check the checkbox or uncheck it.
Kindly help.
I am using jquery-1.10.2.min.js and jquery.mobile-1.4.0.min.js libraries.
Comment: possible duplicate of [JQuery Mobile refreshing checkbox works only once - .checkboxradio('refresh') issue](http://stackoverflow.com/questions/17612806/jquery-mobile-refreshing-checkbox-works-only-once-checkboxradiorefresh-is)
Answer: Use prop() instead of attr()
$('#SaveCheckbox').prop ('checked') != true

As of jQuery 1.6, the .attr() method returns undefined for attributes
  that have not been set. To retrieve and change DOM properties such as
  the checked, selected, or disabled state of form elements, use the
  .prop() method, jQuery Docs

You can also use :checked
if($('#SaveCheckbox').is(":checked"))

OR
if($('#SaveCheckbox:checked').length)

State of Checkbox remains same


Creating links within a document using a preexisting Table of Contents

Question: I've got a large number of OCRed documents that have been partially marked up. I'm trying to create working links within the table of contents. The table of contents are formatted
<document>
  <text>
     <list>
        <item>Chapter 1<ref>7</ref></item>
        <item>Chapter 2<ref>27</ref></item>
        <item>Chapter 3<ref>54</ref></item>
        <item>Chapter 4<ref>77</ref></item>
     </list>

      OCRED text <pb n="7-8" xml:id="VAB0003"/> OCRED text

</document>

Is there a way to test if the value of ref is the same as part of the value of @n in pb and then if so pull the value of @xml:id and use that in the ref element?
Is there a less convoluted way of accomplishing this?
Comment: try to make your title short and descriptive!!
Comment: Will the **n** attribute always consist of two parts, or can it have multiple hyphens in?
Comment: it represents page numbers. it will sometimes consist of two parts formatted n-n (or nn-nn or nnn-nnn) and sometimes only a single part with no dash.
Answer: I think you're looking for something like this:
<xsl:template match="ref*">
  <xsl:variable name="page" select="."/>
  <xsl:variable name="target"
                select="//pb[contains(
                        concat(' ',translate(@n,'-',' '),' '),
                        concat(' ',$page,' '))]/@xml:id"/>
  <xsl:copy>
    <xsl:if test="$target">
      <xsl:attribute name='target'>
        <xsl:value-of select="$target"/>
      </xsl:attribute>
    </xsl:if>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

The complicated concatenations are there in the definition of target to ensure that you match on a full token of the page number; in XSLT 2.0 it can be done a little more gracefully and without the concats, but not much more succinctly.
Comment: If your question has been answered to your satisfaction, the [Stack Overflow convention](http://stackoverflow.com/faq#howtoask) is for you to click on the check-mark outline next to the answer.  (Corny as it sounds, the reputation points you cause the system to give the author of the answer, when you do that, turn out to be surprisingly motivational.)


Multiple outputs for "apt-cache policy "

Question: From what I understand, apt-cache policy <package name> displays the pinning order and thus the releases of package name available in the apt repositories along with their priority orders.
So, if for an uninstalled package, the output consists of various versions (with same priority of 500) which one will be the one to be installed?
For example,  $ apt-cache policy git yields me:
 Installed: (none)
 Candidate: 1:2.25.1-1ubuntu3.2
 Version table:
    1:2.25.1-1ubuntu3.2 500
       500 http://in.archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages
       500 http://security.ubuntu.com/ubuntu focal-security/main amd64 Packages
    1:2.25.1-1ubuntu3 500
       500 http://in.archive.ubuntu.com/ubuntu focal/main amd64 Packages

So, running $ sudo apt install git will install which of the versions in my system?
Comment: The `focal-update` and `focal-security
Answer: "Candidate" indicates the version that will be installed.
It's always the highest version if different ones are available from different repositories. In the specific case of your question it comes from the "focal-updates/main" repository that you manually enabled. Disable it if you want to current version instead of the backport.
Answer: Choose between the two versions:
1:2.25.1-1ubuntu3.2
1:2.25.1-1ubuntu3

Version x3.2 is higher than x3, so 1:2.25.1-1ubuntu3.2 will be installed...unless something on your system requires version x3.

Choose between different pockets that offer the same version:
500 http://in.archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages
500 http://security.ubuntu.com/ubuntu focal-security/main amd64 Packages

Ha -- it's a trick question: The repositories are structured so that all packages sit in one directory (/pool). Both lines point to the same package in the pool.
Comment: "unless something on your system requires version x3"

Will that not be displayed by the priority number or the entries in ``/etc/apt/preferences`` to determine the one to be installed?
Comment: Dependencies do not establish priority. Dependencies come first. If multiple packages satisfy dependencies, then version number. If the same version is available from multiple sources, then priority.


JqueryUI Sortable load use order

Question: I have a Side Menu which I want the user to sort the menu items in his own preference.
How can I, on page load in a user session, load the user's custom order from the DB sending the info with json from my php.
Suppose I have saved the user's order in the DB using the .toArray or .serialize method of .sortable
like this
<code>$("#sidr-id-mainList").sortable({
    stop: function (event, ui) {
        result = $("#sidr-id-mainList").sortable("toArray");
        $.ajax({
            url: "example.com/API/menu/list/save",
            type: "POST",
            xhrFields: {
                withCredentials: true
            },
            dataType: 'json',
            data: {
                Result: result
            }, error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("XMLHttpRequest=" + XMLHttpRequest + "; textStatus=" + textStatus + "; errorThrown=" + errorThrown);
            }
        });
    }
});
</code>
Answer: You can do it like below:
<code>var custumOrder = ["item4", "item2", "item1", "item3"];

var ul = $("#sortable");
var items = $("#sortable li");

for (item of custumOrder) {
    ul.append($('#' + item + ''));
}

$("#sortable").sortable({
    update: function() {
        var order = $(this).sortable('toArray');
        alert(order);
    }
});
</code>
Online demo (jsFiddle)

JqueryUI Sortable load use order


MPV (FFmpeg) stack 2 videos and then crop output without re-encoding?

Question: I have two 16:9 ratio videos, I want to horizontally stack them, but then crop the resulting video output by about 900px from the right border whilst playing it within mpv and without re-encoding.
Libavfilter does have a crop functionality, but in all examples I've found, the cropping happens before stacking. (Visual representation of what I want to achieve)
I currently have this which somewhat does what I want:
mpv "F:\1.mp4" --external-file="F:\2.mp4" --lavfi-complex="[vid1] scale=1920x1080:flags=spline [vid1_scale]; [vid2] scale=1920x1080:flags=spline [vid2_scale]; [vid1_scale][vid2_scale] hstack [vo]"

Is it possible to crop the video output after stacking?
Comment: You say "which somewhat does what I want" but you do not say what it does and what is missing. Have you tried adding cropping to your lavfi parameters?
Answer: Add crop immediately after hstack:
mpv "F:\1.mp4" --external-file="F:\2.mp4" --lavfi-complex="[vid1] scale=1920x1080:flags=spline [vid1_scale]; [vid2] scale=1920x1080:flags=spline [vid2_scale]; [vid1_scale][vid2_scale] hstack,crop=iw-900:ih:0:0 [vo]"

Or crop immediately after one of the scales. Doesn't really matter.


Can Minecraft: Java Edition be opened using the Terminal on MacOS?

Question: I play Minecraft Java Edition, but the launcher takes too long to load.
Is it possible to use a command on my macOS's Terminal to manually launch Minecraft?
Comment: Does this answer your question? [Is there a way to open Minecraft without using the launcher at all?](https://gaming.stackexchange.com/questions/370705/is-there-a-way-to-open-minecraft-without-using-the-launcher-at-all)
Comment: The terminal is another term for the command line. Why has this been downvoted? This is a really good idea.
Comment: Hi, ThatBananaNinja, what terminal?
Comment: I am currently working a solution to this problem.
Comment: That still requires the launcher, and the other answer does not show how exactly.
Answer: Here is a tool (that I created) for this purpose. It supports Mojang and Microsoft accounts.
By default, Minecraft runs in a sort of "portaloo" mode, where the game files (saves, packs etc...) are stored separately. To change this, simple edit the directory property in config.yaml.
Here are the instructions:
First, install Node.js.
Next, download this repository, and unzip it.
In the folder, run:
npm i
node index.js --init

This will create config.yaml:
# The folder to run Minecraft in.
directory: ./minecraft

# The version of Minecraft to run.
version: 1.17.1

# Optional: JVM Arguments.
jvmArgs:
- argument
- another argument
- I have a lot of arguments.

# Optional: Memory settings
memory:
  min: 1G
  max: 2G

# Optional: Java Path.
javaPath: /usr/lib/jvm/java-16-openjdk-amd64/bin/java

Run the game:
node index.js

On first run, this will allow you to log in.
To force a log in (if you have multiple accounts):
node index.js --login

If the repository is suddenly deleted, that will probably be if I accidentally leak information.


Let $p( z)$ be a polynomial with real coefficients, and let $\alpha\in\mathbb{C}.$ Prove that $p(\alpha) = 0$ if and only in $p(\bar{\alpha})=0$

Question:
Let $p( z)$ be a polynomial with real coefficients, and let $\alpha\in\mathbb{C}.$ Prove that $p(\alpha) = 0$ if and only in $p(\bar{\alpha})=0$.

I have just started a linear algebra class and I have no idea how to even start this problem.
Comment: Do you know the general form of a polynomial? By the way, you can learn the basics of typesetting mathematics [here.](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Comment: @WillR Please do not remove the content of the question from the post - the body should contain the question, not the title.
Comment: Hint: $p(\bar{\alpha}) = \overline{p(\alpha)}$.
Answer: Write $p(z)=a_{n}z^{n}+a_{n-1}z^{n-1}+\cdots +a_{1}z+a_{0}$, where $a_{i}\in\mathbb{R}$ for all $0\leq i\leq n$. Then, note that we have:
$$
\begin{aligned}
p(\alpha)=0&\iff a_{n}\alpha^{n}+a_{n-1}\alpha^{n-1}+\cdots +a_{1}\alpha+a_{0}=0\\
&\iff\overline{a_{n}\alpha^{n}+a_{n-1}\alpha^{n-1}+\cdots +a_{1}\alpha+a_{0}}=0\\
&\iff\overline{a_{n}\alpha^{n}}+\overline{a_{n-1}\alpha^{n-1}}+\cdots+\overline{a_{1}\alpha}+\overline{a_{0}}=0\\
&\iff a_{n}\overline{\alpha}^{n}+a_{n-1}\overline{\alpha}^{n-1}+\cdots+a_{1}\overline{\alpha}+a_{0}=0\\
&\iff p(\overline{\alpha})=0,
\end{aligned}
$$
since for all complex $\beta,\gamma$ we have $\overline{\beta\gamma}=\overline{\beta}\overline{\gamma}$ and $\overline{\beta+\gamma}=\overline{\beta}+\overline{\gamma}$, and $\overline{r}=r$ for all $r\in\mathbb{R}$.
Comment: Thanks for showing me the steps and the formulas for each of the steps!
Answer: Let $\alpha$ be a complex number that is not real. And let $Q(x)=(x-\alpha)(x-\overline\alpha)$. Clearly $Q(x)$ is a polynomial with real coefficients.
Suppose that there is a polynomial $R(x)$ with $R(\alpha)=0$. Then $Q(x)$ divides $R(x)$.
Otherwise we have $R(x)=P(x)Q(x)+S(x)$, where $S(x)$ is a nonzero polynomial of degree at most $1$ with $S(\alpha)=0$, none exist, this is a contradiction.
Comment: This answer is "correct," in that it provides just as much information as is necessary for an elegant solution. However, to the intended audience, i.e., someone who doesn't know how to *start* on this problem, I'm not convinced that this answer is either clear or useful.
Answer: write:
$$
f(\alpha) = \Re(f(\alpha))+i\Im(f(\alpha))
$$
when $f$ has a zero, both real and imaginary parts must be zero, ie $\Re(f(\alpha))=0$ and $\Im(f(\alpha))=0$
now notice that if $f$ has real coefficients then
$$
f(\bar \alpha)=\overline {f(\alpha)} =\Re(f(\alpha)) -i\Im(f(\alpha))
$$


Find angle given two isosceles triangles.

Question: $\triangle{ABC}$ such that $AB = AC$. $P$ lies on $\overline{AC}$ and $Q$ lies on $\overline{BC}$ such that $AP = AQ$. Find $m\angle{PQC}$ if $m\angle{BAQ}=30^\circ$.
I constructed the triangle:

Using the fact that all sides of the triangle equal to $180^\circ$, I found the equation
$$x+x+30+\angle{QAC}=180$$
$$\angle{QAC}= 180-2y$$
So
$$15=y-x$$
I tried to find a second equation using the sum of exterior angles, but I kept on resolving equation to the aforementioned one.
I feel that this construction is unique, but I'm unable to find a second equation to solve for either x or y.
EDIT:
I realized that $\angle{PQC}$ is $y-x$. Since we know that $y-x=15$ from the previous equation, we know that this is the answer.
My new question:
Is it possible to find the values of $x$ and $y$ explictily?
Comment: But there's no unique $x$ and $y$.
Answer: Note:
I have deleted the proof. Since OP doesn't want it.
Claim
There are infinitely many triangles satisfying the given properties.
Proof
Take an arbitrary acute angle $x$. Construct the isosceles triangle $ABC$ with angles $x,x,90-2x$. Choose the point $Q$ on $BC$ such that $\angle BAQ = 30^\circ$. Now choose the point $P$ on $AC$ such that $|AQ| = |AP|.$ According to proof of OP we have $\angle PQC = 15^\circ$. Clearly we were able to construct to triangle for an arbitrary $x$. Therefore there can be infinitely many triangles.
Plot of two triangle with large and small $x$

Note: I have misprinted the point $P$ and $Q$ in the first image. Sorry.
Comment: Thank you. As I said, I found that the answer was $15$, but I was asking if  this triangle is unique. In other words, can you find x and y explicitly.
Comment: Oh sorry. Actually $y$ depends on $x$. And for different values of $x$ you can define the point $Q,P$ so that you have the same conditions. So triangles are not unique, you have infinitely many of them.
Comment: Ian, I have included more explanation.


R Markdown - specific issues with header and footer

Question: I am using R Markdown for showing the results of statistical analyses that I am conducting for my company. I would like to include the company logo at the upper right corner of the first page and company info in the footer of each page.
I browsed around this site to find potential answers, however they weren't very helpful for my purpose. I found this thread, but the procedures described within simply result with the logo being present on each page, whereas I only want it on the first page.
Since I couldn't find a way to do it, I gave up and tried to include only company info in the footer. I managed to properly include the company information in the footer; however, each page also contained a header with the name of the current chapter and the name of the document. I couldn't find a way to remove that header.
Is there a way to achieve what I want? Company logo in the header, only on the first page and company info in the footer on each page, with no chapter/document names in the header?
Comment: Could you show what you've tried to get a title-page already?
Comment: It may help you to look for answers in LaTeX, then convert that into Markdown
Comment: If you're going for PDF output (and therefore using LaTeX), you can use the `fancyhdr` latex package. One reference: https://latex.org/forum/viewtopic.php?t=9191. Corey's suggestion to look into latex is the right start, though.
Answer: Are you printing an html file? If yes this should work:
<code>htmltools::img(src = knitr::image_uri("logo.png"),
               alt = 'logo',
               style = 'position:absolute;top:0;right:100px;width:180px;height:100px;padding:10px;')
</code>
This is basic HTML so if you need to adjust the size of your logo you can do it using this part of the code: top:0;right:100px;width:180px;height:100px;


Why is an element that belongs to a set that belongs to another set not an element of the second set?

Question: If $A \in B$ and $a \in A$, does $a \in B$?
I've been told it does not.
Why does it not?
Comment: A human John is a citizen of New York: this can be written as $\text {John} \in \text {New York}$. Obviously NY is in US, and thus you are right. But there are cases when this is not true. NY belongs to the set of US cities. But $\text {John} \notin \text {US cities}$ because John is not a city.
Comment: Imagine the sets are opaque closed boxes
Comment: For example, $ 1 \in \mathbb{N} \in $ S={subsets of $\mathbb{R}$}, but $1 \notin S$.
Comment: This may help: https://math.stackexchange.com/questions/2620616/what-is-the-difference-between-x-and-x-when-x-itself-is-a-set/2620621#2620621
Comment: There is clear distinction in math (but not so clear in "human affairs") between $\in$ and $\subseteq$. Going back to the example above, if we consider the "universe" of humans, both a City and a State are collection of humans. Thus, $\text {John} \in \text {New York}$ and $\text {New York} \subseteq \text {US}$, from which we can correctly conclude with  $\text {John} \in \text {US}$
Answer: How about:
There is a word document on "My Desktop"
The word document contains several pictures, one of which is a picture of a rabbit.
However, there is not a picture of a rabbit on My Desktop.
$$$$
This is hopefully a clearer illustration because you can see the word document is there when looking at "My Desktop". However, you cannot see the picture of the rabbit when looking at "My Desktop". In other words, the word document acts like a black box, which is what we have when it comes to sets.
$$$$
Addendum:
However, it must be noted that sets do not always have a "meaning" and a "purpose" behind them. Sets are mathematical objects and the most important thing is knowing the precise mathematical definitions of things related to sets, e.g. you should know the definition of member of, subset of, complement of, intersection, union etc. The "meaning" and "purpose" of sets, for most people, I imagine, is slowly illuminated to them, the more they work with sets.
Comment: So is it fair to assume then we treat the subset as if it were opaque and we can't see inside it? Why is it helpful to make the subset opaque in that sense?
Comment: You can't see or access the inside the word document *unless* you double click on it. You ask, "why is opaqueness helpful?". But remember - if the word document was not opaque then you would see pictures of rabbits and everything inside all your Desktop Files on the Desktop, which would be a real pain. So black-boxing ("opaqueing") things is necessary for usefully categorising and compartmentalising things, and for giving a structure/ hierarchy. In the "sandwich in a bag in a box" example, the bag has a purpose (keeping the sandwich away from snotty tissues in the bag).
Answer: I found an intuitive solution that I'm happy with.
If you have a set of Animals={Dog, Cat, Elephant, Bird}
and you looked at Dog as a set of parts such as Dog={Ears, Legs, Tail, Eyes, Mouth}
it would not make sense to say that Ears ∈ Animals because Ears are not an animal.
Only when Ears are combined with Legs, Tail, Eyes, and Mouth do you get Dog.
The full set of elements that make up Dog are Necessary to make an animal.
Ears all on its own is not an Animal therefore it cannot be an element of the Set Animals.
Thanks for everyone's help!
Answer: Put a sandwich in a bag, and put the bag in a box. The box contains a bag.
Put a sandwich in a box. The box contains a sandwich.
Comment: I don't think this metaphor is helpful.  I'd certainly say that the sandwich is in the box in the first example.
Comment: If you Put a sandwich in a bag, and put the bag in a box you wouldn't say that the sandwich is inside the box? In reality, the sandwich is in the box. Why do we make this distinction here?
Comment: (Why am I suddenly both hungry and thirsty? Heh.)
Comment: If a bag contains a sandwich, and a box contains that bag why does the box not contain the sandwich? Why do we make this distinction? Why is it helpful to make a distinction between the sandwich being in the box and the sandwich being contained by the box? Hope I'm not being frustrating, and this is an understandable confusion.
Comment: Because "in" means one specific thing. If you drink a glassful of water, and you're standing on the floor, it doesn't mean that there is water on the floor. There is water in you, and you are on the floor. Similarly, you can't just choose to ignore the bag.
Comment: I feel like we're getting closer to my confusion and I really appreciate your time and patience but let me ask in a different way.
Comment: That was going to be question I was about to ask, Benjamin. I agree it is confusing
Comment: I like the water example, but I don't think the sandwich example is helpful.
Comment: The difference is that in the second case you would be willing to eat the contents of the box, but probably not in the first case, unless you like the taste of bags. They are not the same.
Answer: For example, $ 1 \in \mathbb{N} \in $ S={subsets of $\mathbb{R}$}, but $1 \notin S$.
Also, in maths we have precise meanings for subset of and member of. You are conflating the two.
Comment: What does S represent here? Thank you.
Comment: $S$ is the set of all *subsets* of $\mathbb{R}$. Here are three examples of subsets of $ \mathbb{R}: $ { $4,7,8$ } , $ [-4, 1) \cup $ {8}, { $ \ \frac{1}{n}: n \in \mathbb{Z} $} . So basically, any well-defined collection of members of $ \mathbb{R}$ written inside curly brackets is considered to be a subset of $ \mathbb{R}$.
Comment: So note that in my answer, { $1$ } $ \in S $, but $1 \notin S $
Comment: Also, note that { {$1$} } is a subset of $S$, but {$1$} is not a subset of $S$.
Answer: Let $A = \{\{1,2\}, \{3,4\}\}$.  By definition, the only elements of $A$ are those in the comma-separated list: $\{1,2\}$ and $\{3,4\}$.  So $\{1,2\} \in A$ and $\{3,4\} \in A$ but $1 \notin A$.  This is just true by definition; $\in$ is not a transitive relation in standard set theory.  You can't justify this by appeals to intuition; it's just a rule of the game.
We (that is, the mathematical community) could define $\in$ so that it is transitive, but we don't, because it would not be very convenient.  With the definition as it is, it's very easy to tell whether anything is an element of a comma-separated list: it has to be one of the things in the list.  Otherwise, to say for sure that $x \notin A$ you would have to check whether there happens to be any $B \in A$ with $x \in B$, or any $B \in A$ with a $C\in B$ so that $x \in C$, etc., which would create a headache.  With the standard definition, you can say that a set $\{A,B\}$ with $A \neq B$ has exactly two elements: $A$ and $B$, and no more.
Answer: Actually, from just knowing that $A\in B$ and $a\in A$, you cannot decide whether $a\in B$ or not. Both situations are possible.
For example, consider the case that $A=\{a\}$ and $B=\{A\}=\{\{a\}\}$. This could be depicted as follows:

Here the dots denote the sets, and the loops enclose their elements. As you can see, the set $B$ (blue) contains the set $A$ (red), but not the element $a$ (black), as $B$'s loop does not enclose the dot $a$.
On the other hand, consider $A=\{a\}$ and $B=\{a,A\}=\{a,\{a\}\}$. Then $B$ does contain both the set $A$ and its element $a$. This can be depicted as follows:

As you can see, now $B$'s loop not only encloses the set $A$, but also the element $a$ (which is also enclosed by $A$'s loop).
But in both cases you have $A\in B$ (the dot $A$ is enclosed in $B$'s loop) and $a\in A$ (the dot $a$ is enclosed by $A$'s loop).
Comment: How can the set of A and the total elements that are contained by A be separate entities? By making them equal such as A={a} shouldn't they be interchangeable in the equation B={A} and then you substitute in the initial equation and get B={{a}}. Why does B={{a}} not necessitate that B={a}.
Comment: For instance if A had one entity a. We would denote that as A={a}. Why can we not also show that as A=a?
Comment: @BenjaminLeeSchoemann: In general, the elements of a set are not even an entity. For example, consider the set $\{a,b\}$. The elements are $a$ and $b$. Each of them is an entity, but $a,b$ is not. $\{a,b\}$ *is* an entity (is is the set containing $a$ and $b$ and nothing else), but it is not the same as the elements. Or consider the empty set. It is clearly an entity, but it contains nothing. Nothing clearly isn't an entity, or else it wouldn't be nothing. And finally, consider $A$ from above. It contains one element, $a$, but surely *is* not that element: $\{a\}\ne a$.


Adding to a column 10 options on PLSQL

Question: I want to add column but it should be 10 options to my database(PL/SQL).
My sql query is look like this:
ALTER TABLE mytable
ADD NEWCOL

Do you think that is it work?
Answer: I don't have to think, I know it won't work.
SQL> INSERT_INTO MYTABLE
  2  (MYNEW_COL)
  3  VALUES
  4  (1,2,3,4,5,6,7,8,9,10);
INSERT_INTO MYTABLE
*
ERROR at line 1:
ORA-00900: invalid SQL statement

If you want to insert exactly those values, use a row generator:
SQL> insert into mytable (mynew_col)
  2  select level from dual
  3  connect by level <= 10;

10 rows created.

SQL> select * from mytable;

 MYNEW_COL
----------
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10

10 rows selected.

SQL>

Otherwise, discover other valid ways to do that, such as
SQL> insert into mytable (mynew_col)
  2  select 1 from dual union all
  3  select 2 from dual union all
  4  select 3 from dual;

3 rows created.

or
SQL> insert all
  2    into mytable (mynew_col) values (1)
  3    into mytable (mynew_col) values (2)
  4    into mytable (mynew_col) values (3)
  5  select * from dual;

3 rows created.

SQL>

[EDIT] Ah, you turned the question upside down. If you want to add a new column and limit number of valid values, then:
SQL> alter table mytable add newcol number;

Table altered.

SQL> alter table mytable add constraint
  2    ch_col check (newcol between 1 and 10);

Table altered.

Testing:
SQL> update mytable set newcol = 0;
update mytable set newcol = 0
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_COL) violated

SQL> update mytable set newcol = 11;
update mytable set newcol = 11
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_COL) violated

SQL> update mytable set newcol = 2;

16 rows updated.

SQL>

Comment: I edited the answer and added more info; have a look.
Comment: You're welcome. CH_COL is name of the check constraint; that's how I named it, you can use any other name, if you want. But, I prefer PK_ for primary keys, FK_ for foreign keys, CH_ for check constraints so that I know - at the first glance - what they are.
Comment: Sorry, I wrote wrong. I am trying to add a column and the values will be only 1 to 10. so I think I should use ALTER TABLE. I updated question, could you look at again please?
Comment: what is ch_col? btw and thank you for your answer. you helped a lot

Adding to a column 10 options on PLSQL


Disconnect event fire after 2 minutes

Question: I am using node.js and socket.io to create a chat application.
socket.on('disconnect',function(data){
    console.log("disconnected");
}

This event is fired as soon as the client gets disconnected(tab closed or network problem).
I want the disconnect event to be fired after 1 minute of disconnection from client. Is that possible? Is there any configuration in socket.io?
Comment: If there is already an option in socket.io, I can use that instead of writing my own function for timeout.
Comment: Why would this be useful? It's easy enough to add your own timeout for one minute *after* receiving a disconnect event.
Answer: That capability is not built into socket.io.  The disconnect event fires when the socket is disconnected.  Period.  If you want to trigger some activity 1 minute after a disconnect, you can build your own timer to do so.
socket.on('disconnect',function(data){
    setTimeout(function() {
        console.log("disconnected");
    }, 60 * 1000);
}

If you want to trigger your event only if the client does not reconnect within 1 minute, then you can code that also, but it is a little more involved as you have to save the timer for the setTimeout() and then cancel it if that specific client reconnects before the timer fires.

Based on what you put in your answer, here's what I think is an improved version:
(function() {
    var origClose = socket.onclose;
    socket.onclose = function(reason){
      var self = this;
      var args = Array.prototype.slice.call(arguments);

      /* Delay of 1 second to remove from all rooms and disconnect the id */
      setTimeout(function() {
          origClose.apply(self, args);
      }, 60 * 1000);
    }
})();

Answer: You have some parameters to control this behavior server-side. See close timeout and heartbeat timeout here
and if you're using v1.0 you'll need to set the options in the new style described here.
Note that these don't technically do what you're asking - they simply lengthen the amount of time a client has to reconnect.
Answer: Socket.onclose is fired immediately after disconnection before the disconnect event.
disconnect event can be delayed by changing as follows.
socket.onclose = function(reason){
  console.log(socket.adapter.sids[socket.id]);
  Object.getPrototypeOf(this).onclose.call(this,reason);

  /* Delay of 1 seconds to remove from all rooms and disconnect the id */
  setTimeout(function() {
      if (!this.connected) return this;
      debug('closing socket - reason %s', reason);
      this.leaveAll();
      this.nsp.remove(this);
      this.client.remove(this);
      this.connected = false;
      this.disconnected = true;
      delete this.nsp.connected[this.id];
      this.emit('disconnect', reason);
  }, 60 * 1000);
}

Comment: Why do you call the regular `onclose()` before your `setTimeout()`?  Won't that just cause the disconnect event to fire immediately?  Doesn't that defeat the purpose of what you're doing?  Can't you just call the prototype.onclose in your timeout and not duplicate all the code you are duplicating which can easily break in the future if the implementation changes?  I see what you're getting at with this and it appears you can solve your problem in this direction, but the code you've posted doesn't look right.
Comment: See what I put at the end of my prior answer for what I think is an improved version.  FYI, yours will not work as you've shown it because `this` is not correct inside the `setTimeout()` callback.

Disconnect event fire after 2 minutes


Pause HTML audio when particular element is clicked

Question: I want to implement background music on a site i'm creating. Theres also a music video thats pops out when a user hits the play button. How can I pause the background music once the play button is clicked on?
Play button html - The play button triggers a fancybox video popup. This is when I'd like to pause the background sound below.

Audio file
 <audio autoplay>
    <source src="sound.ogg" type="audio/ogg">
    <source src="sound.mp3" type="audio/mpeg">
 Your browser does not support the audio element.
 </audio>

How should I approach this?
Comment: An onclick event listener and `.pause()` on the audio element (and maybe a variable to store `isPlaying` in order to play the music back again) should do the job, but you'll have to try coding a bit yourself.
Answer: You can use pause() Method,
try with the following code.

 <audio autoplay id="myAudio">
    <source src="sound.ogg" type="audio/ogg">
    <source src="sound.mp3" type="audio/mpeg">
 Your browser does not support the audio element.
 </audio>

Comment: This worked fine. Though the music doesn't resume once the video is closed.
Comment: for that you have to use vimeo api, check this [link](http://stackoverflow.com/questions/14625367/fire-event-when-vimeo-video-stops-playing).
Comment: `if (aid.paused) {aid.play();} else {aid.pause();}` try this
Comment: @samsos: if this answers was helpful for you then please upvote.
Answer:  <audio id="bgmusic" autoplay>
    <source src="sound.ogg" type="audio/ogg">
    <source src="sound.mp3" type="audio/mpeg">
 Your browser does not support the audio element.
 </audio>

Comment: Have you tested it ?
Comment: Do you have jquery included?


Is there a way to sweep through floats in python using a for loop?

Question: I'm trying to sweep through values of pi/24 to pi/2 in steps of pi/24. Currently I'm getting an error, with float  object not being able to be interpreted as an integer. Is there any work around to this?
Sample of my code:
for theta in range(np.pi/24,np.pi/2,np.pi/24):
    v_initial_x = np.cos(theta)*velocity
    v_initial_y = np.sin(theta)*velocity

Comment: Pythons `range` can only work with integers. If you can use numpy, you can try: `numpy.linspace`
Comment: pi/24 is not a number that can be accurately represented as a floating-point value, so if this construct were allowed, the value would get increasingly inaccurate with each iteration.  You need to restructure it as an integer loop - perhaps `for i in range(1, 13)`, and then `theta = i * np.pi / 24` inside the loop.  That way, the error stays bounded.
Answer: It is because the built-in function range only takes integers. You can use numpy like so:
for theta in np.arange(np.pi/24, np.pi/2, np.pi/24):
    ''' Do your stuff here '''

Remember that the stop value is excluded from the range, so if you want to include that in your calculation, then you will have to add np.pi/24 to your stop value.
Answer: Another alternative:
import numpy as np
velocity = 4.0
for theta in range(1, 13):
    v_initial_x = np.cos((np.pi*theta)/24) * velocity
    v_initial_y = np.sin((np.pi*theta)/24) * velocity
    print(f"vx - {round(v_initial_y, 2):<10} vy - {round(v_initial_x, 2)}")

vx - 0.52       vy - 3.97
vx - 1.04       vy - 3.86
vx - 1.53       vy - 3.7
vx - 2.0        vy - 3.46
vx - 2.44       vy - 3.17
vx - 2.83       vy - 2.83
vx - 3.17       vy - 2.44
vx - 3.46       vy - 2.0
vx - 3.7        vy - 1.53
vx - 3.86       vy - 1.04
vx - 3.97       vy - 0.52
vx - 4.0        vy - 0.0


How can I update attributes in after_save without causing a recursion in rails 2.3?

Question: I've got a model which has a video attached with Paperclip. After it saves I use the saved video to generate a thumbnail. I need to do this after every save, even when a new video hasn't been uploaded, because the user can change the time where the thumbnail is captured.
I am currently using after_post_process to do this, but it will only generate the thumbnail when uploading a file (this is a callback which is part of Paperclip).
I would ideally use an after_save callback like this:
after_save :save_thumbnail
def save_thumbnail
  #generate thumbnail...
  self.update_attributes(
    :thumbnail_file_name => File.basename(thumb),
    :thumbnail_content_type => 'image/jpeg'
  )
end

Unfortunately update_attributes calls save, which then calls the before_save callback causing an infinite loop. Is there a simple way to circumvent this behaviour?
Answer: Any update_attribute in an after_save callback will cause recursion, in Rails3+.
What should be done is:
after_save :updater!
# Awesome Ruby code
# ...
# ...

private

  def updater!
    self.update_column(:column_name, new_value) # This will skip validation gracefully.
  end

Here is some documentation about it: https://guides.rubyonrails.org/active_record_callbacks.html#skipping-callbacks
Answer: You could wrap it in a conditional, something like:
def save_thumbnail
  if File.basename(thumb) != thumbnail_file_name
    self.update_attributes(
      :thumbnail_file_name => File.basename(thumb),
      :thumbnail_content_type => 'image/jpeg'
    )
  end
end

That way it would only run once.
Comment: Currently the thumbnail always has the same name as the video, so I'd have to encode the time in the thumbnail name, but that should work, thanks!
Answer: Rails 2:
Model.send(:create_without_callbacks)
Model.send(:update_without_callbacks)

Rails 3:
Vote.skip_callback(:save, :after, :add_points_to_user)

See this question:
How to skip ActiveRecord callbacks?
Comment: What if there are other callbacks that do need to be run?
Comment: This might well mess with Paperclip's callbacks, but useful nonetheless! Thanks.
Answer: You can(and should) check if you actually need to update the thumbnail:
after_save :save_thumbnail
def save_thumbnail
  if capture_time_changed? #assuming capture_time contains time when the thumbnail has to be captured
    #generate thumbnail...
    self.update_attributes(
      :thumbnail_file_name => File.basename(thumb),
      :thumbnail_content_type => 'image/jpeg'
    )
  end
end

Here you can read more about 'dirty' attributes: http://apidock.com/rails/ActiveRecord/Dirty
Although I'm not sure if it still can see the attribute changes in after_save. You can use a member variable to indicate changes in case it can't.
Answer: You can run it as a before_save instead.
After it has been validated, update the thumbnail, then let it go on to be saved, but just use the assignment methods
before_save :save_thumbnail
def save_thumbnail
  self.thumbnail_file_name = File.basename(thumb),
  self.thumbnail_content_type = 'image/jpeg'
end

Since that won't call save, you wont recurse, but it will immediately be saved after the method exits.
Something like that should work, unless there is an explicit reason you need it in after save.
Since you are not updating a separate object, but the same one, this will save you a database call as well. This is How i do timestamps and things like that too.
Comment: This doesn't work because the uploaded file won't have been processed by Paperclip yet, this is why I have been using after_post_process.


strcat() add extra characters at the beginning

Question: I would like to concatenate 2 strings in C using strcat(), but it is always add some random characters to the beginning of the new concatenated string.
Could someone please tell me why is this happening and how to solve it?
This is my code:
#include "stdio.h"
#include "string.h"

int main(void)
{

  char text[100];

  strcat(text, "Line 1");
  strcat(text, "Line 2");

  printf("%s", text);

  return 0;
}

When I execute this I get the following output:
???    Line1Line2

I would appreciate any help.
Thank you.
Comment: If `text` is a global variable as apparently shown, there should not be problem, because it is initialised to all 0 value. But if `text` is actually a local variable, it isn't initialised and using `strcat` on an uninitialised variable is *undefined behaviour*. Please post the exact, complete, code that you have, which should `#include` the necessary libraries.
Comment: @ddabrahim: No, people should not allow time before closing topics. If the question is repaired to make it useful, it can be reopened, and closing it until such time avoids cluttering Stack Overflow with multiple answers guessing what the problem actually was. Where patience can be useful is in taking the time to compose a fully prepared statement of the question, including following the guideline to provide a [mre] when suitable. For this question, it would have taken only slight effort to provide a program that correctly reproduced the issue instead of one that did not.
Comment: Good, but the code shown isn't the code you are using. Another solution is to use `strcpy` instead of the first `strcat`.
Comment: @ddabrahim: When replying to other people's comments, beware that the person you are replying to will only be notified of your comment if you use the `@` syntax with their name, when replying to them. If you don't use this syntax, then the person you are replying to may not notice your comment. Press the "Help" button when writing a comment for further information. You will automatically be notified of all comments to your question, but other people will not automatically be notified.
Comment: I can not reproduce.
Comment: Thank you it is the solution, I had to initialise text first.
Comment: Yes I have just fixed the code, people should allow some time before closing topics, it is honestly a bit annoying. It is solved anyway, thanks a lot.
Comment: I understand. I have fixed the problem. Could you reopen the topic now please? I don't want to do the same edit just to trigger reopening. I was notified I am going to be banned if I post one more question that does not follow the guidelines. I am honestly trying, I do my best to follow the guidelines but people act so fast. Thank you.
Comment: Thank you. I have added the #include directives and verified the above code does reproduce my problem. I'm going to make sure in the future to always provide a working example.
Answer: The line
strcat(text, "Line 1");

has undefined behavior, because both arguments of the strcat function call must point to strings, i.e. to null-terminated sequences of characters. However, the first argument is not guaranteed to point to a string, because text consists of indeterminate values, because it is not initialized.
You have two options to fix this bug. You can either

before the first call to strcat, set the first character of text to a terminating null character, i.e. text[0] = '\0';, so that text contains a valid (empty) string, or
replace the first function call to strcat with strcpy, because strcpy does not require that the first function argument points to a valid string.


"unable to open '/usr/share/icons/Pop/16x16@2x/actions/bookmark-new.png.dpkg-new': No such file or directory" error while trying to update

Question: Ign:1 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:2 http://ppa.launchpad.net/daniruiz/flat-remix/ubuntu focal InRelease
Hit:3 http://archive.ubuntu.com/ubuntu focal InRelease
Get:4 http://archive.ubuntu.com/ubuntu focal-updates InRelease [106 kB]
Hit:5 http://dl.google.com/linux/chrome/deb stable Release
Hit:7 http://archive.ubuntu.com/ubuntu focal-backports InRelease
Get:8 http://archive.ubuntu.com/ubuntu focal-security InRelease [107 kB]
Fetched 213 kB in 4s (48.5 kB/s)
Reading package lists... Done
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages will be upgraded:
  pop-icon-theme
1 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/7,360 kB of archives.
After this operation, 46.0 MB disk space will be freed.
Do you want to continue? [Y/n] Y
(Reading database ... 326295 files and directories currently installed.)
Preparing to unpack .../pop-icon-theme_2.1.0~1583343731~20.04~11f18cb~ubuntu1_all.deb ...
Unpacking pop-icon-theme (2.1.0~1583343731~20.04~11f18cb~ubuntu1) over
(1.4.0~1565992228~18.04~2bac292) ...
dpkg: error processing archive /var/cache/apt/archives/pop-icon-
theme_2.1.0~1583343731~20.04~11f18cb~ubuntu1_all.deb (--unpack):
 unable to open '/usr/share/icons/Pop/16x16@2x/actions/bookmark-new.png.dpkg-new': No such file or directory
No apport report written because the error message indicates an issue on the local system
         Errors were encountered while processing:
 /var/cache/apt/archives/pop-icon-theme_2.1.0~1583343731~20.04~11f18cb~ubuntu1_all.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

Output of apt-cache policy pop-icon-theme:
pop-icon-theme:
  Installed: 1.4.0~1565992228~18.04~2bac292
  Candidate: 2.1.0~1583343731~20.04~11f18cb~ubuntu1
  Version table:
     2.1.0~1583343731~20.04~11f18cb~ubuntu1 500
        500 http://archive.ubuntu.com/ubuntu focal/universe amd64 Packages
        500 http://archive.ubuntu.com/ubuntu focal/universe i386 Packages
 *** 1.4.0~1565992228~18.04~2bac292 100
        100 /var/lib/dpkg/status

Answer: I had the same issue. I removed the package and reinstalled using
sudo apt-get remove --purge pop-icon-theme
sudo apt install --reinstall pop-icon-theme


Why my tensorflow do not perform properly

Question: I tried to work tensorflow on my computer but the error message shows as follows1, I did install the tensorflow by following the exact instruction of the official website through pip, I do not understand why it happens. Does anyone have the same question as me?
I think the problem is at the exit code, but I do not find any information about this code.
x_train shape: (50000, 32, 32, 3)
50000 train samples
10000 test samples
y_train shape: (50000, 1)
2022-01-29 23:19:00.983142: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-01-29 23:19:01.360020: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1525] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 3493 MB memory:  -> device: 0, name: NVIDIA GeForce RTX 3060 Laptop GPU, pci bus id: 0000:01:00.0, compute capability: 8.6
Epoch 1/20
2022-01-29 23:19:03.467200: I tensorflow/stream_executor/cuda/cuda_dnn.cc:366] Loaded cuDNN version 8302

Process finished with exit code -1073740791 (0xC0000409)

Comment: Which Cuda version are you using? On Linux you can use `nvcc —version` to retrieve it from command line. If you are using a Docker container, run the command inside the container.
Answer: Please check if you have installed CUDA, cuDNN version compatible to your tensorflow version. You can check the build configurations details here.
Also check how to install tensorflow using pip and make sure you have followed correct path to install the tensorflow.