text:
Q: Why page number is not enabled correctly in listview and datapager I am using listview and datapager for display. I use two level of listview, where inner listview item can be 6 types. I use my own datasource. I only need to display 1 inner listviewitem per page. It display each page correctly, but page number is not set right, eg, when 2nd page (other as well) is click, 2nd page number is not disabled while 1st page number is still disabled. Here is the code:

        <asp:ListView ID="rptExercise2" runat="server"
            ItemPlaceholderID="itemPlaceHolder1" OnItemDataBound="ExerciseBound" OnPagePropertiesChanging="ChangeExercise">
            <LayoutTemplate>
                <asp:PlaceHolder ID="itemPlaceHolder1" runat="server" />
            </LayoutTemplate>

            <ItemTemplate>

<asp:Label ID="lbName" runat="server" />

            <asp:ListView ID="rptContent2" runat="server" ItemPlaceholderID="itemPlaceHolder2" OnItemDataBound="ContentBound">
                <LayoutTemplate>
                    <asp:PlaceHolder ID="itemPlaceHolder2" runat="server" />
                </LayoutTemplate>

                <ItemTemplate>

                        <asp:Label ID="lbID" runat="server" Text='<%# Eval("ID") %>' Visible="false" />

                        <asp:Label ID="lbWrapper" runat="server" Text='<%# Eval("Wrapper") %>' Visible="false" />

                        <asp:Label ID="lbAudioQuestion" runat="server" Visible="false" />

<asp:Label ID="lbAudioAnswer" runat="server" Visible="false" />

<asp:TextBox ID="tbAnswer" runat="server" TextMode="MultiLine" CssClass="tb" Width="50%" Height="60" Visible="false" />

<asp:RadioButtonList ID="rblChoice" runat="server" Visible="false" />

                </ItemTemplate>
            </asp:ListView>

            <asp:Panel ID="pnFeedback" runat="server" Visible="false" CssClass="Feedback">

                    Score:
<asp:TextBox ID="tbScore" runat="server" CssClass="tb" Width="40" /> / <asp:Label ID="lbScore" runat="server" />

                    <asp:Label ID="lbResultID" runat="server" Visible="false" />

                    Feedback

                    <asp:TextBox ID="tbFeedback" runat="server" TextMode="MultiLine" CssClass="tb" Width="200" Height="60" />

                    Recording

                    <asp:Label ID="lbFeedbackAudio" runat="server" />

            </asp:Panel>

            </ItemTemplate>
            <EmptyItemTemplate>

                    Sorry, no exercise is found for this lesson.

            </EmptyItemTemplate>

        </asp:ListView>

        <asp:DataPager ID="DataPager" runat="server" PagedControlID="rptExercise2"
            PageSize="1">
            <Fields>
                <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True"
                    ShowNextPageButton="False" ShowPreviousPageButton="False" />
                <asp:NumericPagerField ButtonCount="10" ButtonType="Button" />
                <asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="True"
                    ShowNextPageButton="False" ShowPreviousPageButton="False" />
            </Fields>
        </asp:DataPager>

public partial class MyPracClass : System.Web.UI.Page
{
    // Current page number
    int i = 0;

    protected classLessons les;
    protected classExercises exc;
    protected List<classExercises> exercises;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["LessonID"] == null)
        {
            return;
        }

        classLessons les = new classLessons(Convert.ToInt32(Request["LessonID"]));
        exc = new classExercises();
        exercises = exc.GetExercisesByLessonID(les.ID);

        if (!IsPostBack)
        {
            lbLessonName.Text = les.Name;
            lbDescription.Text = les.Description;
            //SetPageNumber();

            rptExercise2.DataSource = exercises;
            rptExercise2.DataBind();
        }
    }

    protected void ExerciseBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem item = (ListViewDataItem)e.Item;

            Label lbName = (Label)item.FindControl("lbName");
            string excName = "Exercise " + (i+1) + ": " + exercises[i].Subject;
            lbName.Text = excName;

            Label lbFeedbackAudio = (Label)item.FindControl("lbFeedbackAudio");
            classContent ct = new classContent();
            string test = "exercise" + exercises[i].ID + "student" + Session["StudentID"] + "feedback";
            lbFeedbackAudio.Text = ct.GetPlayingString("exercise" + exercises[i].ID + "student" + Session["StudentID"] + "feedback");

            ListView rptContent2 = (ListView)item.FindControl("rptContent2");
            Panel pnFeedback = (Panel)item.FindControl("pnFeedback");

            if (exercises[i] != null && rptContent2 != null)
            {
                classContent cct = new classContent();

                rptContent2.DataSource = cct.GetContentByExerciseID(exercises[i].ID);
                rptContent2.DataBind();
            }

            var result = new classResults();

            result.GetResultByExerciseID(Convert.ToInt32(exercises[i].ID));

            if (result.ID > 0)
            {
                pnFeedback.Visible = true;
                Label lbID = (Label)item.FindControl("lbResultID");
                Label lbScore = (Label)item.FindControl("lbScore");
                lbScore.Text = exercises[i].Score.ToString();
                TextBox tbScore = (TextBox)item.FindControl("tbScore");
                TextBox tbFeedback = (TextBox)item.FindControl("tbFeedback");

                lbID.Text = result.ID.ToString();
                tbScore.Text = result.Score.ToString();
                tbFeedback.Text = result.Feedback;
            }
        }
    }

    protected void ChangeExercise(object sender, PagePropertiesChangingEventArgs e)
    {
        // Get current page number
        i = e.StartRowIndex / e.MaximumRows;

        rptExercise2.DataSource = exercises;
        rptExercise2.DataBind();
    }

    //protected void DataPager_PreRender(object sender, EventArgs e)
    //{
    //    // Get current page number
    //    //i = e.StartRowIndex / e.MaximumRows;

    //    rptExercise2.DataSource = exercises;
    //    rptExercise2.DataBind();
    //}

    protected void ContentBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = (ListViewDataItem)e.Item;
            var qry = (classContent)dataItem.DataItem;

            Label lbAudioQuestion = (Label)e.Item.FindControl("lbAudioQuestion");
            Label lbAudioAnswer = (Label)e.Item.FindControl("lbAudioAnswer");
            Label lbWrapper = (Label)e.Item.FindControl("lbWrapper");
            TextBox tbAnswer = (TextBox)e.Item.FindControl("tbAnswer");
            RadioButtonList rblChoice = (RadioButtonList)e.Item.FindControl("rblChoice");

            switch (qry.Type)
            {
                case classContent.ContentType.AudioQuestion:
                    lbAudioQuestion.Visible = true;
                    lbAudioQuestion.Text = qry.GetPlayingString(qry.Wrapper);
                    break;
                case classContent.ContentType.TextQuestion:
                    lbWrapper.Visible = true;
                    break;
                case classContent.ContentType.VideoQuestion:
                    lbWrapper.Visible = true;
                    break;
                case classContent.ContentType.AudioAnswer:
                    lbAudioAnswer.Visible = true;
                    lbAudioAnswer.Text = qry.GetRecordingString("content" + qry.ID + "student" + Session["StudentID"]);
                    break;
                case classContent.ContentType.TextAnswer:
                    tbAnswer.Visible = true;
                    break;
                case classContent.ContentType.ChoiceAnswer:
                    rblChoice.DataSource = qry.GetChoiceOptions(qry.ID);
                    rblChoice.DataTextField = "Value";
                    rblChoice.DataValueField = "IsAnswer";
                    rblChoice.DataBind();
                    rblChoice.Visible = true;
                    break;
                default: break; ;
            }

            classAnswers ans = new classAnswers();

            var contentAnswer = ans.GetAnswerByContentID(qry.ID);

            if (contentAnswer.ID > 0)
            {
                switch (qry.Type)
                {
                    case classContent.ContentType.TextAnswer:
                        tbAnswer.Text = contentAnswer.Answer;
                        break;
                    case classContent.ContentType.ChoiceAnswer:
                        rblChoice.SelectedIndex = Convert.ToInt32(contentAnswer.Answer);
                        break;
                    default: break; ;
                }
            }

        }

    }

A: This article tells you everything you might need about utilizing a DataPager control https://web.archive.org/web/20201202213937/https://www.4guysfromrolla.com/articles/011310-1.aspx (see the last section of the article)
The article clearly explains about applying/modifying individual page numbers in the paging area. So I think you will simply have to write a CSS class to disable the current page number's button/link and enable the remaining page numbers.
Hope this helps...


text:
Q: Nhibernate: eager loading two child collections (one being a component list) i have a Parent class that has two child collections ChildCollectionA and ChildCollectionB.
ChildCollectionA is mapped as an association, and has its own ID:
HasMany(parent => parent.ChildCollectionA)
.KeyColumn("IDParent")
.AsBag().Cascade.AllDeleteOrphan();

and ChildCollectionB is mapped has a component list:
HasMany(parent => parent.ChildCollectionB)
    .Table("ChildCollectionBTable")
    .KeyColumn("IDParent")
    .Component(m=>
                {
                    m.References(childB => childB.Task, "IDTask").Not.LazyLoad().Not.Nullable();
                    m.Map(childB  => childB.Date, "Date").Not.Nullable();

                }
        )
    .AsBag().Cascade.AllDeleteOrphan();

I need now all the Parents in the DataBase, because i will have to perform some operations that need both ChildCollectionA and ChildCollectionB.
So I had to eager load them, I used fetch mode to eager load ChildCollectionA first:
    var queryParents = session.CreateCriteria()
        .SetFetchMode("ChildCollectionA", FetchMode.Eager)
        .Add(Expression.Le("ParentDate",endDate));
It returned 492 Parents (should be 481), the total value of the operation i performed was 32,847.46€ (should be 30,790.87€). So i has to eliminate Parent duplicates:
var queryParents = session.CreateCriteria<Parent>()
    .SetFetchMode("ChildCollectionA", FetchMode.Eager)
    .Add(Expression.Le("ParentDate",endDate))
    .SetResultTransformer(new DistinctRootEntityResultTransformer());

I tried the same eager loading with just the ChildCollectionB
var queryParents = session.CreateCriteria<Parent>()
    .SetFetchMode("ChildCollectionB", FetchMode.Eager)
    .Add(Expression.Le("ParentDate",endDate))
    .SetResultTransformer(new DistinctRootEntityResultTransformer());

In both cases returned 481 parents OK, and the value was 30,790.87€ OK.
But I needed to eager load both collections at the same time, I did this:
var queryParents = session.CreateCriteria<Parent>()
    .SetFetchMode("ChildCollectionA", FetchMode.Eager)
    .SetFetchMode("ChildCollectionB", FetchMode.Eager)
    .Add(Expression.Le("ParentDate",endDate))
    .SetResultTransformer(new DistinctRootEntityResultTransformer());

It returned 481 parents OK, and the value was 32,602.57€ (should be 30,790.87€).
Now the number of parents returned is correct, but there are duplicates somewhere else, the values depend on the collections and not the parent, so the duplicates must be somewhere in the ChildCollections.
Right now i'm using an ugly solution:
var queryParents = session.CreateCriteria<Parent>()
    .SetFetchMode("ChildCollectionA", FetchMode.Eager)
    .Add(Expression.Le("ParentDate",endDate))
    .SetResultTransformer(new DistinctRootEntityResultTransformer());

parents= queryParents.List<Parent>();

  foreach (Parent p in parents)
  {
      NHibernateUtil.Initialize(p.ChildCollectionB);
  }

It returned 481 parents OK, and the value was 30,790.87€ OK.
The problem happens when i eager load both collections, if i eager load just one, and then force the lazyload to the other, its works. I don't know if the mapping of ChildCollectionB being a component list instead of an association has something to do with this...
Any clues?
Thanks

A: I believe the problem is the Cartesian product between the two collections is not handled by the DistinctRootEntityTransformer...so you'll have duplicated data in the collections somewhere.
To load multiple collections eagerly it's going to take multiple queries.
var queryParents = session.CreateCriteria<Parent>()
    .SetFetchMode("ChildCollectionA", FetchMode.Eager)
    .Add(Expression.Le("ParentDate",endDate))
    .SetResultTransformer(new DistinctRootEntityResultTransformer());

//load CollectionB in second query...it's linked together by NH
session.CreateCriteria<Parent>()
    .SetFetchMode("ChildCollectionB", FetchMode.Eager)
    .Add(Expression.Le("ParentDate",endDate))
    .List();

What I normally do is fetch the main entity along with all the required many-to-one associations. Then I'll eagerly fetch required collections into the session with a MultiCriteria. If it's only two collections sometimes I do like above and fetch the first collection with distinctrootentity.
For more info see Eager loading aggregate with many child collections

redpajama_set_name: RedPajamaStackExchange


text:
Q: Go (golang), file uid on windows Is it possible to get a file's UID (owner) on Windows? I tried to use FileInfo.Sys(), but it only works on Linux. I'm really stumped on this one and can't figure out how to get the UID.

A: The first problem is that file systems native to Windows which supports file/directory ownership do not have the concept of "owner UID" simply because Windows users have no UIDs either.
The security of the Windows NT line or kernels is implemented using the so-called "access control lists" (ACLs), and security principals (such as users) are identified using the so-called "security identifiers" (SIDs).  A SID is a variable-length multi-field data structure usually passed around as a byte array.
Another complication is that a file on an ACL-enabled Windows file system might have no owner at all (and no ACL attached to it as well); this is rare but possible.
So... If the part of explanation stating "there's no such thing as the entry owner's UID on Windows filesystem" is OK for you, this is all there is to it.
If not, and you actually wanted to ask "how do I get security information for an entry on a Windows filesystem?", the question gets more complicated.
AFAIK the stock standard library shipped with Go does not have the necessary wrappers around the relevant bits of the Win32 API.  So to implement this, you'll need to either wrap them yourself (it's not that hard, after all) or try to find a helper package.


text:
Q: why does vector.erase remove all my duplicates? I'm trying to delete duplicates of numbers in a vector. i use this to do that:
vec1.erase(   unique(vec1.begin(),vec1.end())   ,vec1.end());

found it with google and it works just fine, my question is WHY?
according to what I've read on cplusplus, erase removes from the first parameter to the last.
ex:
vec1.erase(vec1.begin(),vec1.begin()+3);  //removes first 3 elements

and unique returns a pointer to the first duplicate, so in simpler version what I'm writing is:
vec1.erase(first duplicate, vec1.end());

shouldn't my vector end after the first duplicate?

A: std::unique eliminates unique elements in-place and returns a pointer to the resulting end of the range.  For example,
1 2 2 3 3 3
^begin      ^end

becomes
1 2 3 . . . (garbage)
      ^ resulting end

You're thinking of std::adjacent_find, which does return an iterator to the first duplicate element.


text:
Q: how to populate accounts in picklists and display contacts in table based on the selection of the account?(using bootstrap instead of vf) I have tried it using vf but i' m not able to get using bootstrap page.Please kindly help me.

A: Its very easy to do, First create a selectoption list in Apex controller side with the accounts, as below
public list<selectoption> accountOptionList {get; set;}
public string selectedAccountId {get; set;}
public list<contact> selectAccountContacts;
...
for(account acct: [select id, name from Account]){
     accountOptionList.add(new selectoption(acct.id,acct.name));
}

Now in visual-force as you want to try with Bootstrap styling so use the VF tags with Bootstrap styling classes, like:
<apex:selectList styleclass="form-control" value="{!selectedAccountId}" multiselect="false" size="1">
            <apex:selectOptions value="{!accountOptionList}"/>
</apex:selectList>

see bootstrap styles here: http://getbootstrap.com/css/#selects
On selection of account you want to render the contacts, so add action support functionality with apex select-list, like below:
    <apex:selectList styleclass="form-control" value="{!selectedAccountId}" multiselect="false" size="1">
        <apex:actionSupport event="onchange" action="{!getselectAccountContacts}" reRender="ContactsPanel"/>
        <apex:selectOptions value="{!accountOptionList}"/>
    </apex:selectList>

now add one more controller method which retrieve the contacts for selected account, as follows:
public list<contact> getselectAccountContacts(){
   return [SELECT id, name, ... FROM Contact WHERE AccountId :selectedAccountId];
}

now re-render the contacts on VF page: (As you want to use bootstrap so add bootstrap table styling):
<apex:outputPanel id="ContactsPanel">

     ...
     <apex:repeat value="{!selectAccountContacts}" var="contactRec">

          {!contactRec.name}
          ...
          ...

     </apex:repeat>

</apex:outoputPanel>

You can also achieve the same table with <apex:dataTable> tag also, in that tag you need to provide bootstrap styling with styleClass attribute.
In case if your Visial-force Page not rendering bootstrap styling properly then just add one attribute [standardStylesheets = "false"] in your <apex:page> tag, like below:
<apex:page standardStylesheets="false">


text:
Q: Object context of 'this' within a jQuery event Say I have the following defined in javascript:
com.company.long.namespace = {
    actions: {
        add: {
            defaults: {
                url: 'myurl/submit',
            },

            invoke: function () {
                var submitUrl = this.defaults.url;
                com.company.long.namespace.foo.util.server.submit({
                    url: submitUrl,
                    success: function() { }
                });
            },
        }
    }
};

which I then call with within the context of a JQuery click event:
$(myElem).click(function() {
    com.company.long.namespace.actions.add.invoke();
});

Because of the way 'this' works within jQuery event callbacks, this.defaults is undefined when called from this context. Is there anyway to still make use of 'this' within this scope, without having to define the full namespace, or without using jQuery.proxy?

A: You can't call add, it's not a function.
If you call the add.invoke function, this.default is the default object that you have defined in the add object. You don't have to do anything special.
Example: http://jsfiddle.net/p4j4k/

A: To call a function with a context of your choosing you can use .apply(context) (more info about function.apply and function.call):
com.company.long.namespace.actions.add.invoke.apply(com.company.long.namespace.foo.util.context);

Within the invoke function this will refer to the context object.
Check this jsFillde example


text:
Q: How do I correctly allocate more memory in this custom stack implementation? I am trying to make it so that my Stack doubles in size every time the size is exceeded. I need to create a new stack to hold the old stack, but have double the size. The old stack needs to be deleted. The code below keeps giving me errors
"Stack(17854,0x7fff77cd0300) malloc: * error for object 0x1001054b0: pointer being freed was not allocated
* set a breakpoint in malloc_error_break to debug"
Also, the random numbers being generated are the same every time I run my program. HELP!
#include <iostream>
using namespace std;

const int DEFAULT_SIZE = 100;

template< class T >
class Stack {
public:
    Stack( int = 10 );  // default constructor (stack size 10)
    // destructor
    ~Stack() {
            delete [] stackPtr;
    }

    bool push( const T& );
    bool pop( T& );
    int pop();

    // determine whether Stack is empty
    bool isEmpty() const {
            return top == -1;
    }

    // determine whether Stack is full
    bool isFull() const  {
            return top == size - 1;
    }

private:
    int size;     // # of elements in the stack
    int top;      // location of the top element
    T *stackPtr;  // pointer to the stack
};

// constructor
template< class T >
Stack< T >::Stack( int s ) {
    size = s > 0 ? s : 10;
    top = -1;  // Stack initially empty
    stackPtr = new T[ size ]; // allocate memory for elements
}

template< class T >
bool Stack< T >::push( const T &pushValue ) {
    if ( !isFull() ) {
        stackPtr[ ++top ] = pushValue;
        return true;
    }

    T *newPtr = new T[size*2];
    newPtr = stackPtr;
    delete [] stackPtr;
    return true;
}

template< class T >
bool Stack< T >::pop( T &popValue ) {
    if ( !isEmpty() ) {
        popValue = stackPtr[ top-- ];  // remove item from Stack
        return true;
    }

    return false;
}

template <class T>
int Stack< T >::pop() {
    return stackPtr[--size];
}

int main() {
    Stack<int> s;
    int i = 0;
    for (i=0; i < DEFAULT_SIZE; i++) {
        s.push( rand() % 100 +1 );
    }

    for (i=0; i < DEFAULT_SIZE; i++) {
        cout << s.pop() << " , ";
        if (i % 20 == 0) {
            cout << endl;
        }
    }
}

A: Take a look at this code, which is from your push implementation (it's the part where you allocate more memory):
1: T *newPtr = new T[size*2];
2: newPtr = stackPtr;
3: delete [] stackPtr;
4: return true;

Visually, here's what's happening. Before line 1, things look like this:
 +----------+       +-----+-----+-----+-----+
 | stackPtr | ----> | 137 | 271 | 281 | 284 |
 +----------+       +-----+-----+-----+-----+

After executing line 1, things look like this:
 +----------+       +-----+-----+-----+-----+
 | stackPtr | ----> | 137 | 271 | 281 | 284 |
 +----------+       +-----+-----+-----+-----+
 +----------+       +-----+-----+-----+-----+-----+-----+-----+-----+
 |  newPtr  | ----> |  ?  |  ?  |  ?  |  ?  |  ?  |  ?  |  ?  |  ?  |
 +----------+       +-----+-----+-----+-----+-----+-----+-----+-----+

After executing line 2, things look like this:
 +----------+       +-----+-----+-----+-----+
 | stackPtr | --+-> | 137 | 271 | 281 | 284 |
 +----------+   |   +-----+-----+-----+-----+
 +----------+   |   +-----+-----+-----+-----+-----+-----+-----+-----+
 |  newPtr  | --+   |  s  |  o  |     |  a  |  l  |  o  |  n  |  e  |
 +----------+       +-----+-----+-----+-----+-----+-----+-----+-----+

Oops. You just orphaned a bunch of memory.
After executing line 3, things look like this:
 +----------+
 | stackPtr | --+->    kablooie! deleted memory.
 +----------+   |
 +----------+   |
 |  newPtr  | --+
 +----------+

Notice that when you're done, you've ended up with orphaned memory (all the ?'s) and your stackPtr variable now points to dead memory. Oops.
To fix this, you'll need to make a few changes. First, when you wrote
newPtr = stackPtr;

my sense is that you intended to copy over all the elements from the old array to the new one. Unfortunately, as illustrated above, what you wrote doesn't do what you think it does. To fix this, you'll need to explicitly move over the elements one at a time. Consider using a for loop to do this - read from stackPtr one element at a time and write to the corresponding entry in newPtr.
Second, you'll need to change stackPtr so that, after you've blown up the memory that was previously allocated, you have it point to the newly-allocated memory. One way to do this would be to write
stackPtr = newPtr;

after you've freed the memory for stackPtr.
There's one other issue here. Notice that you never actually updated size after allocating the new array. This means that while you will get a brand-new array to work with, you won't actually remember how big it is. Therefore, after you've done everything else, make sure that you update size so that it's twice as big as before.
There may be other issues in the code, but I suspect that this will help get you started. Some things to remember:

*

*It never hurts to draw pictures when working with pointers.

*Be careful not to confuse "assign a pointer" with "copy elements of an array."

*Remember to do all the necessary bookkeeping.

Good luck!

A: T *newPtr = new T[size*2];
newPtr = stackPtr;
delete [] stackPtr;
return true;

This ends with stackPtr pointing to it's now-deleted original memory.  You also never actually move the content of the old memory to the new memory.  It should be something like:
T* newPtr = new T[size*2];
std::move(stackPtr, stackPtr + size, newPtr);
delete[] stackPtr;
stackPtr = newPtr;

Regarding rand returning the same thing every time; you never seed the random generator.  You need to call srand at the beginning of the program, before you ever call rand.

A: This code is clearly wrong:
T *newPtr = new T[size*2];
newPtr = stackPtr;
delete [] stackPtr;

You allocate a new pointer, then immediately discard it, then delete it. So the newly allocated memory is leaked, and stackPtr is already freed and invalid. You're also not updating size when it changes (well, when it would have been changed, if you weren't leaking memory like a sieve), and you sometimes use size when you probably meant top.


text:
Q: Quick way to send file from one branch to another Is there a quick way to inject a file (version) into another branch from the current branch?
Currently, I copy the file to a non-git location from branchX, than switch to branchY, and copy it there from the non-git location I saved it.  But that looks like too many manual steps.

A: You could cherry-pick the commit that added the file in branchX to branchY:
git checkout branchY
git cherry-pick <sha1>

If you made other changes in the same commit they will also be copied over to the current branch.

A: To only copy the file (with no other changes or commit history):
git checkout branchY
git checkout branchX -- /path/to/file

A: Cherry-picking a whole commit is often the right way to get "the file that goes with the commit" (since often you also need any changes made to other files in the same commit).
A direct answer to your question, though, is that you can view, or even check-out, a specific file within a specific commit:
git show <commit-ID>:<path>        # see the file
git checkout <commit-ID> -- <path> # bring it here

The <commit-ID> part can be anything that resolves to a commit SHA-1 (or even a tree SHA-1), such as a branch name like branchX, a relative history version ("what did this file look like three commits ago?  ah, I know how to see: git show HEAD~3:path/to/file.txt), or of course a raw SHA-1.
The difference between show and checkout is that show just looks at the contents (prints it to the standard output), while this form of checkout, with the -- <path> argument, writes the file through the index (so it will be committed on next check-in) and then into your working directory.
There are some subtleties with "smudge filters" as well (show skips them and checkout uses them), but unless you're using smudge filters, that probably won't affect you.
Note that a <path> is generally taken from the top of the repository; if you are in a sub-directory, you can git show HEAD~3:./file.txt to avoid having to remember/type-in the exact path to the sub-directory.


text:
Q: Using C macros in eclipse post-build step This question has been asked before (there are questions that are 5 or 10 years old) but without any real answer, usually a different approach has been used.
I'm working on a project where a different approach is simply not possible. We are using a third-party post-build step that needs some arguments (version) as part of the input. The version is set inside the C code using #define as some settings are set based on different parts of the version.
After some major changes, we have to recompile the code with different versions so I rather keep the version in a single location (in main.h preferably). Is there any way to do it in eclipse or do I have to bear the pain and just change it at multiple locations manually?
I'm using Eclipse Neon.3 Release (4.6.3), since I'm using system workbench and that's their default version.

A: You have some tool that does:

*

*Your build

*This post build step

Extract the version #define from your C project (in 1) and store it instead in a build system variable.  Then pass it as a -D parameter to the necessary files (in 1), and as a parameter in whatever way it's expected by step 2.

A: Using -D parameter (in project properties > C/C++ Build > settings > Tool Settings > Preprocessor) did not do the job for me as the macros or the build variables defined based on them were not expanding in the post-build step.
My workaround was to write a shell script to read the version from the header file and then pass it to the post-build. So I'm calling the other script inside my script that extracts the version. This way I can change the versions inside the code rather than the labyrinth of the eclipse settings.
This line extracts the version:
fw_version=$(cat "$projectdir/../Inc/main.h" | grep "FW_VERSION" | cut -d ' ' -f 3-)


text:
Q: Automapper projection returns empty list when query is not empty I'm implementing automapper for view models in a project and I'm just getting started with it.  A hurdle I'm finding myself up against is a type of behavior I'm not familiar with in Automapper.  I've been using automapper on a couple projects now and I haven't come across this issue before.
Basically in code this is what's happening:
var q = dbContext.Orders.Where(x => x.Name == 'name');
var l = q.ToList(); // count == 10
var shared = q.ProjectTo<OrderSharedModel>().ToList(); // count == 0

I figured out that when mapping a property that's null, it doesn't map anymore and it's like it just skips the mapping of that entity entirely.
For example:
class Order {
  public int OrderId { get; set; }
  public string Name { get; set; }
  public int? OrderTypeId { get; set; }
  public virtual OrderType { get; set; }
}

class OrderSharedModel {
  public int OrderId { get; set; }
  public string Name { get; set; }
  public OrderTypeSharedModel OrderType { get; set; }
}

If OrderType is null in Order then it will cause ProjectTo<OrderSharedModel>().ToList() to return an empty list.  If I commented out OrderType in the shared model, ProjectTo<OrderSharedModel>().ToList() will return the full list.  This is weird to me.
Why would ProjectTo<OrderSharedModel>().ToList() return an empty list if the original query before ProjectTo() is not empty?  Why won't automapper map a null property as null rather than skip the mapping entirely and return an empty list?
--UPDATE--
However if I use the other way mapping:
var l = q.ToList();
var sm = Mapper.Map<List<Order>, List<OrderSharedModel>>(l);

It works great.  I'm doing this for now until I find exactly why the queryable extension breaks.

A: Just encountered the same issue, an inner property of the dto was null and for some reason it was not in the result list. I upgraded from AutoMapper 8.1 to 9.0 and it works fine now.


text:
Q: Capture full webView in android I am unable to capture complete WebView, I'm capturing only visible content of Dashboard(Activity). My WebView is exceeding the activity. Guide me how to capture complete view.
webView.setWebViewClient(new WebViewClient() {

    public void onPageFinished(WebView v, String url) {
        webView.setDrawingCacheEnabled(true);
        webView.buildDrawingCache();
        Bitmap bmp = Bitmap.createBitmap(webView.getWidth(), webView.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        webView.draw(canvas);
        imgView.setImageBitmap(bmp);
    }
});

A: webView.setWebViewClient(new WebViewClient() {

    public void onPageFinished(WebView v, String url) {
        Picture picture = v.capturePicture();
        Bitmap bmp = Bitmap.createBitmap(
                      picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(b);
        picture.draw(canvas);
        imgView.setImageBitmap(bmp);
}

Sorry, I did not notice this

This method was deprecated in API level 19.
  Use onDraw(Canvas) to obtain a bitmap snapshot of the WebView, or saveWebArchive(String) to save the content to a file.
Gets a new picture that captures the current contents of this WebView. The picture is of the entire document being displayed, and is not limited to the area currently displayed by this WebView. Also, the picture is a static copy and is unaffected by later changes to the content being displayed.


text:
Q: How can I improve its runtime Problem Statement: You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin.
Is there a way to make my solution faster?
Explanation: dp[curr_amount] stores the minimum number of how many more coins I would need to reach target amount
def coinChange(self, coins: List[int], amount: int) -> int:

        if amount == 0:
            return 0

        dp = {}
        def backtrack(curr_amount):
            if (curr_amount) in dp:
                return dp[curr_amount]

            if curr_amount == amount:
                return 0

            if curr_amount > amount:
                return inf

            for coin in coins:
                if (curr_amount) not in dp:
                    dp[curr_amount] = inf
                # Take the minimum number of coins needed given all the possible choices
                dp[curr_amount] = min(dp[curr_amount], 1 + backtrack(curr_amount + coin))

            return dp[curr_amount]

        res = backtrack(0)

        if res == inf:
            return -1

        return res

A: Not sure how to fix your way, but can try to see if this can speed up.  It's DP bottom-up approach:
It's kind of follow @joanis thought (inspired by).  Thanks.
def min_coin_change(target, coins):
    # bottom up approach

    dp = [float("inf") for _ in range(target+1)]

    dp[0] = 0

    for i in range(1, target+1):
        for coin in coins:
            if i >= coin:
                dp[i] = min(dp[i], 1 + dp[i-coin])
    return dp[target] if dp[target] != float("inf") else -1

if __name__ == '__main__':
    coins = [1, 2, 5, 10]
    target = 17

    print(min_coin_change(target, coins))  # 3

    print(min_coin_change(24, coins))      # 4
    print(min_coin_change(124, coins))      # 14

A: I would suggest the breadth-first search approach.
The idea is as follows:

*

*Any value c in coins can be reached in one step

*If we can reach a value x in s steps, then we can reach x+c in s+1 steps, for each c in coins.

So, we can expand the mapping from the target to the minimum steps efficiently by using the queue structure.
from collections import deque

def coinChange(coins: list, target: int):
  # breadth-first search using queue data structure
  v = {0: 0}
  q = deque([0])
  while len(q) > 0:
    cur = q.popleft()
    for coin in coins:
      nxt = cur + coin  # we can reach this value in one more step
      if nxt in v:  # we have already covered this amount in shorter step
        continue
      if nxt == target:  # we have reached the target
        return v[cur] + 1
      if nxt < target:
        # we continue the search only for the values smaller than the target
        # because the value is only increasing
        v[nxt] = v[cur] + 1
        q.append(nxt)
  # we could not reach the target value
  return -1

print(coinChange([1, 2, 5, 10], 17))  # 3
print(coinChange([1, 2, 5, 10], 24))  # 4
print(coinChange([1, 2, 5, 10], 124)) # 14
print(coinChange([5, 8], 12))         # -1


text:
Q: Attaching custom view to the top of Android keyboard What is the simplest way to attach a layout defined in xml at the top of Android soft keyboard.
This view should only appear when the keyboard appears.

A: I think the best way is to detect when the keyboard appears and then attach view to the bottom of the screen (it will be above the keyboard after resizing all layout).

A: I think the cleaner way to do this.

*

*Define a layout resource file to use as your custom view

*Create a method which inflates this layout resource file and return it as a view:
Code Snippet
public View returnPayKeyView(){
View simpleView = getLayoutInflater().inflate(R.layout.simpleresource,null);
return simpleView;
}

*Set this returned view as the candidates using the setCandidatesView Method
The returned view will show above your keyboard, using the inflated xml layout resource.

A: One approach is to wrap your usual view layout in a FrameLayout and put the bit you want above the keyboard inside the frame along with your other view layout with a layout gravity of bottom.
My layout was along these lines:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <!-- all your stuff... -->

        </LinearLayout>

    </ScrollView>

    <LinearLayout
        android:id="@+id/stuffAboveKeyboardLayout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_gravity="bottom"
        android:orientation="horizontal"
        android:background="#DDD">

        <!-- stuff above keyboard... -->

    </LinearLayout>

</FrameLayout>

The downside is that it will show even when the keyboard is hidden - but it ought to be possible to show / hide the view when the keyboard shows / hides: How do I Detect if Software Keyboard is Visible on Android Device?


text:
Q: save data in array only once I'm detecting the variable's names from a code file and I want to save them in an array ONLY if I haven't done that already with the same variable name
Suppose this is the file I'm getting the variable names from:
echo $var1; echo $var2; echo $var1;

I would like to get an array like ($var1 $var2) rather than ($var1 $var2 $var1)
How do I check if the variable name already exists and how do I add that to a bash array?

A: If your bash is recent enough (version 4), you can use its associative arrays:
declare -A assoc
assoc[val1]=
assoc[val2]=
assoc[val1]=
echo ${!assoc[@]}


text:
Q: using sort in C++ to sort a string starting from 2nd character to last character I want to sort a string starting from the 2nd character to the last character. Currently I am able to sort the string as per my requirement but I want to utilize sort function in C++ to achieve the same
Sample input:
san test van best

Sample output:
san van test best

My current program
for (int i1 = 0; i1 < n; ++i1) {
    for (int j1 = i1 + 1; j1 < n; ++j1) {
        temp5 = arr[j1].substr(1, arr[j1].length() - 1);
        temp6 = arr[i1].substr(1, arr[i1].length() - 1);
        if (temp6.compare(temp5) > temp5.compare(temp6)) {
            a = arr[i1];
            arr[i1] = arr[j1];
            arr[j1] = a;
        }
    }
}

A: std::sort(std::begin(arr), std::end(arr),
    [](std::string_view const & l, std::string_view const & r){
        return l.substr(1) < r.substr(1);
    }
);

Full working example:
Try it online!
#include <string_view>
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

int main() {
    std::string arr[] = {"san", "test", "van", "best"};
    std::sort(std::begin(arr), std::end(arr),
        [](std::string_view const & l, std::string_view const & r){
            return l.substr(1) < r.substr(1);
        }
    );
    for (auto const & s: arr)
        std::cout << s << " ";
}

Output:
san van test best


text:
Q: I can't install anything anymore because of linux-image errors I'm trying to install the spotify client on Ubuntu 16.04 but I keep getting the following error.
I followed the instructions here: https://www.spotify.com/uk/download/linux/
 Same happens when I try to update mongodb for example. Any suggestions ?
 Reading package lists... Done
    Building dependency tree
    Reading state information... Done
    The following packages were automatically installed and are no longer required:
      linux-headers-4.4.0-36 linux-headers-4.4.0-36-generic linux-image-4.4.0-36-generic linux-image-extra-4.4.0-36-generic ubuntu-core-launcher
    Use 'sudo apt autoremove' to remove them.
    Recommended packages:
      libavcodec54 | libavcodec-extra-54 libavformat54
    The following packages will be REMOVED:
      linux-image-4.4.0-28-generic linux-image-4.4.0-31-generic linux-image-4.4.0-34-generic linux-image-extra-4.4.0-28-generic linux-image-extra-4.4.0-31-generic
      linux-image-extra-4.4.0-34-generic
    The following NEW packages will be installed:
      spotify-client
    0 upgraded, 1 newly installed, 6 to remove and 0 not upgraded.
    15 not fully installed or removed.
    Need to get 0 B/73,2 MB of archives.
    After this operation, 486 MB disk space will be freed.
    Do you want to continue? [Y/n] Y
    (Reading database ... 300801 files and directories currently installed.)
    Removing linux-image-extra-4.4.0-28-generic (4.4.0-28.47) ...
    depmod: FATAL: could not load /boot/System.map-4.4.0-28-generic: No such file or directory
    run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.4.0-28-generic /boot/vmlinuz-4.4.0-28-generic
    run-parts: executing /etc/kernel/postinst.d/dkms 4.4.0-28-generic /boot/vmlinuz-4.4.0-28-generic
    Error! Your kernel headers for kernel 4.4.0-28-generic cannot be found.
    Please install the linux-headers-4.4.0-28-generic package,
    or use the --kernelsourcedir option to tell DKMS where it's located
    run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.4.0-28-generic /boot/vmlinuz-4.4.0-28-generic
    update-initramfs: Generating /boot/initrd.img-4.4.0-28-generic
    WARNING: missing /lib/modules/4.4.0-28-generic
    Ensure all necessary drivers are built into the linux image!
    depmod: ERROR: could not open directory /lib/modules/4.4.0-28-generic: No such file or directory
    depmod: FATAL: could not search modules: No such file or directory
    depmod: WARNING: could not open /var/tmp/mkinitramfs_VAlZ4z/lib/modules/4.4.0-28-generic/modules.order: No such file or directory
    depmod: WARNING: could not open /var/tmp/mkinitramfs_VAlZ4z/lib/modules/4.4.0-28-generic/modules.builtin: No such file or directory
    run-parts: executing /etc/kernel/postinst.d/pm-utils 4.4.0-28-generic /boot/vmlinuz-4.4.0-28-generic
    run-parts: executing /etc/kernel/postinst.d/unattended-upgrades 4.4.0-28-generic /boot/vmlinuz-4.4.0-28-generic
    run-parts: executing /etc/kernel/postinst.d/update-notifier 4.4.0-28-generic /boot/vmlinuz-4.4.0-28-generic
    run-parts: executing /etc/kernel/postinst.d/zz-update-grub 4.4.0-28-generic /boot/vmlinuz-4.4.0-28-generic
    /usr/sbin/grub-mkconfig: 6: /etc/default/grub: Windows 10 (loader) (on /dev/sda1): not found
    run-parts: /etc/kernel/postinst.d/zz-update-grub exited with return code 127
    dpkg: error processing package linux-image-extra-4.4.0-28-generic (--remove):
     subprocess installed post-removal script returned error exit status 1
    Removing linux-image-4.4.0-28-generic (4.4.0-28.47) ...
    Examining /etc/kernel/postrm.d .
    run-parts: executing /etc/kernel/postrm.d/initramfs-tools 4.4.0-28-generic /boot/vmlinuz-4.4.0-28-generic
    update-initramfs: Deleting /boot/initrd.img-4.4.0-28-generic
    run-parts: executing /etc/kernel/postrm.d/zz-update-grub 4.4.0-28-generic /boot/vmlinuz-4.4.0-28-generic
    /usr/sbin/grub-mkconfig: 6: /etc/default/grub: Windows 10 (loader) (on /dev/sda1): not found
    run-parts: /etc/kernel/postrm.d/zz-update-grub exited with return code 127
    Failed to process /etc/kernel/postrm.d at /var/lib/dpkg/info/linux-image-4.4.0-28-generic.postrm line 328.
    dpkg: error processing package linux-image-4.4.0-28-generic (--remove):
     subprocess installed post-removal script returned error exit status 1
    Removing linux-image-extra-4.4.0-31-generic (4.4.0-31.50) ...
    depmod: FATAL: could not load /boot/System.map-4.4.0-31-generic: No such file or directory
    run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.4.0-31-generic /boot/vmlinuz-4.4.0-31-generic
    run-parts: executing /etc/kernel/postinst.d/dkms 4.4.0-31-generic /boot/vmlinuz-4.4.0-31-generic
    Error! Your kernel headers for kernel 4.4.0-31-generic cannot be found.
    Please install the linux-headers-4.4.0-31-generic package,
    or use the --kernelsourcedir option to tell DKMS where it's located
    run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.4.0-31-generic /boot/vmlinuz-4.4.0-31-generic
    update-initramfs: Generating /boot/initrd.img-4.4.0-31-generic
    WARNING: missing /lib/modules/4.4.0-31-generic
    Ensure all necessary drivers are built into the linux image!
    depmod: ERROR: could not open directory /lib/modules/4.4.0-31-generic: No such file or directory
    depmod: FATAL: could not search modules: No such file or directory
    depmod: WARNING: could not open /var/tmp/mkinitramfs_abdXZQ/lib/modules/4.4.0-31-generic/modules.order: No such file or directory
    depmod: WARNING: could not open /var/tmp/mkinitramfs_abdXZQ/lib/modules/4.4.0-31-generic/modules.builtin: No such file or directory
    run-parts: executing /etc/kernel/postinst.d/pm-utils 4.4.0-31-generic /boot/vmlinuz-4.4.0-31-generic
    run-parts: executing /etc/kernel/postinst.d/unattended-upgrades 4.4.0-31-generic /boot/vmlinuz-4.4.0-31-generic
    run-parts: executing /etc/kernel/postinst.d/update-notifier 4.4.0-31-generic /boot/vmlinuz-4.4.0-31-generic
    run-parts: executing /etc/kernel/postinst.d/zz-update-grub 4.4.0-31-generic /boot/vmlinuz-4.4.0-31-generic
    /usr/sbin/grub-mkconfig: 6: /etc/default/grub: Windows 10 (loader) (on /dev/sda1): not found
    run-parts: /etc/kernel/postinst.d/zz-update-grub exited with return code 127
    dpkg: error processing package linux-image-extra-4.4.0-31-generic (--remove):
     subprocess installed post-removal script returned error exit status 1
    Removing linux-image-4.4.0-31-generic (4.4.0-31.50) ...
    Examining /etc/kernel/postrm.d .
    run-parts: executing /etc/kernel/postrm.d/initramfs-tools 4.4.0-31-generic /boot/vmlinuz-4.4.0-31-generic
    update-initramfs: Deleting /boot/initrd.img-4.4.0-31-generic
    run-parts: executing /etc/kernel/postrm.d/zz-update-grub 4.4.0-31-generic /boot/vmlinuz-4.4.0-31-generic
    /usr/sbin/grub-mkconfig: 6: /etc/default/grub: Windows 10 (loader) (on /dev/sda1): not found
    run-parts: /etc/kernel/postrm.d/zz-update-grub exited with return code 127
    Failed to process /etc/kernel/postrm.d at /var/lib/dpkg/info/linux-image-4.4.0-31-generic.postrm line 328.
    dpkg: error processing package linux-image-4.4.0-31-generic (--remove):
     subprocess installed post-removal script returned error exit status 1
    No apport report written because MaxReports is reached already
                                                                  Removing linux-image-extra-4.4.0-34-generic (4.4.0-34.53) ...
    depmod: FATAL: could not load /boot/System.map-4.4.0-34-generic: No such file or directory
    run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.4.0-34-generic /boot/vmlinuz-4.4.0-34-generic
    run-parts: executing /etc/kernel/postinst.d/dkms 4.4.0-34-generic /boot/vmlinuz-4.4.0-34-generic
    Error! Your kernel headers for kernel 4.4.0-34-generic cannot be found.
    Please install the linux-headers-4.4.0-34-generic package,
    or use the --kernelsourcedir option to tell DKMS where it's located
    run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.4.0-34-generic /boot/vmlinuz-4.4.0-34-generic
    update-initramfs: Generating /boot/initrd.img-4.4.0-34-generic
    WARNING: missing /lib/modules/4.4.0-34-generic
    Ensure all necessary drivers are built into the linux image!
    depmod: ERROR: could not open directory /lib/modules/4.4.0-34-generic: No such file or directory
    depmod: FATAL: could not search modules: No such file or directory
    depmod: WARNING: could not open /var/tmp/mkinitramfs_4FQUrq/lib/modules/4.4.0-34-generic/modules.order: No such file or directory
    depmod: WARNING: could not open /var/tmp/mkinitramfs_4FQUrq/lib/modules/4.4.0-34-generic/modules.builtin: No such file or directory
    run-parts: executing /etc/kernel/postinst.d/pm-utils 4.4.0-34-generic /boot/vmlinuz-4.4.0-34-generic
    run-parts: executing /etc/kernel/postinst.d/unattended-upgrades 4.4.0-34-generic /boot/vmlinuz-4.4.0-34-generic
    run-parts: executing /etc/kernel/postinst.d/update-notifier 4.4.0-34-generic /boot/vmlinuz-4.4.0-34-generic
    run-parts: executing /etc/kernel/postinst.d/zz-update-grub 4.4.0-34-generic /boot/vmlinuz-4.4.0-34-generic
    /usr/sbin/grub-mkconfig: 6: /etc/default/grub: Windows 10 (loader) (on /dev/sda1): not found
    run-parts: /etc/kernel/postinst.d/zz-update-grub exited with return code 127
    dpkg: error processing package linux-image-extra-4.4.0-34-generic (--remove):
     subprocess installed post-removal script returned error exit status 1
    No apport report written because MaxReports is reached already
                                                                  Removing linux-image-4.4.0-34-generic (4.4.0-34.53) ...
    Examining /etc/kernel/postrm.d .
    run-parts: executing /etc/kernel/postrm.d/initramfs-tools 4.4.0-34-generic /boot/vmlinuz-4.4.0-34-generic
    update-initramfs: Deleting /boot/initrd.img-4.4.0-34-generic
    run-parts: executing /etc/kernel/postrm.d/zz-update-grub 4.4.0-34-generic /boot/vmlinuz-4.4.0-34-generic
    /usr/sbin/grub-mkconfig: 6: /etc/default/grub: Windows 10 (loader) (on /dev/sda1): not found
    run-parts: /etc/kernel/postrm.d/zz-update-grub exited with return code 127
    Failed to process /etc/kernel/postrm.d at /var/lib/dpkg/info/linux-image-4.4.0-34-generic.postrm line 328.
    dpkg: error processing package linux-image-4.4.0-34-generic (--remove):
     subprocess installed post-removal script returned error exit status 1
    No apport report written because MaxReports is reached already
                                                                  Errors were encountered while processing:
     linux-image-extra-4.4.0-28-generic
     linux-image-4.4.0-28-generic
     linux-image-extra-4.4.0-31-generic
     linux-image-4.4.0-31-generic
     linux-image-extra-4.4.0-34-generic
     linux-image-4.4.0-34-generic
    E: Sub-process /usr/bin/dpkg returned an error code (1)


text:
Q: WCF, dealing with simultaneous requests from multiple servers I have a block of work which ive split into smaller blocks. I want to assign each block to an instance of NumberCruncher (Each instance would be hosted at a unique EndPoint and would be run on a specific thread on the server). The instance of NumberCruncher at the specified EndPoint would then go and crunch those numbers passed to it by the Client proxy, before returning the results in a txt file format.
From a client side, Im assuming i need to keep 2 threadsafe list, 1 containing the EndPoints linked to instances of NumberCruncher which are waiting to return their results. A 2nd for the instances of NumberCruncher which are waiting to be assigned more work?
Regarding adding items to these lists, how is it possible to deal with multiple requests from Servers? Only one can be added at a time, so im assuming the client need to send a message back to the service saying "Yes you were successfully added to the list, now stop requesting to be added."?
EDIT
I'm currently trying to run some analysis on a time series i have collected. Ive written a program (Number Cruncher) which splits the different parameters i want to check and assigns them to different threads (determined by the number of cores in my pc). Each thread then runs Number Cruncher with the assigned input. Unfortunately this is taking a stupid amount of time on my pc even when using all the cores. So i wanted to run this same program but on several pc's (servers), and write a single program which would allocate work to all the servers. Each simulation takes about ~1hr. So im looking at 520hrs of computation time (ie not feasible for a single pc).

A: I think you're over thinking this.
In WCF you do have some control over the number of instances (single, per-session and per-request) and whether an instance is single or multi-threaded. But not over thread-affinity of a request.
And you don't need to, it seems to me you should just configure instance-per-request (depends very much on details of the coding and state-management).
You can throttle the server to achieve maximum capacity and acceptable latency. Don't mess with thread-management if you don't have to.

After the Edit
You can use WCF for this but it is a distributed computing problem, specialized software exists.
You could run the worker PCs as server, this seems to be your current direction. But I would:

*

*run 1 server that splits the work and administers the workitems

*

*needs to check for 'overdue' items and re-issue them

*run multiple clients that can ask for as much workitems as they have cores

*

*need to be configured for max load. could be cores+2 or cores-1


text:
Q: Add new column from conditional logic in Octave Let's say I have this vector (or matrix)
 a = [1; 2; 3]

it is a 3x1
1
2
3
How would I add another column based off conditional logic?
Say I want the second column to be 1 or 0 depending on if the first column is>= 2
What vectorized code would conditionally create and concatenate to create this?
1  0
2  1
3  1
I know R better, and with data.table I can do something similar to
data[col1 >= 2, second col := 1, ]

A: You can either use [] to implicitly horizontally concatenate the two
b = [a, a >= 2];            % Implicit horizontal concatenation

Or you can use horzcat or cat to accomplish the same thing
b = horzcat(a, a >= 2);     % Horizontal contatenation
b = cat(2, a, a >= 2);      % Concatenate along the second dimension


text:
Q: Row Level Security with multiple users for one row I'm trying to implement Row Level Security in SQL Server 2016.
The problem is, I can have multiple users that should have read permissions over given rows, and when I write some complex condition in the predicate the performance gets like very very very bad.
I tried to keep all usernames in one column of the table and in the predicate to search through them for the SYSTEM_USER with % LIKE  % but performance is low.
Example of the values in the Usernames column in my controlled table for one row:
domain\john.wick;domain\red.eagle;domain\spartak.something....
Here is my function:
CREATE FUNCTION fn_securitypredicate(@Usernames AS nvarchar(4000))
  RETURNS TABLE
WITH SCHEMABINDING
AS
  RETURN
  SELECT 1 as Result
  WHERE @Usernames LIKE '%' + SYSTEM_USER + '%'

With this execution time from 2 sec became 50 sec. Any suggestions for improvement.
CREATE SECURITY POLICY [Policy]
ADD FILTER PREDICATE [fn_securitypredicate]([Usernames])
ON [dbo].[Products];

A: This is the solution I came up with for my previous team.
This requires a a users table, a users permissions table as well as a permission column on your controlled table. It should also have a user group and user group permissions table to scale with users.
users                   user_permissions            controlled_table
+-----------+---------+ +---------+---------------+ +---------------+------+------+
| user_name | user_id | | user_id | permission_id | | permission_id | pk_1 | pk_2 |
+-----------+---------+ +---------+---------------+ +---------------+------+------+
| admin     |       1 | |       1 |             0 | |             2 |    1 |    1 |
| user1     |       2 | |       2 |             1 | |             2 |    1 |    2 |
| user2     |       3 | |       2 |             2 | |             3 |    1 |    3 |
| user3     |       4 | |       2 |             3 | |             4 |    2 |    1 |
|           |         | |       2 |             4 | |             3 |    2 |    2 |
|           |         | |       3 |             1 | |             1 |    2 |    3 |
|           |         | |       3 |             2 | |             1 |    3 |    1 |
|           |         | |       4 |             2 | |             5 |    3 |    2 |
|           |         | |       4 |             3 | |             4 |    3 |    3 |
|           |         | |       4 |             4 | |             2 |    4 |    1 |
|           |         | |         |               | |             3 |    4 |    2 |
|           |         | |         |               | |             3 |    4 |    3 |
+-----------+---------+ +---------+---------------+ +---------------+------+------+

For performance, you will want to add the permission_id to whatever index you were using to search the controlled table. This will allow you to join permissions on the index while searching on the remaining columns. You should view the execution plan for specific details on your indexes.


text:
Q: Reformat SQL Server Table Column Names and Pivot I have a table stored in a SQL Server database that contains user ID, Product Name and values by week stored in columns. The column names for the weeks are named like this "trx_2015#08#07" and the value for that week is stored in each column:
UserId, ProductName, trx_2015#08#07, trx_2015#08#014, trx_2015#08#21

I would like to clean up those column names (I can't alter the table) to just be the week value (2015-08-07) then pivot the data to be in this format:
userID, ProductName, Week, Value

Any thoughts on the easiest way to accomplish this?

A: SQL Server provides a method for manipulating the data as you would like to with the use of the UNPIVOT relational operator. Below is an example of how to accomplish this in addition to dynamically obtaining the column names (ideally, we would not want to update the query every time a column is added).
Schema/Data Setup for Answer
CREATE TABLE tbl (
  UserId INT,
  ProductName NVARCHAR(1000),
  [trx_2015#08#07] INT,
  [trx_2015#08#014] INT,
  [trx_2015#08#21] INT
);

INSERT INTO tbl(UserId, ProductName, [trx_2015#08#07], [trx_2015#08#014], [trx_2015#08#21])
VALUES (1, 'Product #1', 123, 456, 789);

Dynamically obtaining trx column names
We will need an aggregate concatenation of the trx colmn names to pass to the UNPIVOT relational overator's IN clause.
SELECT STUFF((SELECT ',' + QUOTENAME(COLUMN_NAME)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE
    TABLE_NAME = 'tbl'
    AND COLUMN_NAME LIKE 'trx_%'
  FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '')

Building the query
Ultimately, we would like the query to look like this:
SELECT UserId, ProductName, Value, trx
FROM tbl
  UNPIVOT(
    Value FOR trx IN ([trx_2015#08#014],[trx_2015#08#07],[trx_2015#08#21])
  ) AS unpvt

The query must be built dynamically in SQL because the IN clause here cannot accept a result set.
Query:
DECLARE @SQLString NVARCHAR(MAX);
SET @SQLString = CONCAT(
  'SELECT UserId, ProductName, Value, trx FROM tbl UNPIVOT(Value FOR trx IN (',
  (SELECT STUFF((SELECT ',' + QUOTENAME(COLUMN_NAME)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE
    TABLE_NAME = 'tbl'
    AND COLUMN_NAME LIKE 'trx_%'
  FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '')),
  ')) AS unpvt'
);

EXEC(@SQLString);

Result Set:
UserId  ProductName Value   trx
1       Product #1  456     trx_2015#08#014
1       Product #1  123     trx_2015#08#07
1       Product #1  789     trx_2015#08#21


text:
Q: What Partition of HDD should Ubuntu be installed?
*

*Does installation of Ubuntu from WUBI require another partition for loading? If it loads on C: then is it and OS Environment only? Kindly explain.

*Should it be a Primary Partition only? As I understand that only form Primary partition the OS can be loaded.

A: *

*Installing Ubuntu using WUBI (i.e. from within Windows) doesn't require any extra partitions to be created. It simply creates a file on your Windows partition, and adds an entry to the Windows boot loader to boot an OS (Ubuntu) from this image file.
It also adds an entry to your "Add/Remove Programs" section of Windows so that you can easily remove this Ubuntu image file from your C: (i.e. your Windows partition). The only real downside to this AFAIK is a very slight decrease in speed due to being restrained by the Windows filesystem (NTFS or FAT) speed-wise, but this is only a slight decrease and it's not really noticeable to most users.

*See (1), WUBI installs don't need any partitioning.

A: WUBI does not need a partition. It uses a loop device which is a virtual disk therefore it must be installed on a Windows filesystem (C: Drive is OK).


text:
Q: How to get a geo location and show to the map I have been trying to get a location address from a text box then get the latitude and longitude from the address and show the nearest train station from the address.
I can get the latitude and longitude of an address
I also can show the nearest train stations from a specific latitude and longitude.
My problem is when I try to get the latitude and longitude form an address and put the address latitude and longitude to show the nearest train station, I failed.
Please find my code below(problem is in alert-)-
function initialize() {

        // start
        var latitude;
        var longitude;
        geocoder = new google.maps.Geocoder();
        var address = document.getElementById('address').value;
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
                latitude = results[0].geometry.location.lat();
                longitude = results[0].geometry.location.lng();
                alert(longitude);

            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });

        alert(longitude);

        var pyrmont = new google.maps.LatLng(-37.8176108, 145.0422631);

        map = new google.maps.Map(document.getElementById('map-canvas'), {
            center: pyrmont,
            zoom: 15
        });

        var request = {
            location: pyrmont,
            radius: 1000,
            types: ['train_station', 'bus_station', 'subway_station',   'transit_station']
        };
        infowindow = new google.maps.InfoWindow();
        var service = new google.maps.places.PlacesService(map);
        service.nearbySearch(request, callback);

    }

A: The issue is that geocoder.geocode runs asynchronously, you'll not be able to access the results before the callback has been called, so you should invoke the following (nearbySearch) in the callback.
Another problem: currently you'll not be able to geocode/search again without creating a new map(of course you may always create a new map by calling initialize again, but this will result in bad performance and will also increase the map-loads...which are limited).
a solution which separates the map-creation from the geocoding/search(wraps the address-field into a form, the geocoding/search will be invoked when the form will be submitted)

function initialize() {

  "use strict";
  var map = new google.maps.Map(document.getElementById('map-canvas'), {
      center: new google.maps.LatLng(-37.8176108, 145.0422631),
      zoom: 1
    }),
    field = document.getElementById('address'),
    form = field.form,
    marker = new google.maps.Marker(),
    info = new google.maps.InfoWindow(),
    //I use this object later to hide previously added markers
    mvc = new google.maps.MVCObject(),
    geocoder = new google.maps.Geocoder(),
    service = new google.maps.places.PlacesService(map);

  //use the field as control when you want to
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(form);

  google.maps.event.addListener(marker, 'click', function() {
    google.maps.event.trigger(info, 'open', this);
  });

  //this will open the infowindow for a clicked marker
  //the infowindow-content will be retrieved from the
  //content-property of the marker
  google.maps.event.addListener(info, 'open', function(marker) {
    this.setContent(marker.get('content'));
    this.open(marker.getMap(), marker);
  });

  marker.bindTo('map', mvc, 'map');

  //this separates the geocoding/places-search from the map-creation
  //it will be executed when the form will be submitted
  //(e.g. by hitting ENTER in the address-field)
  google.maps.event.addDomListener(form, 'submit', function(e) {
    if (e) e.preventDefault();

    //this hides all markers and the infowindow
    mvc.set('map', null);

    if (field.value.match(/\S+/)) {
      geocoder.geocode({
        'address': field.value
      }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          mvc.set('map', map);
          if (results[0].geometry.viewport) {
            map.fitBounds(results[0].geometry.viewport);
          } else {
            map.setCenter(results[0].geometry.location);
          }

          marker.setValues({
            position: results[0].geometry.location,
            content: results[0].formatted_address
          });

          service.nearbySearch({
            location: results[0].geometry.location,
            radius: 1000,
            types: ['train_station', 'bus_station', 'subway_station', 'transit_station']
          }, function(places, status) {

            if (status == google.maps.places.PlacesServiceStatus.OK) {

              //will be used later to set the viewport
              //so that it contains all markers
              var b = new google.maps.LatLngBounds();

              places.forEach(function(place, i) {

                var m = new google.maps.Marker({
                  position: place.geometry.location,
                  icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png',
                  content: place.name
                });

                b.extend(place.geometry.location);
                m.bindTo('map', mvc, 'map');

                google.maps.event.addListener(m, 'map_changed', function() {
                  if (!this.getMap()) this.unbindAll();
                });

                google.maps.event.addListener(m, 'click', function() {
                  google.maps.event.trigger(info, 'open', this);
                });

              });

              if (places.length > 1) {
                map.fitBounds(b);
              }
            } else {
              alert('NearbySearch was not successful for the following reason: ' + status);
            }

          });
        } else {
          alert('Geocoding was not successful for the following reason: ' + status);
        }
      });
    }
    return false;
  });
  //trigger form-submit for the initial search
  google.maps.event.trigger(form, 'submit');

}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
  height: 100%;
  margin: 0;
  padding: 0;
}
#address {
  width: 300px;
}

<form>
  <input id="address" value="21 Elphin Grove, Hawthorn VIC 3122, Australia" placeholder="insert an address and hit ENTER" title="insert an address and hit ENTER"/>
</form>


text:
Q: Alternating sum of combinations of the n by consecutive k Like in this question I have to prove that the alternating sum equals 0. If n is even the case is easy: there exist a bijection between the elements of the series and they cancel each other out. If n is odd than I get an alternating sum of the numbers from a given row in Pascal's trangle... and what now?

A: Sorry guys, nevermind. The answer is at:
https://www.math.hmc.edu/~benjamin/papers/DIE.pdf


text:
Q: How can I write information to two database tables from one "if "statement? I wish to post the users entered information into two different tables in the same data base. However my code does not seem to work, it only writes into the second table that I have asked it to write to. Why wont it write to the first table as well?
if ($_POST['entereddetail']) {

$sql = "INSERT INTO firsttable (thedetail, date)
VALUES ('". $_POST['entereddetail'] ."', NOW())";

$sql = "INSERT INTO secondtable (thedetail, code, branch, user, date)
VALUES ('". $_POST['entereddetail'] ."','". $_POST['codedetail'] ."', '', '', NOW())";

if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
   }
}

I know my code could be subject to SQL injection. I am only learning the basics at the moment and then I deal with security after as I am only new to SQL and databases. My branch and users field are also left blank as I will be dealing with them later.

A: That's because you're overwriting your $sql variable.
Adapt your code like this:
$sql = "INSERT INTO firsttable (thedetail, date)
VALUES ('". $_POST['entereddetail'] ."', NOW());";

$sql .= "INSERT INTO secondtable (thedetail, code, branch, user, date)
VALUES ('". $_POST['entereddetail'] ."','". $_POST['codedetail'] ."', '', '', NOW());";

Notice: If you look closely, you'll see a ; at the of the sql-statements. The .= will combine the two $sql variables into one string of two MySQL-statements.

A: Your only executing the second query...
if ($_POST['entereddetail']) {

$sql = "INSERT INTO firsttable (thedetail, date)
            VALUES ('". $_POST['entereddetail'] ."', NOW())";
if ( mysqli_query($conn, $sql) ) {
    $sql = "INSERT INTO secondtable (thedetail, code, branch, user, date)
               VALUES ('". $_POST['entereddetail'] ."','". $_POST['codedetail'] ."', '', '', NOW())";

    if(mysqli_query($conn, $sql)){
        echo "Records inserted successfully.";
    } else{
       echo "ERROR: Could not execute $sql. " . mysqli_error($link);
   }
}
else{
       echo "ERROR: Could not execute $sql. " . mysqli_error($link);
   }


text:
Q: Quetion About The Proof of Noether's Theorem My quetion is about the proof of Noether's theorem in Arnold Mathematical Methods Of Classical Mechanics.
Let $M$ be a smooth manifold, suppose the Lagrange function $L(q,\dot{q})$ is a smooth function on the tangent bundle $TM$.
Let $h^s:M\to M,s\in\mathbb{R}$ be a one-parameter group of diffeomorphism that satisfies
$$L(h^s_*v)=L(v),\forall v\in TM, \forall s\in\mathbb{R},$$
where $h_*$ is the pushforward induced by $h$.
Let $\varphi(t)$ be a solution of lagrange equation $\frac{\partial L}{\partial q}-\frac{\mathrm d}{\mathrm d t}\frac{\partial L}{\partial\dot{q}}=0$, and let $\Phi(s,t)=h^s(\varphi(t))$.
It seems that Arnold used $\frac{\mathrm d}{\mathrm d s}\frac{\mathrm d}{\mathrm d t}\Phi=\frac{\mathrm d}{\mathrm d t}\frac{\mathrm d}{\mathrm d s}\Phi$ in the proof, but I don't know why does it holds.


text:
Q: Flutter test: The value of a foundation debug variable was changed by the test When I run my integration test, the test failed with this error:
[+1358 ms] flutter: ══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
[        ] flutter: The following assertion was thrown running a test:
[        ] flutter: The value of a foundation debug variable was changed by the test.
[        ] flutter:
[        ] flutter: When the exception was thrown, this was the stack:
[        ] flutter: #0      debugAssertAllFoundationVarsUnset.<anonymous closure> (package:flutter/src/foundation/debug.dart:30:7)
[        ] flutter: #1      debugAssertAllFoundationVarsUnset (package:flutter/src/foundation/debug.dart:32:4)
[        ] flutter: #2      TestWidgetsFlutterBinding._verifyInvariants (package:flutter_test/src/binding.dart:834:12)
[        ] flutter: #3      TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:821:7)
[        ] flutter: <asynchronous suspension>
[        ] flutter:
[        ] flutter: The test description was:

When I debug into the exception, I found that this checkpoint is failed:
debugDefaultTargetPlatformOverride != null  // it is TargetPlatform.macos

I'm not sure how to deal with this error. The value can be changed everywhere and it make my test fail.
Any solution or workaround?

A: Had the same, my solution was:
You have to set the TargetPlatform to null before finishing of tests
 debugDefaultTargetPlatformOverride = TargetPlatform.iOS;

//  HERE RUN YOUR TESTS AND CHECKS

debugDefaultTargetPlatformOverride = null;


text:
Q: private vs final как метка "этот метод нельзя переопределить" Создавая класс мы проектируем его таким образом, чтобы классы-наследники могли с ним работать через специальный интерфейс публичных методов. Скрытую реализацию мы помечаем как private. Но как понять, что лучше использовать - private или final? И осмысленно ли применение обоих?

A: Вы правы в одном - как final, так и private - оба не дают вам переопределить метод в наследнике.
Однако предназначение у них совершенно разное. Это как сравнивать машину и самолёт только потому, что у них есть колёса.
А теперь пример. Что, если вы хотите сделать открытый (public) метод, но без возможности переопределения? private вам тут не поможет.
Пусть будет класс Dog и класс Bulldog (и вы не хотите, чтобы в подклассе класса Dog можно было изменить количество ног собаки, ведь все собаки с 4-мя ногами, верно?):
public class Dog {
    public final int getLegsCount() {
        return 4;
    }
}

public class Bulldog extends Dog {

}

И в вашей программе вы всегда сможете получить количество ног собаки, будь то бульдог или просто некая абстрактная собака:
Dog dog = new Dog();
dog.getLegsCount();

Dog bulldog = new Bulldog();
bulldog.getLegsCount();

Bulldog bulldog2 = new Bulldog();
bulldog2.getLegsCount();

Хоть вы и можете получить количество ног, но вы не можете сделать собаку с 3-мя ногами, к примеру.
С другой стороны - пометь вы метод getLegsCount() как private, а не public final, вы бы не смогли вызвать его в вашей программе (вне класса Dog).


text:
Q: Why is String Templating Better Than String Concatenation from an Engineering Perspective? I once read (I think it was in "Programming Pearls") that one should use templates instead of building the string through the use of concatenation.
For example, consider the template below (using C# razor library)
<in a properties file>
Browser Capabilities
Type = @Model.Type
Name = @Model.Browser
Version = @Model.Version
Supports Frames = @Model.Frames
Supports Tables = @Model.Tables
Supports Cookies = @Model.Cookies
Supports VBScript = @Model.VBScript
Supports Java Applets = @Model.JavaApplets
Supports ActiveX Controls = @Model.ActiveXControls

and later, in a separate code file
private void Button1_Click(object sender, System.EventArgs e)
{
    BrowserInfoTemplate = Properties.Resources.browserInfoTemplate; // see above
    string browserInfo = RazorEngine.Razor.Parse(BrowserInfoTemplate, browser);
    ...
}

From a software engineering perspective, how is this better than an equivalent string concatentation, like below:
private void Button1_Click(object sender, System.EventArgs e)
{
    System.Web.HttpBrowserCapabilities browser = Request.Browser;
    string s = "Browser Capabilities\n"
        + "Type = "                    + browser.Type + "\n"
        + "Name = "                    + browser.Browser + "\n"
        + "Version = "                 + browser.Version + "\n"
        + "Supports Frames = "         + browser.Frames + "\n"
        + "Supports Tables = "         + browser.Tables + "\n"
        + "Supports Cookies = "        + browser.Cookies + "\n"
        + "Supports VBScript = "       + browser.VBScript + "\n"
        + "Supports JavaScript = "     +
            browser.EcmaScriptVersion.ToString() + "\n"
        + "Supports Java Applets = "   + browser.JavaApplets + "\n"
        + "Supports ActiveX Controls = " + browser.ActiveXControls
              + "\n"
    ...
}

A: The engineering principles at play here are readability and DRY.
The primary driver of readability is length. Shorter code is more readable (for readers of adequate skill level), so the first case reads better.
A secondary driver is clutter. The absence of punctuation and extraneous characters favours the first case.
The DRY point here is that symbols such as browser and \n are concealed in the abstraction in case 1, and repeated in case 2. If either of those needed to be changed there would be less places to change in case 1 than case 2.
Set against this is WYSIWYG. In the first case there is something missing between the code you see and how it is put to work, where in the second case all the machinery is plain to see.
[At the opinion level, I would strongly favour case 1; others would not. But that would make this an opinion-based question and it might get closed, so we wouldn't want to venture there.]


text:
Q: How to test a component from @vscode/webview-ui-toolkit/react with jest? In a vscode extension that I am working on, I am using a component from @vscode/webview-ui-toolkit/react.
Actually, I am just importing a component like this import { VSCodeTextField } from '@vscode/webview-ui-toolkit/react'; to a react component that I created.
All works well in my extension but a test that I wrote where I am checking just the rendering of my component (jest + enzyme) throws an error:
Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box, Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

I tried many different potential solutions e.g 1 2 for this error but none helped me. Next, I went to the official repository trying to find how they test the components there and I noticed that they are moving directories around with some scripts. Here https://github.com/microsoft/vscode-webview-ui-toolkit/blob/main/scripts/move-react-build-dir.js and here https://github.com/microsoft/vscode-webview-ui-toolkit/blob/main/scripts/setup-webview-test-env.js
Do I have to do something similar or is there any configuration in jest config that can help?
Does anyone have experience testing react components that make use of components from vscode-webview-ui-toolkit?
Thanks for your help


text:
Q: AWS Elastic Beanstalk - What's the difference between the Java platform and the Tomcat platform? Our programmers are currently switching our code over to Springboot. They gave me a .war file and if I deploy it in Elastic Beanstalk and select the "Tomcat" platform it will come up and work. If I select the "Java" platform our site will not work.
I want to understand what is happening in the background. When I select "Tomcat" is Elastic Beanstalk spinning up and configuring tomcat automatically for me and installing our .war to use it?
What about when Java is selected? What will be the servlet container and how is it set up? Is it trying to set up Nginx when Java is selected?

A: From the documentation:

AWS Elastic Beanstalk supports two platforms for Java applications.
Tomcat – A platform based on Apache Tomcat, an open source web
container for applications that use Java servlets and JavaServer Pages
(JSPs) to serve HTTP requests. Tomcat facilitates web application
development by providing multithreading, declarative security
configuration, and extensive customization. Elastic Beanstalk has
platform branches for each of Tomcat's current major versions. For
more information, see The Tomcat platform.
Java SE – A platform for applications that don't use a web container,
or use one other than Tomcat, such as Jetty or GlassFish. You can
include any library Java Archives (JARs) used by your application in
the source bundle that you deploy to Elastic Beanstalk. For more
information, see The Java SE platform.

To answer your question:

I want to understand what is happening in the background. When I
select "Tomcat" is Elastic Beanstalk spinning up and configuring
tomcat automatically for me and installing our .war to use it?

Yes that's exactly what Elastic Beanstalk is doing.

What about when Java is selected? What will be the servlet container
and how is it set up? Is it trying to set up Nginx when Java is
selected?

It is expecting you to provide a Java deployment artifact that does not depend on Tomcat, such as a Spring Boot runnable Jar.


text:
Q: Apache-2.2 Set-Cookie on logic from a response header I need to set a cookie based on a response header (as opposed to a request header). The response header is set by a SOAP call to a backend - and is out of apaches control.
I've looked into SetEnvIf, but it states that it investigate request headers only. mod_rewrite's {HTTP:parm} construct also seems to apply to request headers only.

*

*Request coming in

*Response header is generated by backend

*Apache investigates respond header FooBar

*Apache add Set-Cookie if the respond header FooBar value matches "string"

Any ideas out there?

A: It looks like this can be done with mod_headers, but unfortunately only with Apache 2.4, since expressions were only added in 2.4. You would do something like:
Header set Set-Cookie "cookie-contents-here" "expr=%{resp:Content-Type} =~ m|application/pdf|"

If you can't upgrade to 2.4, you might consider putting Varnish Cache in front of your Apache install. It's a powerful HTTP processor and can easily handle modifying the response for you. You could also implement caching with it and increase the performance of your site, but it can just be used as a pass-through HTTP processor if you don't want to do that. Perhaps there's a simpler solution but that would work.
Another option could be to put a layer in between Apache and your back-end, such as a PHP script, that handles passing the call to the back-end and modifying the headers on the way back out. Probably not great for performance though; upgrading Apache or implementing Varnish Cache would be better.
If you're using a separate back-end out of Apache's control, then you might take Apache out of the loop completely and go straight from Varnish Cache to your back-end.
Hope the ideas help.


text:
Q: Android: when spinner item is selected how to prompt for additional details Trying to make a checklist type app that when you select an element from a spinner you will be prompted for additional information. For instance if you select apple it will ask you how many and give you an editable text box to select.
Should I design the page so that it uses a new intent after each item is selected and creates a new page with the prompting and previous selections in it?
Or is there a better method?

A: OnItemSelectedListener and AlertDialog is the way.
1.Use OnItemSelectedListener and override the ItemSelected()
2.create and show the AlertDialog with edittext inside the ItemSelected method.

A: If you are not taking so many inputs from user then you can create a simple AlertDialog for getting those values on every item selected from Spinner or if there are lot of inputs needed then you should call a separate activity for that.


text:
Q: get output of Html.BeginForm() into string I am trying to get the string output of Html.BeginForm() as a string inside a view, without printing it in the view. Is it possible?
EDIT >
I am trying to implement some text helpers to work with html tags inside C#, such ass:
using(Html.BeginText("p")){
    Hi, my name is Ashley. I love

    using(Html.BeginText("small")){
        small letters
    }
}

I used IDisposable, so I don't have to worry about the closing tags and I can insert html text inside the brackets, but I want to get this values as string, not to print it to the user.


text:
Q: greatest common divisor of 4 integers I've come up with this question in a programming book, and couldn't figure it out :

Given four positive integers $a, b, c$ and $d$, explain what value is computed
      by $\gcd(\gcd(a, b), \gcd(c, d))$.

A: Your title give the answer: the expression gives the greatest common divisor of all four of the integers $a,b,c,$ and $d$.
This is the largest integer that divides all four of the numbers. Such a number exists since $1$ divides all four numbers and anything larger than the maximum of the four numbers will not divide any of them.

A: Let $g=\gcd(\gcd(a, b), \gcd(c, d))$. Then by the definition $g\mid \gcd(a, b)$ and since $\gcd(a, b)\mid a, \gcd(a, b)\mid b$ therefore $g\mid a$ and $g\mid b$. similarly $g\mid c$ and $g\mid d$. So g is a common divisor of these four integers. To see why $g$ is the greatest common divisor of these integers, assume that $f$ is any common divisor of $a,b,c$ and $d$. Then $f\mid a$ and $f\mid b$ and hence $f\mid \gcd(a, b)$ and indeed, $f\mid \gcd(c, d)$. So $f$ must divide $\gcd(\gcd(a, b), \gcd(c, d))$ or $f\mid g$. By the definition, $g$ is the greatest common divisor of $a,b,c$ and $d$.


text:
Q: How to get the matched return value from find module in ansible? I am running an Ansible playbook that looks into a directory and if the size is greater than 1 megabyte, then it has found a match. I just want to verify that it found the correct file. However, I am having a hard time capturing the output. I used the debug module in the documentation, but I still haven't solved it.
- hosts: node2
  tasks:
    - name: Recursively find /tmp files with last access time greater than 3600 seconds
      find:
        paths: /tmp/myFile/outputs
        size: 1m
        recurse: yes

    - debug:
        matched:

I get this error:
TASK [debug] *******************************************************************************************************************************************************************************************
fatal: [10.245.61.245]: FAILED! => {"msg": "Invalid options for debug: matched"}

A: You can save the return value of a task to a variable and after that you can print out the variable.
(I slightly modified your code)
- hosts: node2
  tasks:
    - name: Recursively find /tmp files with last access time greater than 3600 seconds
      find:
        paths: /tmp
        size: 1k
        recurse: yes
      register: result

    - debug:
        var: result

Here are some useful links, if you want to go more in depth:

*

*https://docs.ansible.com/ansible/latest/modules/find_module.html

*https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html

*https://docs.ansible.com/ansible/latest/modules/debug_module.html
I hope I could help you :)


text:
Q: Refresh JTree(TreeNode) without TreeModel In my Java application, I've already got data in a tree-like structure. therefore it was the easiest way to have each class representing a "node" implement the TreeNode interface.
public class GPXObject implements TreeNode {
    public Enumeration<TreeNode> children() {}
    public boolean getAllowsChildren() {}
    public TreeNode getChildAt(int childIndex) {}
    public int getChildCount() {}
    public int getIndex(TreeNode node) {}
    public boolean isLeaf() {}
}

the tree is instantiated using the JTree(TreeNode) constructor:
GPXObject gpxRoot = new GPXObject();
gpxRoot.add(....) // add child nodes & subtrees ....
JTree tree = new JTree(gpxRoot);

now, I can't find a way to refresh the tree when nodes are added via external data sources since
- there is no custom TreeModel
- there is no tree.getModel.reload() method
- there are no DefaultMutableTreeNodes
did I get the purpose of JTree(TreeNode) wrong?
do I have to implement a custom TreeModel anyway?
tnx


text:
Q: Android - Save an rtsp (h264) stream to mp4 file I am working on a project where I need to

*

*Read input H.264 encoded stream from an IPCamera  - I am able to fetch this in through an rtsp url like rtsp://192.168.1.83:8001/

*Display the IPCamera stream - This I am able to do using the

final VideoView vv = (VideoView) findViewById(R.id.video_view_h264);
        MediaController mc = new MediaController(getApplicationContext());
        vv.setVideoURI(video);
        vv.setMediaController(mc);
        vv.requestFocus();
        vv.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mp) {
                vv.start();
            }
        });

*

*Now I want to record this stream to an MP4 file. This is where I am stuck and I am considering the following options

a) MediaRecorder - Based on my google searches I believe for this class the input can only from a device camera. Is there a way to tweak this where I can provide an input from rtsp stream ?
b) MediaCodec API - 4.1 onwards Android has released this low level API with and MediaExtractor and MediaCodec. For this option I think an rtsp stream cannot be used in the following snippet
final String STREAM_URL = "rtsp://192.168.1.83:8001/";
MediaExtractor mediaExtractor = new MediaExtractor();
mediaExtractor.setDataSource(STREAM_URL); // I get an exception 04-28 18:30:18.914: E/AndroidRuntime(8140): Caused by: java.io.IOException: Failed to instantiate extractor.

c) Can I do a read from the url and store it like a file. How to I convert this stream to an MP4 file ? Any code snippet will be really helpful.
I had also tried to use FFMPEG but the performance was so poor that I dropped this option.
Any inputs on the above three options or any other additional option which I can consider will be greatly appreciated.
Thanks !!

A: It is true that MediaRecorder doesn't have any support for handling direct streaming content. From a frameworks perspective, there are parser objects as in MediaExtractor and codec objects like MediaCodec, but not writer abstractions (yet).
In AOSP, recordVideo is a command line utility aimed for a simple file based recording. As part of the implementation, an encoder is created and passed to the MPEG4Writer as observed here. You could potentially reuse this code and try to write the incoming stream into the file directly.
For this you could model your streaming input as a MediaSource and pass it to the writer directly. You would have to setup certain basic metaData from the streaming source and pass it to the downstream writer. You may not require to create a new MediaRecorder, if you could model the input source directly.

A: Got the exact same problem over here. FFmpeg solves the problem and seems very efficient to me but it is hardware dependent, it need to be compiled for the specific arm version of each device's cpu.
Another approach  jcodec (http://jcodec.org/)  but haven't yet figured out how to save a rtsp stream with it. It is a purely java library, but there isn't much documentation available.
Please tell me if you figure out a way of doing it.


text:
Q: Conflicts between SWC skin and Spark drawing API I have a project where we are trying to skin Spark components from a third party library that are built up from the drawing API primitives.  Our first attempt involved creating a Flex skin  (SWC) in Illustrator/Flash and applying that skin to the Spark components via CSS.  We found that even with only a single instance of one of the components skinned in this way on stage, the application was brought to it's knees.  For example, it failed to respond in repaint scenarios in a timely manner, and exhibited all the symptoms of being hung.
Our next approach will be to recreate the same skin artifacts in MXML  classes that are in turn associated with the third-party components.  Although the complexity of some of the skins leads me to believe that we might not avoid performance problems with this approach either.
My question is the following: Is there a correct or recommended way to apply either a SWC or  based skin to a component that is built up from the Spark drawing API to begin with?   Even as I ask the question I recognize that the  approach means using the Spark drawing API in two places and will probably have unexpected consequences.

A: I've had good luck building the skins using MXML skin classes that inherit from s:Skin in terms of rendering performance.  The recommended method (from Adobe) is to start by copying an existing skin file from the SDK and modifying the MXML to suit your needs.  Regarding drawing, FXG works very well for defining how you want the skin to be drawn.  FXG is XML based, so you don't need to write ActionScript to do your drawing, like we used to do for Flex 3 programmatic skins.  You can also create skins using Adobe Catalyst.  I have not used Catalyst, so I can't speak to its effectiveness, but many people seem to like it.  Hope that helps.


text:
Q: $\lim_{n \to \infty} \frac{\cal P(n)}{n}$ In an exercise I'm asked to evaluate the following limit:

$$\lim_{n \to \infty} \frac{\cal P(n)}{n}$$
Where $\cal P(n)$ is the number of prime numbers that devide $n$.

I have no idea how to approach this. I know that $1< \cal P(n) <n$ So this must mean that
$$\lim_{n \to \infty} \frac{\cal P(n)}{n} \in [0,1]$$
if the limit exists.
But I'm not able to find the exact value.

A: Even if $\mathcal P(n)$ counts prime factors with multiplicity, it's easy to show that $\mathcal P(n)\le\log_2n$. Take the prime factorisation $n=\prod_ip_i^{m_i}$ and replace all $p_i$ by $2$; since all primes are at least $2$ the product cannot increase, yielding $n\ge2^{\mathcal P(n)}$. Thus the limit expression is upper-bounded by $\frac{\log_2n}n$ and the limit is $0$.


text:
Q: Disable cmd.exe resizing Is it possible to make the command prompt (cmd.exe) on Windows non-resizable?
I've specified buffer size (ScreenBuffSize) in the HKCU\Console registry, but I can click and drag the border of the window to make it smaller (just not bigger). I would like to disable resizing at all.


text:
Q: How to convert UTC time to unix timestamp I am looking for an option to convert UTC time string to unix timestamp.
The string variable I have is 02/28/2016 10:03:46 PM and it needs to be converted to a unix timestamp like 1456693426
Any idea how to do that?

A: First of, the unix timestamp 1456693426 does not have the time 10:03:46 PM but 9:03:46 PM in UTC.
In the time package there is the function Parse with expects a layout to parse the time. The layout is constructed from the reference time Mon Jan 2 15:04:05 -0700 MST 2006. So in your case the layout would be 01/02/2006 3:04:05 PM. After using Parse you get a time.Time struct on which you can call Unix to receive the unix timestamp.
package main

import (
    "fmt"
    "time"
)

func main() {
    layout := "01/02/2006 3:04:05 PM"
    t, err := time.Parse(layout, "02/28/2016 9:03:46 PM")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(t.Unix())
}


text:
Q: How to Create Multiple Data Frames in For Loop I have a list of names (I changed them to letters) that correspond with values in a data frame column.
names = ['A','B','C','D','E','F','G','H']

I am trying to create a separate data frame for each name containing that name's associated QTY grouped by part number.
for x in names:
    name_data = data[data['Name']== x]
    name_dict = name_data.groupby(['Part No.']).Quantity.sum().to_dict()
    df1= pd.DataFrame.from_dict(name_dict, orient = 'index',columns = ['QTY'])

As you can see from the code each time it loops it writes the new loop data over the previous loop's data in df1. How to I iterate a new data frame name each time it loops, so that I end of with 8 separate data frames?

A: You could save the dataframes to a list:
list_of_dfs = list()

for x in names:
    df = data[data['Name'].eq(x)].groupby('Part No.')['Quantity'].sum().rename("QTY").to_frame()
    list_of_dfs.append(df)


text:
Q: Do I have to do feature selection prior to applying my machine learning algorithm? My question is,

Does the machine learning algorithm takes care of selecting the best features in my data ? or shall I do feature selection and scaling prior to my machine learning algorithm.

I am aware of few supervised classification machine learning algorithms such as kNN, Neural Networks, Adaboast etc.
But is there some you recommend me looking at ?

A: There is no definite answer to this. The current trend is not do feature selection and let the classifier decide which features to use. Take current image datasets for example which also have 1000+ features (depending on the image resolution). They are fed to a CNN usually without any preprocessing. However, this is not generally true. If for example you assume to have a lot of correlations in the data, feature selection might help.