text:
Q: Can NServiceBus publish to subscribers in the same AppDomain? I have a simple web site. In my API controller I am capturing a Command and Sending it to a Handler. This works perfectly. In the handler I do some processing, and then Publish an event. The event NEVER gets published. I cannot even begin to describe the list of changes I have done to get this working, all to no avail.
About the only thing I can see that is different between my app and any sample is that mine has the publisher and subscriber in the same assembly. At this point in time I don't see the need for having a separate NServiceBus process, although I will likely do that at some point.
Handler
public sealed class PortfoliosHandler : IHandleMessages<CreatePortfolioCommand>, IHandleMessages<PortfolioCreatedEvent>
{
    public void Handle(CreatePortfolioCommand message)
    {
        // Processing logic, this executes just fine

        Bus.Publish(new PortfolioCreatedEvent { Name = portfolio.Name });
    }

    public void Handle(PortfolioCreatedEvent message)
    {
        // This NEVER executes
    }
}

Config
<UnicastBusConfig ForwardReceivedMessagesTo="audit">
    <MessageEndpointMappings>
        <add Assembly="Project.Domain" Namespace="Project.Domain.PM.Commands" Endpoint="messagebus" />
        <add Assembly="Project.Domain" Namespace="Project.Domain.PM.Events" Endpoint="messagebus" />
    </MessageEndpointMappings>
</UnicastBusConfig>

Config Code
NServiceBus.Configure.Transactions.Enable();

var config = NServiceBus.Configure.With();

config = config
    .AutofacBuilder(container)
    .Log4Net(new DebugAppender {Threshold = Level.Warn})
    .UseTransport<Msmq>()
    .PurgeOnStartup(true)
    .UnicastBus()
    .LoadMessageHandlers()
    .RunHandlersUnderIncomingPrincipal(false)
    .InMemorySubscriptionStorage()
    .UseInMemoryTimeoutPersister();

var bus = config
    .CreateBus()
    .Start(() => Configure.Instance.ForInstallationOn<NServiceBus.Installation.Environments.Windows>()
                            .Install());

Not only does the event handler never fire, but no event message ever appears in the queues, and no record of it being published ever appears in the logs. It's almost as if I never sent it. Here are the log entries emitted by calling the Publish method above:
NServiceBus.Unicast.UnicastBus: 15:52:11,984 DEBUG UnicastBus:0 - Invoking transport message mutator: NServiceBus.Transports.Msmq.CorrelationIdMutatorForBackwardsCompatibilityWithV3
NServiceBus.Unicast.UnicastBus: 15:52:11,984 [23] DEBUG NServiceBus.Unicast.UnicastBus [(null)] <(null)> - Invoking transport message mutator: NServiceBus.Transports.Msmq.CorrelationIdMutatorForBackwardsCompatibilityWithV3
NServiceBus.Unicast.UnicastBus: 15:52:12,240 DEBUG UnicastBus:0 - Invoking transport message mutator: NServiceBus.Impersonation.Windows.WindowsIdentityEnricher
NServiceBus.Unicast.UnicastBus: 15:52:12,240 [23] DEBUG NServiceBus.Unicast.UnicastBus [(null)] <(null)> - Invoking transport message mutator: NServiceBus.Impersonation.Windows.WindowsIdentityEnricher
NServiceBus.Unicast.UnicastBus: 15:52:12,488 DEBUG UnicastBus:0 - Invoking transport message mutator: NServiceBus.Unicast.Monitoring.VersionMutator
NServiceBus.Unicast.UnicastBus: 15:52:12,488 [23] DEBUG NServiceBus.Unicast.UnicastBus [(null)] <(null)> - Invoking transport message mutator: NServiceBus.Unicast.Monitoring.VersionMutator
NServiceBus.Unicast.UnicastBus: 15:52:12,743 DEBUG UnicastBus:0 - Invoking transport message mutator: NServiceBus.Unicast.Monitoring.SentTimeMutator
NServiceBus.Unicast.UnicastBus: 15:52:12,743 [23] DEBUG NServiceBus.Unicast.UnicastBus [(null)] <(null)> - Invoking transport message mutator: NServiceBus.Unicast.Monitoring.SentTimeMutator
NServiceBus.Unicast.UnicastBus: 15:52:12,984 DEBUG UnicastBus:0 - Invoking transport message mutator: NServiceBus.Unicast.Monitoring.CausationMutator
NServiceBus.Unicast.UnicastBus: 15:52:12,984 [23] DEBUG NServiceBus.Unicast.UnicastBus [(null)] <(null)> - Invoking transport message mutator: NServiceBus.Unicast.Monitoring.CausationMutator
NServiceBus.Unicast.UnicastBus: 15:52:13,228 DEBUG UnicastBus:0 - Invoking transport message mutator: NServiceBus.Sagas.OriginatingSagaHeaderMutator
NServiceBus.Unicast.UnicastBus: 15:52:13,228 [23] DEBUG NServiceBus.Unicast.UnicastBus [(null)] <(null)> - Invoking transport message mutator: NServiceBus.Sagas.OriginatingSagaHeaderMutator
NServiceBus.Unicast.UnicastBus: 15:52:13,475 DEBUG UnicastBus:0 - Invoking transport message mutator: NServiceBus.Sagas.AutoCorrelateSagaOnReplyMutator
NServiceBus.Unicast.UnicastBus: 15:52:13,475 [23] DEBUG NServiceBus.Unicast.UnicastBus [(null)] <(null)> - Invoking transport message mutator: NServiceBus.Sagas.AutoCorrelateSagaOnReplyMutator
NServiceBus.Unicast.UnicastBus: 15:52:13,721 DEBUG UnicastBus:0 - Invoking transport message mutator: NServiceBus.MessageHeaders.MessageHeaderManager
NServiceBus.Unicast.UnicastBus: 15:52:13,721 [23] DEBUG NServiceBus.Unicast.UnicastBus [(null)] <(null)> - Invoking transport message mutator: NServiceBus.MessageHeaders.MessageHeaderManager
NServiceBus.Unicast.UnicastBus: 15:52:13,969 DEBUG UnicastBus:0 - Invoking transport message mutator: NServiceBus.Gateway.HeaderManagement.GatewayHeaderManager
NServiceBus.Unicast.UnicastBus: 15:52:13,969 [23] DEBUG NServiceBus.Unicast.UnicastBus [(null)] <(null)> - Invoking transport message mutator: NServiceBus.Gateway.HeaderManagement.GatewayHeaderManager

These are the log entries that occur shortly thereafter:
NServiceBus.Unicast.UnicastBus: 15:52:58,866 DEBUG UnicastBus:0 - Finished handling message.
NServiceBus.Unicast.UnicastBus: 15:52:58,866 [23] DEBUG NServiceBus.Unicast.UnicastBus [(null)] <(null)> - Finished handling message.
NServiceBus.Timeout.Hosting.Windows.TimeoutPersisterReceiver: 15:53:00,900 DEBUG TimeoutPersisterReceiver:0 - Polling for timeouts at 09/20/2013 15:53:00.
NServiceBus.Timeout.Hosting.Windows.TimeoutPersisterReceiver: 15:53:00,900 [17] DEBUG NServiceBus.Timeout.Hosting.Windows.TimeoutPersisterReceiver [(null)] <(null)> - Polling for timeouts at 09/20/2013 15:53:00.
NServiceBus.Timeout.Hosting.Windows.TimeoutPersisterReceiver: 15:53:01,152 DEBUG TimeoutPersisterReceiver:0 - Polling next retrieval is at 09/20/2013 15:54:01.
NServiceBus.Timeout.Hosting.Windows.TimeoutPersisterReceiver: 15:53:01,152 [17] DEBUG NServiceBus.Timeout.Hosting.Windows.TimeoutPersisterReceiver [(null)] <(null)> - Polling next retrieval is at 09/20/2013 15:54:01.

Please help. I am at my wits end. I ported from MassTransit to NServiceBus specifically because of the separation between Commands, Events, and Messages, but after 4 days of banging my head against this, MassTransit looking mighty good.
I'm sure it's something really stupid I'm doing, but I'm a noob to NServicebus. I even bought the book to try and help me, to no avail. I cannot see what I'm doing wrong, and I have tried so many permutations of settings I cannot keep track of them all.
Updated 2013/09/23
A suggested I have:

*

*Split the handler in two: a PortfolioCreatedHandler and a CreatePortfolioHandler.

*Removed sealed from the handler

*Created my own SubscriptionStorage, wrapping InMemorySubscriptionStorage for debugging purposes

I was already using IEvent to mark my events, and ICommand for my commands. Commands are published by the web controllers, and only the handlers publish events.
My TestSubscriptionStorage class is being called for Init and GetSubscriberAddressesForMessage, and not for Subscribe and Ubsubscribe, so it looks like the problem is that the events are not being subscribed, which is difficult to reconcile with the logs entries below.
Here are the logs mentioning the PortfolioCreatedEvent:
NServiceBus.Unicast.Routing.StaticMessageRouter: 09:34:25,886 DEBUG StaticMessageRouter:0 - Routing for message: Project.Domain.PM.Events.PortfolioCreatedEvent set to messagebus@SL-T50009909L
NServiceBus.Unicast.Routing.StaticMessageRouter: 09:34:25,886 [1] DEBUG NServiceBus.Unicast.Routing.StaticMessageRouter [(null)] <(null)> - Routing for message: Project.Domain.PM.Events.PortfolioCreatedEvent set to messagebus@SL-T50009909L
MessageType: Project.Domain.PM.Events.PortfolioCreatedEvent, Recoverable: True, TimeToBeReceived: Not set
MessageType: Project.Domain.PM.Events.PortfolioCreatedEvent, Recoverable: True, TimeToBeReceived: Not set
NServiceBus.Unicast.MessageHandlerRegistry: 09:34:25,906 DEBUG MessageHandlerRegistry:0 - Associated 'Project.Domain.PM.Events.PortfolioCreatedEvent' message with 'Project.PM.Handers.PortfolioCreatedHandler' handler
NServiceBus.Unicast.MessageHandlerRegistry: 09:34:25,906 [1] DEBUG NServiceBus.Unicast.MessageHandlerRegistry [(null)] <(null)> - Associated 'Project.Domain.PM.Events.PortfolioCreatedEvent' message with 'Project.PM.Handers.PortfolioCreatedHandler' handler
NServiceBus.Unicast.MessageHandlerRegistry: 09:34:25,916 DEBUG MessageHandlerRegistry:0 - Associated 'Project.Domain.PM.Commands.CreatePortfolioCommand' message with 'Project.PM.Handers.CreatePortfolioHandler' handler
NServiceBus.Unicast.MessageHandlerRegistry: 09:34:25,916 [1] DEBUG NServiceBus.Unicast.MessageHandlerRegistry [(null)] <(null)> - Associated 'Project.Domain.PM.Commands.CreatePortfolioCommand' message with 'Project.PM.Handers.CreatePortfolioHandler' handler
NServiceBus.Serializers.XML.XmlMessageSerializer: 09:34:26,120 DEBUG XmlMessageSerializer:0 - Initializing type: Project.Domain.PM.Events.PortfolioCreatedEvent, Project.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
NServiceBus.Serializers.XML.XmlMessageSerializer: 09:34:26,120 [1] DEBUG NServiceBus.Serializers.XML.XmlMessageSerializer [(null)] <(null)> - Initializing type: Project.Domain.PM.Events.PortfolioCreatedEvent, Project.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
NServiceBus.Unicast.Subscriptions.MessageDrivenSubscriptions.MessageDrivenSubscriptionManager: 09:34:35,445 INFO  MessageDrivenSubscriptionManager:0 - Subscribing to Project.Domain.PM.Events.PortfolioCreatedEvent, Project.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null at publisher queue messagebus@SL-T50009909L
NServiceBus.Unicast.Subscriptions.MessageDrivenSubscriptions.MessageDrivenSubscriptionManager: 09:34:35,445 [18] INFO  NServiceBus.Unicast.Subscriptions.MessageDrivenSubscriptions.MessageDrivenSubscriptionManager [(null)] <(null)> - Subscribing to Project.Domain.PM.Events.PortfolioCreatedEvent, Project.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null at publisher queue messagebus@SL-T50009909L
NServiceBus.AutomaticSubscriptions.DefaultAutoSubscriptionStrategy: 09:34:35,555 DEBUG DefaultAutoSubscriptionStrategy:0 - Autosubscribed to event Project.Domain.PM.Events.PortfolioCreatedEvent
NServiceBus.AutomaticSubscriptions.DefaultAutoSubscriptionStrategy: 09:34:35,555 [18] DEBUG NServiceBus.AutomaticSubscriptions.DefaultAutoSubscriptionStrategy [(null)] <(null)> - Autosubscribed to event Project.Domain.PM.Events.PortfolioCreatedEvent

A: Well, thanks for buying the book! Yes, you can absolutely subscribe to events from the same AppDomain. Here are some thoughts as to what might be happening.

*

*Do you see log entries that indicate they are subscribing to the event? If not then they are not subscribing.

*You didn't post code for your command and event, so I'm not sure if you're using Unobtrusive Mode or directly implementing IEvent. NServiceBus 4 will not automatically subscribe to anything not recognized as an event.

*I see InMemorySubscriptionStorage in your code. This makes it a little difficult to actually look at that storage. You could try injecting an ISubscriptionStorage somewhere so that you can look at what's in there in the debugger. Or just switch to the default Raven subscription storage for awhile so that you can navigate to the RavenDB Studio at http://localhost:8080 and look at the subscription documents.

*I'm not sure why you sealed your handler class. I can't think of a specific problem that might cause but it might be a good idea to take it out to eliminate it as a possible problem.

*Try separating your handlers into separate classes. There's no reason for one class to implement both anyway - the container will spin up new instances for each message so you can't share state, so it's probably best to not give another developer the impression that they could.

*Also this issue could have something to do with it?

And of course I get to be a broken record sometimes with this but I would caution you not to publish events from a web application in the first place.


text:
Q: What are the necessary and sufficient conditions for Euler path in directed graph? The definition says
"A directed graph has an eulerian path if and only if it is connected and each vertex except 2 have the same in-degree as out-degree, and one of those 2 vertices has out-degree with one greater than in-degree (this is the start vertex), and the other vertex has in-degree with one greater than out-degree (this is the end vertex)."
But i need to understand that is it that by connected,does it mean strongly connected or unilaterally connected?

A: The exact condition you need is that every vertex must be reachable from the start vertex (except for any vertices with in-degree and out-degree $0$, which we don't care about when looking for an Euler path). Equivalently, every edge must be reachable from the start vertex. That is, for every edge, there is a path from the start vertex including that edge.
This condition is clearly necessary; if an edge is not reachable from the start vertex, you can never include that edge in a directed path. You can verify that this condition is sufficient by checking that a modified version of Hierholzer's algorithm (Wikipedia link) will find an Euler path.
Hierholzer's algorithm, modified for Euler paths in directed graphs, starts by taking an arbitrary path from the start vertex to the end vertex. Then, as long as there are vertices on the path with unused out-edges, we:

*

*Start at one of these vertices and keep taking unused out-edges until we return to that vertex, creating a directed cycle;

*Splice that cycle into our path from the start vertex to the end vertex, creating a longer path.

The degree condition ensures that we never get stuck in step 1. But it's the connectedness condition given above that ensures that, as long as there are unused edges anywhere in the graph, there must be unused edges leaving vertices on the path we've found.

redpajama_set_name: RedPajamaStackExchange


text:
Q: DELL restore not working I have the Dell XPS M1330 and it came with Windows Vista Home pre-installed but I did a stupid thing and installed Vista Professional over it now I can't restore it to its previous state.
I can still see the restore drive but I can't seem to restore it?  Any tips?
I want to restore it back to factory settings.
EDIT:  When I reboot and press F8 I don't have any options for repairing my PC - boot to windows etc.

A: Installing Vista Professional may have just overwritten the boot menu which contained the option to boot into the recovery partition.
You may be able to use EasyBCD to search for the recovery partition, add it back into the boot menu and then boot into it as you were trying to do.


text:
Q: R, tidyverse: How to use spread() together with group_by() I have data in long format and am trying to spread data to long format group_by an identifier. I have tried the solution posted here and and receive this error message Error in -x : invalid argument to unary operator. I have also tried the solution posted here.
My dataset looks like this;
iden<-c(rep(1:25, 2), rep(26:50, 2))
group<-c(rep(5, 25), rep(20, 25), rep(-18, 25), rep(-80, 25))
value<-sample(100:5000, 100, replace=TRUE)
df<-data.frame(iden, group, value)

Please help me figure out how to get the data in wide format without duplicate identifiers
(see attched image here for expected output).
For image of @Ronak Shah's answer see  image here


text:
Q: How to keep a hidden view in responder chain? I have a NSSplitViewController and in one of the items I have multiple buttons with keyboard shortcuts.
Once the user hides the item, the shortcuts don't fire.
Is there any way to keep the buttons in the hidden view as part of the responder chain?

A: Sounds like the simple answer is no, according to Apple's docs.  A simple workaround, however, might be to move the buttons out of the visible area by, say, shifting their bounds right by 10,000 or so.  If they are in a scrollview/clipview that would expand to show the items in their new position, then this would not work so well, but if they aren't, it ought to work fine.  If they are in a scrollview, then you might find a way to make them completely transparent, to achieve a similar effect.
That said, perhaps it is worth considering whether you have the right design in the first place, since having buttons that are not visible respond to key events is a questionable design from a user-interface perspective (as reflected by the fact that Apple tries to prevent it).  Maybe those keyboard events should really be getting handled by a view higher in the view hierarchy, or by the window, or some such entity?


text:
Q: Is there no proof of Dirichlet's results on quadratic residues without analysis? Wikipedia states that all known proofs of Dirichlet's results
$$
L(1) = -\frac{\pi}{\sqrt q}\sum_{n=1}^{q-1} \frac{n}{q} \left(\frac{n}{q}\right) \gt 0
$$
and
$$
L(1) = \frac{\pi}{\left(2-\left(\frac{2}{q}\right)\right)\!\sqrt q}\sum_{n=1}^\frac{q-1}{2}\left(\frac{n}{q}\right) \gt 0\;,
$$
both valid for primes $q\equiv3\bmod4$, rely on analysis and that no "simple or direct" proof has ever been published. It cites the third edition of Davenport's Multiplicative Number Theory from $2000$, but the second edition from $1980$ that's available online (at archive.org and at Google Books) only contains the "simple and direct" claim and doesn't mention analysis (though it gives Dirichlet's proof, which uses a moderate amount of analysis).
Since these inequalities correspond to the rather basic number-theoretic facts that for primes $q\equiv3\bmod4$ the sum of the quadratic residues in $[1,q-1]$ is less than the sum of the non-residues and there are more quadratic residues than non-residues in $[1,(q-1)/2]$, respectively, I found this rather surprising and am wondering whether this claim is correct and up to date.
At Evaluate a character sum $\sum\limits_{r = 1}^{(p - 1)/2}r \left( \frac{r}{p} \right) = 0$ for a prime $p \equiv 7 \pmod 8$, David Speyer gives an elementary proof of the equation in the title, i.e. of the fact that the sums of the quadratic residues and non-residues in $[1,(q-1)/2]$ are equal for $q\equiv7\bmod8$. His proof also yields an elementary proof of the equality of Dirichlet's two expressions for that case (which means an elementary proof of either inequality would also yield a proof of the other for that case), but I don't see how to turn it into a proof of their positivity, even for that case. But the elementary character of his proof of a directly related result adds to my feeling that one shouldn't need analysis to prove the other results.
I also found this comment by Terry Tao on MO from 2011 saying that "a proof that $L(1,\chi)\ne0$ [...] seems to require some nontrivial machinery at some point" (where $\chi$ is a quadratic character), linking to On elementary proofs of the Prime Number Theorem for arithmetic progressions, without characters by Andrew Granville and apparently referring to the remark at the bottom of the second page.
So is it true that there is no proof of these inequalities that doesn't use analysis? Are there new developments in this regard? Or could you provide some insight to someone with a limited number-theoretical background why one might expect these proofs to require analysis?

A: By Kronecker's formula, the value at $s=1$ of $L(s,\chi)$ functions associated with quadratic characters depends on a class number, so there actually is an algebraic counterpart dealing with reduced binary quadratic forms. The basic problem is to find the sign of a Gauss sum, where $G(\chi)^2 = p$ is almost trivial. However, I am not so sure that "the algebraic way" is actually more elementary than the analytic one, and that is probably the meaning of Granville's remark.


text:
Q: Pasting Html text in Edittext How to restrict HTML content while pasting some text from a website to our EditText?.
Example I copy some text from a website, when I paste the text in my EditText the HTML font and text size also comes along. What i want is to restrict any HTML content while I paste the text. Tried several methods using TextWatcher and InputFilters, but none of them are working. Whatsapp is handling it somehow. Please help.
Edit: The string can be converted to non-HTML but how to make changes in EditText?

A: This is likely a Rich Text Formatting issue.
According to this question you can add a TextWatcher to your EditText and use this method:
public void afterTextChanged(Editable string)
{
    CharacterStyle[] toBeRemovedSpans = string.getSpans(0, string.length(),
                                                MetricAffectingSpan.class);
    for (int index = 0; index < toBeRemovedSpans; index++)
        string.removeSpan(toBeRemovedSpans[index]);
    }
}

Reference:
https://stackoverflow.com/a/24777290/5457878


text:
Q: I installed Python for all users (Windows 10) but it still created a user installation I'm not sure I understand what's going on here, since I create a virtual environment and it seems to be using the "all users" installation, but whenever I update pip, it does so in a user-specific folder?
I've just installed the latest Python version (using the Windows installer from python.org). I carefully selected the custom installation option and selected to add Python to environment variables and "install for all users", so I saw how the default user folder changed to C:\Program Files\Python39, as seen here:

Then I tried to update pip (from version 21.1.1 to 21.1.2) so I ran python -m pip install --upgrade pip and got this message:

Defaulting to user installation because normal site-packages is not
writeable Requirement already satisfied: pip in c:\program
files\python39\lib\site-packages (21.1.1) Collecting pip   Using
cached pip-21.1.2-py3-none-any.whl (1.5 MB) Installing collected
packages: pip   WARNING: The scripts pip.exe, pip3.9.exe and pip3.exe
are installed in
'C:\Users\Currentuser\AppData\Roaming\Python\Python39\Scripts' which is
not on PATH.   Consider adding this directory to PATH or, if you
prefer to suppress this warning, use --no-warn-script-location.
Successfully installed pip-21.1.2 WARNING: You are using pip version
21.1.1; however, version 21.1.2 is available. You should consider upgrading via the 'C:\Program Files\Python39\python.exe -m pip install
--upgrade pip' command.

So what's with this C:\Users\Currentuser\AppData\Roaming\Python\Python39 folder?
If I run pip --version` I get:

pip 21.1.2 from
C:\Users\Currentuser\AppData\Roaming\Python\Python39\site-packages\pip
(python 3.9)

So it looks like it has created a user-only installation in C:\Users\Currentuser\AppData\Roaming\Python\Python39?
The problem is that now I have 2 versions, and venv uses the old one. I created a C:\Users\Currentuser\Desktop\test folder and then created a virtual environment within it. In this environment, pip list shows me it uses the old pip version:
Package    Version
---------- -------
pip        21.1.1
setuptools 56.0.0
WARNING: You are using pip version 21.1.1; however, version 21.1.2 is available.
You should consider upgrading via the 'c:\users\currentuser\desktop\test\my-venv\scripts\python.exe -m pip install --upgrade pip' command.

So how do I prevent Python from using this C:\Users\Currentuser\AppData\Roaming\Python\Python39 folder and force it to use the C:\Program Files\Python39\ I installed to?


text:
Q: Jquery Dropdown select update input field on cloned forms So i have a form that I'm dynamically cloning with Jquery .clone. So when a user selects a choice in the drop down menu depending on what the value is, it will update a text box with a value automatically while still allowing the user to change they value if they don't agree with whats there. The code that i have updates the fields but it is updating all input fields with the id i specify i have tried referencing the parent item then looking for the next input box with an id. I'm not sure if maybe I'm processing this wrong in my head. Any help would be appreciated.
My form code:

                File Type:
               <select id="book_type")
                   <option value="1">1</option>
                   <option value="2">2</option>
                   <option value="3">3</option>
              </select>

              Book ID<input type="text" id="book_id" name="book_id" />

                Tray Number: <input type="text" name="tray_number" required id="tray_number" class="tray_nu" placeholder="Required" value="" />

                Comments: <input type="text" name="comments" id="comments" value="" />
                <input type="button" id="delBttn" name="delBttn" disabled value="X" />

<input type="button" id="addbutton" value="Add Another Book" />

My Copy Code (Which works great) and my change code(this is not working properly)
$(document).ready(function () {
    $("#addbutton").click(function(){
        var clone = $("#test").clone(true).insertBefore("#new_section:last");
        clone.find('[id*="delBttn"]').attr('disabled', false);
        clone.find('[id*="book_type"]').val('');
        clone.find('[id*="comments"]').val('');
    });

$("#delBttn").click(function(e) {
    $(this).closest("span").remove();
    e.preventDefault();
});
$("#book_type").change(function(){
    var book_type =  $(this).val();
    if(book_type === '2'){
        $('span').parent().find("#tray_number").val('2');
    }
});

}); //end of DOM

So now when you click on the dropdown box and change it to option 2, its filling all boxes with the value of option 2. I'm trying to get it to only change the value of tray number in the same row as the drop down box.

A: You are selecting all spans on the page in your change handler. To just get the span that is parent of the changed dropdown, you can use $(this) to get the changed <select> element and use .closest('span') to traverse up the DOM tree and select the first span that is a parent of that select.
$("#f_types").change(function(){
    var book_type =  $(this).val();
    if(book_type === '2'){
        $(this).closest('span').find("#tray_number").val('2');
    }
});

A: There are quite a few issues with your HTML and JavaScript, which I've fixed in the example below.  The biggest issue was the fact that you will end up with duplicate IDs, and you cannot have more than one element with the same ID.
After changing the IDs for classes, use this code to find the closest parent with class 'test', then find the child with class 'tray_nu' and set its value.
$(this).closest('span').find(".tray_nu").val('2');

Full Example:
HTML:

    File Type:
        <select class="book_type">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>

    Book ID
        <input type="text" class="book_id" name="book_id" />

    Tray Number:
        <input type="text" name="tray_number" required class="tray_nu" placeholder="Required" value="" />

    Comments:
        <input type="text" name="comments" class="comments" value="" />
        <input type="button" class="delBttn" name="delBttn" disabled value="X" />

<input type="button" id="addbutton" value="Add Another Book" />

JavaScript:
$(document).ready(function () {
    $("#addbutton").click(function () {
        var clone = $(".test").clone(true).insertBefore("#new_section:last");
        clone.attr('class', 'testnew');
        clone.find('[class*="delBttn"]').attr('disabled', false);
        clone.find('[class*="book_type"]').val('');
        clone.find('[class*="comments"]').val('');
    });

    $(".delBttn").click(function (e) {
        $(this).closest("span").remove();
        e.preventDefault();
    });
    $(".book_type").change(function () {
        var book_type = $(this).val();
        if (book_type === '2') {
            $(this).closest('span').find(".tray_nu").val('2');
        }
    });

}); //end of DOM

Demo:  http://jsfiddle.net/BenjaminRay/mv9y6xrL/


text:
Q: Caching objects but ignoring NULL properties to save space in .NET I have a strongly typed list of objects I want to cache, that will have a lots of properties that are null.  I would like to ignore those when caching these to save space.  Is there something I can specifically do to save space on caching properties with null values?
HttpRuntime.Cache.Insert(key,
   data.Data,
   null,
   DateTime.Now.AddMinutes(data.Minutes ?? minutes),
   TimeSpan.Zero,
   System.Web.Caching.CacheItemPriority.Default,
   null);


text: Q: dompdf Blank Page On Large Content I am using dompdf to print email summaries, these emails are printed sequentially once I have a large email that doesn't fit in the remaining of the page, a new page is created and the content is printed there. resulting the first page to partially or fully blank I can't find a solution for that.


text:
Q: If cell text equals cell highlight background
I am trying to highlight the background of the off days, for each cell I am creating a separate custom formula rule containing:
=IF(TEXT(F6,"dddd")=H4)

just to test it out, but I am unable to get any results.
What am I missing?

A: Assuming G4 and H4 are text (formula would be simpler if a full date formatted as dddd) and that you want both off day columns formatted, please clear any existing CF from C8:I16, select C8:I16 and HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::
=OR(LEFT(TEXT(C$7,"ddd"),2)=LEFT($G$4,2),LEFT(TEXT(C$7,"ddd"),2)=LEFT($H$4,2))

Format..., select choice of formatting, OK, OK.
Note this will override formatting in Rows12:14 which will have to be reset even if applied with CF unless Applies to range for above is changed to:
=$C$8:$I$11,$C$15:$I$16

and existing CF formatting is not cleared first.
OR
LEFT
TEXT


text:
Q: Deleting same number of records from SQL Server database takes either 0.2 sec or 30 sec I am using SQL Server 2008 R2. I am deleting ~5000 records from a table.  While I was testing performance with the same data I have found that the deletion either takes 1 sec or 31 sec.
The test database is confidential so can not share it here.
I have already tried to separate the load and only delete 1000 record at a time but I still experience the deviation.
How should I continue my investigation? What could be the reason for the performance difference?
The query is simple, something like: delete from PART where INVOICE_ID = 64225

A: DELETE clause uses a lot of system and transaction log resources and thats why it can take a lot of time. If possible try to TRUNCATE the table instead.

A: When you run the DELETE for the first time perhaps the data wasn't in the buffer pool so had to be read off storage, the second time you run it will be in storage. Other factors will include if the checkpoint process is running your changed pages off to storage. Post your query plan ->
set statistics xml on

select * from sys.objects

set statistics xml off

A: Argh! After having a closer look at the execution plan I have noticed that one index was missing. After adding the index all executions are running fast. Note that after this I have removed the index to test if the problem comes back. The performance deviations re appeared.


text:
Q: Polar coordinates for improper integrals One way to prove that the area under the graph of the Gaussian function $e^{-x^2}$ is $\sqrt{\pi}$ is to compute the quantity $\int_{-\infty}^\infty \int_{-\infty}^\infty e^{-x^2-y^2}$ using a change to polar coordinates. However, this proof uses the fact that
$$\int_{-\infty}^\infty \int_{-\infty}^\infty f(x,y) \thinspace dy \thinspace dx
= \int_0^{2\pi} \int_0^\infty f(r\cos\theta, r\sin\theta)r \thinspace dr \thinspace d\theta.$$
The only calculus text I own is Stewart's Calculus, which does not go into improper integrals in polar coordinates. Where can I find a proper statement and proof of this fact?


text:
Q: How to show an activity without showing parent activity? I have an SMSReceiver class, which extends BroadcastReceiver. Once SMS is received, I create notification. When it is clicked, I start my own (not main!) activity - DialogActivity:
Intent mIntent = new Intent(context, DialogActivity.class);
...
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent mPendingIntent =
    PendingIntent.getActivity(
    context,
    mNotificationId,
    mIntent,
    0
);
mBuilder.setContentIntent(mPendingIntent);

However, it is always shown on top of the main activity. So, if I call finish from the DialogActivity, then the main activity is shown. How could I avoid that?
DialogActivity class looks like below:
public class DialogActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog); // android:theme="@android:style/Theme.Dialog"

        Button dialogBtnNo = (Button) findViewById(R.id.dialog_btn_no);

        dialogBtnNo.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                finish(); // close this activity
            }
    ...

and manifest file:
   <activity
        android:name="my.package.DialogActivity"
        android:label="@string/title_activity_dialog"
        android:theme="@android:style/Theme.Dialog"
        android:configChanges="keyboardHidden|orientation">
    </activity>

A: Use the FLAG_ACTIVITY_CLEAR_TASK to clear the current task before starting the new activity.
The problem with FLAG_ACTIVITY_NEW_TASK- from the docs:

When using this flag, if a task is already running for the activity
  you are now starting, then a new activity will not be started;
  instead, the current task will simply be brought to the front of the
  screen with the state it was last in.

This flag is available in api 11 or later and in the v4 support library.

A: Use android:launchMode="singleInstance" in DialogActivity tag of AndroidManifest.xml. It will be correctly works.


text:
Q: What is required for realtime messaging system? I want to create a realtime messaging system in Web. Which programming languages and styling languages are required for this project?
Thanks for your answers, have a nice day..

A: Basically, you need

*

*Html

*Javascript

*CSS


text:
Q: AXI4 throughput on FPGA I'm working on a 7 series FPGA, and am planning to use MIG memory controller for interface with DDR3, and an AXI4 interface between memory controller and the other modules inside the FPGA. What sort of throughput efficiency will I get, say if I run it at some X clock and 64-bit data. What I mean is 64X is illogical to assume. What fraction of it is lost in handshaking for burst mode and a non-burst mode? I'm just looking for rough values, not exact. Something in the ballpark.
Thank you.

A: Per Xilinx's xapp792 70% efficiency is a reasonable number. This is for video which generally has very burstable DDR SDRAM friendly access patterns.  Random memory access will probably be far less.


text:
Q: MySql reclaim blob space with InnoDB I need to build a table that will contain a large BLOB that will take up 98% of the row size.  However, this BLOB will only be kept temporarily in the row and will be moved to another location and then the BLOB column will be set to NULL.  Can MySQL reuse this space or will it always be part of the row?  If it can not be automatically re-used, is there another way (say an optimize table) that I can use to manually reclaim this space?  If not, I may need to find another solution for handling this particular set of data.

A: Sounds like you will definitely be better off using Redis or even just storing your blob on the file system. This is in fact what I recommend; save the data on a file and place the filename on the table. After async upload to s3 has completed set it to null. If you are using a file system optimized to handle large objects, this will always be faster than an insert into a database.
How exactly blobs are stored depends not just on the length of the data but also on the version of mysql that you are actually using. Deleted rows can always be reused and when subsequent inserts don't reuse the space, it can be recovered with optimize table. But optimize table will take a lock on that table. So you are slowing down the system a second time.


text:
Q: Best way to set default value for javabean I has a javabean like this:
public class Foo {
    private String bar;

    ...getter/setter...

}

Then I want to set value like this:
if (foo.getBar() == null) {
    foo.setBar("def");
}

Is there a simpler way to do it?
For example:
callIfNull(foo.getBar(), foo.setBar("def");

A: Just declare it as
private String bar = "def";

If someone calls the setter, it will get overwritten, otherwise this will be the default value.

A: You have a default constructor in Java, and I always recommend using it. It is valuable to define a default value for all fields as something non-null. By defining your default constructors, you are declaring that the instance of a bean will be initialized in default way, with non-null features.
public class Bean {
  private int foo;
  private String bar;

  public Bean() {
    this(0, "");
  }

  public Bean(int foo, String bar) {
    this.foo = foo;
    this.bar = bar;
  }
...
// + getters and setters


text:
Q: Merge routes in servicestack I have a Dto like this:
[Route("/clients/", HttpMethods.Post)]
[Route("/clients/{Dummy}", HttpMethods.Post)]
public class ClientPostDto : IReturnVoid
{
    public string Dummy { get; set; }
}

And the post method in my service:
public class ClientService : Service
{
    public void Post(ClientPostDto request)
    {
        // do some stuff
    }
}

Is it possible to merge these two routings?
So the following two POST request are handled by the same Method in my Service:
localhost:12345/clients/
localhost:12345/clients/CLIENT_IDENTIFIER

I won't need the Dummy property at all, because the clients are stored in a list with the full path.

A: You can use the magic {ignore} literal instead, i.e. if you want to specify a wildcard without needing to specify an existing property, e.g:
[Route("/clients/{ignore}", "POST")]
public class ClientPostDto : IReturnVoid {}

A: That should just work.  But you should keep the dummy variable so you know what has been requested perhaps retitled to ClientIdentifier.


text:
Q: tabla sql con espacio en el nombre y los campos Tengo la siguiente situación, me pidieron hacer un proyecto con una base de datos SQL ya creada pero me encuentro que los nombres de las tablas y los campos de las tablas están escritos con espacios y cuando trato de ejecutar mi consulta me envía un error de sintaxis. Esta base datos se encuentra funcionando con una aplicación hecha en Visual Basic y yo estoy haciendo una aplicación web con php. A continuación le dejo mi código:
Select Customer.AR Cust Password, Customer.AR Cust User Name FROM AR Customer AS Customer

Error:

19:04:05 Kernel error: [FreeTDS][MSSQL Server] , Server EC2AMAZ-977S99A\APPBSC, Line 1
  Incorrect syntax near 'Password'.

A: En SQL Server los delimitadores para los identificadores que se pueden utilizar son:

*

*Comillas Dobles

*Corchetes

Delimitadores
Drop table if exists "mi tabla";
Create table "mi tabla" (id int);
go
Drop table if exists [mi tabla];
Create table [mi tabla] (id int);
go

Si bien aunque ambos son igual de válidos, las comillas dobles en determinadas ocasiones pueden ser no válidas.
SET QUOTED_IDENTIFIER OFF
Drop table if exists "mi tabla";
Create table "mi tabla" (id int);

Mens. 102, Nivel 15, Estado 1, Línea 8 Sintaxis incorrecta cerca de
  'mi tabla'.

GO
-- Opción válida
SET QUOTED_IDENTIFIER OFF
Drop table if exists [mi tabla];
Create table [mi tabla] (id int);
GO

Los comandos se han completado correctamente.

Set Quoted_Identifier

A: el interpretador de sql no distingue los campos y las columnas y que tiene espacios.. cuando llames estos debe ir sobre corchetes
select [Id],[Doc Number],[Internal Doc Number]
from [TABLEA Con Espacio];

si los llamas asi:
select Id,Doc Number,Internal Doc Number from TABLEA Con Espacio

si necesitas renombra la columna para parsearla en un objeto lo puedes hacer asi
select [Id],[Doc Number] as Doc_Number
from [TABLEA Con Espacio];

el motor no sabe hasta donde estan columnas y las tablas
Aqui puedes ver un ejemplo
en las ultima linea esta una consulta con error (sin corchetes)
espero que te sirva la informacion

A: solo usa los backticks `nombre de tabla` Alt Gr + {   ó   }  para obtenerlos


text:
Q: Three AA batteries in series, only 1 depleted? I am powering an ESP8266 with 3 rechargeable AA batteries. The ESP logs the voltage, so I saw the voltage getting lower over time. Much earlier than expected, the ESP stopped working since the voltage got too low. I measured the batteries afterwards and I noticed one of them had a really low voltage while the other two were fine (1.2v). What would cause only one cell to get depleted faster than the others? And how can that situation be avoided in the future?
Thanks!

A: Simply put, one of your batteries is bad.  Or at least less good than the others.  In series, the current is the same through all cells.  So it is impossible for one cell to be drained faster than the others.  They are drained at exactly the same rate.  The problem is that one of the cells has less capacity than the others, so its voltage drops earlier.
Putting cells of any kind (rechargeable or primary) in series demands that the cells be well matched or have some sort of balancing circuitry integrated into the pack.
Basically, if you want to use multiple rechargeable AAs in series, they need to be the same brand, the same age, from the same pack, and should live and die together.  Charged together in series, depleted together in series, everything that happens to one cell happens to all the cells.
And even then, sometimes you'll just have a bad cell.
In this case, let's consider the current running through the cells in series.
It will always be the same current through all three cells.  If one is significantly lower voltage, that means that the effective capacity of that cell is less than the others.  And, in this application, for all intents and purposes, the capacity of the batteries is going to be the capacity of the weakest link in the chain, as the voltage drops too far otherwise.
How is it that one of the cells is delivering a lower capacity than the other two?  It could be any number of reasons.  Perhaps one is older, or has been used more.  Perhaps it is just a bad cell.  This can happen even when the batteries are new and all from the same pack.  It's not common, but it's also not exactly rare.
It is absolutely vital that you use well-matched cells when in a series application like this.  Fortunately, I don't think the ESP8266 can drain the cells enough to cause a reversal of a bad cell, but it is something to think about:
Let's say you are discharging 4 cells in series, and one of them has lost some of its capacity, for whatever reason.  The current will be the same through all the cells at all times.  But, your device is able to run off the voltage produced even by just 3 cells working and 1 cell totally dead.
What happens?
Well, the bad cell is going to be discharged below the minimum voltage it should be, further and further, all the way down to 0V.  If you measured the cells, there would be 0V across this cell.  However, since your device can keep running even with a dead cell, it continues drawing current.  At this point, current is actually going to be forced through the dead cell, but in the wrong direction (discharging).  This is cell reversal.  In low discharge rate applications, it usually damages or destroys the cell prematurely.  In high discharge rate applications, it can cause the bad cell to vent (explode).
Just be wary about batteries in series - you can't just mix and match rechargeable AAs in series, if that's what you're doing.

A: All cells in a good module are matched to within 1% of each other, and any difference in the initial matching amplifies towards the module end of life... you may have had only a 5% cell-match at module-creation which then caused an earlier end of life for the cell that failed.
The product of Ic=C*dV/dt implies that the smallest charge or the weakest cell dies first from overvoltage or undervoltage and lack of a BMS (battery management system), which would have prevented the overvoltage or undervoltage and prolonged the life of the weak cell and therefore your module.


text:
Q: Unresolved Symbols linking w/ Boost Serialization under Ubuntu 12.10 I'll start by stating I'm feeling like a moron tonight. I'm trying to minimally reproduce a work issue I have under RHEL5.6, gcc 4.1.2, boost 1.44.0, with Boost Serialization.
The environment I'm having this issue with is Ubuntu Server (with dev packages installed), gcc 4.7.2, and a build of boost 1.44.0 (against the system compiler, packages, etc).
My code compiles cleanly, but I'm getting a myriad of undefined symbols related to various boost::archive types.  Running strace on my make, I see it picking up the expected boost_serialization library:
668 43569 stat("/usr/local/boost/1.44.0/lib/libboost_serialization.so", {st_mode=S_IFREG|0755, st_size=700481, ...}) = 0
669 43569 open("/usr/local/boost/1.44.0/lib/libboost_serialization.so", O_RDONLY) = 8

My makefile is:
default: test-app
all: test-app

BOOST := /usr/local/boost/1.44.0

CPPFLAGS := -fPIC -Wall -Wextra -Werror
INCDIRS := -isystem$(BOOST)/include
.LIBDIRS. := $(BOOST)/lib
.LIBS. :=boost_serialization
LIBS := $(foreach lib,$(.LIBS.),-l$(lib))
LIBDIRS := $(foreach dir,$(.LIBDIRS.),-L$(dir))
CPPFLAGS += $(INCDIRS)

base.o : base.cpp base.hpp
        g++ $(CPPFLAGS) --compile $< -o $@ -g

derived.o : derived.cpp base.hpp derived.hpp
        g++ $(CPPFLAGS) --compile $< -o $@ -g

main.o: main.cpp derived.hpp
        g++ $(CPPFLAGS) --compile $< -o $@ -g

test-app: main.o derived.o base.o
        g++ -o $@ $(LIBDIRS) $(LIBS) $^

clean:
        rm -f *.o test

A (very) small sample of the linker errors I'm getting are like:

base.o: In function void
  boost::archive::basic_text_oprimitive<std::ostream>::save<boost::archive::class_id_reference_type>(boost::archive::class_id_reference_type
  const&)':
  /usr/local/boost/1.44.0/include/boost/archive/basic_text_oprimitive.hpp:91:
  undefined reference to
  boost::archive::archive_exception::archive_exception(boost::archive::archive_exception::exception_code,
  char const*, char const*)'
  /usr/local/boost/1.44.0/include/boost/archive/basic_text_oprimitive.hpp:91:
  undefined reference to
  boost::archive::archive_exception::~archive_exception()'
  /usr/local/boost/1.44.0/include/boost/archive/basic_text_oprimitive.hpp:91:
  undefined reference to
  boost::archive::archive_exception::~archive_exception()' base.o: In
  function void
  boost::archive::basic_text_oprimitive<std::ostream>::save<boost::archive::tracking_type>(boost::archive::tracking_type
  const&)':
  /usr/local/boost/1.44.0/include/boost/archive/basic_text_oprimitive.hpp:91:
  undefined reference to
  boost::archive::archive_exception::archive_exception(boost::archive::archive_exception::exception_code,
  char const*, char const*)'
  /usr/local/boost/1.44.0/include/boost/archive/basic_text_oprimitive.hpp:91:
  undefined reference to
  boost::archive::archive_exception::~archive_exception()'
  /usr/local/boost/1.44.0/include/boost/archive/basic_text_oprimitive.hpp:91:
  undefined reference to
  boost::archive::archive_exception::~archive_exception()' base.o: In
  function void
  boost::archive::basic_text_oprimitive<std::ostream>::save<unsigned
  int>(unsigned int const&)':
  /usr/local/boost/1.44.0/include/boost/archive/basic_text_oprimitive.hpp:91:
  undefined reference to
  boost::archive::archive_exception::archive_exception(boost::archive::archive_exception::exception_code,
  char const*, char const*)'
  /usr/local/boost/1.44.0/include/boost/archive/basic_text_oprimitive.hpp:91:
  undefined reference to
  boost::archive::archive_exception::~archive_exception()'
  /usr/local/boost/1.44.0/include/boost/archive/basic_text_oprimitive.hpp:91:
  undefined reference to
  boost::archive::archive_exception::~archive_exception()'

Likewise, if I do a symbol dump on the referenced .so's, I see the required symbols:

objdump -t /usr/local/boost/1.44.0/lib/libboost_serialization.so |
  c++filt | grep
  "boost::archive::archive_exception::~archive_exception()"
  000000000004e670 g     F .text  0000000000000065
  boost::archive::archive_exception::~archive_exception()
  000000000004e6e0 g     F .text  0000000000000009              virtual
  thunk to boost::archive::archive_exception::~archive_exception()
  000000000004e6f0 g     F .text  0000000000000012
  boost::archive::archive_exception::~archive_exception()
  000000000004ed60 g     F .text  000000000000005c
  boost::archive::archive_exception::~archive_exception()
  000000000004e710 g     F .text  0000000000000009              virtual
  thunk to boost::archive::archive_exception::~archive_exception()

I've been banging my head against the table for a while now...hoping someone can help. I don't think the specific source matters, but if requested, I can post it.
Additional environmental details:

g++ --version g++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2 Copyright (C)
  2012 Free Software Foundation, Inc. This is free software; see the
  source for copying conditions.  There is NO warranty; not even for
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
ld --version
GNU ld (GNU Binutils for Ubuntu) 2.22.90.20120924
Copyright 2012 Free Software Foundation, Inc.
This program is free software; you may redistribute it under the terms of
the GNU General Public License version 3 or (at your option) a later version.
This program has absolutely no warranty.

Additionally, this is on a VM running under Hyper-V on Windows 8, although, I don't think that matters here.
Complete link line:
g++  -L/usr/local/boost/1.44.0/lib -lboost_serialization -o test-app main.o derived.o base.o

A: I've had the same problem, putting -lboost_serialization at the end like

g++ -L/usr/local/boost/1.44.0/lib -o test-app main.o derived.o base.o -lboost_serialization

should solve it

A: the binary object .o is not linked with libs.
first verify that in /usr/local/boost/1.44.0/lib there are file's lib
boost_serialization.
and next, that lib is registered:
    sudo ldconfig -v | grep boost_serialization
if not, create file boost1.44.0.conf in /etc/ld.so.conf.d with user root. With this ligne
    usr/local/boost/1.44.0/lib
then start this command
    sudo ldconfig -v | grep boost_serialization


text:
Q: Move other Views to the view which is hidden hello I am new to IOS and I am struggling in one functionality which I am trying to implement. I have a UIViewController in which I am showing a custom UIView on the top and the below I have a dynamic TableView. I am hiding and showing the custom UIView on some conditions but the problem is If I hide it, my table don't take a place of that view so I can see the space over there. I think I have do something with the autolayout but I am not good in autolayout so If any one can help would be great. I am attaching a demo screens here so that you can understand. What should I do to make it work so that table will take the custom UIView place when  UIView is hidden

This is the result I am getting If I hide the above portion Custom UIView

A: in order to achieve this functionality you need to do the following steps:

*

*Create height constraint for your top view and save it in @IBOutlet

@IBOutlet weak var topViewHeightConstraint : NSLayoutConstraint!

*When you are hiding your top view change also your height constraint to 0 in order that the tableview will take its place .  in order to change it to 0 you just need to change the constant value to 0

topViewHeightConstraint.constant = 0

Link for downloading a swift project that show how to do it can be found here


text:
Q: Getting invalid ELF header issue When i am trying to install the npm getting this followed issue....
module.js:485
  process.dlopen(filename, module.exports);
          ^
Error: /projects/node_modules/xml2json/node_modules/node-expat/build/Release/node_expat.node: invalid ELF header
    at Object.Module._extensions..node (module.js:485:11)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)
    at Object.<anonymous> (/projects/node_modules/xml2json/node_modules/node-expat/lib/node-expat.js:4:13)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)

any one can help how to solve this issue.
Thanks in advance.

A: My best guess: you installed it on your local machine, then tried to run it on your whichever VM. Try uninstalling it and then installing it on your vagrant locally.


text:
Q: trigger that monitors the value of an specific field I hope someone can help me with the following: I
need to know if it is possible to implement a trigger that monitors
the value of an specific field, and when it changes the value, it should update the value of another field in another table.

A: Please see the below example
IF EXISTS (SELECT name FROM sys.objects
      WHERE name = 'reminder' AND type = 'TR')
   DROP TRIGGER Person.reminder;
GO
CREATE TRIGGER reminder
ON Person.Address
AFTER UPDATE
AS
IF ( UPDATE (StateProvinceID) OR UPDATE (PostalCode) )
BEGIN
RAISERROR (50009, 16, 10)
END;
GO
-- Test the trigger.
UPDATE Person.Address
SET PostalCode = 99999
WHERE PostalCode = '12345';
GO


text:
Q: Create log instance when creating a new class in eclipse i have two impl packages (contains implementation for service/dao methods)
and i want when creating any new class in this package
the following line gets added to class by default (log instantiation):
Log log = LogFactory.getLog(getClass());

another thing is that i want when adding unimplemented method in the impl package for dao is to add the spring annotation
@Transactionl

any ideas how to accomplish those things in eclipse (i am using Eclipse Helios 3.6).

A: I don't think it's possible to have a specific template for a given package.
Some notes, though :

*

*the service layer should demarcate transactions. Not the DAO layer.

*you could inherit a base class with a protected log field, and all the subclasses would inherit it. Since you're calling initializing the log with getClass(), the actual subclass name would be used.

*Only public methods should be transactional. The other ones aren't intercepted by Spring, so their transactional annotation would be ignored anyway.

*if you want to have all the methods of a bean to be transactional, put the annotation on the class rather than each individual method.


text:
Q: A wallet for coins, using weight to display the contents value? In England common goverment produced coins are:
1p (3.56g), 2p (7.12g), 5p (3.25g), 10p (6.5g), 20p (5g), 50p (8g), £1 (9.5g) and £2 (12g)
They have different weights, but I think coins of the same type should have the same weight as each other.
Can the value of the coins be calculated from the total weight? If so then how?
For example: 16g total would presumably have to contain two 50p coins, whereas 22.5g would also contain a 10p.

A: No. A wallet containing 48 grams could be worth 8 GBP  (four two-pound coins) or 3 GBP (six times 50p). What you want would be possible if the weights are either rationally independant or proportional to the value (the latter is the case with 1p and 2p, so if you know that only those coins are involved then the value can be detemrined from the weight, but not the number of coins used).
In the lack of rational independnce / in the view of measurement errors and production tolerances, the best we can get is that the weight determines the value provided it is below some limit (which, as seen above, is certainly at most 48g for British money).

A: I'm leaving 'Hagen's answer as the correct one, but now I'm thinking about this correctly, TY Hagen, I can add some more thoughts that is probably best done as an answer like this.
The problem being that any two rational numbers will share multiples.
So weights like 5g, 1/3g or 1.234g won't work in all situations, unless as Hagen states weights are proportional to value.
20p (1g), 50p (Πg), £1 (√2g), £2 (1.1010010001...g) might work.


text:
Q: devtools::test() fails: Dependency package X not available Related questions:

*

*Dependency package "package_name" not available

*How to make devtools::test() consider package dependencies
I have two homemade packages, A and B. B depends on A for some functions and has A in its DESCRIPTION file like this:
Depends: A
I have unit tests written using testthat. Loading B normally works fine, and running the tests manually (running code as a chunk) works fine. However, trying to use automated tests with devtools::test() fails with:
>devtools::test()
Loading B
Error in (function (dep_name, dep_ver = NA, dep_compare = NA)  :
  Dependency package A not available.

I can't figure out how to begin debugging this as it runs in its own environment etc., so I can't even print anything. I suspect a .libPaths() issue, but can't confirm.
I don't know how to minimally reproduce the problem, and I cannot share the code because it is proprietary.
traceback() call:
> traceback()
6: stop("Dependency package ", dep_name, " not available.")
5: (function (dep_name, dep_ver = NA, dep_compare = NA)
   {
       if (!requireNamespace(dep_name, quietly = TRUE)) {
           stop("Dependency package ", dep_name, " not available.")
       }
       if (xor(is.na(dep_ver), is.na(dep_compare))) {
           stop("dep_ver and dep_compare must be both NA or both non-NA")
       }
       else if (!is.na(dep_ver) && !is.na(dep_compare)) {
           compare <- match.fun(dep_compare)
           if (!compare(as.numeric_version(getNamespaceVersion(dep_name)),
               as.numeric_version(dep_ver))) {
               warning("Need ", dep_name, " ", dep_compare, " ",
                   dep_ver, " but loaded version is ", getNamespaceVersion(dep_name))
           }
       }
       return(TRUE)
   })(dots[[1L]][[5L]], dots[[2L]][[5L]], dots[[3L]][[5L]])
4: mapply(check_dep_version, deps$name, deps$version, deps$compare)
3: load_depends(pkg)
2: load_all(pkg, quiet = TRUE)
1: devtools::test()

sessionInfo():
> sessionInfo()
R version 3.4.4 (2018-03-15)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Linux Mint 18.2

Matrix products: default
BLAS: /usr/lib/libblas/libblas.so.3.6.0
LAPACK: /usr/lib/lapack/liblapack.so.3.6.0

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8
 [6] LC_MESSAGES=en_US.UTF-8    LC_PAPER=en_US.UTF-8       LC_NAME=C                  LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.17                          bindr_0.1.1                           xml2_1.2.0
 [4] magrittr_1.5                          roxygen2_6.0.1                        devtools_1.13.6
 [7] tidyselect_0.2.4                      R6_2.2.2                              rlang_0.2.1
[10] stringr_1.3.1                         plyr_1.8.4                            dplyr_0.7.6
[13] tools_3.4.4                           B_1.0                                 withr_2.1.2
[16] commonmark_1.5                        digest_0.6.15                         assertthat_0.2.0
[19] tibble_1.4.2                          bindrcpp_0.2.2                        purrr_0.2.5
[22] testthat_2.0.0                        memoise_1.1.0                         glue_1.3.0
[25] stringi_1.2.3                         compiler_3.4.4                        pillar_1.2.3
[28] pkgconfig_2.0.1

A: It's possible to debug the situation using debugonce() on the devtools::test() function. This allows interactive debugging of the testing environment.
A call to installed.packages() revealed no issues, i.e. packages A and B were installed in the correct path.
Using debugonce(), I traced from devtools::test() to devtools:::load_depends() to devtools:::check_dep_version() to requireNamespace() which failed with the following error:
Loading required namespace: A
Failed with error:  'object 'mutate' not found whilst loading namespace 'A''

So apparently, some kind of hidden namespace error involving a mutate() method. Problem is that the quiet=TRUE to requireNamespace() is on, and not alterable, so the error message does not get to the user, sending them down the wrong path.
Thus the answer turned out to be similar to a previous question I had answered before, just didn't realize the connection.


text:
Q: I had a problem with Appium and couldn't fix it
''' An unknown server-side error occurred while processing the
command. Original error: Error executing adbExec. Original error:
'Command 'D:\program\android-sdk\platform-tools\adb.exe -P 5037 -s
f8cb3e08 install -g
E:\appium\resources\app\node_modules\appium\node_modules\io.appium.settings\apks\settings_apk-debug.apk'
exited with code 1'; Stderr: 'adb: failed to install
E:\appium\resources\app\node_modules\appium\node_modules\io.appium.settings\apks\settings_apk-debug.apk:
Security exception: You need the
android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission to use
the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag
java.lang.SecurityException: You need the
android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission to use
the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag at
com.android.server.pm.PackageInstallerService.createSessionInternal(PackageInstallerService.java:596)
at
com.android.server.pm.PackageInstallerService.createSession(Package';
Code: '1' '''

I've turned on administrator mode
Usb debugging is also enabled
And other environments are already configured
This is my parameter
{
  "platformName": "Android",
  "platformVersion": "7.0",
  "deviceName": "f8cb3e08",
  "appPackage": "com.tencent.qqlive",
  "appActivity": "ona.activity.SplashHomeActivity",
  "noReset": "true",
  "autoGrantPermissions": "true"
}

A: Use automation name as capability.
"automationName":"UiAutomator2"

You can use appium instead UiAutomator2 as default.


text:
Q: find the path of jdk and set JAVAHOME I've got java installed on my Ubuntu VirtualBox, and I am trying to run sunspot, but sunspot can't find java.
typing 'java' from the command line return

The program 'java' can be found in the following packages:
 * gcj-4.4-jre-headless
 * gcj-4.6-jre-headless
 * openjdk-6-jre-headless
 * gcj-4.5-jre-headless
 * openjdk-7-jre-headless

and everything I've seen says that java should be in '/usr/lib/jdk', but I don't have '/usr/lib/jdk' in my directory.
How can I:

*

*Find the install for openjdk-7-jre-headless

*sudo export home, as I've had problems in the past setting the export home, without proper access

A: You can make sure you have a java package installed using:
$ sudo dpkg -l | grep jre
$ sudo dpkg -l | grep jdk

From the error you got after typing java, I think java is not installed.
Also, you can use which java to search for the binary java in your path. To export the java, you can for example use:
$ export JAVA_HOME=/path/to/your/java/home

A: I'm not sure what you mean exactly by your questions, but...
Find the install for openjdk-7-jre-headless
You can do this by using apt-get at the command line:
apt-get install openjdk-7-jre-headless

Follow the prompts and it'll install this package and everything it needs.
sudo export home, as I've had problems in the past setting the export home, without proper access
If you execute the command sudo export home, it does nothing - and wouldn't work. export is a shell internal command, and sudo requires a binary. Even if you made that command work through shell trickery, you'd just set the variable (which should be JAVA_HOME) in a new shell then forgets it when the command is done.
You might need to run java as root, but I wouldn't do that either: fix the permissions on the files and executables, and don't run as root as this will open your system up to hackers and miscreants.


text:
Q: How to refresh the plot after adjusting radio button and slider? For a shiny app I'm working on, I'm expecting the histogram will refresh after the user adjust the slider as well as the radio button.

How could I link the radio button and the slider with the plot?

I've tried using filter() and it always ends up the plot not appearing when the radio button adjust to "yes" or "no". However, when the radio button stays at "All" the plot appears well.
Below is the server.r, I've used:
plotdata<- reactive({
    if(input$DayTrade=="All")
        {dataset %>%
         filter(dataset$INVEST<=input$INVEST[2],
               dataset$INVEST>=input$INVEST[1],
               dataset$Age<=input$Age[2],
               dataset$Age>=input$Age[1],dataset$DayTrade==dataset$DayTrade)}
    else if (input$DayTrade=="No")
        {dataset %>%
         filter(dataset$INVEST<=input$INVEST[2],
               dataset$INVEST>=input$INVEST[1],
               dataset$Age<=input$Age[2],
               dataset$Age>=input$Age[1],dataset$DayTrade=="No")}
    else
        {dataset %>%
         filter(dataset$INVEST<=input$INVEST[2],
                dataset$INVEST>=input$INVEST[1],
                dataset$Age<=input$Age[2],
                dataset$Age>=input$Age[1],dataset$DayTrade=="Yes")}

})
output$histogramplot<-renderPlot({
  datos<-plotdata()
  ggplot(datos, aes(factor(Age),fill=factor(SEX))) + geom_bar(bins=15)
})

Below is the ui.r, I've used:
tabPanel("no-Eaccount",sidebarLayout(
    sidebarPanel(

      sliderInput("INVEST","Invest Range:",min = 0,max = 5000,value = c(100,300),pre="$"),
      sliderInput("Age","Age Range:",min = 0,max = 100,value = c(20,30)),
      radioButtons("DayTrade", "Day Trade:",
                   choices = c("Yes", "No","All"),
                   selected = "All")

    ),

    mainPanel(
      div(plotOutput("histogramplot"),style="width:100%")
    )
    ))

How do I solve this problem?

A: We can use eventReactive to listen on radiobutton and slider and reacted when they changed. here an example
shinyApp(
  ui = fluidPage(
    column(4,
           radioButtons("x", "Value x", choices = c('5'=5,'7'=7,'8'=8), selected = 5),
           sliderInput("y", "Value y", value = 7,6,10)
    ),
    column(8, tableOutput("table"))
  ),
  server = function(input, output, sessio) {
    # Take an action every time button is pressed;
    # here, we just print a message to the console
    observeEvent(input$x, {
      cat("Showing", input$x, "rows\n")
    })
    # Take a reactive dependency on input$x or input$y, but
    # not on any of the stuff inside the function
    df <- eventReactive(as.numeric(input$x) | input$y, {
      data.frame(x=input$x,y=input$y)
    })
    output$table <- renderTable({
      df()
    })
  }
)


text:
Q: Can we classify a pointer as built-in datatype in data structure? BUILT-IN DATATYPES IN DATA STRUCTURES
How can we classify pointer as datatype ?
I want to ask that how a pointer can be classified as built-in datatype in data structure.


text:
Q: Error in running SQL Query in PHPmyadmin Table Schema:
Employee (empid, emp_name, age, DOB, designation, doj, basic_salary, salary_amt, medical_allowance, pension, GPFund, TA, House_allowance)
Monthly_salary (id, empid, year, month, total_salary)

Query:
UPDATE `monthly_salary`
     SET `total_salary`=`employee`.'salary_amt' -`employee`.'medical_allownces' - `employee`.'pension'
     WHERE `employee`.'empid'=`monthly_salary`.'emp_id'

I'm trying to run this Query in phpmyadmin but its not running and giving errors.
Employees empid is used as foreign key in monthly-salary table.

A: Remove the single qoutes '
Should looke like this
UPDATE `monthly_salary` salary
JOIN    `employee`      employee    ON employee.empid=salary.emp_id
SET     salary.total_salary=employee.salary_amt - employee.medical_allownces - employee.pension

I gave the tables alias names, makes it easier to read.

A: join in update is not used in your query.
UPDATE monthly_salary a
    JOIN employee b  ON  b.empid = a.emp_id
SET a.total_salary=b.salary_amt - b.medical_allownces - b.pension;


text:
Q: Upgrading Azure AKS without downtime I was looking for method to upgrade k8s version without downtime for Azure AKS and found this amazing blog post https://omichels.github.io/zerodowntime-aks.html but I got error at the start only
So currently running version of k8s in my region is no more available. When I tried to create a temporary nodepool got below error
(AgentPoolK8sVersionNotSupported) Version 1.19.6 is not supported in this region.
Please use [az aks get-versions] command to get the supported version list in this region.
For more information, please check https://aka.ms/supported-version-list

What can I do to achieve zero downtime upgrade?

A: Here is how I upgraded without downtime, for your reference.

*

*Upgrade control plane only. (Can finish it on azure portal)

*Add a new Node pool. Now the version of new node pool is higher(same with control plane). Then add a label to it, e.g.  nodePool=newNodePool.

*Patch all application to the new node pool. (By nodeSelector)
$ kubectl get deployment -n {namespace} -o name | xargs kubectl patch -p "{\"spec\":{\"template\":{\"spec\":{\"nodeSelector\":{\"nodePool\":\"newNodePool\"}}}}}" -n {namespace}

*Check the pods if are scheduled to the new node pool.
$ kubectl get pods -owide

*Delete the old node pool.


text:
Q: What is the Beta-Function used for in Calculus? For a Calculus I course we have to learn about the Beta-function which is defined by $$B(q,p) = \int_0^1x^{p-1}(x-1)^{q-1}dx$$
What is the use/application for this? We are only given it as-is without any practical explanation.


text:
Q: How do i trouble shoot a failed ajax return I have some JavaScript that  calls a function to repopulate a drop down list. There are 2 calls that populate 2 different drop down lists. The both work fine in local Dev. On the server only one works. The one Errors out. I remote debugged and the call reaches the function and the function returns the proper results. Its after it leaves the function that the error occurs. The application is asp.net mvc 3 the server is windows server 2008 iis7.
How can i narrow down what is causing the issue.
<script type="text/javascript">

function getSects(abbr) {
    $.ajax({
        url: "@Url.Action("SectionSwitch", "Assets")",
        data: { abbreviation: abbr },
        dataType: "json",
        type: "POST",
        error: function () {
            alert("An error occurred.");
        },
        success: function (data) {
            // var test = JSON.parse(data);
            //alert(test);
            var items = "";
            $.each(data, function (i, item) {
                items += "<option value=\"" + item.sectionNum + "\">" +      item.sectionname + "</option>";

            });

            $("#Asset_Section_SectionKey").html(items);
        }
    });
}

function getDivs(abbr) {
    $.ajax({
        url: "@Url.Action("DivisionSwitch", "Assets")",
        data: {abbreviation: abbr},
        dataType: "json",
        type: "POST",
        error: function() {
            alert("An error occurred.");
        },
        success: function (data2) {
           // var test = JSON.parse(data);
            //alert(test);
            var items = "";
            $.each(data2, function(i, item) {
                items += "<option value=\"" + item.DivisionKey + "\">" + item.DivisionDescription + "</option>";

            });

            $("#Asset_Section_Division_DivisionKey").html(items);
        }
    });
}

$(document).ready(function(){
    $("#Asset_Section_Division_Department_DepartmentKey").change(function () {
        var abbr = $("#Asset_Section_Division_Department_DepartmentKey").val();

        getDivs(abbr);
    });

    $("#Asset_Section_Division_DivisionKey").change(function () {
        var abbr = $("#Asset_Section_Division_DivisionKey").val();

        getSects(abbr);
    });
});
</script>

Its the function getDivs that is throwing the error. Here are the functions:
 public ActionResult DivisionSwitch(int abbreviation)
    {

        var newdivision = from f in db.Divisions
                          where f.DepartmentKey == abbreviation
                          select f;

        return Json(newdivision);

    }

    public ActionResult SectionSwitch(int abbreviation)
    {

        var newsection = (from t in db.Sections
                          where t.DivisionKey == abbreviation
                          select new sectionInfo { sectionNum = t.SectionKey, sectionname = t.SectionDesciption });

        return Json(newsection);

    }

A: Set up an error handler and see what it has to say
$( document ).ajaxError(function(event, jqxhr, settings, exception) {
    console.log(jqxhr);
    console.log(exception);
});

A: Change your error properties on your ajax methods to take 3 parameters (jqXHR, textStatus, errorThrown) and alert the errorThrown and textStatus:
error: function (jqXHR, textStatus, errorThrown) {
        alert("Error, status: " + textStatus + " error: " + errorThrown);
    },

A: The error part of your $.ajax can accept three parameters of type  jqXHR, textStatus,  errorThrown.
The first parameter is an object of type jqXHR, the other two are strings. You could use jqXHR.responseText to see the error.
$.ajax({ // Some settings
    error: function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR.responseText);
        // or
        console.log(jqXHR);
    }

According to jQuery web site, their example suggests following:
$.ajax({ // your settings

}).done(function(data, textStatus, jqXHR) {
    // Handle success
}).fail(function(jqXHR, textStatus, errorThrown) {
    // Handle error here
});

For more information have a look at jQuery.ajax() and read the Depreciation section.

A: I appreciate all the help but i decided to rewrite what was being returned similar to what the working call was returning. Apparently the server had a problem with what was being returned.
public ActionResult DivisionSwitch(int abbreviation)
{

    var newdivision = from f in db.Divisions
                      where f.DepartmentKey == abbreviation
                      select f;

    return Json(newdivision);

}

public ActionResult SectionSwitch(int abbreviation)
{

    var newsection = (from t in db.Sections
                      where t.DivisionKey == abbreviation
                      select new sectionInfo { sectionNum = t.SectionKey, sectionname = t.SectionDesciption });

    return Json(newsection);

}

I have now changed to code to this:
public ActionResult DivisionSwitch(int abbreviation)
    {

        var newdivision = (from f in db.Divisions
                          where f.DepartmentKey == abbreviation
                           select new DivisionInfo { DivisionNum = f.DivisionKey, Divisionname = f.DivisionDescription });

        return Json(newdivision);
}

I just created a new class to store  the result in and narrow it down to the two  feilds required.
     public class DivisionInfo
{
    public int DivisionNum { get; set; }
    public string Divisionname { get; set; }
}


text:
Q: Access .NET controls from another application I've enumerated window tree of Minesweeper (Windows 7 version) game with EnumThreadWindows, EnumChildWindows WinAPI functions and got the following (titles):
(Minesweeper)
\_(empty)
(GDI+ Window)
(Default IME)

It seems, this application now uses .NET GUI controls (based on GDI?), not enumeratesd with used WinAPI calls. How do I access .NET controls?
I need to read their values (or at least obtain images of individual components) and if possible emulate clicks.


text:
Q: Why can't I convert milliseconds from C# to a JavaScript Date Object? I've written a function in .net that returns a date.  I need to get that date into a Date Object in JavaScript.
According to https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date, I should be able to invoke new Date(x) where x is the number of milliseconds in my date.
Therefore, I've written the following in my ASP.net MVC 3 code:
ViewBag.x = new TimeSpan(someDate.Ticks).TotalMilliseconds;

Then, in JavaScript, I get the following code:
new Date( 63461023004794 )

The date being represented should be January 1st, 2012.
However, the date that JavaScript reads is December 31st, 3980.
What's going wrong here?

A: Your .NET code is giving you the number of milliseconds since Jan. 1st, 0001.
The JavaScript constructor takes the number of milliseconds since Jan. 1st, 1970.
The easiest thing would probably be to change your .NET code to:
ViewBag.x = (someDate - new DateTime(1970, 1, 1)).TotalMilliseconds;

A: someDate.Ticks is measured since January 1st, 0001.
Javascript dates take milliseconds since January 1st, 1970, UTC.

A: That's because the DateTime structure counts ticks since 0001-01-01, while the Date object counts milliseconds since 1970-01-01.
Take the difference from 1970-01-01 as milliseconds:
ViewBag.x = (someDate - new DateTime(1970, 1, 1)).TotalMilliseconds;

A: The Unix calender's epoch is 1970-01-01 00:00:00 UTC. Assuming your times are already UTC (not a given):
DateTime someDate   = GetSomeDate() ;
DateTime UNIX_EPOCH = new DateTime(1970,1,1) ;
Timespan ts         = someDate - UNIX_EPOCH ;

should do you. Then pass javascript, the TimeSpan's TotalMilliseconds property.

A: Rules:

C# Ticks measures since 0001-01-01.
Javascript dates take milliseconds since 1970-01-01, UTC.

Then you need subtract 2665800000 milliseconds from your C# DateTime variable (someDate):

2665800000 is a const: different between 1970-01-01 and 0001-01-01 as milliseconds

Use:
ViewBag.x = (someDate - new DateTime(2665800000)).TotalMilliseconds;


text:
Q: Python output in spreedsheet instead of .txt file Just playing with codes and trying to learn now I am stuck
Here is code
import tweepy
import time
import codecs
import re
import sys
import xlsxwriter

screenName = "abc"

dirf = '/'

consumer_key = 'wabc'
consumer_secret = 'abcs'
access_token = 'abc'
access_secret = 'abcF'

auth = tweepy.auth.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)

time1 = time.time()

g = codecs.open( screenName + '_followers.txt', 'w', 'utf-8')

l = []
if (api.verify_credentials):
    print('Login successful')
cycle = 0
users = tweepy.Cursor(api.followers, screen_name=screenName, include_entities=True, include_status=True).items()
while True:
    try:
        user = next(users)
        cycle += 1
        if cycle % 300 == 0: print(cycle)
        fine = True
    except tweepy.TweepError:
        print('sleep 3min')
        time.sleep(3 * 60)
        fine = False
    except StopIteration:
        break
    if fine:
        g.write('screen_name: ' + str(user.screen_name) + '\n')
        g.write('name: ' + str(user.name) + '\n')
        g.write('id_str: ' + str(user.id_str) + '\n')
        g.write('profile_image_url: ' + str(user.profile_image_url_https) + '\n')
        try:
            expanded_url = str(dict(user.entities.get('url', {}).get('urls', [])[0]).get('expanded_url', []))
        except:
            expanded_url = ''
        g.write('url: ' + expanded_url + '\n')
        desc = str(user.description)
        desc = desc.replace('\n', ' ').replace('\r', ' ').replace('\t', '    ')
        g.write('description: ' + desc + '\n')
        g.write('location: ' + str(user.location) + '\n')
        g.write('protected: ' + str(user.protected) + '\n')
        g.write('statuses_count: ' + str(user.statuses_count) + '\n')
        g.write('friends_count: ' + str(user.friends_count) + '\n')
        g.write('followers_count: ' + str(user.followers_count) + '\n')
        g.write('listed_count: ' + str(user.listed_count) + '\n')
        try:
            acd = str(user._json.get('created_at', []))
        except:
            acd = ''
        g.write('acc_creation_date: ' + str(acd) + '\n')
        try:
            last_tweet = str(user.status._json.get('text', []))
            last_tweet_cd = str(user.status._json.get('created_at', []))
            last_tweet = last_tweet.replace('\n', ' ').replace('\r', ' ').replace('\t', '    ')
        except:
            last_tweet = ''
            last_tweet_cd = ''
        g.write('last_tweet: ' + last_tweet_cd + ' ' + last_tweet + '\n')
        g.write('*' * 50 + '\n')

g.close()
time2 = time.time()
difftimeinmin = (time2 - time1) / 60.
print("%.2f minutes" % difftimeinmin)
print('Done.')

I am getting a text file in output which looks like this
screen_name: Happy5725
name: Happy
id_str: 901793150074621953
profile_image_url:e_images/default_profile_normal.png
url:
description:
location:
protected: False
statuses_count: 0
friends_count: 150
followers_count: 3
listed_count: 0
acc_creation_date: Sun Aug 27 13:06:56 +0000 2017
last_tweet:
**************************************************
screen_name: siachitoba
name: Innocent Siachitoba
id_str: 4529375896
profile_image_url: profile_images/888394481170558977/1KmZsi6d_normal.jpg
url:
description:
location: Lusaka, Zambia
protected: False
statuses_count: 17
friends_count: 374
followers_count: 16
listed_count: 0
acc_creation_date: Fri Dec 18 23:00:56 +0000 2015
last_tweet: Tue Aug 29 15:52:08 +0000 2017 My family-Petronella,Mutinta,Mum,Innocent and Chilala. #Godloves /mmjMnkYhfQ
**************************************************
screen_name: eduooko
name: Edwin Ooko
id_str: 626409078
profile_image_url:
url:
description:
location:
protected: False
statuses_count: 16
friends_count: 75
followers_count: 5
listed_count: 0
acc_creation_date: Wed Jul 04 09:49:29 +0000 2012
last_tweet: Mon Aug 14 13:20:06 +0000 2017 @michaelggitonga hii ndio huitwa kutubeba ujinga
**************************************************

I want to get my output in a Microsoft spreedsheet.
I tried something like
workbook = xlsxwriter.Workbook(screenName + '_followers.xlsx', 'w', 'utf-8')
worksheet = workbook.add_worksheet()

but I wasn't able to arrange my data in rows and columns. I want my columns should be look like
###id    screen name    name     location    description
..     ..             ..        ..            ..
..     ..             ..        ..            ..

in Microsoft Excel
i hope someone will help me out
thank you in advance

A:
Question: I wasn't able to arrange my data in rows and columns

Do the following:
currentRow = 0
while True
    ...

    if fine:
        # Define a Empty List for every Row of Data
        data = []

        # Append each Column Data to the List
        data.append(user.screen_name)
        data.append(user.name)
        data.append(user.id_str)
        data.append(user.profile_image_url_https)
        ... and so on

        # Write all Data to current Row Starting at Column A
        worksheet.write_row(currentRow, 0, data)
        currentRow += 1

A: I agree with the comment above that using the csv module may be the way to go, as it is easily opened in Excel, and there appears to be no obvious reason for an actual excel file?
If you really want to use an Excel file format, look at the question here:


text:
Q: How to get responses in the same order as the original list using parallelStream I have an original list and i am using parallel processing on that list(calling a method).
What is want is to store the response of that method to a new list in the same order as the original list.
public List<XYZResponse> process(List<String> inputs) {
        List<XYZResponse> myResponse = new ArrayList<>();
        inputs.parallelStream().forEach(input -> {
            myResponse.add(processStringInput(input));
        });
    }
    return myResponse;
}

private XYZResponse processStringInput(String input) {
    return new XYZResponse.Builder().resp(input).build();
}

Here i want my List to be in the same order as the inputs Array.
Have tried a few other answers from stack overflow, but with no luck.
Any help is appreciated.

A: The reason it can come out of order is because forEach is an unordered stream terminal operation. From the docs:

For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.

Given that, you can choose to use something like the forEachOrdered alternative or map and collect to preserve the order. Here's the map and collect version:
inputs.parallelStream()
    .map(input -> processStringInput(input))
    .collect(Collectors.toList());

There are more details about the difference between ordered vs unordered and sequential vs parallel streams in this answer: How to ensure order of processing in java8 streams?.


text:
Q: Feynman's attempt at QFT theory of graviton as spin-2 particle Feynman has tried to describe gravitation in term of spin-2 quantum field theory. A quite detailed account is given of this attempt in his "Lectures on Gravitation". However, my grasp of QFT is not enough to see where the theory fails to be satisfactory. To this day, the interpretation of graviton as a spin-2 particle is still something very speculative, and I wanted to know why, at least from a theoretical point of view. Any reference to specific published papers is welcome.

A: The problem lies in the fact that we define QFT perturbatively, and in doing so we meet divergences (as in almost any Feynmann diagram with loops). So, we need to remove divergences, and this process is called renormalization.
Without getting too much in the technicalities (if you need any clarification, I'll be glad to edit the answer), in order to renormalize the theory one must modify the action of the theory. This happens by redefining the coupling constants or adding other interaction terms between fields in the action, with new coupling constants to be found by experiment. In principle you could need to add infinite new terms, and infinite coupling constants: such a theory requires infinite measurements before giving predictions, so it is non predictive. For some theories, at low energy many coupling terms give a neglectable effect, so the theory can be used as an effective theory, but at high energies it gives no predictions.
Not with all theories the process of renormalization goes smoothly. In the standard model the renormalization can be always carried out by redefining already existing coupling constants, and no additional constants are needed: we say that the standard model is renormalizable, and it makes sense as a perturbative QFT. Sure, maybe it is inappropriate to use in strong coupling situations (like low energy QCD) due to its perturbative nature, but at least the theory is well defined. Note that the action of the standard model only contains a spin 0 boson (the Higgs field), spin $1/2$ fermions (leptons and quarks), and gauge spin 1 bosons (the vector mediators of the forces). No spin 2 particle is present.
Inserting the graviton has terrible consequences. The graviton is a spin 2 particle, and the renormalization process does not work for those particles. If you define gravity perturbatively (by starting from the Einstein-Hilbert action and linearizing gravity), the renormalization process does not go smoothly and you find out that you need to add infinite terms in the Lagrangian. I don't know if there is an energy scale under which this theory has only a finite number of important interaction terms, but it surely cannot be used as fundamental theory (that must be valid and predictive at all energies). So we say that quantum gravity is not renormalizable.

A: Feynman's theory is expressed as a perturbation series in the strength of the gravitational coupling.  It will be qualitatively wrong in situations where gravity is strong (e.g., very high energy density), such as in the very early universe.


text:
Q: How to get host-name from DHCP server via Network Manager? I can get hostname and ip address from DHCP server with invoking the script under /etc/dhcp/dhclient-exit-hooks.d/ directory as explained here on client side .
EDITED: I assigned host-name and ip address in /etc/dhcp/dhcpd.conf on server side:
...
host slave1 {
    hardware ethernet 00:50:56:89:A5:90;
    fixed-address 192.168.1.100;
    option host-name "slave1";
}
...

But it stopped after installed network manager. I realize that network manager doesn't invoke scripts under /etc/dhcp/dhclient-exit-hooks.d/ directory. After some research, I found that I can run a script under /etc/NetworkManager/dispatcher.d/ directory as explained here. I tried it (moved file, then gave permissions) but It didnt work. Because I can not reach variables like $reason, $interface, hostname etc. under that directory. I'm stuck here. So is there a way to get hostname from dhcp server via network manager? or how to run a script under dhclient-exit-hooks.d directory on boot even if network manager runs ?

A: I searched about 8 days to find a solution but I found nothing. I developed my own method. It is not the best way but It works.
First step: Ubuntu always shows "Waiting for network configuraion..." and waits 2 minute to pass that. I changed two lines in failsafe.conf and disabled "sleep" functions to solve this problem.
* sudo nano /etc/init/failsafe.conf

...
$PLYMOUTH message –text="Waiting for network configuration…"
#sleep 40

$PLYMOUTH message –text="Waiting up to 60 more seconds for network…"
#sleep 59
...

Second step: Network fails after disable "sleep" functions. I changed rc.local to run /etc/init.d/networking restart to configure network correctly before login.
* sudo nano /etc/init/rc.local

/etc/init.d/networking restart
exit 0

I hope it will be useful for someone who faced the same problem.


text:
Q: How to navigate to specific activity/fragment after tapping on one signal push notification? can someone provide me the proper documentation or code to navigate to specific activity by tapping on one signal push notification, i want to open the specific fragment
here is my code where i extened application class and initialize one signal :

package com.example.nasapp;

import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.util.Log;

import com.example.nasapp.ui.home.HomeFragment;
import com.example.nasapp.ui.information.InformationFragment;
import com.onesignal.OSMutableNotification;
import com.onesignal.OSNotification;
import com.onesignal.OSNotificationAction;
import com.onesignal.OSNotificationOpenedResult;
import com.onesignal.OSNotificationReceivedEvent;
import com.onesignal.OneSignal;

import org.json.JSONException;
import org.json.JSONObject;

public class OneSignalApplication extends Application {
    private static final String ONESIGNAL_APP_ID = "e855e254-9b4e-4e6f-a64a-e48db6f35d07";

    @Override
    public void onCreate() {
        super.onCreate();

        // Enable verbose OneSignal logging to debug issues if needed.
        //OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);

        // OneSignal Initialization
        OneSignal.initWithContext(this);
        OneSignal.setAppId(ONESIGNAL_APP_ID);

        // promptForPushNotifications will show the native Android notification permission prompt.
        // We recommend removing the following code and instead using an In-App Message to prompt for notification permission (See step 7)
        OneSignal.promptForPushNotifications();

        OneSignal.setNotificationOpenedHandler(new OneSignal.OSNotificationOpenedHandler() {
            @Override
            public void notificationOpened(OSNotificationOpenedResult result) {
                JSONObject data = result.getNotification().getAdditionalData();
                Log.i("OneSignalExample", "Notification Data: " + data);
                String notification_topic;
                if (data != null) {
                    try {
                        System.out.println(data.getString("job_id"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    notification_topic = data.optString("notification_topic", "hii");

                    if (notification_topic != null) {
                        OneSignal.addTrigger("level", notification_topic);
                    }
                }
            }
        });

    }
}

here is my NotificationServiceExtensionClass:

public class NotificationServiceExtension extends Service implements OneSignal.OSRemoteNotificationReceivedHandler  {
    @Override
    public void remoteNotificationReceived(Context context, OSNotificationReceivedEvent notificationReceivedEvent) {
        OSNotification notification = notificationReceivedEvent.getNotification();

        // Example of modifying the notification's accent color
        OSMutableNotification mutableNotification = notification.mutableCopy();
        mutableNotification.setExtender(builder -> {
            //... do stuff
            builder.setTimeoutAfter(30000);
            Intent intent = new Intent();
            JSONObject data = notification.getAdditionalData();
            // check the data and create intent
            intent = new Intent(context, InformationFragment.class);
            // or any other depends on data value
            intent.putExtra("data", (Parcelable) data);
            PendingIntent pendIntent = PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
            builder = builder.setContentIntent(pendIntent);
            return builder;
        });
        JSONObject data = notification.getAdditionalData();
        Log.i("OneSignalExample", "Received Notification Data: " + data);
        // If complete isn't call within a time period of 25 seconds, OneSignal internal logic will show the original notification
        // To omit displaying a notification, pass `null` to complete()
        notificationReceivedEvent.complete(mutableNotification);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

In manifest i declare this service class:
    <service
        android:name=".service.NotificationServiceExtension"
        android:permission="android.permission.BIND_JOB_SERVICE"
        android:exported="false">

am i missing some code or what am i doing wrong in code ,can please someone help?


text:
Q: How to detect when all images are loaded and elements are rendered at their appropriate heights How can I check (with jquery or vanilla js) that all images on a page are loaded, and that they have been rendered at their final, full height, and that their parent elements have adjusted to that height?
I'm implementing a scrollspy function using jquery - something that determines where a user is on a page and highlights their position in a nav, updating their position as they scroll. In order for this to work properly, I need to know the offset.top of each section on the page I want to spy on. If I calculate the offset.top too early, before all images are loaded and displaying at their full height, the offset().top calculation will be incorrect. I want to avoid running the offset().top calculation too many times.
Things i've tried that don't fulfill my needs:
$(document).ready() and $(window).onload() are both too early, as images may not have been rendered at their full height, therefore making the sections not rendered at their full height.
the imagesLoaded library. same problem as above, doesn't account for rendering of images to their full height.

A: Based on my experience I think it's not trivial. window.onload may help, but it's not reliable when images are loaded dynamically. In the past I was using some kind of hack to make it workable. Basically, I was using window.setInterval and checking if image is really available by looking at property naturalWidth (see: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement).
Here is an example of implementation: https://jsfiddle.net/yu8zr20h/

A: You are solving this issue in an incorrect way. You need to compare the current Y-value of the users window to the Y-value of all the components, or at least the containers containing the different nav values.
Imagine this is your html-code:

Now you can check the height relative to the complete html page using
document.gelElementBtId('element-id').offsetTop
and the current height of the user using
scrollY
More information using this JSFiddle.

A: If you have image size metadata (e.g. Rails Active Storage provide it out of the box), you can write height to say dataset:

Then wait for it to be rendered (watch natural height):
let timer;
let image = document.getElementById("image");
function waitImage() {
    if (image.naturalHeight < image.dataset.height) {
        timer = setTimeout(function(){
            showItems();
        }, 300);
    } else {
        clearTimeout(timer);

        useYourFullyRenderedImage();
    }
}