text:
Q: How to mock SignalR used in a service layer I need to test ClientConnectionProvider class, but can not mock private IHubContext<SignalrServerHub, IBroadcast> HubContext { get; set; } in test class given below. How can I mock client in hubcontext used in test class?
public class ClientConnectionProvider : IConnectionProvider
{
    private readonly ILogger<ClientConnectionProvider> logger;

    private IHubContext<SignalrServerHub, IBroadcast> HubContext { get; set;}

    /// <summary>
    /// Initializes a new instance of the <see cref="ClientConnectionProvider"/> class.
    /// </summary>
    /// <param name="logger"></param>
    /// <param name="hubContext"></param>
    public ClientConnectionProvider(ILogger<ClientConnectionProvider> logger, IHubContext<SignalrServerHub, IBroadcast> hubContext)
    {
        this.logger = logger;
        HubContext = hubContext;
    }

    /// <summary>
    /// To create and save  a connection based on clients on connect.
    /// </summary>
    /// <param name="groupName"><see cref="string"/>.</param>
    /// <returns>Task of <see cref="Task"/>.</returns>
    public async Task<ServiceMethodResponse> SubscribeConnectionToAGroup(ClientConnection connection)
    {
        await HubContext.Groups.AddToGroupAsync(connection.ConnectionId, "HubUsers");

        return new ServiceMethodResponse()
        {
            IsSuccess = true,
            IsValid = true,
            Message = "Subscribed to a group"
        };
    }
}

public class ConnectionProviderTest
{
    private Mock<ILogger<ClientConnectionProvider>> logger;
    private Mock<IDispatcher> dispatcher;
    private Mock<IServiceProvider> serviceProvider;
    private Mock<IConnectionProvider> connectionProvider;
    private Mock<IHubContext<SignalrServerHub, IBroadcast>> HubContext;
    //Mock<IClientProxy> mockClientProxy = new Mock<IClientProxy>();
    private Mock<IClientProxy> mockClientProxy = new Mock<IClientProxy>();

    /// <summary>
    /// Initializes a new instance of the <see cref="ConnectionProviderTest"/> class.
    /// </summary>
    public ConnectionProviderTest()
    {
        this.logger = new Mock<ILogger<ClientConnectionProvider>>();
        this.HubContext = new Mock<IHubContext<SignalrServerHub, IBroadcast>>();
        this.connectionProvider = new Mock<IConnectionProvider>();
        this.dispatcher = new Mock<IDispatcher>();
    }

    [Fact]
    public async Task SendNotificationToAllFoundSuccess()
    {
        Mock<IHubClients> mockClients = new Mock<IHubClients>();
        Mock<IClientProxy> mockClientProxy = new Mock<IClientProxy>();
        mockClients.Setup(clients => clients.All).Returns(mockClientProxy.Object);
        ClientConnectionProvider clientConnectionProvider = new ClientConnectionProvider( this.logger.Object, this.HubContext.Object);

        this.HubContext.Setup(x => x.Clients).Returns(() => (IHubClients<IBroadcast>)mockClients.Object);

        NotificationPayload payload = new NotificationPayload
        {
            Message = "RnadomHashString",
            SubscriptionTypes = new List<SubscriptionType>() { new SubscriptionType { SubscriptionTypeName = "HubUsers" } },
        };

        ServiceMethodResponse response = await clientConnectionProvider.SendNotificationToAll(payload).ConfigureAwait(true);
        Assert.True(response.IsValid);
    }
}

How do I test ClientConnectionProvider's methods? Getting error System.InvalidCastException : Unable to cast object of type 'Castle.Proxies.IHubClients`1Proxy' to type 'Microsoft.AspNetCore.SignalR.IHubClients`1[Platform.PushNotification.Services.SignalRHub.IBroadcast]'.

A: Maybe I did not make myself clear before. What I meant to say:

*

*you could wrap the instance of SignalrServerHub used in IHubContext in your actual code.

*you could then mock that interface.

The exception you are getting is because the class SignalrServerHub cannot be mocked, as it is not interfaced.
// The wrapper interface
public interface ISignalrServerHub
{
    // Specify the methods / properties of SignalrServerHub, which you need
    void SomeMethodYouNeed();
    bool SomeMethodWithReturnValue();
}

// The wrapper
public class WrappedSignalrServerHub : ISignalrServerHub
{
    private SingalrServerHub _wrappedInstance;

    public WrappedSignalrServerHub(SignalrServerHub instance)
    {
        _wrappedInstance = instance; // TODO add null check
    }

    public void SomeMethodYouNeed()
    {
        _wrappedInstance.SomeMethodYouNeed();
    }

    public bool SomeMethodWithReturnValue()
    {
        return _wrappedInstance.SomeMethodWithReturnValue();
    }
}

// The changed class
public class ClientConnectionProvider : IConnectionProvider
{
    private readonly ILogger<ClientConnectionProvider> logger;

    private IHubContext<ISignalrServerHub, IBroadcast> HubContext { get; set;}

    /// <summary>
    /// Initializes a new instance of the <see cref="ClientConnectionProvider"/> class.
    /// </summary>
    /// <param name="logger"></param>
    /// <param name="hubContext"></param>
    public ClientConnectionProvider(ILogger<ClientConnectionProvider> logger, IHubContext<ISignalrServerHub, IBroadcast> hubContext)
    {
        this.logger = logger;
        HubContext = hubContext;
    }

    // [snipped for brevity]
}

// The changed test
public class ConnectionProviderTest
{
    // [snipped for brevity]
    private Mock<IHubContext<ISignalrServerHub, IBroadcast>> HubContext;
    // [snipped for brevity]

    /// <summary>
    /// Initializes a new instance of the <see cref="ConnectionProviderTest"/> class.
    /// </summary>
    public ConnectionProviderTest()
    {
        this.logger = new Mock<ILogger<ClientConnectionProvider>>();
        this.HubContext = new Mock<IHubContext<ISignalrServerHub, IBroadcast>>();
        this.connectionProvider = new Mock<IConnectionProvider>();
        this.dispatcher = new Mock<IDispatcher>();
    }

    // [snipped for brevity]
}


text:
Q: How to show multiple detail in single section in crystal report? I am working on crystal reports and I am stuck here with one problem. I am showing results for  IDs and they are working like:
ID        Name         Date              Comments
1         A           '2012-01-01'      Comments 1 on the date
1         A           '2012-01-01'      Comments 2 on the same date

Now if I want to show data like:
Details of the ABC Company
...............................................................................
ID        Name         Date              Comments
1          A          '2012-01-01'       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
                                         ccccccccccccccccccccccccccccccccccccccccc

Details of DEF company
...............................................................................
ID        Name         Date              Comments
2          B          '2013-01-11'       rciwtyiabtbtaerynct
                                         hubytnituinmyuimyumiy
                                         jk jk jk jk jk jk jk uir

How to achieve that? I am least interested in creating a subreport for the sections below.

A: I guess your main concern is only the Header section which says 'Details of the ABC Company' etc etc.For that you may use GroupExpert(RightClick on Report-->Insert-->Group) and you may group it with your Details company header section
for grouping you may refer Grouping 1
and here Grouping 2
Hope it helps

A: You can create a formula that would be the combination of ID, name and Date.
Then  group on that formula
if it is okay to have a different line, then simply put the fields ID, name and Date and group at teh group level and comment at the detail level
if it is not okay to have a different line, then put hte fields ID, name, Date and comment to the detail line and do a suppress formula so that they are only showed on the first element of the group (formula to be find out)

A: In your crystal report right click the details section and select insert section below,now u have two details sections a and b.u can add mulitple details section and page header also.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to use an asp.net page to have the get results from the server sent back as an XML file? My application sending SMS request to Mblox XML interface through, I have get response from Mblox as XML file.
string RequestXML = GenerateRequestXML();

string uri = string.Empty; uri = "http://xml.us.mblox.com:8180/send";

HttpWebRequest request =(HttpWebRequest)WebRequest.Create(uri);

request.KeepAlive = false;

request.ProtocolVersion = HttpVersion.Version11;

request.Method = "POST";

request.ContentType = "text/xml";
HttpWebResponse respon = (HttpWebResponse)request.GetResponse()

A: You are almost there... You already have your response, just get a reference to ResponseStream and read the XML returned:
HttpWebResponse respon = (HttpWebResponse)request.GetResponse();
Stream receiveStream =    request.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader( receiveStream, encode );
//now you should be able to use readStream to get your XML. That's your homework.

See a complete example here


text:
Q: Why do blank alert statements affect execution of other code? I'm working on the front page of a website that will have a section that will show news articles. The articles will fade into the next one every 10 seconds. For some reason the code only executes correctly (keep in mind it's not entirely finished so there may be other errors) with the inclusion of a couple alert() statements. These were previously in there just for debugging, but currently, it seems as though they serve some functional purpose. Without them, the code will give different results if any at all.
I'm mainly a Java programmer, so there are probably some idiosyncrasies about JavaScript alert() statements that I'm not familiar with. The other odd thing that I noticed was that at times I would run the code multiple times with no changes and get different results. I used some of the alert() statements in the loadArticles() function to output the value of i and would occasionally get a different result without changing the code. The only idea I have so far is that my computer is taking time to run the statements that is allowing some other process to finish, but there shouldn't be any multi-threading involved.
The init() function is called in onload from the HTML and there's a div with id="news" somewhere in the center of the page.
On top of the main question, extra credit for anyone who could help out with why I'm sometimes not getting the articles to fade in and out. I'm pretty sure it has something to do with the article or container being null, but I haven't had time to get to that yet.
Here's the JavaScript:
var article_count = 0;
var count = 0;

function init() {

    getArticleCount();
    loadArticles();
    changeSlide();

    resize();
    resize();

}

function getArticleCount() {

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            article_count = xmlhttp.responseText;

        }

    };

    xmlhttp.open("GET", "getArticleCount.php", true);
    xmlhttp.send();

}

function loadArticles() {
    alert();
    for(i = 1; i <= article_count; i++) {
        alert();
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {

            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                alert();
                var news = document.createElement("iframe");
                news.className = "news";
                news.src = "articles/" + xmlhttp.responseText;
                news.style.zIndex = 0 - i;

                var container = document.getElementById("news");
                container.appendChild(news);

            }

        };
        alert();
        xmlhttp.open("GET", "getArticles.php?q=" + i, true);
        xmlhttp.send();
        alert();

    }
}

function changeSlide() {

    var article = document.getElementsByClassName("news")[count];
    var interval = setTimeout(function() {

        var fadeOut = article.fadeOut(1000, function() {

            if(count < article_count) {

                count++;
                changeSlide();

            } else {

                count = 0;
                resetSlides();

            }

        });

    }, 10000);

}

function resetSlides() {

    var articles = document.getElementsByClassName("news");

    for(j = 0; j < article_count; j++) {

        var fadeIn = articles[j].fadeIn(1000);

    }

    changeSlide();

}

function resize() {

    var body = $(document.body);
    var news = $("#news");

    $("#menu_left").width((body.outerWidth() - news.outerWidth()) / 2 - 3);
    $("#menu_right").width((body.outerWidth() - news.outerWidth()) / 2 - 3);
    $("#menu_contact").width(body.outerWidth());

}

A: There are lots of mistakes in your code, mostly related to the asynchronous nature of Ajax calls.  You will need to more about programming with asynchronous operations to write correctly functioning and reliable and consistent code.
alert() statement change the relative timing of asynchronous operations (such as Ajax calls vs. when your other code runs.
In general, stop using alert() statements at all as a debugging tool because it can influence the timing too much.  Instead, use console.log() statements.  Since console.log() just outputs to the console and does not block execution of the Javascript thread at all, it will not impact the timing of things nearly as much as an alert() statement.
Here's a trivial example to show you how an alert() can change the timing of things:
var img = new Image();
img.src = "http://somedomain.com/myimg.jpg";
alert("Press OK to continue");
if (img.complete) {
    console.log("image is done loading");
} else {
    console.log("image is not yet done loading");
}

With the alert statement, you will get image is done loading in the console.  Without the alert, you will get image is not yet done loading.  The alert has changed the flow of your code.

Another thing that can affect the timing of your code is whether resources are in the browser cache or must be loaded over the network.  In nearly all cases, properly written code that only uses resources when it knows they have been loaded will continue to work in either case.  But, in cases with poorly written code, you may see a different behavior the first time a page is loaded vs. subsequent times when some of the resources are now cached.

To fix your specific code, you need to program asynchronously.  That means using completion handlers for asynchronous operations like Ajax calls and calling callbacks to notify other code when asynchronous operation are done.
For example, your getArticleCount() function is asynchronous.  It will finish its Ajax operation some time AFTER the getArticleCount() has already returned.  You can change it to accept a callback like this:
function getArticleCount(callback) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            callback(xmlhttp.responseText);
        }
    };
    xmlhttp.open("GET", "getArticleCount.php", true);
    xmlhttp.send();
}

And, then you use it like this:
getArticleCount(function(cnt) {
    // in here you can use the article count
});

As for your .fadeOut() and .fadeIn() operations, those are not native DOM methods so you can't call them on DOM objects like you are trying to do.  It appears that you are attempting to use the jQuery methods with this name.  To do, you must load jQuery into your page and then you must create jQuery objects that contain the relevant DOM objects and call .fadeOut() and .fadeIn() on the jQuery objects, not on the DOM objects.

Your loadArticles() function can be fixed by putting the ajax calls inside an internal function inside the method.  This will allow each ajax operation you are starting to have it's own separate variables rather than having all of them collide and try to use the same variables.  You can do that by using an IIFE (Immediately Invoked Function Expression) inside your for loop like this:
function loadArticles() {
    for (i = 1; i <= article_count; i++) {
        (function() {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    var news = document.createElement("iframe");
                    news.className = "news";
                    news.src = "articles/" + xmlhttp.responseText;
                    news.style.zIndex = 0 - i;
                    var container = document.getElementById("news");
                    container.appendChild(news);
                }
            };
            xmlhttp.open("GET", "getArticles.php?q=" + i, true);
            xmlhttp.send();
        })();
    }
}

Note, because Ajax operations have an indeterminate timing, this code does not guarantee that the items you are adding to the page will be added in any particular order.  They are more than likely to be added in the order of your for loop, but that is not guaranteed.  If the serve happens to be quicker with one of the requests vs. another, it might finish first and get added to the page first, even though it was not the first one requested.

And, since your resize() function appears to use jQuery, you will find it a TON easier to use jQuery's ajax support rather than coding your own Ajax calls.  Plus with jQuery Ajax, you can use the built-in promise interface to make your asynchronous programming and error handling substantially easier.

A: The reason removing the alert calls in your code made it not work anymore is because your functions getArticleCount(), loadArticles() are making asynchronous requests for data. Alert popups made the program halt, while the AJAX request was off retrieving data and it had returned the result by the time you closed the alert popup.
You can change those 2 functions to execute a callback function as a way to let other functions know that it's finished:
function init() {
    getArticleCount(function() {
        // finished getting article count
        loadArticles(function() {
            // finished loading articles
            changeSlide();
            resize();
            resize();
        });
    });
}

function getArticleCount(callback) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            article_count = xmlhttp.responseText;
            callback(); // done
        }
    };
    xmlhttp.open("GET", "getArticleCount.php", true);
    xmlhttp.send();
}

function loadArticles(callback) {
    for(i = 1; i <= article_count; i++) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {

            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var news = document.createElement("iframe");
                news.className = "news";
                news.src = "articles/" + xmlhttp.responseText;
                news.style.zIndex = 0 - i;

                var container = document.getElementById("news");
                container.appendChild(news);
                callback(); // done
            }

        };
        xmlhttp.open("GET", "getArticles.php?q=" + i, true);
        xmlhttp.send();

    }
}

As a side note, you can debug using the browser Developer Tools, and use console.log() and debugger;

A: XMLHttpRequest is an asynchronous call.
You make a getArticleCount request in order to get a count of articles.
Then, you have a loop:
for (i = 1; i <= article_count; i++) {

getArticleCount request didn't complete by the time of this loop, and article_count is still equal to zero. You need to use onreadystatechange and move your consequent dependent calls into callbacks:
function init() {
    getArticleCount();
}

function getArticleCount() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            article_count = xmlhttp.responseText;
            loadArticles();
        }
    };

    xmlhttp.open("GET", "getArticleCount.php", true);
    xmlhttp.send();
}

function loadArticles() {
    var container = document.getElementById("news");

    for(i = 1; i <= article_count; i++) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var news = document.createElement("iframe");

                news.className = "news";
                news.src = "articles/" + xmlhttp.responseText;
                news.style.zIndex = 0 - i;

                container.appendChild(news);
            }

        };

        xmlhttp.open("GET", "getArticles.php?q=" + i, true);
        xmlhttp.send();
    }
}

Anyway, you have some architectural problems:

*

*Making count request apart from data requests is redundant. Moreover, the value could change while you execute your articles.

*Making many HTTP requests will cause a huge performance drop.

You need to make a single PHP-file, which will return a JSON array with all articles. Then, you will able to work with its length and every item, and it will work much faster while not causing any synchronization problems.

A: The alerts are (somewhat) syncronizing your ajax calls. You have dependencies between getArticleCount and loadArticles. The alert() at the top of loadArticles is causing execution to pause until you cancel the alert. In that time the AJAX request to "getArticleCount.php" has completed and assigned a value to article_count.
Without the alerts pausing execution, your code is non-deterministic b/c AJAX calls can not be strung together in a procedural fashion and behave synchronously. You will need to use a functional programming style to get AJAX calls to behave synchronously.
For example you could make write it like this
function init() {

    getArticleCount(loadArticles);
    resize();
    resize();

}

function getArticleCount(callback) {

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {

    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        //callback will be loadArticles()
        callback.call(null, xmlhttp.responseText);

    }

    xmlhttp.open("GET", "getArticleCount.php", true);
    xmlhttp.send();

}

function loadArticles(articleCnt) {

    for(i = 1; i <= articleCnt; i++) {

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {

            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

                var news = document.createElement("iframe");
                news.className = "news";
                news.src = "articles/" + xmlhttp.responseText;
                news.style.zIndex = 0 - i;

                var container = document.getElementById("news");
                container.appendChild(news);
                if(i == i){
                    //modify function to use passed in count instead of global
                    changeSlides(articleCnt);
                }
            }

        };

        xmlhttp.open("GET", "getArticles.php?q=" + i, true);
        xmlhttp.send();

    }

}
When calling getArticleCount the callback parameter would be loadArticles which has been modified to accept the article_count as a parameter instead of using the global. The above code will fix your issue. You should modify other functions to take a local article count and stop relying on the global.


text:
Q: Javascript/jquery second prompt value filling previous prompt value I'm creating a mini game that has a user roll to randomly create two dogs with various genetics. Everything is done front-end because I have no knowledge of back-end. Once the user has rolled the dog they want, they click a button to keep that dog. When that button is clicked, I want a prompt to pop up to ask them what they want to name this dog. The only problem is when they roll the second dog and name it, that name overwrites the first dog's name.
Here's the code for when the keep male button is pressed. The female version is identical except for the variable names:
$('#keepMale').on('click', function() {
    //remove any remaining rolls left to the user
    maleCount = 0;

    //prompt the user to name their new dog
    newMale.name = prompt("Name your new male:");

    //add the current dog to the user's dog array
    ownedDogs[dogCount] = newMale;

    //change the dog count to reflect the user's number of dogs
    dogCount++;

    //changes the male rolls alert to reflect that a male has been chosen
    $('#maleRolls').text('You\'ve chosen your first male!');
    $('#maleRolls').removeClass('alert-warning alert-danger');
    $('#maleRolls').addClass('alert-success');

    //change the male kept variable to reflect that a male has been kept
    maleKept = 1;

    //run bothKept to check if both keep buttons have been clicked
    bothKept(femaleKept, maleKept);
});

This is what I'm using later to call the name value:
$('#dogList').html('
'
 + ownedDogs[0].name + '

'
+ ownedDogs[1].name + '
');

Both divs show up the exact same, and even when I check the values on the console directly after they're applied, they show up the same. The ownedDogs array is global to the document and every other value is working properly. I'm not sure what I've done wrong here.
I'm sorry if this is too specific a question, I've just spent a lot of time searching and comparing my code to working code, and I can't find what I've done wrong. Any help would be much appreciated. Thank you.


text:
Q: How do I choose between "as to", "on", "of", and "about"? I know that "as to", "on", and "of" are synonymous with "about", but I also know these words are not always interchangeable.  I was wondering if there are rules for picking between these prepositions.

*

*There is still no news as to whether he will leave the company. (all four can be used with no change in meaning)

*I don't know what you are talking about.  (only about and of can be used)

*I heard of that from Jim. (only of and about)

*The speaker spoke on the issue of liquidity markets. (all four?)

Thanks for the help.

A: The most basic answer to your question is that when and how they can be used all comes down to their definitions. The words "of" and "on" have quite a few variations and so there is no single right way to use them, but several.

*

*"As to" almost always points to a decision that needs to be made, is going to be made, or can be made. It seems to always be followed by an adverb, but I am not sure whether or not that is the rule.

*

*I am unsure as to how we will go about this. (how to go about this is what must be decided)

*As to whether or not you won, I could not say. (The winner has not been decided)

*"On" usually indicates a detailed or direct relation between the subject and its modifying prepositional phrase. Think of it like an object sitting on a table - there is direct contact.

*

*He gave a speech on the ramifications of not wearing protective gear while cycling. (The ramifications were the main topic of the speech he gave.)

*She was working on a solution for the global climate crisis. (The global climate crisis was the main subject of her work.)

*"Of" often lends itself to less knowledge or detail on a subject on the surface, though that is not always the case.

*

*I have heard of him before. (I have at least a general awareness of him, but don't necessarily know much more detail.)

*Of all the cars, twenty were red. (There were twenty red cars, but specifically which ones were is left uncertain.)

*"About" simply signifies a relation or subject. It can indicate great detail or a general association. Often times "of" or "on" can be used in place of "about."

*

*He knew many things about life and love. (He knew a good number of things about life and love. It's very general. Both of and on can be used here.)

*Her story was about the joys of sailing. (The subject of her story was the joys of sailing. Both on and of can be used here, though I feel on would work better.)

A: Right, they aren't exact synonyms, and it's all pretty idiomatic.
So no hard-and-fast rules, no.
In 1, "news of whether" does not really work and would have to be reworded as "news of the possibility that" instead I would say.
In 4, "spoke of" has more of a meaning of "merely mentioned", whereas the others would mean closer to "spoke directly about". And "spoke to" would be less awkward than "spoke as to".
In general, "about" has a connotation of "directly but also around", where "on" means more "specifically to", and "of" requires a more definite object than the others. "As to" is a bit highfalutin as well.

A: In all of the examples, about can be used. Sentence #3 would sound better with about, while sentence #4 probably sounds better as written. Also, regarding sentence #3, if "I heard that from Jim" accurately conveys the meaning, it would be better than what is written.


text:
Q: issue using progressbar to track ftp fiel upload So i am trying to use a progressbar to visually show the progress of a file upload via ftp.
I cant seem to figure out as to why, the progressbar and 3 other labels (labelSpeed, labelPerc, labelUploaded) isn't working.
Any help would be greatly appreciated. Thanks.
PS: I attached a snipet of my code for viewing.
Stopwatch sw = new Stopwatch(); //<-- The stopwatch which we will be using to calculate the upload speed

public void Upload(string ftpServer, string username, string password, string filename, string folder1, string folder2, string folder3)//<-- Uploads image to ftp directory
    {
        string ftpfolderpath = folder1 + "/" + folder2 + "/" + folder3;
        MakeFTPDir(ftpServer, ftpfolderpath, username, password); //<-- Makes the new directory, if there isnt one already

        using (WebClient client = new WebClient())
        {
            client.UploadFileCompleted += new UploadFileCompletedEventHandler(Completed); //<--NEW
            client.UploadProgressChanged += new UploadProgressChangedEventHandler(ProgressChanged); //<--NEW
            sw.Start(); //<-- Start the stopwatch which we will be using to calculate the upload speed

            client.Credentials = new NetworkCredential(username, password);
            client.UploadFile(ftpServer + "/" + folder1 + "/" + folder2 + "/" + folder3 + "/" + new FileInfo(filename).Name, "STOR", filename); //<-- uploads image to ftp Directory
        }
    }

    private void ProgressChanged(object sender, UploadProgressChangedEventArgs e) //<-- The event that will fire whenever the progress of the WebClient is changed
    {
        // Calculate upload speed and output it to labelSpeed.
        labelSpeed.Text = string.Format("{0} kb/s", (e.BytesSent / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));

        // Update the progressbar percentage only when the value is not the same.
        progressBar1.Value = e.ProgressPercentage;

        // Show the percentage on our label.
        labelPerc.Text = e.ProgressPercentage.ToString() + "%";

        // Update the label with how much data have been uploaded so far and the total size of the file we are currently uploading
        labelUploaded.Text = string.Format("{0} MB's / {1} MB's",
            (e.BytesSent / 1024d / 1024d).ToString("0.00"),
            (e.TotalBytesToSend / 1024d / 1024d).ToString("0.00"));
    }

    private void Completed(object sender, UploadFileCompletedEventArgs e) //<-- The event that will trigger when the WebClient is completed
    {
        if (e.Error != null)
        {
            string error = e.Error.ToString(); // error = "Custom error message here";
            MessageBox.Show(error);
            return;
        }

        sw.Reset(); // Reset the stopwatch.

        if (e.Cancelled == true)
        {
            MessageBox.Show("Image Upload has been canceled.");
        }
        else
        {
            MessageBox.Show("Image Upload completed!");
        }
    }

A: You are using UploadFile method which is blocking the calling UI thread. Instead, on the GUI thread, one should use UploadFileAsync to not block.
One can see an example of something similar WebClient.UploadProgressChanged Event (System.Net)
EDIT:: Here is what I meant. Replace
client.UploadFile(ftpServer + "/" + folder1 + "/" + folder2 + "/" + folder3 + "/" + new FileInfo(filename).Name, "STOR", filename); //<-- uploads image to ftp Directory

with
client.UploadFileAsync(new Uri(ftpServer + "/" + folder1 + "/" + folder2 + "/" + folder3 + "/" + new FileInfo(filename).Name), "STOR", filename); //<-- uploads image to ftp Directory


text:
Q: Trigger gitlab pipeline only when in specific branches What I have so far
I have configured gitlab ci/cd pipeline for my project. So I have used base template which has 2 stages, build & package:
The build stage builds the project and creates a jar file.
The package stage creates an image and store it in the container registry. A .gitlab-ci.yml file has been created.
image: docker:latest
services:
  - docker:dind

stages:
  - build
  - package

build:
  image: gradle:5.6.1-jdk11
  stage: build
  script:
    - gradle clean build -x test
  artifacts:
    paths:
      - build/libs/*.jar

package:
  stage: package
  script:
    - docker build -t registry.gitlab.com/my-project/sample .
    - docker login -u $CI_DOCKER_USERNAME -p $CI_DOCKER_PASSWORD registry.gitlab.com
    - docker push rregistry.gitlab.com/my-project/sample

My problem
I don't want to trigger a build for all every branch. I want to trigger only in the development- and master-branch.
Is there anyway we can do that at project level instead of adding only in each stage?

A: The only way to limit when jobs are created is by using only/exceptin the .gitlab-ci.yml file.
To not have to write so much text, you can use extends and also sometimes yaml anchors. More info here:
https://docs.gitlab.com/ee/ci/yaml/#extends
and here:
https://docs.gitlab.com/ee/ci/yaml/#anchors
An example of how extends can be used:
image: docker:latest
services:
  - docker:dind

.only-master-and-develop:
  only:
   - master
   - development

stages:
  - build
  - package

build:
  extends: .only-master-and-develop
  image: gradle:5.6.1-jdk11
  stage: build
  script:
    - gradle clean build -x test
  artifacts:
    paths:
      - build/libs/*.jar

package:
  extends: .only-master-and-develop
  stage: package
  script:
    - docker build -t registry.gitlab.com/my-project/sample .
    - docker login -u $CI_DOCKER_USERNAME -p $CI_DOCKER_PASSWORD registry.gitlab.com
    - docker push rregistry.gitlab.com/my-project/sample

(I haven't tested this file, please let me know if there's something wrong with it.)

A: You should specify the target branch using via $CI_COMMIT_BRANCH == "<your_branch_name>".
rules:
    - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "master"'
      something regarding the project..

    - if: '$CI_PIPELINE_SOURCE == "web" && $CI_COMMIT_BRANCH == "development"'
      something regarding the project..

I hope above example can help anyone!
Also here is the documentation for these types of questions.


text:
Q: how to parse and reduce multiple if condition to one line in text file? I try to analyze old PL/1 source files after normalization it with Python to make it more efficient. There are too many if conditions, but I can't find a way to reduce this effectively. like this:
if cond == 'A'
 | cond == 'B'
 | cond == 'C'
 | cond_ex == 'A_EX'
 | cond == 'D'
 | cond_ex == 'B_EX'
 then;

I want to change and reduce code like this:
if cond in ('A','B','C','D') | cond_ex in ('A_EX','B_EX') then;

Can you tell me solution to parse those code using python regex or text replace?

A: You can parse data as following and make an if statement according to your need.
>>> a = """if cond == 'A'
...  | cond == 'B'
...  | cond == 'C'
...  | cond_ex == 'A_EX'
...  | cond == 'D'
...  | cond_ex == 'B_EX'
...  then;"""
>>> b = a.replace("if", "").replace("then","").replace(";","").replace("|","").replace(" ","")
>>> c = b.split()
>>> print c
["cond=='A'", "cond=='B'", "cond=='C'", "cond_ex=='A_EX'", "cond=='D'", "cond_ex=='B_EX'"]


text:
Q: Importance of Execution Environment in Eclipse Project Settings I was going through how the execution environment works in eclipse project settings. What I read is that -source parameter conveys what version your source code is compatible with. What does it mean? Does this mean if I have JDK 1.8 in my build path and I've used Java 8 features (Lambda Expression or Stream API) in my codebase and I set -source version to 1.7, it will give me error during compilation?
Why would someone want to use lower values of -source and -target parameters if they are actually building their application using comparatively higher java version?
PS: I already went through many Stackoverflow articles related to this but still struggling to understand the actual use.


text:
Q: Notification When someone connects to my local network , ARP, Notification file I have a question concerning Ubuntu 12.04 LTS Desktop - notifications (same notification as Rhythmbox application when playing music back and forth), technically if I'm not mistaken it should be called "freedesktop.Notifications.service". I just want to add notifications when one of my devices such as; laptop, phone, tablet connect to my local network. My configuration is as follows:
I have a wireless router. My router is connected directly to my desktop computer with a wire, I'm using LAN, the other devices connect through WI-FI.
By way of example, let's say :
My router's ip address : 192.168.1.1 & MAC address XX:XX:XX:XX:XX:XX
Me - as server - 192.168.1.101 & MAC address YY:YY:YY:YY:YY:YY
Smartphone - 192.168.1.102 & MAC address ZZ:ZZ:ZZ:ZZ:ZZ:ZZ
Laptop - 192.168.1.103 & MAC address KK:KK:KK:KK:KK:KK

*

*What I want to do is simple; add those IP addresses along with their MAC addresses in the ARP and finally modify the notification file, whenever those devices connect to my local network I get notified. That's it.

P.S : I said "ARP". However, I'm not sure if it is suitable, I'm just supposing it has something to do with ARP config file, and notification file. Any suggestion using terminal or other application will be acceptable.
I will be much appreciated if someone can help me.

A: You can send notifications by use of notify-send yourmessage but what you want to do is a bit strange.
Your router is the one handling the connections, a connection to your network will not be logged or noticed by your computer unless the device actually connects / interacts to your computer. Of course you could be making a monitor by regularly scanning the network like:
nmap -sn 192.168.1.*

and then read you data from here (or arp, because now you can find them there). But basically the device for monitoring connections is your router, not your pc.
If your router supports it, you could parse the logging of the router to the syslog of your pc. Now you get an message in the syslog when a connection is made, which you can then send to your desktop environment if you want.
But to answer the question, add a script to your cron which will do a nmap -sn, pipe this to temp file and compare this with the previous situation by use of diff. Diff out means offline, diff in means online.
A rough example (only handles first ip change per run):
#!/bin/bash
#
#Script to monitor the network and put changes to notification
#
#Save previous scan
cp scan.txt previousscan.txt
#get numeric list of online hosts
nmap -n -sn 192.168.178.* > scan.txt
#collect the difference, only the lines with ip-numbers
message=$(diff previousscan.txt scan.txt | grep 192)
#get first char which indicates if the host came up or went away
iostring="${message:0:1}"
#get first ip-number from the list
computer="${message:23:17}"

#show ip-number in notify if host came up
if [ "$iostring" = \> ]; then
        notify-send "$computer online"
        fi
#show ip-number in notify if host went away
if [ "$iostring" = \< ]; then
        notify-send "$computer offline"
        fi


text:
Q: Conductor of quaternionic representation Classical work by Casselman shows that for an irreducible admissible representation $\rho$ of $GL_2$ over a non-archimedean field $k$, there is a minimal power $n\geq 0$ of the prime ideal $\mathfrak{p}$ such that $\rho$ has a fixed vector under $(\begin{smallmatrix} * & * \\ \mathfrak{p}^n & 1+\mathfrak{p}^n\end{smallmatrix})\subset GL_2(\mathcal{O}_k)$. Furthermore, the fixed space is 1-dimensional.
Suppose $\rho$ is special or supercuspidal. Then it corresponds by Jacquet-Langlands to an irreducible, admissible $D^\times$-representation $\pi$, where $D$ is the non-split quaternions over $k$.
My question is:
Is there a compact open subgroup $K\subset D^\times$ such that $\pi^K$ is one-dimensional?
Edit: I think, when $\rho$ is special $\chi\cdot St$, its JL-transfer is just $\chi\circ Nrd$, so this case is easy.

A: I consider a Casselman type of local newform theory on quaternion algebras in my paper on the basis problem (sections 2 and 3), which gives you a positive answer to your question half of the time (Cases 1 and 2 below). Here is a brief summary.  For simplicity, I'll assume trivial central characters.
Let's say $\pi'$ is the Jacquet-Langlands transfer of $\pi$ to GL(2) and the conductor is $n$.  Then $n$ is the minimal positive integer such that $\pi$ is trivial on $U_D^{n-1}=1+P_D^{n-1}$, the $(n-1)$-st higher unit group in $D$ (here $P_D$ is the prime ideal of $D$).  Incidentally this is a normal subgroup of $D$, so $\pi$ factors through the finite group $D^\times/U_D^{n-1}$.
Thus if you want an open $K$ such that $\dim \pi^K = 1$ we may as well assume $K$ contains $U_D^{n-1}$.
Case 1: $\pi'$ is special, so $\pi$ is 1-dimensional (factors through the reduced norm as you observed).  Then you can just take $K=U_D^{n-1}$
and $\dim \pi^K = 1$.
Case 2: $\pi'$ is supercuspidal of conductor $n=2m+1$.  Then you can take $K=O_E^\times U_D^{2m}$ where $E/F$ is the unramified quadratic extension,
and $\dim \pi^K = 1$ (see Theorem 3.5 in my paper).
Case 3: $\pi'$ is supercuspidal of conductor $n=2m$.  For simplicity also assume $\pi$ is minimal (conductor is minimal among twists).  Then you can take $K = O_E^\times U_D^{2m-1}$ where $E/F$ is any ramified quadratic extension to get $\dim \pi^K = 2$.
Here there is no subgroup that contains a maximal quadratic order which will give you dimension 1 (if you take $E$ unramified, the dimension is 0).  But you can pick out a 1-dimensional space by specifying how $\pi$ acts on a unifomizer $\varpi_D$ (necessarily $\pm 1$).
Subgroups $K$ of the above form are unit groups of Hijikata-Pizer-Shemanske orders and are natural objects to consider for certain reasons.  I do not know whether there are other subgroups one can use to get dimension 1 in Case 3, but I know of no suitable natural choices.
Note by allowing $K$ to be non-compact however (adjoin in $\langle \varpi_D \rangle$) you can get $\dim \pi^K = 1$ but to me choosing this vector in the 2-dimensional space given in Case 3 is not really the right thing to do for a local newform theory.  My feeling is that you would just picking out a 1-dimensional space arbitrarily for the sake of getting a 1-dimensional space, but it would make more sense to pick the vector whose eigenvalue for $\varpi_D$ matches with an epsilon factor.  This however depends upon $\pi$.


text:
Q: Tell Visual C++ where to look for DLLs I can set global search directories for headers and libraries in VC++ Tools->Options->Projects and Solutions.
But what about DLLs? Can I do this through VC++ itself which would be preferable?

A: It is not VC++ which will search for dlls but it is your application which will search for dlls. Here is how it works
Your application search for the dll in the following folder
 system - system32 - windows - folder specified in path - application directory
If the dll is not found on any of these locations, it will raise an error.
To resolve this, you can always specify the exact path of dll in the application itself. Refer to this link http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx for further explanation.


text:
Q: Getting worker name in Apache access log My Apache httpd 2.2 is configured to load-balance two Tomcat servers.
How can I configure my access.log in Apache to capture worker name to which request is getting re-directed?

A: Apache's access log cannot provide this information. As the name implies, it captures only clients' access data, irrespective of how these are processed internally. Your best bet will be setting the JkLogLevel to debug and checking the JkLogFile for the desired routing information (assuming you use mod_jk, see Logging).


text:
Q: FlatList not rendering it showing anything other than FlatList I was trying to render a list but it is not rendering if I try to render a text or an image it is rendering but the FlatList is not rendering this is the code that I have written
**
 return(
    <SafeAreaView  forceInset={{ top: 'always' }} >
        <Image
    style={styles.tinyLogo}
    source={require('../../assets/img.png')}
  />
  <Text> checking </Text>
  <FlatList
      data={menu}
      renderItem={(item) => {
        return <Text>{item.name}</Text>
      }}
      keyExtractor={(item) => item.key }
  />
    </SafeAreaView>

**

A: Update your renderItem to this
renderItem={({item}) => {
  return <Text>{item.name}</Text>
}}


text:
Q: has JSR-335 special support in JVM? Boost for functional JVM-based languages? JSR-335 is said to come soon along with Java 8. It brings i.e. support for closures and virtual extension methods.
I wonder if there is any particular support for this on the JVM level?
If so, can we hope for speed improvements in JVM-based functional languages that provide closures and extension-methods-like features (such as traits or implicits in scala)?
Edit:
reading this oracle presentation on Java 8 by Brian Goetz, it would appear that:
 - closures don't require
 - virtual extension methods do require
particular JVM-support.
Could this mean that in scala, some of the implicits, and traits could be reimplemented in a more efficiently way?

A: I don't think extension methods can be used to implement traits -- a method implementation can't call super on them (afaik -- I might be wrong), and the override semantics would be different. Furthermore, it would not cover fields, just methods.
There isn't anything JVM can do to help with implicits, because there's no inherent problem with them. They are normal instances passed as normal parameters. Looking them up makes the compiler slow, but JVM can't help with that either.
I don't see any of these features helping with anything in Scala, but that's almost moot, actually. Scala still generates JVM 1.5 bytecode with JVM 1.5 classfiles. You can turn on JVM 1.6 bytecode, which makes little difference. With Scala 2.10, 1.6 classfiles will be enabled on an experimental basis.
The reason for that is pretty simple: Java 1.7 runs 1.5 classfiles with 1.5 bytecode, but not the other way around. There's still a lot of people running older versions of Java, and that is unlikely to change.
So I don't see any Java 1.8 features in the radar, unless they bring a huge advantage. And, even then, they'll most likely be available for code compiled with Scala, but not on the Scala library itself. Likewise, unless it brings a huge advantage, I don't see libraries being made available in both versions.

A: I think the speed of Scala is very close to Java already. It is the dynamic typed jvm languages are slow (such as Groovy). And actually JDK 7 came out with the new feature invokedynamic for the purpose of improve those dynamic jvm language:
http://java.sun.com/developer/technicalArticles/DynTypeLang/


text:
Q: Setting widths of buttons in ConstraintLayout programmatically I have a few buttons inside a ConstraintLayout with different widths (as below). What I would like to accomplish is that every button has the width of the widest button in this layout. As it is fairly easy to extract the maximum width of these buttons,
    int maximumWidth = 0;

    for (View button : allButtons) {
        if (button.getWidth> maximumWidth) {
            maximumWidth = width;
        }

it is not as easy to set the widths in an equally easy manner. Any help or suggestions are much appreciated.

A: You can get the layout params of the widest button and apply to the rest.
 val width = widestButton.layoutParams.width

    restOfbuttons.layoutParams.width = width

Also you can try:  btnLocation.measuredWidth()


text: Q: how to hide an element in xamarin forms webview I have a website and now want to make iOS/Android APP to show content of my website. I plan to use Xamarin.Forms and WebView. The problem is, APP doesn't need to show as much as website, so I want to hide some elements of webpages. For example, there is an element whose id is "test", I want to use EvaluateJavaScriptAsync to hide it.


text:
Q: Mysql + aspx - How to fill the array using reader This is my aspx code when i want to fetch just one record.
            conn = new SqlConnection(cs);
            string sql = "SELECT * FROM [school_database].[arrest_school].[registration_allstudent] where RegistrationId='llts4da2'";
            SqlCommand cmd = new SqlCommand(sql, conn);
            conn.Open();
            reader = cmd.ExecuteReader();
            reader.Read();
            Model.Registration regis = new Model.Registration();
            regis.Address = reader["Address"].ToString();
            return regis;

Now i want to fetch all the records and return regis array. How to do it.
I know how to count the row in read and then how to fill it regis array.
Regis has 5 fields...Address, city, name, class, phoneno

A: To read all the records, one way is this:
using(IDataReader reader = cmd.ExecuteReader())
{
    List<Registration> result  = new List<Registration>();
    while(reader.Read())
    {
        result.Add(new Registration{Address=reader["Address"].ToString()});
    }
    return result;
}

Another way is this:
DataTable t = new DataTable();
t.Load(cmd.ExecuteReader);
var result  = from c in t.AsEnumerable()
              select new Registration{Address=c.Field<string>("Address")};
return result.ToList();

A:             int i = 0;
            Model.Registration regis = new Model.Registration();
            if (reader.HasRows)
            {
                do
                {
                    i++;
                    regis.Address = regis.Address + reader["Address"].ToString();
                } while (reader.Read());
            }
            regis.Address = i.ToString() + " " + regis.Address;
            return regis;

I was looking for a simpler method...this also helped


text:
Q: Drupal 7 - Registration pop up for new guest users I own a drupal 7 site.
I have users that are coming to many pages of my site (not only home page) from different sources on the internet.
My goal is that when a guest user is entering the site, no matter which page, he will get nice popup that will offer him to register to the site. On the popup, I will write short text explaining the benefits of the site, even put a video (if possible).
I saw that in many sites, I get a popup message on top on the site (the rest of the site becomes dark) that offer me to register. I want to do something similar.
Can someone help me achieve this goal?

A: You can use Popup On Load module for displaying a pop up for guest visitors in a Drupal 7 site.


text:
Q: Unable to map / fetch the response entity on 422 error code in Microprofile Rest Client I have an API, when I call it through postman it gives the below response on the following cases:
Case1: status code: 200
{"success": "student record is present",
  "error": null}

Case2: status code: 422
{"success": null,
  "error": "studentname should not contain numerics"}

I want to achieve the same above results of two case through microprofile restclient using quarkus/java project. So created the below classes
Java DTO Class:
public class StudentResponse{

    private String success;

    private String error;

    public String getSuccess() {
        return success;
    }

    public void setSuccess(String success) {
        this.success = success;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    @Override
    public String toString() {
        return "StudentResponse [success=" + success + ", error=" + error + "]";
    }

}

Rest-Client Class:
package com.tatadigital.rest.service;
@RegisterRestClient(configKey = "student-client-api")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public interface StudentService {

    @POST
    @Path("/checkStudent")
    StudentResponse checkStudent(@RequestBody StudentCheck studentCheck);
}

Finally, I tested it through the app, and for case-1, receiving the response body with status code 200 as expected. But for case-2 as the status code is 422 the exception is thrown and getting handled but in the exception object we have response object and inside it we have response entity. This response entity is null and even studentResponse is also null. I want to get the error message(json response) in 422 status code case with microprofile rest client case.
Any approach/suggestion to achieve this?

A: Edit
You can also achieve the same behavior from the DefaultResponseExceptionMapper by adding
resteasy.original.webapplicationexception.behavior=true
in the application.properties.
When this option is false, the DefaultResponseExceptionMapper wraps the WebApplicationException and returns an exception according to the HTTP status code, for example
} else if (e instanceof BadRequestException) {
    return new ResteasyBadRequestException((BadRequestException)e);
}

which doesn't contain the entity from the response.
If you enable the original behavior, the exception is returned as is and the response entity is available for you to read it.
wae.getResponse().readEntity(StudentResponse.class);

In case of a status code >=400 a WebApplicationException is thrown that holds a Response object, but is handled by the DefaultResponseExceptionMapper.
Create a custom exception mapper and throw a WebApplicationException that contains only the response
public class HttpExceptionMapper implements ResponseExceptionMapper<Throwable> {

    @Override
    public Throwable toThrowable(Response response) {
        throw new WebApplicationException(response);
    }

}

Register the mapper to your rest client with the appropriate annotation
@RegisterProvider(HttpExceptionMapper.class)
and you will be able to read the entity in the response
StudentResponse studentResponse;
try {
  studentResponse = checkStudent(studentCheck);
} catch(WebApplicationException wae) {
  studentResponse = wae.getResponse().readEntity(StudentResponse.class);
}

A: Unfortunately this isn't something supported by the Microprofile client.
However this sounds like a useful feature, so do you mind opening an issue in the Quarkus issue tracker?


text:
Q: Error-grub:PCIe Bus Error: severity=Corrected, type=Physical Layer, id=00e5(Receiver ID) I have install 16.04 Ubuntu OS beside with Windows 10 on my laptop. When I start my laptop or use dmesg command on terminal. I always get this error log
pcieport 0000:00:1c.5: PCIe Bus Error: severity=Corrected, type=Physical Layer, id=00e5(Receiver ID)
pcieport 0000:00:1c.5:   device [8086:9d15] error status/mask=00000001/00002000
pcieport 0000:00:1c.5:    [ 0] Receiver Error         (First)
pcieport 0000:00:1c.5: AER: Corrected error received: id=00e5
pcieport 0000:00:1c.5: can't find device of ID00e5
pcieport 0000:00:1c.5: AER: Corrected error received: id=00e5

And I have tried adding to the grub pci=nomsi, pci=noaer and pcie_aspm=off. But nothing improve, and I have try editing /etc/default/grub file like this
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash pcie_aspm=off"
GRUB_CMDLINE_LINUX="text pcie_aspm=off"

Before, I have tried to adding for pci=nomsi and pci=noaer parameter in /etc/default/grub file like above.
Please help me to solve it!
Thanks


text:
Q: Collapse large database table to one row per user I am running a casino (not real money) website that everytime a user plays a row is generated on a table "trans" on my database that make this database grow soo much that is crashing my server
This is the table structure
    Name        Type            Collation   Attributes          Null    Default     Extra       Action
 1  user_id     int(11)         No          None                Change  Change      Drop Drop    Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 2  amount      decimal(16,8)   No          None                Change  Change      Drop Drop    Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 3  aff         int(11)         No          0                   Change  Change      Drop Drop    Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 4  jackpot     int(11)         No          0                   Change  Change      Drop Drop    Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 5  paidout     int(11)         No          0                   Change  Change      Drop Drop    Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 6  type        int(11)         No          0                   Change  Change      Drop Drop    Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 7  created     timestamp       No          CURRENT_TIMESTAMP   Change  Change      Drop Drop    Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More

This table has abount 4 million rows actually and only 30000 users (user_id )
My question is , is there a way to to collapse the table let say daily and save only one row per user and keep their balances (amount).
I am trying this without success:
update trans
SELECT * FROM  trans group by user_id
set amount = (select sum(amount) from trans

A: here are some broad steps:

*

*create a new summary table.

*add a trigger on the original table to look up this user and add the amount to his total in the summary table

*clear out all the old entries on some schedule

or

*

*change your application logic to do an update instead of an insert

or
you can write one single GROUP BY style query to add up all the users info and return that instead of all the detail - probably what you are doing is select * which is using up all your memory.. bad


text:
Q: OCMock test code with intermediate variable I am new to using OCMock. I have the following simplified code I want to test -
@implementation ViewController

- (void)presentSomething:(NSString *)string {
    NSLog(@"doSomethingElseWithString - %@", string);
}

- (BOOL)handleResult:(NSString *)result
{
    BOOL handled = YES;
    NSString *changedString = [result uppercaseString];
    [self presentSomething:changedString];
    return handled;
}

@end

and I have a test as follows
- (void)testExample {
    ViewController *vc = [ViewController new];
    id mockViewController  = OCMPartialMock(vc);
    OCMStub([mockViewController presentSomething:@"1234"]);

    BOOL handled = [vc handleResult:@"1234"];
    XCTAssertTrue(handled);

    OCMVerify([mockViewController presentSomething:@"1234"]);
}

I want to verify presentSomething gets called with the correct argument after I call handleResult.
The test either gives a EXC_BAD_ACCESS while verifying or fails saying the presentSomething method was not invoked.
If I change the handleResult method as follows the test runs and passes.
- (BOOL)handleResult:(NSString *)result
{
    BOOL handled = YES;
    [self presentSomething:result];
    return handled;
}

It seems that intermediate [result uppercaseString] and variable caused the issue. Is this an issue with how I am using OCMock or a bug in OCMock?

A: Must be trying to do a pointer comparison instead of isEquals. I haven't tried debugging the issue against the source code yet, but there is a workaround:
- (void)testExample
{
    ViewController *vc = [ViewController new];
    id mockViewController  = OCMPartialMock(vc);
    OCMExpect([mockViewController presentSomething:@"1234"]);
    BOOL handled = [vc handleResult:@"1234"];
    XCTAssertTrue(handled);
    OCMVerifyAll(mockViewController);
}


text:
Q: javax.el.PropertyNotFoundException: Property not found on type org.hibernate.collection.internal.PersistentSet I try to recuperate data from association ManyToMany but i can't, this is my code.
Entity Produit :
@Entity
public class Produit implements Serializable {

@Id
@Column(name="Produit_ID")
@GeneratedValue
private Long id;
private String dq;
private String icForme;
private String ich;
private String icht;

@ManyToMany(cascade = {CascadeType.ALL})
 @JoinTable(name="produit_terminal",
                joinColumns={@JoinColumn(name="Produit_ID")},
                inverseJoinColumns={@JoinColumn(name="Terminal_ID")})
    private Set<Terminal> terminals = new HashSet<Terminal>();

//getter setter

Entity Terminal :
@Entity
public class Terminal implements Serializable{

@Id
@GeneratedValue
@Column(name="Terminal_ID")
private Long id;
private String crimpkontakt;
private String equipment;
private String geometrie;
private String dcbt;
private String icb;
private String ak;

@ManyToMany(mappedBy="terminals")
private Set<Produit> produit = new HashSet<Produit>();

//getter setter

Class : ModuleJPADao
public List<Produit> parProduit(String cat){
    cat = "%" + cat + "%";
    Query query = getEntityManger().createQuery( "from "+ getPersistentClass().getSimpleName()
            +" u where u.produit LIKE :cat").setParameter( "cat", cat );
    List<Produit> module = (List) query.getResultList();
    return module;

}

Class : ModuleService
public List<Produit> tousModuleProduit(String produit) {

    if(produit!= null){
        return moduleDao.parProduit(produit);
    }
    else{
        return null;
    }
}

main-flow.xml
<view-state id="accueil" view="accueil.xhtml">
    <on-render>
        <evaluate expression="moduleService.tousModuleProduit(module.getProduit())"
            result="viewScope.recherche" />

    </on-render>
</view-state>

file.xhtml
 <p:accordionPanel value="#{recherche}" var="car">

                    <p:tab title="IcForme : #{car.icForme}">

                        <h:panelGrid columns="4" cellspacing="20">

                            <p:outputLabel value="ICHT: " />
                            <p:inputText value="#{car.icht}" />

                            <p:outputLabel value="terminals : " />
                            <h:form>
                                <h:dataTable value="#{car.terminals}" var="der" >
                                    <p:column>
                                        <h:outputText value="#{der.geometrie}" />
                                    </p:column>

                                </h:dataTable>
                            </h:form>

                        </h:panelGrid>
        ....

i can't get the value of geometrie; i got this erreur:
javax.el.PropertyNotFoundException: /WEB-INF/flows/main/accueil.xhtml @84,53 value="#{der.geometrie}": Property 'geometrie' not found on type org.hibernate.collection.internal.PersistentSet

A:
<h:dataTable value="#{car.terminals}" var="der">
    <p:column>
        <h:outputText value="#{der.geometrie}" />

javax.el.PropertyNotFoundException: Property 'geometrie' not found on type org.hibernate.collection.internal.PersistentSet

Thus, the #{car.terminals} is a Set<E>. The <h:dataTable>, <p:dataTable> and <ui:repeat> components doesn't support iterating over a Set<E>. The #{der} will then basically represent the Set<E> itself. The builtin support for iterating over Set<E> will come in future JSF 2.3 version.
If it's not an option to replace Set<E> by a List<E>, then just get an array out of it as below:
<h:dataTable value="#{car.terminals.toArray()}" var="terminal">


text:
Q: Why's the Firefox Button gray? Shouldn't the orange color be the default for the Firefox Button on Linux as well? Ubuntu even has orange colored buttons in the default theme, but why's the Firefox button gray?

A: It looks like Mozilla had decided to make the button grey on Linux. You can try this addon (not tested by me):
https://addons.mozilla.org/firefox/addon/themed-button-for-linux/


text:
Q: In unordered_map of C++11, how to update the value of a particular key? In Java's hashmap:
map.put(key, new_value)

will update the entry of key=key with new_value if it exists in the hashmap.
What's the correct way to do the similar thing in unordered_map of C++11?
I haven't found an API like updateXXX, and the documentation says the unordered_map::insert function will succeed only when there isn't any such pair with a key.

A: If you know that the key is in the map, you can utilize operator[] which returns a reference to the mapped value. Hence it will be map[key] = new_value. Be careful, however, as this will insert a (key, new_value) if the key does not already exist in the map.
You can also use find which returns an iterator to the value:
auto it = map.find(key)
if(it != map.end())
    it->second = new_value;

A: If the type value has no default constructor you can use:
map.emplace(key, new_value).first->second = new_value;

This also has all the other advantages of emplace vs [] operator and insert.

A: I thought that Java's map.put inserted the element if it wasn't already in the map and updated it if it was in the map, see put:

put

  public V put(K key, V value)

  Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

This would be equivalent to unordered_map::operator[]:

If k matches the key of an element in the container, the function returns a reference to its mapped value.

  If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

A: *

*Check if the key exists

*Update the value by referencing the key

if(map.count(key)){
  map[key] = value;
}


text:
Q: How can I trigger an event or notification when an AWS SSM RunCommand Script completes executing on my EC2 Instance? Some background:
I am writing an application (using AWS Ruby SDK/API) that deploys another application on AWS EC2 instances.  Specifically, I deploy it as an ECS Cluster of 4 ec2 instances and then start ECS Tasks (not services), one on each ec2 instance and run these docker images.  That all works fine.  The problem is that at some point I need to save one of those docker images off in my ECR repo.  I do that by using Simple System Manager(SSM)'s aws:runShellScript to run the command on the ECS Container Instance.  That command may take 1-4 minutes and I don't have any way of finding out when the command completes. Right now I do a sleep and then just grab the tagged container image from the repository and that is error prone.
The question:
Is there any way to:

*

*wait_until for an SSM run command to complete? or

*have my deploying application be notified through AWS Lambda or some such? or

*Listen for events?

A: I resolved this problem by checking periodically if command's status is no longer "InProgress". The code is in bash, but the logic should be applicable elsewhere as well.
ID="instance_id"
COMMAND_ID=$(aws ssm send-command --instance-ids $ID --document-name "AWS-RunShellScript"
             --parameters commands="python" --output text --query "Command.CommandId")
STATUS=$(aws ssm list-commands --instance-id $ID --command-id $COMMAND_ID
         --query "Commands[0].Status")

while [ $STATUS "==" '"InProgress"' ]; do
    sleep 30;
    STATUS=$(aws ssm list-commands --instance-id $ID --command-id $COMMAND_ID
             --query "Commands[0].Status");
done

A: Here are some options I can think of:

*

*You could add a final step to the SSM command which would send an email or post to an SNS topic or something similar.

*The AWS SSM send_command API takes a notification_config parameter which you can configure to send a notification to an SNS topic when the command is in certain states, like the "Success" state. This is probably the best option for monitoring the state of the command.

Once you have done something to post to an SNS topic, you can configure a Lambda function to be triggered by messages in that SNS topic.


text:
Q: Difference between tables created in SQL DataWarehouse and Database I know it sounds very silly question but I want to know in what way the tables and their properties would differ if it is created in data warehouse and database.

A: So data warehouse is an another way to store data but it remains a database.
DATABASE: Any collection of data organized for storage, accessibility, and retrieval.
DATA WAREHOUSE: A type of database that integrates copies of transaction data from disparate source systems and provisions them for analytical use.

The main differences are on high level schema, but at low level they're both databases.
For a more deep explanation: https://www.differencebtw.com/difference-between-database-and-data-warehouse/


text:
Q: Replace element in array by average I have a question about the exercise from my course:
Write a program that takes array of real numbers as parameter and replaces each element that is smaller than average of the first and last element, by this average. This is my code:
#include <iostream>
#include <string>
using namespace std;

void replaverage(int arr[], int n)
{
    for (int i; i < 6; i++) {
        cout << "Enter the numbers" << endl;
        cin >> arr[i];
    }
    int f = arr[0];
    int l = arr[n - 1];
    double av = f + l / 2;
    for (int i; i < n; i++) {
        if (arr[i] < av) {
            arr[i] = av;
        }
    }
}

int main()
{
    int n;
    int arr[n];
    replaverage(arr, n);
    cout << arr << " " << endl;
    return 0;
}

Code is working, however as an output, it is giving some kind of address "0x7fff2306a5c0". I'm beginner so I apologize, maybe my error is stupid but I don't know how to fix it. Thanks for helping!

A: #include <iostream>
#include <string>
using namespace std;

void replaverage(int arr[], int n)
{
    for (int i = 0; i < n; i++) {
        cout << "Enter the number: ";
        cin >> arr[i];
        cout << endl;
    }
    int f = arr[0];
    int l = arr[n - 1];
    double av = (f + l) / 2;
    for (int i = 0; i < n; i++) {
        if (arr[i] < av) {
            arr[i] = av;
        }
    }
}

int main()
{
    int n = 6; // Making 6 since you had it hardcoded
    int arr[n];
    replaverage(arr, n);
    for (int i = 0; i < n; i++) {
       cout << arr[i] << endl;
    }
    return 0;
}

*

*First problem: Initialize your loop counters to 0;

*Second problem: Initialize n in main being passed as parameter to
something

*Third problem: Your average calculation is incorrect. It should be (f+l) / 2. Otherwise it will be doing l/2 + f, which is incorrect.

*Fourth problem: You need to loop over your array to see all the
elements


text:
Q: type mismatch error when attempting to access a sorted list within a dictionary I have two sheets Lkups and dataResponseTimes. I am reading the data from
both initially into arrays.
I am then using the function GetAmbStpMappingsDict to create a dictionary of sorted lists from the array AmbSTPLkupArr.
Sample data from sheet dataResponseTimes:
| Category   | Code    | Amb             | Incidents | Total (hours) | Mean (min:sec) | 90th centile (min:sec) | HCP incidents | Date       | Processed Date   |
|------------|---------|-----------------|-----------|---------------|----------------|------------------------|---------------|------------|------------------|
| Category 1 | England | England         | 27703     | 18:36:00      | 00:07:55       | 00:13:44               |               | 01/10/2017 | 02/02/2018 07:45 |
| Category 1 | RX9     | East Midlands   | 4588      | 14:47:36      | 00:08:25       | 00:14:52               |               | 01/10/2017 | 02/02/2018 07:45 |
| Category 1 | RYC     | East of England | 0         | 00:00:00      | 00:00:00       | 00:00:00               |               | 01/10/2017 | 02/02/2018 07:45 |

Sample data from sheet Lkups:
| Amb Code | STP                             |
|----------|---------------------------------|
| RYC      | CAMBRIDGESHIRE AND PETERBOROUGH |
| RYC      | HERTFORDSHIRE AND WEST ESSEX    |
| RYC      | MID AND SOUTH ESSEX             |
| RX9      | DERBYSHIRE                      |
| RX9      | HUMBER, COAST AND VALE          |
| ENGLAND  | ENGLAND                         |

The idea being I create a structure such that there is a dictionary key e.g. 'RYC' and associated list e.g. Cambridgeshire etc.:
| RYC | CAMBRIDGESHIRE AND PETERBOROUGH |
|     | HERTFORDSHIRE AND WEST ESSEX    |
|     | MID AND SOUTH ESSEX             |

The code I have written creates the structure but in sub test I get the

Type mismatch (Error 13)

on line:  Set sList = dict(key)
The sub PrintItems, adapted from an answer by @Thomas Inzina, can print out the contents of the dictionary dict, but trying to adapt this to use without a For Each loop is leading to the aforementioned error.
I am assuming this is because, without looping the keys, I am attempting to shortcut access the list in some way. Debugging shows that dict(key) is returning empty.
I don't want to deploy another loop if possible (i.e. of the keys). I have tried changing datatypes for sList, which, tbh, I didn't expect to work.
I would like to be able to loop testArr and use the value of testArr(rowIndex, 2), the code field from dataResponseTimes, to return the list from the dictionary, for that particular Code; e.g. If  testArr(rowIndex, 2) were RYC I want the three items Cambridgeshire.... as previously described.
The end goal being that I will duplicate each row, in dataResponseTimes, the matching number of times, for the same Code, as in the list e.g. For RYC I will be duplicating the following row 3 times (once for each region in the lookup mapping (Lkups).
| Category 1 | RYC     | East of England | 0         | 00:00:00      | 00:00:00       | 00:00:00               |               | 01/10/2017 | 02/02/2018 07:45 |

So, a shorter route might be simply to access via the Code, as a key, the associated sList.Count. The original reason for trying to access the actual list values was that I was going to append the list value e.g. CAMBRIDGESHIRE AND PETERBOROUGH to the row.
Please could someone help me resolve this?
Code:
Option Explicit

Public Sub test()
    'Tools > references > ms scripting runtime
    Dim sht As Worksheet
    Set sht = ThisWorkbook.Worksheets("dataResponseTimes")

    Dim dict As Dictionary
    Set dict = GetAmbStpMappingsDict

    Dim testArr()
    testArr = sht.Range("A2:J4").Value

    Dim rowIndex As Long

    For rowIndex = LBound(testArr, 2) To UBound(testArr, 2)

        Dim sList As Variant, stpName As String
        Dim x As Long
        Dim key As Variant
        key = testArr(rowIndex, 2)       'testArr(rowIndex, 2) is a Variant/string

        Set sList = dict(key)             'Error

        For x = 0 To sList.Count - 1
            stpName = sList.GetKey(x)
            Debug.Print stpName
        Next

    Next rowIndex

End Sub

Public Function GetAmbStpMappingsDict() As Dictionary

    Dim dict As New Scripting.Dictionary

    Dim AmbSTPLkupArr As Variant

    AmbSTPLkupArr = ThisWorkbook.Worksheets("Lkups").Range("A2:B7").Value

    Dim rowIndex As Long

    For rowIndex = LBound(AmbSTPLkupArr, 1) To UBound(AmbSTPLkupArr, 1)

        If Not dict.Exists(AmbSTPLkupArr(rowIndex, 1)) Then

            dict.Add AmbSTPLkupArr(rowIndex, 1), CreateObject("System.Collections.SortedList")
            dict(AmbSTPLkupArr(rowIndex, 1)).Add AmbSTPLkupArr(rowIndex, 2), AmbSTPLkupArr(rowIndex, 1)

        Else

            dict(AmbSTPLkupArr(rowIndex, 1)).Add AmbSTPLkupArr(rowIndex, 2), AmbSTPLkupArr(rowIndex, 1)

        End If

    Next rowIndex

    Set GetAmbStpMappingsDict = dict

End Function

Sub PrintItems(dict As Object)                   'Modified from code by @Thomas Inzina

    Dim sList As Variant, ambTrust As Variant, stpName As String
    Dim x As Long
    For Each ambTrust In dict
        Set sList = dict(ambTrust)
        Debug.Print "Parent Dictionary ambTrust: "; ambTrust
        For x = 0 To sList.Count - 1
            stpName = sList.GetKey(x)            'sList.GetByIndex(x)
            Debug.Print stpName
        Next
    Next
End Sub

A: Credit goes to @Rory for correctly identifying the issue.
1) I had failed to spot the difference in case for one item in the lookup table/sheet (Lkups) versus the data sheet dataResponseTimes. As @Rory states, the keys here are case sensitive. Changing England to ENGLAND; And,
2) Correcting a transcription error for the loop i.e.
For rowIndex = LBound(testArr, 1) To UBound(testArr, 1) not  For rowIndex = LBound(testArr, 2) To UBound(testArr, 2) resolved the issue.


text:
Q: How to rotate outer div not inner content How to fit an image inside a div and this div is rotated at 45deg?

A: Add scale value in transform style for img like this:

.profile-photo { width: 210px; height: 210px; position: relative; left: 43px; top: 50px; border: 8px solid #000; border-radius: 60px; transform: rotate(45deg); overflow: hidden; z-index: 2; background: #34983e;padding:0 }

.profile-photo img {
  width: 100%;
  transform: rotate(-45deg) scale(1.21)
}

A: use below code.
HTML

CSS
.div
    {
        width: 500px;
        background: lightblue;
        transform: rotate(40deg);
    }

W3schools transforms


text:
Q: how to to loose couple html and javascript How to to loose couple html and javascript... Is it necessary, worth ?
You have to always use some html elements inside javascript logic...
I know from c# you can lose couple for maintenance and test scenarios.

A: One of the best frameworks for separating the DOM and your javascript is Knockout.JS.
I find it incredibly smart with the separation of concerns. The view model can be completely unit testable.

A: You can separate them pretty easily; just keep the majority of the JavaScript separate from the JavaScript that interacts with the DOM, using functions and the like. Kinda like views and controllers.


text:
Q: How to use react-dnd-scrollzone in our application.? I am very new to reactJS. I have to add autoscrolling feature with drag and drop component. that's why i am using react-dnd-scrollzone.
While using example from  "https://github.com/azuqua/react-dnd-scrollzone", I am having following errors :

'Scrollzone' is not defined
  'ScrollingComponent' is assigned a value but never used

Please if anyone can help me with this and tell me how to use this in my code.
The snippet below is showing few lines of my code where i used scrollzone.

const DndComponent = DragDropContext(HTML5Backend)(ScheduleBoard);
const ScrollingComponent = withScrolling(ScheduleBoard);
const vStrength = createVerticalStrength(500);
const hStrength = createHorizontalStrength(300);

const zone = (
  <Scrollzone verticalStrength={vStrength} horizontalStrength={hStrength}/>

);

export default connect(
  mapStateToProps,
  {
    clearErrors,
    getToday,
    setPage,
    getDepartments,
    getTaskList,
    getUnscheduledTasks,
    unscheduleTask,
    putUnscheduleTask,
    rescheduleTask,
    putRescheduleTask,
    mergeTasks,
    putMergeTasks,
    unmergeTasks,
    putUnmergeTasks,
    resizeWindow,
    startLoader,
    startDeptLoader,
    unscheduledFilter,
    createReservationNote,
  }
)(DndComponent);

A: You forgot the define a ScrollZone as said in react-dnd-scrollzone documentation. Here is the basic example.
import withScrolling, { createVerticalStrength, createHorizontalStrength } from 'react-dnd-scrollzone';

const Scrollzone = withScrolling('ul');
const vStrength = createVerticalStrength(500);
const hStrength = createHorizontalStrength(300);

// zone will scroll when the cursor drags within
// 500px of the top/bottom and 300px of the left/right
const zone = (
  <Scrollzone verticalStrength={vStrength} horizontalStrength={hStrength}>

  </Scrollzone>
);


text:
Q: Graphics card causes motherboard to delay power off Recently a glass of fruit juice was dumped into my tower. I immediately scrapped the motherboard and power supply unit, replacing both, and attempted to salvage both the RAM, GPU, and the CPU. I took every component out, and meticulously cleaned everything with isopropyl alcohol and electrical contact cleaner, attempting to clean the dried stains off of my graphics card PCB (fan faces the bottom). The CPU and RAM were relatively okay, even before cleaning.
After replacing the motherboard and PSU, the computer boots up and everything seemingly runs just as it did before. The only problem i've got now is when I send a shutdown signal from my OS, the OS shuts down properly and the GPU cycles the monitors off, but there is about a 30 second delay before the mobo shuts off. Turning it back on is similar, I cycle on and there is about a 20-30 second delay before it begins posting and booting my OS. As well, if I attempt to switch from my GUI to a virtual console within the OS, the OS makes the switch but cycles off my monitors instead of showing tty1, with no errors reported from the kernal or rsyslog. Switching back from tty1 to the GUI, again about a 20-30 second delay, I get a beep from the motherboard, and my monitors cycle on and I can resume from the GUI.
I believe I've singled this out to my graphics card. If I remove the GPU from the system, everything seems to go back to normal, OS shuts down relatively quick and posts as normal.
I guess what I'm asking is that before I go back to scrubbing more juice off the GPU, is there anything I can do to fix this issue specifically? I'm still not 100% sure it's the GPU and not something wrong with the motherboard itself as I replaced it at the same time as the GPU (ie. PCI bus). Is this something a graphics card can be responsible for?
And and all advice would be greatly appreciated. I'd prefer not to have to replace the card as everything else works okay except for this one thing.
Thanks for reading my wall of text
~ llldino

A: I assume u r running windows. That delay would be Windows querying a component (seemingly in your case the GPU) and not getting the response it is looking for either fast enough or not at all.
The best thing to do when one spills anything on electronics is to wash it in fresh water (a dishwasher will work) and put it into an oven on min temp for at least 24 hours to dry it. The longer the better. (We did just that at an industrial service outfit I worked for).
U might look at the event viewer to see if there r any errors or warnings reported. That my give u a good clue.


text:
Q: Reload entity that has been modified in another context Let's say I have this code, using EF6 and WPF
// db model
class Category
{
    public string Name { get; set; }
    ...
}

// db model
class Bar
{
    public virtual Category { get; set; }
}

class Foo
{
    private Bar bar;

    void Load()
    {
        using(var context = new ApplicationDbContext())
        {
            bar = context.Bars.First(x => x.Id == 1);
        }
    }

    void Mutation()
    {
        using(var context = new ApplicationDbContext())
        {
             context.Attach(bar);
             bar.Category.Name = "Hello";
             context.SaveChanges();
        }
    }
}

class Baz
{
    private Bar bar;

    void Load()
    {
        using(var context = new ApplicationDbContext())
        {
            bar = context.Bars.First(x => x.Id == 1);
        }
    }

    void Print()
    {
        // Reload entity???
        Console.WriteLine(bar.Category.Name);
    }
}

Now let's say I instanciate both Foo and Baz. Both of their instance of bar have been loaded by different contexts, but represent the same record in the database. If I were to call Mutation() on Foo, bar.Category.Name of Baz wouldn't be updated.
How would I go about reloading Baz.bar? I have tried almost everything I could find online with no success.
For example, this does not work
context.Entry(bar).Reload()

A single context for the whole application would fix this tracking issue, but it is considered bad practice. I hope I was clear enough!


text:
Q: iOS Firebase push messaging not receiving I have been doing to integrate Firebase Push Notification.(Silent messaging)
I can receive data message when app is in foreground state.
But I can not receive any messaging when app is background and closed state.
I want to receive and handle messages when receiver is in closed state.
If I can receive not handled messages when I open app from closed state then it would be ok.
But Just now I can receive only app is in foreground state.
If I close app and send messages. And then open app then does not receive any messaging.
For a few months ago, I confirmed that messages were receiving when I open app from closed state, but not now.
I am trying to fix it during a few days.
But still does not find any solution.
How can I fix it?
I used data messaging , not push notification
And used Swift 3.
Thank you.


text:
Q: Microsoft Graph - Teams API works on Graph Explorer but not via code I have a requirement to automatically post a message on a Teams channel and mention the channel. Unfortunately via MS Flow, the option to mention an entire channel is not available, however it seems that through the beta version of the Graph API, I can mention an entire channel.
I have first tried via Graph Explorer, changing the VERB to POST and setting the URL to <https://graph.microsoft.com/beta/teams/{group ID}/channels/{channel id}/messages>
Moreover added the below request body
{
    "subject": "@Mention in Teams channel post!",
    "body": {
        "content": "Hello <at id ='0'>{channel name}</at>, Test message on the channel with at mention.",
        "contentType": "html"
    },
    "mentions": [
        {
            "id": 0,
            "mentionText": "{channel name}",
            "mentioned": {
                "conversation": {
                    "id": "{channel id}",
                    "displayName": "{channel name}",
                    "conversationIdentityType@odata.type": "#Microsoft.Teams.GraphSvc.conversationIdentityType",
                    "conversationIdentityType": "channel"
                }
            }
        }
    ]
}

When the Run Query is pressed, the message is successfully posted and the channel is mentioned. I've then retrieved the code snippet from the graph explorer for C# code, which resulted in the below code
GraphServiceClient graphClient = new GraphServiceClient(authProvider);

var chatMessage = new ChatMessage
{
    Subject = "@Mention in Teams channel post!",
    Body = new ItemBody
    {
        Content = "Hello <at id ='0'>{channel name}</at>, Test message on the channel with at mention.",
        ContentType = BodyType.Html
    },
    Mentions = new List<ChatMessageMention>()
    {
        new ChatMessageMention
        {
            Id = 0,
            MentionText = "{channel name}",
            Mentioned = new IdentitySet
            {
                AdditionalData = new Dictionary<string, object>()
                {
                    {"conversation", "{\"id\":\"{channel id}\",\"displayName\":\"{channel name}\",\"conversationIdentityType@odata.type\":\"#Microsoft.Teams.GraphSvc.conversationIdentityType\",\"conversationIdentityType\":\"channel\"}"}
                }
            }
        }
    }
};

await graphClient.Teams["{group id}"].Channels["{channel id}"].Messages
    .Request()
    .AddAsync(chatMessage);

However when executing the code, the error below is displayed:

ServiceException: Code: BadRequest
Message: Invalid request body was sent.

Removing the Mentions or changing the mentions to make use of the User works successfully. Also, kindly note that I've tried using both the Microsoft.Graph and Microsoft.Graph.Beta

A: I had done a long research on this and found that its a Deserialization issue happening on the Graph server because of the code written this way. The main problem is with the conversation in the Mentioned property. The Graph server was unable to understand the serialized content so try deserializing it before sending the request as shown below.
Identity A = JsonConvert.DeserializeObject<Identity>("{\"id\":\"{channel id}\",\"displayName\":\"{channel name}\",\"conversationIdentityType@odata.type\":\"#Microsoft.Teams.GraphSvc.conversationIdentityType\",\"conversationIdentityType\":\"channel\"}");
            var chatMessage = new ChatMessage
            {
                Subject = "@Mention in Teams channel post!",
                Body = new ItemBody
                {
                    Content = "Hello <at id ='0'>General</at>, Test message on the channel with at mention.",
                    ContentType = BodyType.Html
                },
                Mentions = new List<ChatMessageMention>()
                {
                    new ChatMessageMention
                    {
                        Id = 0,
                        MentionText = "General",
                        Mentioned = new IdentitySet
                        {
                            AdditionalData = new Dictionary<string, object>()
                            {
                                {"conversation", A}
                            }
                        }
                    }
                }
            };

            try
            {
                await graphClient.Teams["d3b31e36-d63d-4bbe-9478-b4cc7cb17a3d"].Channels["19:342b9f379eb340048b16d9859d9e3712@thread.tacv2"].Messages
                .Request()
                .AddAsync(chatMessage);

            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }

It will work.


text:
Q: Standard Library vs Windows API Speed My question is about whether or not I should use the Windows API if I'm trying to get the most speed out of my program, where I could instead use a Standard Library function.
I assume the answer isn't consistent among every call; Specifically, I'm curious about stat() vs dwFileAttributes, if I wanted to figure out if a file was a directory or not for example (assuming file_name is a string containing the full path to the file):
WIN32_FIND_DATA fileData;
HANDLE          hSearch;

hSearch = FindFirstFile(TEXT(file_name), &fileData);

int isDir = fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY

vs.
struct stat info;
stat(file_name, &info);

int isDir = S_ISDIR(info.st_mode);

If anyone knows, or can elaborate on what the speed difference between these libraries generally is (if any) I'd appreciate it.

A: Not an answer regarding speed, but @The Corn Inspector, the MSVC CRT code is open sourced.  If you look at an older version ( before .net and common UCRT), and look at the stat() function, it is INDEED a wrapper around the same OS call.
int __cdecl _tstat (
        REG1 const _TSCHAR *name,
        REG2 struct _stat *buf
        )
{  // stuff omitted for clarity
        _TSCHAR *  path;
        _TSCHAR    pathbuf[ _MAX_PATH ];
        int drive;          /* A: = 1, B: = 2, etc. */
        HANDLE findhandle;
        WIN32_FIND_DATA findbuf;

        /* Call Find Match File */
        findhandle = FindFirstFile((_TSCHAR *)name, &findbuf);

Of course there is addtional code for mapping structures, etc. Looks like it also does some time conversion:
 SYSTEMTIME SystemTime;
            FILETIME LocalFTime;

            if ( !FileTimeToLocalFileTime( &findbuf.ftLastWriteTime,
                                           &LocalFTime )            ||
                 !FileTimeToSystemTime( &LocalFTime, &SystemTime ) )
            {

so theoretically, it could be slower, but probably so insignificant, as to make no practical difference in the context of a complete, complex program.  If you are calling stat() a million times, and worry about milliseconds, who knows.  Profile it.


text:
Q: SFGUI rendering issue c++ I'm making a server menu system however when I remove all the items from the sfgui system and move on to another game state the labels from the previous game state are visible under a circumstance which I will explain in a minute, first let me show you the issue.
Server Menu:

Here you can see the issue:

The code for removal is as follows.
void S_ServerMenu::Exit() {
  ServerSelectWindow->Show(false);
  desktop.RemoveAll();
  desktop.Refresh();
}

However this issue only occurs on refresh of servers here is the code for refresh.
void S_ServerMenu::RefreshServers() {
  Document d;
  d.Parse<0>(LoadInServers().c_str());
  servers = ServerParser(d);
  ServerListTable->RemoveAll();
  ServerListTable->RefreshAll();
  for(int i = 0; i < servers.size(); i++) {
    auto label = sfg::Label::Create();

    label->SetText(servers[i].Name);

    MenuItem utm;
    utm.lbl = label;
    utm.index = i;
    utm.owner = this;
    label->SetAlignment(sf::Vector2f(0, 0));
    label->FontSize = 16;
    label->SetParent(ServerListTable);
    label->cont = ServerSelectWindowContainer;
    ServerListTable->Attach(label, sf::Rect<sf::Uint32>(1, i, 1, 1), sfg::Table::FILL | sfg::Table::EXPAND);

    label->GetSignal(sfg::Label::OnLeftClick).Connect(std::bind(&MenuItem::Clicked, utm));
  }
  ServerSelectWindow->RefreshAll();
}

Do any of you know how to solve this if so that would be great.

A: I fixed this by creating a separate Desktop for each screen.


text:
Q: How to forward port between localhost and two remote hosts localhost can access host-a and host-b.
host-a cannot access host-b.
host-b can access host-a.
How can I connect to a service on host-b from host-a?

A: You can try autossh with -R for an easy way out. (not very secure)
Correct way is to use ssh -R w/o ssh -L if you want security.
Or just use socat tcp-listen:myport tcp-connect:b:b-port and on host-a connect to the intermediate-host:myport
You can use nc -l -p port and nc addr port for testing


text:
Q: How to fix hanging popen3 in Ruby? I am getting unexpected behaviour using popen3, which I want to use to run a command like tool ala cmd < file1 > file2. The below example hangs, so that stdout done is never reached. Using other tools than cat may cause hanging, so that stdin done is never reached. I suspect, I am suffering from buffering, but how do I fix this?
#!/usr/bin/env ruby

require 'open3'

Open3.popen3("cat") do |stdin, stdout, stderr, wait_thr|
  stdin.puts "foobar"

  puts "stdin done"

  stdout.each_line { |line| puts line }

  puts "stdout done"

  puts wait_thr.value
end

puts "all done"

A: Your code is hanging, because stdin is still open!
You need to close it with IO#close or with IO#close_write if you use popen3.
If you use popen then you need to use IO#close_write because it only uses one file descriptor.
 #!/usr/bin/env ruby
 require 'open3'

 Open3.popen3("cat") do |stdin, stdout, stderr, wait_thr|
   stdin.puts "foobar"

   stdin.close   # close stdin like this!  or with stdin.close_write

   stdout.each_line { |line| puts line }

   puts wait_thr.value
 end

See also:
Ruby 1.8.7 IO#close_write
Ruby 1.9.2 IO#close_write
Ruby 2.3.1 IO#close_write

A: The answers by Tilo and by sepp2k are right: If you close stdin, your simple test will end. Problem solved.
Though in your comment to the answer of sepp2k, you indicate that you still experience hangs.
Well, there are some traps that you might have overlooked.
Stuck on full buffer for stderr
If you call a program that prints more to stderr than the buffer of an anonymous pipe can hold (64KiB for current Linuxes), the program gets suspended. A suspended program neither exits nor closes stdout. Consequently, reading from its stdout will hang. So if you want to do it right, you have to use threads or IO.select, non-blocking, unbuffered reads in order to read from both stdout and stderr in parallel or by turns without getting stuck.
Stuck on full buffer for stdin
If you try to feed more (much more) than "foobar" to your program (cat), the buffer of the anonymous pipe for stdout will get full. The OS will suspend cat. If you write even more to stdin, the buffer of the anonymous pipe for stdin will get full. Then your call to stdin.write will get stuck. This means: You need to write to stdin, read from stdout and read from stderr in parallel or by turns.
Conclusion
Read a good book (Richards Stevens, "UNIX Network Programming: Interprocess communications") and use good library functions. IPC (interprocess communications) is just too complicated and prone to indeterministic run-time behavior. It is for too much hassle to try to get it right by try-and-error.
Use Open3.capture3.

A: stdout.each_line is waiting for further output from cat because cat's output stream is still open. It's still open because cat is still waiting for input from the user because its input stream hasn't been closed yet (you'll notice that when you open cat in a terminal and type in foobar, it will still be running and waiting for input until you press ^d to close the stream).
So to fix this, simply call stdin.close before you print the output.