text:
Q: Reporting information during code execution: best design I always had doubts when it comes to designing proper report of execution.
Say you have the following (stupid, to be simple) case. I will use python.
def doStuff():
    doStep1()
    doStep2()
    doStep3()

Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really debug: just informative behavior of the application.
A first, easy solution is to put prints
def doStuff():
    print "starting doing stuff"
    print "I am starting to do step 1"
    doStep1()
    print "I did step 1"
    print "I am starting to do step 2"
    doStep2()
    print "I did step 2"
    print "I am starting to do step 3"
    doStep3()
    print "I did step 3"

In general, this is quite bad. Suppose that this code is going to end up in a library. I would not expect my library to print stuff out. I would expect it to do the job silently. Still, sometimes I would like to provide information, not only in debug situations, but also to keep the user informed that something is actually in the process of being done. Print is also bad because you don't have control of the handling of your messages. it just goes to stdout, and there's nothing you can do about it, except redirection.
Another solution is to have a module for logging.
def doStuff():
    Logging.log("starting doing stuff")
    Logging.log("I am starting to do step 1")
    doStep1()
    Logging.log("I did step 1")
    Logging.log("I am starting to do step 2")
    doStep2()
    Logging.log("I did step 2")
    Logging.log("I am starting to do step 3")
    doStep3()
    Logging.log("I did step 3")

This has the advantage that you sort of know a unique place for your logging service, and you can tinker this service as much as you want. You can silence it, redirect it onto a file, to stdout, or even to a network. Disadvantage is that you get a very strong coupling with the Logging module. Basically every part of your code depends on it, and you have calls to logging everywhere.
The third option is to have a report object with a clear interface, and you pass it around
def doStuff(reporter=NullReporter()):
    reporter.log("starting doing stuff")
    reporter.log("I am starting to do step 1")
    doStep1()
    reporter.log("I did step 1")
    reporter.log("I am starting to do step 2")
    doStep2()
    reporter.log("I did step 2")
    reporter.log("I am starting to do step 3")
    doStep3()
    reporter.log("I did step 3")

Eventually, you can also pass the reporter object to doStepX() if they have more to say.
Advantage: it reduces coupling with a module, but it introduces coupling with the instantiation of the NullReporter object. This can be solved by using None as default and checking before calling log, which is clumsy, because in python you have to write a conditional every time (in C you could define a macro)
def doStuff(reporter=None):
    if reporter is not None:
        reporter.log("starting doing stuff")
        # etc...

Edit:
Another option is to work Qt-like, and have an emit() signal strategy. As your code executes, it emits information with proper status codes, and anyone interested can subscribe to the signals and provide info. Nice and clean, very decoupled, but requires a little of coding, as I don't think this can quickly be done with the python battery included.
Finally, you can raise exceptions with a meaningful error message, but this of course can be used only if you are exiting from an error condition. it does not work for occasional reporting.
Edit: I'd like to clarify the fact that the situation is more general, and not limited just to a sequence of invoked steps. it could also involve control structures:
 if disconnected:
     print "Trying to connect"
     connect()
 else:
     print "obtaining list of files from remote host"
     getRemoteList()

The report could also be into the actual routines, so you would have a "print" in the connect() and getRemoteList() routines as a first statement.
The question therefore are:

*

*What do you think is the best design for some code (notably in the case of a library) to be at the same time silent when noise could be disruptive for the client, but verbose when useful?

*How to handle a balanced intermix between logic code and reporting code ?

*Intermixing between code and error checking has been solved with exceptions. What could be done to partition the "noise" of reporting from the code logic ?

Edit: more thoughts for the mind
I think it's not only a matter of decoupling the Logging code from the logic code. I think it's also a matter of decoupling the information production from the information consumption. Similar techniques already exist, in particular to handle UI events, but I don't really see the same patterns applied to the logging problem.

Edit: I accepted the answer from Marcelo because he points out at the factual evidence that a compromise is the best solution in this case, and there's no silver bullet. However, all the others were interesting answers as well, and I was really pleased to upvote all of them. Thanks for the help!

A: I think the best solution for a library is one along the lines of adding e.g.
Log.Write(...)

where the behavior of Log is picked up from the ambient environment (e.g. app.config or an environment variable).
(I also think this is a problem that's been approached and solved many times, and while there are a few 'sweet spots' in the design space, the answer above is best IMO for the situation you describe.)
I don't see any good way to 'decouple' the 'normal' part of your code from the 'logging' part.  Logging tends to be relatively non-intrusive; I do not find the occasional Log.Write(...) to be a distraction to real-world code.

A: Another option would be to write the code without logging and then apply some transform to insert the appropriate logging statements before executing the code. The actual techniques to do this would be highly dependant on the language, but would be pretty similar to the process of writing a debugger.
It probably isn't worth the added complexity though...

A: I found this while searching for Aspect Oriented Programming for python. I agree with other posters that such concerns shouldn't be mixed with core logic.
In essence,points where you want to put logging might not always be arbitary, may be concepts like "all the points before error" could be identified by a pointcut. Other totally arbitary points can be captured using simple logging techniques.

A: I often use DTrace for this.  On OS X, python and ruby are both already set up with DTrace hooks.  On other platforms, you'd probably have to do this yourself.  But being able to attach debug traces to a running process is, well, awesome.
However, for library code (let's say you're writing an http client library), the best option is to pass in an optional logger as a parameter, as you mentioned.  DTrace is good for adding logging to something that's gone wrong in production (and sometimes elsewhere), but if other people might conceivably need access to logs to debug their code that subsequently calls into yours, then an optional logger as a parameter is absolutely the way to go.

A: There should be tooling to allow boilerplate log messages a la "entering method A with parameters (1,2,3)", "returning from method B with value X, took 10 ms" to be automatically (and selectively) generated (controlled at run or deploy time). Writing that stuff by hand is just too boring/repetitive/error-prone.
Not sure if there is, though.
If you are going to write manual log messages, be sure to include some useful contextual information (user id, URL that is being looked at, search query, or such), so that if something does go wrong you get more information than just the method name.

A: I would use the standard logging module that's been part of the standard library since Python 2.3.
That way, there is a good chance that people looking at your code will already know how the logging module works.  And if they have to learn then at least it's well-documented, and their knowledge is transferable to other libraries that also use logging.
Is there any feature that you want but can't find in the standard logging module?

A: I think the simplest solution is the best here. This depends on language, but just use a very short, globally accessible identifier - in PHP I use a custom function trace($msg) - and then just implement and re-implement that code as you see fit for the particular project or phase.
The automatic, in-compiler version of this is the standard debugger. If you want to see meaningful labels, you need to write those labels yourself, unfortunately :)
Or you could try temporarily transforming inline comments into function calls, but I'm not sure that would work.

A: In response to your edit about information production/consumption:  That's a valid concern for the general case, but logging is not the general case.  In particular, you should not be relying on logging output from one part of your program to affect the execution of another part.  That would indeed tightly couple the consumer to the implementation of the producer.
Logging should be considered incidental to your main execution.  Your systems should not know or care about the presence or contents of such log files (with the exception possibly of monitoring tools).  That being the case, the notion of decoupling "consumption" of the logs from their production is inconsequential.  Since you aren't using the logs to do anything meaningful, coupling is not an issue.

A: I think there is a point where you must draw a line and make a compromise.
I see no way to completely decouple logging from the system because you have to send those messages somewhere and in a way that someone understands.
I would go with the default logging module, because... it's the default module. It's well documented and comes with the default library, so no dependency issues here. Also, you save yourself from reinventing the wheel.
That said, if you are really into doing something new, you could make a global reporter object. You can instantiate and configure it at the beginning of your process (logging, no logging, redirecting streams, etc. Even in a per process/function/step basis) and call it from everywhere, no need to pass it around (maybe in a multi threaded environment, but that would be minimal).
You can also put it inside another thread and catch log events a la Qt.


text:
Q: How do you perform multiple queries? I am trying to perform multiple subsequent queries based upon arguments in my function.  I can't quite figure out the syntax.
let returnVideoInfo catId isFeatured

    // main query
    let vidQuery = query{
        for row in db.Movies do
        where(row.IsFeatured = isFeatured)
        select row
    }

    // I want to apply filters here based upon if arguments are null or not
    vidQuery
    |>
    (fun x ->
    if catId <> null then
        Seq.filter (fun x -> x.CategoryId = catId) x
    else
    x)

This obviously doesn't work at all, so how can I fix this?

A: I'm not sure what you mean after first pass read (could provide a dataset, format and expected return result), but would this work:
let returnVideoInfo catId (isFeatured : bool) =
    let vidQuery =
        match catId with
        | null -> ()
        | _ ->
            query{
                for row in db.Movies do
                where(row.IsFeatured = isFeatured && row.CatId = catId)
                select row
                exactlyOneOrDefault
            }
    vidQuery

or
let returnVideoInfo catId (isFeatured : bool) =
    let vidQuery =
        if catId <> null
            query{
                for row in db.Movies do
                where(row.IsFeatured = isFeatured && row.CatId = catId)
                select row
                exactlyOneOrDefault
        }
    vidQuery

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android Studio: Basic programming for a game I recently managed to develope some arcade games with the default Java GUI editor. Now I want to try to the same on android.
I can say that I´m pretty familiar with the layouts on android and some other basic stuff, but I´m struggling to find an effective method to move objects (Images) around, like you can do it in with the "timer" for the GUI.
Some say that the timer doesn´t work that well for android, so I´m trying to find an alternative way. And thats why I´m here. I tried to use object.animate(), but that didn´t worked for me at all, because the images are not moving with the same speed for the given duration.
So, is it possible to move my objects (images) in another way?
Thanks for your help!


text:
Q: Keep both pendingIntents with the same requestCode I am developing an alarm application in Android. The flow is really simple, Im just creating a PendingIntent and then I call the setExact() method in the AlarmManager much like below.
        Intent myIntent = new Intent(context, BroadcastReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
        System.currentTimeMillis() + difference, pendingIntent);

After some tests I realized that with the above snippet I can set only one alarm because I set the requestCode of the pendingIntent to zero, and if I set another alarm with the requestCode set to 0 then it will overwrite the previous one. Is there a way to fix this without changing the requestCode? I was thinking maybe the flags can help me but I didn't find a flag that doesn't overwrite the previous pendingIntent.
I know that the obvious solution is to change 0 to another int and then keep track of all my ints, picking one that is not used. That solution would be fine if I was just starting the project, however I am already in the middle and I use as request codes predefined Enums. It is very difficult to change this mechanic and keep track of individual ints thats why I am asking if there is a way of not overwriting a pendingIntent when a new one with the same requestCode is registered. Thank you in advance.

A: You can make the Intents unique be setting a different ACTION on each one. Then you could still use the same requestCode and would have different PendingIntents.
You'll need to keep track of the ACTIONs you use if you want to be able to cancel the alarms later.

A:
I am asking if there exists a certain type of flag that will be able to differentiate them

There is not, and it makes sense because this is already the purpose of the requestCode parameter.
For information, these are your options regarding flags:

You will have to change your mechanism to make it possible to have different requestCodes for Pending Intents. It may be a lot of work, but it is what you have to do.


text:
Q: how to reseed in pymssql I wish to reseed the userprofile table from python code. I have done as below
stmt =  "DBCC CHECKIDENT ('UserProfile', RESEED,52)"
cursr.execute(stmt)

But it is not getting set. I checked with
DBCC CHECKIDENT('UserProfile',NORESEED) in sql server

Any help will be appreciated


text:
Q: How do I change the background image in Phonegap? These intuitive snippets don't work at all:
<div id="box" style="background-image: url(img/heart.jpg); ">

or

<style>
#box
{
    background-image: url("img/heart.jpg");
}

How do you change the background image?


text:
Q: Test click events on router-link of vuejs using jest

  <router-link to="/" tag="li" active-class="active" exact>Home</router-link>
  <router-link to="/contact" tag="li" exact>contact</router-link>
  <router-link to="/other" tag="li" exact>other</router-link>

Test.spec.js
(i am trying to trigger the click event and check the other component is loaded or not)
await wrapper.findAll('a').at(2).trigger('click')
await wrapper.vm.$nextTick()
expect(wrapper.contains('This is other Page')).toBe(true)

but the test is failing

A: You dont need to do test about router-link, the behavior of this you dont care, becouse; the behavior that you need is only know that the  is rendered. No more.
You can do test like this
 const wrapper: any = shallowMount(YourComponent, {
    stubs: ['router-link', 'router-view']
  });

expect(wrapper.html()).toContain('to="/contact"');

Other thing that you can doing is verify that the prop "to" recived exactly the string "/contact"
For me, is enough .toContain(...)
PD: sorry for my english.


text:
Q: Why does the electronic contribution to the specific heat of a conductor not depend on the heat supplied to it? The usual explanation given for why electrons do not contribute much to the specific heat of a material (for the purposes of the question consider a conductor) is that the fermi energy of conductors is pretty large (for copper, it's 7 eV) compared to the thermal heat produced (0.026 eV) in the conductor at about 300 K, so that only electrons in the band within 0.026 eV of the fermi level can thermally participate.
I have an obvious question here - if we are actually supplying heat to such a conductor, what would happen if the energy we're supplying is large compared to the 7 eV of the Fermi level? When I think of gases, it makes sense that the specific heat should be independent of the heat supplied, but in the case of conductors (considering the electronic contribution) I think it's more like:
greater the heat supplied ---> more electrons participate thermally ---> more electrons absorb that heat and thus increase the heat capacity.
Of course, I am making a foolish mistake here, but I can't tell where exactly. Also, I don't know anything about solid state physics, since I'm only in high school.

A: Adding an amount of energy to a metal comparable to its Fermi energy would vaporise it.
In theory, you're right that at sufficiently high temperatures, electrons far from the Fermi surface can contribute to the heat capacity. But for all practical situations (i.e., where the metal remains a crystal) the usual assumption holds.
However, you are right that the heat capacity of a free electron gas is proportional to temperature.
This is a slightly more formal way of saying, I think, the same thing as you mean by "greater the heat supplied … increase the heat capacity". Actually this is easiest seen at very low temperatures, where the heat capacity from phonons (vibrations of the atomic nuclei) is small. Under these circumstances, the heat capacity goes as $C = \beta T + \gamma T^3$, where the $T$ contribution comes from the electrons and the $T^3$ from the vibrations. Thus a plot of $C/T$ against $T^2$ gives a straight line, which can be seen in experimental data.


text:
Q: How do i implement Headers Exchange in RabbitMQ using Java? i am a newbie trying to implement Headers exchange in java client . im aware that  This is what the "x-match" binding argument is for. When the "x-match" argument is set to "any", just one matching header value is sufficient. Alternatively, setting "x-match" to "all" mandates that all the values must match.
but can anyone provide me a skeleton code for better understanding.

A: For using a headers exchange you just need to declare your exchange as headers type:
channel.exchangeDeclare("myExchange", "headers", true);

Then you need to declare a queue that will be the final destination of the messages before a consumer consumes them:
channel.queueDeclare("myQueue", true, false, false, null);

Now we need to bind the exchange to queue declaring a binding. In this declaration is where you set which headers you want for routing messages from your exchange to your queue. An example could be:
Map<String, Object> bindingArgs = new HashMap<String, Object>();
bindingArgs.put("x-match", "any"); //any or all
bindingArgs.put("headerName#1", "headerValue#1");
bindingArgs.put("headerName#2", "headerValue#2");

...
channel.queueBind("myQueue", "myExchange", "", bindingArgs);
...

This will create the binding using headerName#1 and headerName#2. I hope this helps!


text:
Q: How to reload AngularJS controller and resolver? I am using Angular's UI Router and I am looking to create a $scope function (ultimately to pass to the view to have a ng-click call it) to reload a controller and its associated resolver. How would I do this?
I've tried this but it doesn't seem to reload the resolver:
$scope.reloadMe = function() {
    $state.transitionTo($state.current, $stateParams, { reload: true, inherit: false, notify: true });
};

A: just inject $route into the controller and call $route.reload so the code would look like:
$scope.reloadMe = function () {
  $route.reload();
};

You can read the documentation here: https://docs.angularjs.org/api/ngRoute/service/$route

A: You can inject $injector and load $state to reload. Here I put two examples, you can use one of them.
function MyController($injector, data) {
    $injector.get('$state').reload(); // this reload all states and controllers scopes
    // or
    $injector.get('$state').go($state.current, {}, {reload: true}); // second parameter is for $stateParams
}

Otherwise, in case i need to reload the page, i use javascript
window.location.reload()

This question is asked here


text:
Q: Twitter OAuth integration without HTTPS on my side Do I need HTTPS on my server with some SHA-2 certificate for Twitter OAuth integration?
Or may I simply send HTTPS requests to the Twitter API after receiving OAuth access token?


text:
Q: Javascript/jquery - Add a class to list at variable position I have a variable which contains an item number ... like this:
myvariable = '3'; //Note: This is currently a string so it might need converting?

Then I have the code which populates the listview:
$('#listview').live("pageinit", function(){
$.getJSON("myjson.json", function(data){
    $.each(data.unis, function(index, value){

        $('
' + value.name + '
').insertAfter('#' + value.sortLetter);

        $('#' + value.sortLetter).show();

    });

    $("#listview").listview("refresh");

});

All the above works fine.
Now, what I need to do it to insert a class into the item which is at the position myvariable value.
So, if myvariable is 3 then the listview will look like this:

' + value.name + '

' + value.name + '

' + value.name + '

if myvariable was to be 1 then:

' + value.name + '

' + value.name + '

' + value.name + '

and so on...
How could I do this?

A: You can use :eq() selector, note that :eq() is zero-based.
$('ul li:eq("'+ (myvariable-1) +'") a').addClass('class');

Or:
$('ul li').eq(myvariable-1).find('a').addClass('class');

A: One way is to build the class list dynamically for each item, optionally adding your class if the index matches the magic number that you specify in your variable. Change your code to this:
$.each(data.unis, function(index, value){
    var classList = 'listItem';
    if(index == (myvariable - 1)) {
        classList += ' addedClass';
    }
    $('
' + value.name + '
').insertAfter('#' + value.sortLetter);

    $('#' + value.sortLetter).show();
});

A: There is also an eq() method:
$('ul li').eq(myvariable - 1).find("a").addClass('class');

se http://api.jquery.com/eq-selector/ for more docs.
Note: Watch out if you are using multiple (or nested) ul on same page, then you need a different approach...


text:
Q: How to get customer session data outside Magento I want to know if it is possible to get customer session data outside of magento2
<?php
error_reporting(E_ALL | E_STRICT);
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
$app = Mage::app('default');
Mage::app();
?>

A:  require '/app/bootstrap.php';
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    /** @var \Magento\Framework\App\Http $app */
    //$app = $bootstrap->createApplication('DemoApplication');
    //$bootstrap->run($app);

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $state = $objectManager->get('Magento\Framework\App\State');
 $state->setAreaCode(\Magento\Framework\App\Area::AREA_GLOBAL);
//mysql connection
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();

$customerSession = $objectManager->get('Magento\Customer\Model\Session');

if($customerSession->isLoggedIn()) {
   echo $emial =    $customerSession->getCustomer()->getEmail();

}


text:
Q: Convert Factor Dates to Dates in R I'm very new to R. I imported some csv data containing dates which got made into factors. Trying to make them into R dates but with no success. I've tried the code below.
> class(mydata$Date)
[1] "factor"
> as.Date(mydata$Date, format = "%Y-%m-%d")

Date still shows up as factors, what can be done? Dates are originally in the format of YYYY-MM-DD, example: 2015-05-08


text:
Q: Are there linked lists in Ul++? Are there linked list in NTL or somewhere in Ultimate IDE? I guess there is not but correct me if I am wrong.

A: Just about every compiler that reasonably conforms to the C++ standard provides a standard libary implementation, which includes linked lists.
You're looking for std::list (a doubly-linked list implementation in C++), which is located in the <list> header.
Example:
#include <list>

int main()
{
    std::list<int> numbers;

    numbers.push_back(1);
    numbers.push_back(2);
    numbers.push_back(3);
    numbers.push_back(4);
    numbers.push_back(5);

    for(std::list<int>::iterator i = numbers.begin();
        i != numbers.end(); ++i)
    {
        // Do something with each element.
        // Each element can be accessed by dereferencing i.
        // For example:
        int number = *i;
    }

    return 0;
}

Nitpick: The Ultimate++ IDE is simply a graphical front-end for a C++ compiler - the IDE has no bearing on the availability of libraries.


text:
Q: What exactly is Angel's curse? It is noted in Buffy The Vampire Slayer and Angel that whenever Angel makes love to Buffy, he loses his soul and becomes Angelus the vicious vampire.
My question, is his "moment of true happiness" that making love to someone he loves e.g. Buffy can turn him into Angelus or can anything that makes him happy turn him into Angelus?
As a bonus question, is the curse defined as inflicting a soul upon him with the restriction of no moment of happiness or is it the curse of living an entire life as a demi-human knowing if he makes love he will turn into Angelus?

A:
Angel was meant to suffer. Not to live as human. One moment of true
  happiness, of contentment, one moment where the soul that we restored
  no longer plagues his thoughts, and that soul is taken from him."

Also

"Vengeance demands that his pain be eternal, as ours is. If this -
  this girl - brings him even one minute of happiness. That is one
  minute too many."
  - Enyos of the Kalderash

The ritual is intended to curse a vampire by re-ensouling him or her, thus forcing the vampire to accept massive amounts of remorse, guilt and torment for all the lives that they have taken as a soulless beast. As far as is aware, Angel is the only vampire who has been re-ensouled in this way, and it is unclear whether other soulless demons can be re-ensouled in this way.
Restoring a vampire's soul in this way is not intended as a gift. It is very much a form of revenge, or a curse since if ever there comes a time when the restored soul no longer torments the vampire, the moment the vampire is not plagued by the guilt of what they had done for the sake of evil in the past, then in that instant the soul is taken from them. Angel's soul has been lost this way twice.
Whenever the curse takes effect, it takes a few moments for the vampire to remember their actions while soulless, and when it is broken, the vampire suffers debilitating pain as his soul is ripped from his body.
While the Clan Kalderash intended the ritual as a curse, when the Scooby Gang and later Angel Investigations had the ritual used on Angel again, it was intended merely to restore Angel's soul and bring back Angel rather than Angelus. This is in contrast to the intentions of the Clan who wanted Angel to suffer because of the ritual.

A: The curse is guilt, the guilt of knowing what he's done and caring about it.  Being a monster, and having a conscience.  Basically, it's what he was before Buffy started: they wanted him to be a traumatized wretch, living in the sewers because he refuses to kill, haunted by the visions of the people he's murdered and the horrible things he's done.
The "moment of perfect happiness" thing wasn't so much a part of the curse, as a safety mechanism.  As Jenny's relative says, they gave him his soul to punish him, not reward him.  If he'd "gotten over" his guilt and become a well-adjusted guy (as he started to do under Buffy's influence), the curse would have failed to serve its purpose, because he was no longer suffering.  Thus, if he ever feels true happiness, the soul goes away.  They'd rather he returned to being a monster than started enjoying his life.
As for what exactly constitutes a "moment of true happiness," it's never specifically said.  Sex with Buffy will do it, but I seem to recall a moment of artificially-induced happiness (through taking drugs, I think?) being a danger during an episode of Angel.  Presumably, it's anything that would inspire total, unreserved joy and contentment.

A: Anything that makes Angel truly happy can cause him to lose his soul. We know this because of how Angel loses his soul in season 4 of Angel.
In order to gain more information on the season's big bad, Angel Inc. decides to ask Angelus so they hire a mystic to de-ensoul Angel. The mystic accomplishes this by creating a fantasy for Angel in which Angel and friends defeat the bad guy by working together. In the process Angel reconnects with his friends and bonds with his son. This is what brings him true happiness, not sex.
We also know that Angel can have sex without losing his soul. In season 2 of Angel, he retains his soul after his night with Darla. Again in season 5, Angel and Nina the werewolf are able to make love without any soul-lossage. Wesley explains to Angel that 99 percent of the time, sex does not result in true happiness, Angel and Buffy simply had a remarkable bond.


text:
Q: Excel MAX IF Function To Ingore Zero Date (1/0/00) =MAX(IF('[YTD -2021.xlsx]OB'!$H$2:$H$23967=$C5,IF('[YTD -2021.xlsx]OB'!$J$2:$J$23967=$B$1,'[YTD -2021.xlsx]OB'!$A$2:$A$23967)))
I want to ignore Zero date and result should give me 0 or blank instead of 0/01/1900.

A: *

*Add a new column with formula if(date=0,"",date)

*Do the max on the new column

*(optional) hide one of the columns (maybe the old one) for aesthetics

Q: Why is bothering you in the first place? 0 is only the max-date if there are no dates?
MAX(01/01/1900, 16/02/2021) = MAX(0, 16/02/2021) = 16/02/21

A: The question is actually simply asking how to have a 0 or a blank if the result of his calculation is 0. As opposed to the resulting 0 being shown as a date of 0. He is happy with his method of achieving a result, just wants a different display if it is 0.
For that, you need do nothing more than change the formatting for the result cells. Currently, it is presumably some date format. Excel allows regular number formatting to have formatting set for as many as four kinds of results for each cell:

*

*Positive values

*Negative values

*Zero values

*Text values

You place a semi-colon (;) between parts.
They are specified in that order too. So if you want positive results with no decimal places and no "thousands" separators, negative numbers with the Alt-0151 character instead of a negative sign, two decimal places, and in RED, zeros to show as a blank, and text to show in a general manner, you would use the following:
0;[Red]—0.00;;@

Naturally, date formats are fine as well. Anything, in fact, that Excel allows for number formatting. So. If you want dates (that are not zeros, but rather are meaningful dates) to show as "12/23/2024", negative numbers to display as RED and an integer so these things that are seriously wrong in your results stand out, zeros to be blanks, and text to be "whatever" (let's color text RED as well, make that error stand out too), you could use:
mm/dd/yyyy;[Red]0;;[Red]@

You only expect dates and zeros, so the other two kinds of results will stand out like a RED thumb. Any real dates in Excel are ALWAYS positive values, so the first part makes them look normal. You can get zeros, but notice the two ;; with nothing between them:  that means nothing at all will be displayed for a zero.
Supressing zeros can be done other ways, if desired, and not harmful. You can turn off the display of zeros at all, but that affects all cells, not just the ones you have this formula in. You can double the size and work of your formula by copying it all, then saying if THIS = 0, then "", else THIS... but that makes it a beast of double proportions and hard to understand later. Why do that when simply changing the formatting solves the problem, eh? A literal example of the logic using your formula would be:
=IF( MAX(IF('[YTD -2021.xlsx]OB'!$H$2:$H$23967=$C5,IF('[YTD -2021.xlsx]OB'!$J$2:$J$23967=$B$1,'[YTD -2021.xlsx]OB'!$A$2:$A$23967))) = 0, "", MAX(IF('[YTD -2021.xlsx]OB'!$H$2:$H$23967=$C5,IF('[YTD -2021.xlsx]OB'!$J$2:$J$23967=$B$1,'[YTD -2021.xlsx]OB'!$A$2:$A$23967))) )

You do that if you have to, but... you don't have to.
Also, if you would prefer a "0" (your other acceptable result) to be displayed rather than a blank cell, just put a single "0" character between those two ;;:
mm/dd/yyyy;[Red]0;0;[Red]@

By the way, there is something else you can do with this formatting functionality, but not germane to your question. However, you cannot mix this kind of formatting with that kind, so if you know about it and are using it in these cells, you will have to choose something like the doubled formula I showed above.

A: I would like to suggest few examples, ignore ZERO while calculation.
=MAX(IF($A$2:$A$15=F$1,IF($B$2:$B$15=F$2,IF($C$2:$C$15<>0,$C$2:$C$15,0))))

*

*Where this part IF($C$2:$C$15<>0 ignores ZERO, and will works with DATE value also, since basically DATE value is Numeric data, and then formatted to display as a DATE.
=MINIFS($J$2:$J$20, $I$2:$I$20, ">=1/1/2021", $I$2:$I$20, "<2/28/2021", $J$2:$J$20, "<>0")

Another is:
=SUMPRODUCT(MAX(($A$2:$A$12=F1)*($B$2:$C$15=G2)*($D$2:$D$15<>0)*($D$2:$D15)))

N.B.
- Adjust cell references in the formula as needed.


text:
Q: When uploading a image for one user to firebase storage, the link of the image updates for every user in database I'm creating this app in Android Studio using Firebase Realtime Database and Firebase Storage. When a user registers through my app the data will store in the Firebase Realtime Database. Then on the profile page, there is a place to upload a picture. When a user uploads a picture it will store in the firebase storage and the link will update in the database on a new field under the respective user.
It worked correctly the last time I checked. But when I added a new user and uploaded his profile picture, that link updates on every other user as well. But in the Firebase Storage, there were no changes. It only happens in Firebase Realtime Database. I couldn't find any solution to this.
This is the part I update the link of the profile.

      private void UploadProfPic(Uri image_uri) {

            final StorageReference strRef = storageReference.child("users/"+ email_i +"/profile.jpg");
            strRef.putFile(image_uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(getApplicationContext(), "Image has been uploaded", Toast.LENGTH_LONG).show();
                    strRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            Picasso.get().load(uri).fit().into(profPic);

                            imgRef = uri.toString();

                            usrRF.addValueEventListener(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot snapshot) {
                                    for(DataSnapshot dss : snapshot.getChildren()){
                                        String key = dss.getKey();

                                        Map<String, Object> updates = new HashMap<String, Object>();
                                        updates.put("profile_url", imgRef);
                                        usrRF.child(key).updateChildren(updates);

                                    }
                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError error) {

                                    Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
                                }
                            });

                        }
                    });
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull /*@org.jetbrains.annotations.NotNull*/ Exception e) {
                    Toast.makeText(getApplicationContext(), "Failed to update profile picture", Toast.LENGTH_LONG).show();
                }
            });
        }

here usrRf = FirebaseDatabase.getInstance().getReference("users");
Here is my database structure
Any help will be appreciated. Thank you.

A: According to your last comment:

Yes, Firebase email Authentication

Then you should consider saving user data, under the UID that comes from the authentication process and not under a pushed ID, as I see in your screenshot now. This means that you should add a User object to the database using:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
usersRef.child(uid).setValue(userObj).addOnCompleteListener(/* ... /*);

And not using:
usersRef.push().setValue(userObj).addOnCompleteListener(/* ... /*);

That beeing said, to be able to update the image that is uploaded to the node of the logged-in user, then please use the following updated method:
final StorageReference strRef = storageReference.child("users/"+ email_i +"/profile.jpg");
strRef.putFile(image_uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        Toast.makeText(getApplicationContext(), "Image has been uploaded", Toast.LENGTH_LONG).show();
        strRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                Picasso.get().load(uri).fit().into(profPic);
                imgRef = uri.toString();

                String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
                DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
                DatabaseReference usersRef = rootRef.child("users");
                Map<String, Object> updates = new HashMap<String, Object>();
                updates.put("profile_url", imgRef);
                usersRef.child(uid).updateChildren(updates).addOnSuccessListener(/* ... /*);
            }
        });
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull /*@org.jetbrains.annotations.NotNull*/ Exception e) {
        Toast.makeText(getApplicationContext(), "Failed to update profile picture", Toast.LENGTH_LONG).show();
    }
});

See, there is no for-loop involed? That was causing you trouble, as it was updating all child under "users" node.


text:
Q: Laravel jordanmiguel/laravel-popular error I'm using Laravel/popular and when I add 3 classes and migrate it gives me error. Here that 3 classes are listed:
JordanMiguel\LaravelPopular\LaravelPopularServiceProvider::class,
Illuminate\Foundation\Providers\ArtisanServiceProvider::class,
Illuminate\Auth\AuthServiceProvider:class,

Laravel popular
In Connection.php line 664:

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
  was too long; max key length is 1000 bytes (SQL: alter table visits
  add unique visits_ip_visitable_id_visitable_type_date_unique(ip,
  visitable_id, visitable_type, date))

In Connection.php line 458:

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
  was too long; max key length is 1000 bytes

A: In ur app\Providers\AppSErviceProvider.php file add these two lines:
at the top:
use Illuminate\Support\Facades\Schema;
inside the boot function:
Schema::defaultStringLength(191);

Updated:
After seeing ur comments its not working, u may need to run the below mysql query in your phpmyadmin (if u have access).
CREATE TABLE `visits` (
  `id` int(10) UNSIGNED NOT NULL,
  `ip` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `visitable_id` int(11) NOT NULL,
  `visitable_type` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `date` date NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `visits`
--
ALTER TABLE `visits`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `visits_ip_visitable_id_visitable_type_date_unique` (`ip`,`visitable_id`,`visitable_type`,`date`),
  ADD KEY `visits_ip_index` (`ip`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `visits`
--
ALTER TABLE `visits`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;COMMIT;

This will create the table for you, no need to run php artisan migrate
Its not the perfect answer but it solves your problem, temporarily.

A: In your AppServiceProvider, add this line to boot method-
public function boot()
{
    Schema::defaultStringLength(191);
}


text:
Q: How to enable all the possible backup options of MySQL I normally use MySQL Administrator to backup my database. I want to enable all the backup options for the available backup types in MySQL. I noticed that Binary Logging is not running on my PC. How to enable it? I also want to know what all parameters to include in a command-line mysqldump command to take a perfect guaranteed backup.

A: Add the following to my.ini
[mysqld]
log-bin=mysql-bin

Then, restart mysql
As for mysqldump, most of the options you need are defaulted already in --opt. Here are my choice parameters:
mysqldump -h... -u... -p... --master-data=2 --routines --triggers --flush-privileges --all-databases > DataDump.sql

Here is an explanation for my choices (including default --opt)
--opt               Same as --add-drop-table, --add-locks, --create-options,
                    --quick, --extended-insert, --lock-tables, --set-charset,
                    and --disable-keys. Enabled by default, disable with
                      --skip-opt.
-R, --routines      Dump stored routines (functions and procedures).
--triggers          Dump triggers for each dumped table.
--flush-privileges  Emit a FLUSH PRIVILEGES statement after dumping the mysql
                    database.  This option should be used any time the dump
                    contains the mysql database and any other database that
                    depends on the data in the mysql database for proper
                    restore.
--master-data[=#]   This causes the binary log position and filename to be
                    appended to the output. If equal to 1, will print it as a
                    CHANGE MASTER command; if equal to 2, that command will
                    be prefixed with a comment symbol. This option will turn
                    --lock-all-tables on, unless --single-transaction is
                    specified too (in which case a global read lock is only
                    taken a short time at the beginning of the dump; don't
                    forget to read about --single-transaction below). In all
                    cases, any action on logs will happen at the exact moment
                    of the dump. Option automatically turns --lock-tables
                    off.

You will need --master-data if you want to setup the dump to prepare replication slaves. The master log and position at the time of the dump will be recorded as a comment (using --master-data=2) or as a command (using --master-data=1) on line 22 of the dump file.
UPDATE 2011-07-26 15:20 EDT
If you would like to dump separate databases and separate tables, please follow the instructions at this URL.

A: Rolando mentioned how to enable binary logging in the log. All you need to do is set the log-bin variable and restart mysql.
You can ensure that binary logging is enabled on a running server with:
mysql> SHOW VARIABLES LIKE 'log_bin%';
+---------------------------------+-------+
| Variable_name                   | Value |
+---------------------------------+-------+
| log_bin                         | ON    |
| log_bin_trust_function_creators | OFF   |
| log_bin_trust_routine_creators  | OFF   |
+---------------------------------+-------+
3 rows in set (0.05 sec)

I think it's VERY important to note that you're never really guaranteed a perfect backup everytime. As in life, nothing is guaranteed.
You need to set up a backup strategy and test a restore periodically.
Doing this ensures...

*

*you can restore from your backup

*you are familiar with your strategy so WHEN disaster hits, you won't be fumbling around.

*you'll already know how to get it back online.


text:
Q: How to control for the amount of noise added to x, y spatial points in R? Fairly novice R user, and I'm sure there's an easy solution for this - but I can't find it. I have a data frame with a series of spatial coordinates, as well as a host of other attributes. Many of the spatial coordinates are the exact same - and I would like to add a set amount of noise to them, so that I can keep them within a certain radius - in this case 0.4 meters, or 40 centimeters while also keeping track of their associated attributes.
I am essentially looking for an R version of this question: https://gis.stackexchange.com/questions/35479/adding-noise-to-overlapping-x-y-coordinates-so-no-longer-in-exact-same-place
... because when I follow the directions for the answer to this question using ArcGIS - I get a series of random points but I lose the attributes associated with those points, and I can't easily find a way to match them back up.
Is there a way to use the jitter function in R or something similar and specify the radius in a spatial context (e.g. 40 cm) that the spatial coordinates are randomly distributed within that range? I don't understand how to manipulate the factor and amount argument in order to get my desired output.
Edit:
Here's an example df with fake coordinates. As you can see the coordinates in the first and third column are the same, because the animal was under the same rock twice. I would like to be able to add jitter to these coordinates so they are slightly different, but I want to control the jitter to be within 40 centimeters (no more than the size of the rock)
mydf <- data.frame("point_id" = 1:6, "date_time" = c("6/5/2018 10:57","6/5/2018 14:30","6/6/2018 10:06","6/6/2018 11:06","6/7/2018 10:35","6/7/2018 15:50"), "Animal_ID" = c(4,5,4,5,4,6), "Rock_ID" = c(1,2,1,3,4,5), x_proj = c(831120.3759,831441.0415,831120.3759,831433.4414,831128.4778,831422.0822), y_proj = c(5877582.998,5875337.074,5877582.998,5875328.897,5877575.360,5875338.216))

#make a separate object for the coordinates#
xy <- mydf[,c(5,6)]

#Convert to a spatialpoints data frame (insert own epsg)
sp.mydf <- SpatialPointsDataFrame(coords = xy, data = tumbling_test, proj4string = CRS("+init=epsg:xxxxx"))

I want my newly generated coordinates to still contain the attribute data from other columns (i.e. Animal_ID, date, etc) because other methods I have used in ArcGIS generate a series of new random pts but I can't match them back to the attributes.
Also if there is a way to only add the jitter to points that have more than one occurrence at a rock, that would be neat. For example here I only need to add the jitter to rows 1 and 3, because the other coordinates do not repeat. Once the jitter is added, I want to convert the results back to a regular dataframe that I will export to a .csv

A: There is, and it is much easier if you're working with an sf object.
You'll need to dig into coordinate reference systems (CRS) a little as well in order to jitter the points the correct distance.
If you're starting with a spatialPointsdataframe, use st_as_sf() to return an sf object.
Below is a reproducible example with points jittered around 5km.  The jittering is somewhat random and in this example varies from ~2-5.5 kilometers.
library(sf)
#> Linking to GEOS 3.6.2, GDAL 2.2.3, PROJ 4.9.3
library(tidyverse)

# load example data
nc <- read_sf(system.file('gpkg/nc.gpkg', package = 'sf'))

#make single points from polygons
nc_points <- st_centroid(nc)
#> Warning in st_centroid.sf(nc): st_centroid assumes attributes are constant over
#> geometries of x
#> Warning in st_centroid.sfc(st_geometry(x), of_largest_polygon =
#> of_largest_polygon): st_centroid does not give correct centroids for longitude/
#> latitude data

# Transform to a crs that uses meters as the distance
nc_points <- st_transform(nc_points, 3358)

nc_points_jittered <- st_jitter(nc_points, amount = 5000)

p1 <- ggplot(nc_points) +
  geom_sf() +
  ggtitle('Original')

p2 <- ggplot(nc_points_jittered) +
  geom_sf() +
  ggtitle('Jittered')

p3 <- ggplot() +
  geom_sf(data = nc_points, color = 'red') +
  geom_sf(data = nc_points_jittered, color = 'black') +
  ggtitle('Both')

cowplot::plot_grid(p1, p2, p3, ncol = 1)

Created on 2020-01-12 by the reprex package (v0.3.0)


text:
Q: vscode: how to remove the white highlight on the terminal? Here is a printscreen of the problem (with the inspect tool opened, on the right, in case it could help). As you can see in the setting (the file that is opened) the word "terminal" is only mentioned 2 times, and there is no background/highlight color mentioned with it.

EDIT: when I comment all my settings.json, it output this:

Any idea how to remove this annoying white background?

A: I finally solved it (I guess so). In settings.json I needed to replace:
"terminal.integrated.shell.windows":  "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"

with this:
"terminal.integrated.shell.windows":   "C:\\WINDOWS\\System32\\cmd.exe"

No idea why powershell causes this problem (bug?)


text:
Q: Using Powershell to update users home directory I am trying to change the home directory path to a bunch of users.
I wrote a script in Ppowershell which should change the path the username like so:
\\serverName\shareName\$_.SamAccountName

The problem is that I get the DistinguishedName instead of the SamAccountName like so:
\\serverName\shareName\CN=UserName,OU=OuName,DC=domainName,dc=local

This is the script I wrote:
Get-ADUser -Filter * -SearchBase 'ou=XX,dc=domainName,dc=local' | ForEach-Object {
Set-ADUser $_.SamAccountName -HomeDrive "Z:" -HomeDirectory "\\serverName\shareName\$_.SamAccountName"
}

Can anyone see why this is not working?

A: This is because of the way Powershell handles variables in quotes. Basically, rather than getting
$_.SamAccountName

You were actually getting
$_ + "SamAccountName"

To resolve this simply use the following method to encapsulate your variables:
Set-ADUser $_.SamAccountName -HomeDrive "Z:" -HomeDirectory "\\serverName\shareName\$($_.SamAccountName)"

Update: @JScott has informed me that this method is called a "subexpression"

A: $users = Get-Content C:\temp\homedir\test.txt
foreach ($user in $users) {
    $h = Get-ADUser $user -Properties * | select-object -expandproperty cn
    Set-ADUser $H -HomeDrive "H:" -HomeDirectory "\\my.domain.com\myserver\homedirs\$H"
}


text:
Q: MEF & optional plugin dependencies - best practice? so I have a rather stupid question, but I just can't think of a really good way to solve this "dilemma".
I'm developing an application with MEF and trying to come up with a good way to handle optional dependencies.
Random example, assume there are two plugins; "MyPlugin", and a StatusBar plugin which may or may not be loaded by the main application.
MyPlugin is supposed to have an optional dependency to the Status Bar Manager; if that plugin is loaded by MEF, it'll use it to output something to the status bar; if not, it simply won't.
[ModuleExport(typeof(MyPlugin))]
public class MyPlugin : IModule
{
  [ImportingConstructor]
  public MyPlugin([Import(AllowDefault = true)] StatusBarManager optionalStatusBarManager OptionalStatusBar)
  {
    if(optionalStatusBarManager != null)
      optionalStatusBarManager.Display("Hi from MyPlugin!");
  }
}

In order to be aware of the type "StatusBarManager", the MyPlugin-project would need a reference to the StatusBarManager project / its dll.
Now from my gut feeling, it makes little sense to have an optional dependency, if MyPlugin needs the StatusBarManager's dll to be accessible anyway because it relies on its exposed types.
But what are my options? Is there any decent way to have such optional dependencies without requiring the main application to have access to the optional dependency's dlls?
So far, I could only come up with importing these by contract name using the "dynamic" type. But then I'd lose any and all compile time safety obviously in MyPlugin.
Or I could create another project, such as StatusBarManagerAbstractions which contains only interface definitions. Then at least MyPlugin would only have a hard dependency to the relatively small interface project, without requiring the (potentially large) implementation libraries to be there. Better than nothing, but still doesn't strike me as a fully "optional" dependency.
Am I just overthinking this?! Is there any best practice to handle such an issue?

A: tldr; you're probably over-thinking this :)
Long Version

I'm developing an application with MEF and trying to come up with a good way to handle optional dependencies.

As the dependencies are optional, the current sample code should suffice. However, as a general best practice, all dependencies will be referenced / coded against by interface, not the concrete type. During the dependency resolution in MainModule, the implementation of interfaces defined in CommonModule are resolved by the MEF container through assembly references, file directory scanning, etc... and builds up the dependency graphs as needed.

Is there any decent way to have such optional dependencies without requiring the main application to have access to the optional dependency's dlls?

The MainModule does not need to have a reference to the StatusBarModule as long as the dll is deployed to the MainModule bin; a DirectoryCatalog can then be built up to compose the MEF container. As you're using "plugins", you'd want to use a DirectoryCatalog anyhow so that the dll's can be discovered at runtime.
For example, based on the given scenario, the solution structure should look something like the following which removes all references except the CommonModule to the MainModule:
Solution
- MainModule
    - starts the app (console, winform, wpf, etc...)
    - references: CommonModule (no other project references)
- CommonModule
    - references: no other modules
    - purpose: provides a set of common interfaces all projects can reference
    - note: the actual implementations will be in other projects
- MyPluginModule
    - references: CommonModule
    - purpose: provides plugins for the app
    - Implements interfaces from CommonModule
    - note: uses dependencies defined by interfaces in CommonModule and implemented by other modules
    - build: build step should copy the dll to the MainModule's bin
- StatusBarModule
    - references: CommonModule
    - purpose: provides plugin dependencies required by the application
    - note: uses dependencies defined by interfaces in CommonModule and implemented by other modules
    - build: build step should copy the dll to the MainModule's bin

The MyPluginModule and StatusBarModule are almost identical where neither references each other; rather, they share interfaces through the CommonModule interface definitions. The dependencies/concrete implementations are resolved at runtime through a DirectoryCatalog.
The underlying code/implementations would be as follows. Note, that there are 2 options for the optional dependency where one (MyPlugin) is using .ctor injection while the other (MyOtherPlugin) is using property injection:
MainModule
class Program
{
    static void Main()
    {
        // will output 'Hi from MyPlugin!' when resolved.
        var myPlugin = MefFactory.Create<IMyPlugin>().Value;

        // will output 'Hi from MyOtherPlugin!' when resolved.
        var myOtherPlugin = MefFactory.Create<IMyOtherPlugin>().Value;

        Console.ReadLine();
    }
}

public static class MefFactory
{
    private static readonly CompositionContainer Container = CreateContainer();

    public static Lazy<T> Create<T>()
    {
        return Container.GetExport<T>();
    }

    private static CompositionContainer CreateContainer()
    {
        // directory where all the dll's reside.
        string directory = AppDomain.CurrentDomain.BaseDirectory;

        var container = new CompositionContainer( new DirectoryCatalog( directory ) );

        return container;
    }
}

CommonModule
public interface IModule { }
public interface IMyPlugin { }
public interface IMyOtherPlugin { }
public interface IStatusBarManager
{
    void Display( string msg );
}

MyPluginModule
[Export( typeof( IMyPlugin ) )]
internal class MyPlugin : IModule, IMyPlugin
{
    private readonly IStatusBarManager _manager;

    [ImportingConstructor]
    public MyPlugin( [Import( AllowDefault = true )] IStatusBarManager manager )
    {
        _manager = manager;
        if( _manager != null )
        {
            _manager.Display( "Hi from MyPlugin!" );
        }
    }
}

[Export( typeof( IMyOtherPlugin ) )]
internal class MyOtherPlugin : IModule, IMyOtherPlugin
{
    private IStatusBarManager _statusManager;

    [Import( AllowDefault = true )]
    public IStatusBarManager StatusManager
    {
        get { return _statusManager; }
        private set
        {
            _statusManager = value;
            _statusManager.Display( "Hi from MyOtherPlugin!" );
        }
    }
}

StatusBarModule
[Export( typeof( IStatusBarManager ) )]
internal class StatusBarManager : IStatusBarManager
{
    public void Display( string msg )
    {
        Console.WriteLine( msg );
    }
}


text:
Q: Python moving modules into sub directory (without breaking existing import structure) Supposing I am writing library code with a directory structure as follows:
- mylibrary/
|
|-----foo.py
|-----bar.py
|-----baz.py
|-----__init__.py

And to better organise I create a sub directory:
- mylibrary/
|
|-----foobar/
|     |-----foo.py
|     |-----bar.py
|-----baz.py
|-----__init__.py

I want all client code to keep working without updates so I want to update init.py so that imports don't break.
I've tried adding this to init.py:
from foobar import foo

Now if I open a shell I can do:
from mylibrary import foo
print(foo.Foo)

However if I do this:
from mylibrary.foo import Foo

I get No module named mylibrary.foo error.
Here is the traceback from my actual example:
Type "help", "copyright", "credits" or "license" for more information.
>>> from global_toolkit import section
>>> section.Section
<class 'global_toolkit.serialization.section.Section'>
>>> from global_toolkit.section import Section
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'global_toolkit.section'
>>>

Can anyone explain this behaviour?

A: Add this in your __init__.py :
from .foobar import foo, bar
import sys
for i in ['foo','bar']:
  sys.modules['mylib.'+i] = sys.modules['mylib.foobar.'+i]

Now, from mylib.foo import Foo should work.


text:
Q: Call specific method on static const member Here is the idea: I have a class that has some member variable(s), say x. This class also has a method, A(), which does not modify the member variable(s), but returns info about them. There is also a method B() which does modify the member variable(s). So basically, this is the setup:
class Class
{
    int x;
    Class(int x) : x(x) { }

    int A() { return x; /* info about x */ }
    void B() { x++; /* updates x! */ }
}

So far so good. But now I want to have some special version of this class that will be used throughout the project, and I want it to have a specific set of member variable(s), say, x = 3. My idea was to add a const static Class mySpecialCase member to Class, and just refer to Class::mySpecialCase whenever necessary.
The problem however, is that I need to call A() on this object, to fetch some information, but do not want B() to be called on this object, since it would modify x, which would affect all future usage of the 'special case'.
Any ideas on how to solve this?

A: It's already illegal to call Class::mySpecialCase.B(), since mySpecialCase is const and B() is not a const member.  You just need to make it possible to call A(), by making A() a const member function:
class Class
{
    int x;
public:
    Class(int x) : x(x) { }

    static const Class mySpecialCase;

    int A() const { return x; /* info about x */ }
    void B() { x++; /* updates x! */ }
};

// In class.cpp:
const Class Class::mySpecialCase{3};

A:
The problem however, is that I need to call A() on this object, to fetch some information, but do not want B() to be called on this object, since it would modify x,

Declare the object and B() as const but not A():
 class Class {
     public:
          [...]
          int A();
          void B() const;
 };

 // Initialize const object.
 const Class specialCase(3);

Calling specialCase.A() will be a compile error, but specialCase.B() is still okay because the const modifier indicates to the compiler this method does not alter the object.

A:
So far so good.

Not really. A should be const:
int A() const { return x; /* info about x */ }

But now I want to have some special version of this class

By version, you mean instance, right?
Add a static member function returning a reference to a static local instance of Class:
#include <iostream>

class Class
{
public:
    int x;
    Class(int x) : x(x) { }

    int A() const { return x; /* info about x */ }
    void B() { x++; /* updates x! */ }

    static Class &SpecialInstance()
    {
        static Class instance(3);
        return instance;
    }
};

int main()
{
    Class a(1);
    Class b(2);
    Class c = Class::SpecialInstance();

    std::cout << c.A() << "\n";
}


text:
Q: Почему axios не получает data? JS файл с запросом:
axios.post('file.php', {table: 'users'})
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });

PHP на сервере (openserver, apache):
echo 'Ответ сервера';

Результат консоли:
{data: "", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data: ""
headers: {date: "Wed, 27 Feb 2019 09:54:15 GMT", server: "Apache", connection: "Keep-Alive", keep-alive: "timeout=10, max=97", content-length: "0", …}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: "OK"
__proto__: Object

В чем может быть ошибка? Битый час ломаю голову, что только уже не пробовал. Подскажите куда копать?

A: axios.post('file.php', {table: 'users'})
    .then(function (response) {
      console.log(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });

в php файле сделайте
<?php
    echo json_encode($_POST);
?>


text:
Q: How to use tornado.httpclient.AynscHTTPClient to fetch a page which need login? I'm write a litter web app with tornado. And I am write the unittest use the tornado.httpclient.AynscHttpClient to test the index page,but the index page need user to be login. I rewrite the get_current_user need the user in the db, the login page has a xsrf_input, so I can't fetch the login page with post.
I find the tornaod.httpClient.HTTPRequest has a paramter auth_username and auth_password. but it doesnot work. I donot what it mean. but I'm strap now.
Hope for you help

A: Set xsrf_cookies=False.
Try it again。


text:
Q: Symfony vich uploader and doctrine loggable extension problem? I am using this two libraries to create an entity that has a picture using vich/uploader-bundle and I am logging entity changes history using the loggable doctrine extension provided from stof/doctrine-extensions-bundle which provides the extension from atlantic18/doctrineextensions.
So here is the problem: I have an entity that has a Vich uploadable picture field and it is using doctrine's Gedmo loggable extension with annotations.
/**
 * @var VersionedFile
 *
 * @ORM\Embedded(class="App\Entity\Embedded\VersionedFile")
 *
 * @Gedmo\Versioned()
 */
private $picture;

/**
 * @var File
 *
 * @Vich\UploadableField(
 *     mapping="user_picture",
 *     fileNameProperty="picture.name",
 *     size="picture.size",
 *     mimeType="picture.mimeType",
 *     originalName="picture.originalName",
 *     dimensions="picture.dimensions
 * )
 */
private $pictureFile;

/**
 * @var DateTimeInterface
 *
 * @ORM\Column(type="datetime", nullable=true)
 *
 * @Gedmo\Versioned()
 */
private $pictureUpdatedAt;

The embedded entity class App\Entity\Embedded\VersionedFile has all the needed annotations in order to version properly using the loggable doctrine extension.
// Not the whole code but just to get the idea for property versioning

/**
 * @ORM\Column(name="name", nullable=true)
 *
 * @Gedmo\Versioned()
 */
protected $name;

And now the problem. When I upload the file and persist the entity the following thing happens. The entity manager persist the entity and the onFlush method of the Gedmo loggable listener (Gedmo\Loggable\LoggableListener) is called. This listeners checks the changes and schedules log entries to be inserted.
The problem is that the VichUploaders upload listener (Vich\UploaderBundle\EventListener\Doctrine\UploadListener) is called after the loggable listener and then the file is uploaded which changes the properties name, size, etc. The computed changes about name, size, etc. are not available in theLoggableListener` becaues it is called first and so it doesn't know that they should be inserted.
Am I missing some configuration or am I doing something wrong. The idea is to log changes made to the picture. For now in the database the log entries consist only of the $pictureUpdatedAt field.
I debugged the problem and all I can see is the order and that in LoggableListener the method getObjectChangeSetData is returning only the $pictureUpdatedAt field that has changed. I don't think this has something in common with the Embedded entity because I think the calling order of the listeners is the problem. The first idea I had was to change the listeners priority but even if I do that the order of the calling is not changed mainly because when onFlush is called it is triggering the preUpdate method which triggers the UploadListener of the uploader bundle.

A: You are correct, the root of the problem is the UploadListener listens to prePersist and preUpdate while the LoggableListener listens to onFlush. Since onFlush is triggered before preUpdate, file changes are never logged. This can be fixed in a few steps.
1. Create New UploadListener
First, you can write your own UploadListener to listen to onFlush instead.
// src/EventListener/VichUploadListener.php using Flex
// src/AppBundle/EventListener/VichUploadListener.php otherwise
namespace App\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;
use Vich\UploaderBundle\EventListener\Doctrine\UploadListener;

class VichUploadListener extends UploadListener
{
    public function onFlush(OnFlushEventArgs $args): void
    {
        $em = $args->getEntityManager();
        $uow = $em->getUnitOfWork();

        foreach ($uow->getScheduledEntityUpdates() as $entity) {
            $this->preUpdate(new LifecycleEventArgs($entity, $em));
        }

        // Required if using property namer on sluggable field. Otherwise, you
        // can also subscribe to "prePersist" and remove this foreach.
        foreach ($uow->getScheduledEntityInsertions() as $entity) {
            // We use "preUpdate" here so the changeset is recomputed.
            $this->preUpdate(new LifecycleEventArgs($entity, $em));
        }
    }

    public function getSubscribedEvents(): array
    {
        return [Events::onFlush];
    }
}

In this example, I reuse the original UploadListener to make things easier. Since we are listening to onFlush, it is important we recompute the entity changeset after the file is uploaded which is why I used the "preUpdate" method for both scheduled updates and inserts.
You do have to be careful when changing events like this. If you have another listener that expects the value of one of your file fields to be set (or unset), this may change the expected behavior. This is especially true if you use the second foreach to handle new uploads. prePersist is triggered before onFlush, so this would make new uploads get set later than before.
2. Create New CleanListener
Next, we now have to create a new CleanListener. This listener deletes old files when we update the file field if delete_on_update is set to true. Since it listens to preUpdate, we have to change it to onFlush so old files are properly deleted.
// src/EventListener/VichCleanListener.php on Flex
// src/AppBundle/EventListener/VichCleanListener.php otherwise
namespace App\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;
use Vich\UploaderBundle\EventListener\Doctrine\CleanListener;

class VichCleanListener extends CleanListener
{
    public function onFlush(OnFlushEventArgs $args): void
    {
        $em = $args->getEntityManager();
        $uow = $em->getUnitOfWork();

        foreach ($uow->getScheduledEntityUpdates() as $entity) {
            $this->preUpdate(new LifecycleEventArgs($entity, $em));
        }
    }

    public function getSubscribedEvents(): array
    {
        return [Events::onFlush];
    }
}

3. Configure New Listeners
Now, we need to override the default listeners in our config with the ones we just wrote.
# config/services.yaml on Flex
# app/config/services.yml otherwise
services:
    # ...

    vich_uploader.listener.upload.orm:
        class: 'App\EventListener\VichUploadListener'
        parent: 'vich_uploader.listener.doctrine.base'
        autowire: false
        autoconfigure: false
        public: false
    vich_uploader.listener.clean.orm:
        class: 'App\EventListener\VichCleanListener'
        parent: 'vich_uploader.listener.doctrine.base'
        autowire: false
        autoconfigure: false
        public: false

4. Change Gedmo Extension Priorities
If all that wasn't enough, now comes the other problem you brought up: listener priority. At a minimum, we need to make sure LoggableListener is triggered after our upload/clean listeners. If you are using any of the other Gedmo extensions, you need to make sure they are loaded in the order you need them. The defaults set by VichUploaderExtension set the CleanListener to 50 and the UploadListener to 0. You can see the Gedmo Listener defaults in StofDoctrineExtensionsExtension.
For me, I have a property namer that depends on a sluggable field, so I want to make sure SluggableListener is called before the UploadListener. I also use softdeleteable and want soft deletes logged as "remove", so I want to make sure LoggableListener is registered before SoftDeleteableListener. You can change these priorities by overriding the services in your config.
# config/services.yaml on Flex
# app/config/services.yml otherwise
services:
    # ...

    stof_doctrine_extensions.listener.sluggable:
        class: '%stof_doctrine_extensions.listener.sluggable.class%'
        autowire: false
        autoconfigure: false
        public: false
        calls:
            - { method: 'setAnnotationReader', arguments: ['@annotation_reader'] }
        tags:
            - { name: 'doctrine.event_subscriber', connection: 'default', priority: 5 }

    stof_doctrine_extensions.listener.loggable:
        class: '%stof_doctrine_extensions.listener.loggable.class%'
        autowire: false
        autoconfigure: false
        public: false
        calls:
            - { method: 'setAnnotationReader', arguments: ['@annotation_reader'] }
        tags:
            - { name: 'doctrine.event_subscriber', connection: 'default', priority: -1 }

    stof_doctrine_extensions.listener.softdeleteable:
        class: '%stof_doctrine_extensions.listener.softdeleteable.class%'
        autowire: false
        autoconfigure: false
        public: false
        calls:
            - { method: 'setAnnotationReader', arguments: ['@annotation_reader'] }
        tags:
            - { name: 'doctrine.event_subscriber', connection: 'default', priority: -2 }

Alternatively, you could create a compiler pass to just change the priorities of the doctrine.event_subscriber tags for these services.
// src/DependencyInjection/Compiler/DoctrineExtensionsCompilerPass.php on Flex
// src/AppBundle/DependencyInjection/Compiler/DoctrineExtensionsCompilerPass.php otherwise
namespace App\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class DoctrineExtensionsCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $listenerPriorities = [
            'sluggable' => 5,
            'loggable' => -1,
            'softdeleteable' => -2,
        ];

        foreach ($listenerPriorities as $ext => $priority) {
            $id = sprintf('stof_doctrine_extensions.listener.%s', $ext);

            if (!$container->hasDefinition($id)) {
                continue;
            }

            $definition = $container->getDefinition($id);
            $tags = $definition->getTag('doctrine.event_subscriber');
            $definition->clearTag('doctrine.event_subscriber');

            foreach ($tags as $tag) {
                $tag['priority'] = $priority;
                $definition->addTag('doctrine.event_subscriber', $tag);
            }
        }
    }
}

If you go this route, make sure to register the compiler pass with a higher priority (higher than 0) to ensure it is ran before RegisterEventListenersAndSubscribersPass.
// src/Kernel.php on Flex
// src/AppBundle/AppBundle.php otherwsie

// ...

use App\DependencyInjection\Compiler\DoctrineExtensionsCompilerPass;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;

// ...

protected function build(ContainerBuilder $container)
{
    $container->addCompilerPass(new DoctrineExtensionsCompilerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 5);
}

Now, just ensure your cache is cleared.


text:
Q: How to use tensorflow serving? I am learning to use Tensorflow serving but I have a very hard time finding examples including in Stackoverflow.
I am using flower example in TensorFlow website. The training part is successful and having a hard time deploying.
I ran the server as follows :
docker run -p 8501:8501 --mount type=bind,source=C:\tmp\saved_models,target=/models/flowers -e MODEL_NAME=flowers -t tensorflow/serving &

To look at all SignatureDef, I used the following
saved_model_cli show --dir c:\tmp\saved_models\1 --all

The response is
MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:

signature_def['serving_default']:
  The given SavedModel SignatureDef contains the following input(s):
    inputs['image'] tensor_info:
        dtype: DT_STRING
        shape: ()
        name: DecodeJpeg/contents:0
  The given SavedModel SignatureDef contains the following output(s):
    outputs['classes'] tensor_info:
        dtype: DT_STRING
        shape: (5)
        name: Const:0
    outputs['prediction'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 5)
        name: final_result:0
  Method name is: tensorflow/serving/predict

As I have seen here it suppose to have "Method name is: tensorflow/serving/classify"
Why is it missing in my example ?
My RESTAPI request is as follows :
http://localhost:8501/v1/models/flowers/versions/1:classify

Body :
{
  "signature_name": "serving_default",
  "flowers": [
    {
      "image": { "b64": "c:/Users/pubud/OneDrive/Pictures/bird.jpg=" },
      "rose": "flower"
    }
  ]
}

The error I get is :
{
    "error": "Expected classification signature method_name to be tensorflow/serving/classify. Was: tensorflow/serving/predict"
}

Any help is really appreciated.

A: Your RESTful URL specifies ...:classify, which is different from what's in the signature_def['serving_default'] - predict.
Try changing the RESTful URL to be ...:predict, and then refer to the instructions here for the json body of the request.
Here is more information about the SignatureDefs:
https://www.tensorflow.org/serving/signature_defs
Good luck!


text:
Q: Alert if a website is either down or there is change in status In my database i have notifications table that has URL to be checked and check frequency column and alert frequency column. what iam trying to do now with is code is. After sending a http request the code should able to do the following.

*

*check if the website is up and if the status changed, then send notification . else do nothing.

*if the website is down and if status changed, then send notification.

*if the website is down and the status doesn't change  check the alert frequency. if the elapse_time is greater than the alert frequency, send notification.

that is what iam trying to achieve but failed to do some. my code need some improvement.
<?php
namespace App\Http\Controllers;
use GuzzleHttp\Client;
use App\Utilities\Reporter;
use GuzzleHttp\Exception\ClientException;
use App\Notification;
use App\Status;
use App\Setting;
use Carbon;
class GuzzleController extends Controller
{
    private $default_check_frequency;

    protected $client;

    protected $reporter;

    public function __construct()
    {
        $this->client = new Client();

        $this->reporter = new Reporter;

        $this->default_check_frequency = Setting::defaultCheckFrequency();

        $this->default_alert_frequency = Setting::defaultAlertFrequency();
    }

    private function addStatusToNotification(Notification $notification, Status $status, $resCode)
    {
        $notification->statuses()->attach($status, [
            'values' => $resCode === 200
                ? 'up'
                : 'down'
        ]);
    }

    private function report(Notification $notification, $resCode)
    {
        /* how to send slack to different slach channels, now it is sending only to one channel!*/

        $this->reporter->slack($notification->website_url . ':' . '  is down' . ' this is the status code!' . ' @- ' .$resCode,
                               $notification->slack_channel);

        $this->reporter->mail($notification->email,$notification->website_url.' is down '. ' this is the status Code: '. $resCode);
    }

    private function sendNotification(Notification $notification, Status $status, $status_health, $frequency, $resCode)
    {
        $elapsed_time = \Carbon\Carbon::parse($status_health['timestamp'])->diffInMinutes();

        if ($elapsed_time >= $frequency) {
            $this->addStatusToNotification($notification, $status, $resCode);

            if ($resCode != 200) {
                $this->report($notification, $resCode);
            }
        }
    }

    public function status()
    {
        $notifications = Notification::where('active', 1)->get();

        $status = Status::where('name', 'health')->first();

        foreach ($notifications as $notification) {
            $this->updateStatus($notification, $status);
        }
    }

    private function updateStatus(Notification $notification, Status $status)
    {
        $resCode = $this->getStatusCode($notification->website_url);

        $this->sendNotification(
            $notification,
            $status,
            $notification->status('health'),
            $this->getFrequency($notification, $resCode),
            $resCode
        );
    }

    private function getFrequency(Notification $notification, $resCode)
    {

        switch ( $resCode) {
          case '200':
            return isset($notification->check_frequency)
            ? intval($notification->check_frequency)
            : $this->default_check_frequency;
            break;

          default:
            return isset($notification->alert_frequency)
            ? intval($notification->alert_frequency)
            : $this->default_alert_frequency;
            break;
        }
    }

    private function getStatusCode($url)
    {
        try {
            $response = $this->client->get($url, [
                'http_errors' => false
            ]);

            return $response->getStatusCode();

        } catch (\GuzzleHttp\Exception\ConnectException $e) {

        }
    }
}

would you please help[ me with this problem. some thing is missed in my code?


text:
Q: inspect data (url variable) before inserting to mysql My php script is posting bad urls that ajax send to it.  When I try to filter the url and cancel the insert into mysql, it doesn't work.  What I want to do is verify the $link variable if it a link.  If not, don't post data to mysql. Can i know what I did wrong and how to fix it?   Thank you :)
Here is my code
$con = mysql_connect("localhost","root","");
if (!$con) {
   die('Could not connect: ' . mysql_error());
}

mysql_select_db("database", $con);

$link = $_POST['new'];
$name = $_POST['name'];
$size = $_POST['size'];
$cat = $_POST['cat'];

// PHP 5.3.5-1ubuntu7.2
$link = mysql_real_escape_string($link);
$name = mysql_real_escape_string($name);
$size = mysql_real_escape_string($size);
$cat = mysql_real_escape_string($cat);

if (filter_var($link, FILTER_VALIDATE_URL)) {} else {
  echo "URL is NOT valid";
  mysql_close($con);
  exit();
}

$check = mysql_query("SELECT link FROM links WHERE  link = '{$link}';");

if (mysql_num_rows($check) == 0) {
    // insert

    $sql="INSERT INTO links (link, name, size, category) VALUES ('$link','$name','$size','$cat')";
    if (!mysql_query($sql,$con))
      {
      die('Error: ' . mysql_error());
      }
    echo "1 record added.  Redirecting!";

    mysql_close($con);
}

A: try this one:
if(filter_var($link, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) === false){
    echo "URL is NOT valid";
    mysql_close($con);
    exit();
}

Your are right xxxhxtxtp://example.com will pass as valid url.
Try it with preg_match instead.
if (!preg_match("#^http(s)?://[a-z0-9-_.]+\.[a-z]{2,4}#i", $link)) {
    echo "URL is NOT valid";
    mysql_close($con);
    exit();
}

With this regex you need to have http(s) scheme. So you can search for another regex if that don't work for you.

A: Is this what you're trying to do? Perhaps you need a regex solution.
if (filter_var($link, FILTER_VALIDATE_URL)) {
    $check = mysql_query("SELECT link FROM links WHERE  link = '{$link}';");

    if (mysql_num_rows($check) == 0) {
        // insert

        $sql="INSERT INTO links (link, name, size, category) VALUES ('$link','$name','$size','$cat')";
        if (!mysql_query($sql,$con))
          {
          die('Error: ' . mysql_error());
          }
        echo "1 record added.  Redirecting!";

        mysql_close($con);
    }
} else {
  echo "URL is NOT valid";
  mysql_close($con);
  exit();
}


text:
Q: Add email to PayPal's DoDirectPayment request I'm using the PayPal PHP SDK to do a DoDirectPayment request and the example code and the class documentation doesn't explain how to add an email address to the request. Is that possible somehow?
Thanks!

A: The email address can be supplied using the Payer property on PayerInfoType as explained here.


text:
Q: Safe to use asyncio in Django? I have a small Django app that is highly dependent on other services. In one situation, the client makes one request to our app, and the Django app makes 3 or 4 requests to another server, aggregates the data, and saves it. This is a slow process as I need to make these calls synchronously although there is no requirement for the requests to be made sequentially.
Given the above, this particular set of calls seem like a good candidate for async programming and the asyncio package is provided with newer Python versions.
I've implemented what I have described using loop.run_until_complete and hooked it into a view and it seems to work fine, as well as provide a significant performance increase.
However, I am worried that I am missing something in the magic. Doing multiple google searches on whether this is a good idea in Django has given me a mixed bag of answers and I'm still unclear on the negatives of doing so.
I realize this could all be done by JavaScript client in a well supported manner, I'm just trying to reduce complexity on that side, and am more interested in the implications of doing this running Django in prod environment with WSGI.


text:
Q: Add a Skip Ad button to Brightcove Player I'm trying to add a Skip Ad Button to my Brightcove Player but I don't know hot to do it.   Brightcoves supports tell me that I need to create a plugin with a custom component to my player, but I don't know how to do this.

A: You need to understand how to use and build SWF plugins:
http://support.brightcove.com/en/video-cloud/docs/creating-custom-player-components
And then use the stopAD method in the AdvertisingModue
https://docs.brightcove.com/en/video-cloud/player/com/brightcove/api/modules/AdvertisingModule.html#stopAd()


text:
Q: Writing large file in Nodejs using fs.createWriteStream I have function, which in perfect world should create an huge 1M lines file. Here it is:
    const fileWriteStream = fs.createWriteStream(path.resolve(filePath));
    let ableToWrite = true;
    for (let i = 0; i < 1e6; i++) {
        if (ableToWrite) {
            ableToWrite = fileWriteStream.write(`.testClass${itr}-${i%2} { background: red } \n`);
        } else {
            fileWriteStream.once('drain', () => {
                ableToWrite = fileWriteStream.write(`.testClass${itr}-${i%2} { background: red } \n`);
            })
        }
    }

Unfortunetly for me, i'm getting the following error pretty fast:
MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 drain listeners added. Use emitter.setMaxListeners() to increase limit

I don't really want to increase listeners count for this function.
What is correct way to write such a big file using streams?
Many thanks!

A: The easiest way to asynchronously continue when the stream drains is to use await in the loop with a promise:
const fileWriteStream = fs.createWriteStream(path.resolve(filePath));
for (let i = 0; i < 1e6; i++) {
    const ableToWrite = fileWriteStream.write(`.testClass${itr}-${i%2} { background: red } \n`);
    if (!ableToWrite) {
        await new Promise(resolve => {
            fileWriteStream.once('drain', resolve);
        });
    }
}

The alternative is using a recursive approach instead of a loop:
function go(i) {
    if (i >= 1e6) return;
    const ableToWrite = fileWriteStream.write(`.testClass${itr}-${i%2} { background: red } \n`);
    if (ableToWrite)
        go(i+1);
    else
        fileWriteStream.once('drain', () => {
            go(i+1);
        });
}
const fileWriteStream = fs.createWriteStream(path.resolve(filePath));
go(0);


text:
Q: MapThread with several cells as output Assume I have defined the following function:
FF[{x_, y_}] := {x^2 + y^3, 3.5*x*y}

I would like to apply FF on a list of input such as:
XX = {xa, xb, xc}
YY = {ya, yb, yc}

In order to do it I input the following syntax:
MapThread[FF, {XX, YY}]

but as output I get just the first element of the function:
{xa^2+ya^3, xb^2+yb^3, xc^2+yc^3}

what am I doing wrong here?

A: I would not use MapThread in this case. From the point of functional programming I consider this
FF /@ Transpose[{XX, YY}]

as more consistent. This is because the signature of FF, namely taking a tuple and returning a tuple, is exactly what you want to express mathematically. Therefore, I would not use the solution
MapThread[FF[{##}] &, {XX, YY}]

because although it works, it has to recreate the tuple parameter by wrapping FF with a pure function.
Another point: Maybe you know that most basic operations like multiplication, powers, etc work with list arguments. Thats why you could spare the Map (/@) of my first example and simply write
Transpose[FF[{XX, YY}]]


text:
Q: Should reused Visitors be static? I'm writing a Canvas painting app.
For some operation I have a visitor that is to be used every time a drawing in selected by the mouse.
At the moment I recreate the visitor always again like:
Visitor visitor = isStateSelected ? new SelectionVisitor() : DrawVisitor();

Should I consider making these visitors static, or at least introduce a private field for them? Or could one argue that the present way is more clean and object creation is not a big overhead?

A: I would suggest using a State Pattern for triggering the appropriate Visitor. Caches are really a bad idea in the application layer. Domain model classes should not refer to them, they should exist only in the config layer.

A: If this object creation is a bottleneck for your app, I think a private cache would be the next step.  If it's not slowing you down, I think you can move on to the next problem.
I love attempts to keep code clean.  If you don't want to muddy your code with a cache of visitors, you can keep it separate by wrapping this in a private getVisitor() method of its own that manages the cache variables.


text:
Q: onJNILoad not being called when calling System.loadLibrary I have add a print log statement in JNI_OnLoad, but I found that it is not being called. Here is my JNI_OnLoad method.
extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
    __android_log_print(ANDROID_LOG_INFO,  __FUNCTION__, "onLoad");
   // some init code
}

Do I need to declare JNI_OnLoad in a specific file or declare sth in Android.MK tells system where to find the JNI_OnLoad method? Now I just put to one of the many .cpp files.
compiled .so lib is attached. I try to dump the so file, and I am sure the JNI_OnLoad method is exported.
https://docs.google.com/file/d/0B089WeEZXTb3ZjZiQllaYThuUUk/edit
Actually, I am trying to port a library from android source (libcorejava.so). To avoid class path conflict, I already change the class path.
And here is the file that declares JNI_OnLoad:
https://android.googlesource.com/platform/libcore/+/master/luni/src/main/native/Register.cpp
I already change the signature to the above one in order to match the standard signature
EDIT:
I found that android source does not load it by System.loadLibrary! It says libcorejava is used to implement System.loadLibrary, so we cannot use System.loadLibrary to load it. But in my case, it should not be a problem as I only need part of the function (ICU related).
https://android.googlesource.com/platform/dalvik/+/master/vm/Init.cpp
 // Most JNI libraries can just use System.loadLibrary, but you can't
    // if you're the library that implements System.loadLibrary!
    loadJniLibrary("javacore");
    loadJniLibrary("nativehelper");

EDIT 2:
It turns out that it is because the name conflict of the library!
But it seems that libjavacore requires other library. Does there any tool that can list out what the dependency I am missing?
java.lang.UnsatisfiedLinkError: Cannot load library: reloc_library[1286]: XXX

EDIT 3:
TextClock is a new api for displaying time. It only exists in 4.2+ api up. I am trying to backport it so that older sdk can uses it. It depends on a ICU library which resides in libjavacore. So I modify the Android.mk file to make sure the libjavacore only include the icu related source file and the final compiled so file is being included in my apk.
TextClock:
http://developer.android.com/reference/android/widget/TextClock.html
It now works in the phone which originally support TextClock, but doesn't work in old devices. Here is the exception log. I think it is because libjavacore is the wrapper of ICU library. Apart from the wrapper, I still need to port the ICU library. But I am going to give up as the size of ICU library is quite large and seems doesn't worth for it...
    12-13 14:07:54.859: E/AndroidRuntime(2091): java.lang.UnsatisfiedLinkError: Cannot load library: reloc_library[1306]:    36 cannot locate '_ZN6icu_516Locale14createFromNameEPKc'...
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at java.lang.Runtime.loadLibrary(Runtime.java:370)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at java.lang.System.loadLibrary(System.java:535)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at com.example.time.MainActivity.onCreate(MainActivity.java:20)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at android.app.Activity.performCreate(Activity.java:5008)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at android.os.Handler.dispatchMessage(Handler.java:99)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at android.os.Looper.loop(Looper.java:137)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at android.app.ActivityThread.main(ActivityThread.java:4745)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at java.lang.reflect.Method.invokeNative(Native Method)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at java.lang.reflect.Method.invoke(Method.java:511)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    12-13 14:07:54.859: E/AndroidRuntime(2091):     at dalvik.system.NativeStart.main(Native Method)

A: You can dump the symbols in your .so file using readelf in your toolchains folder.  Check to see that JNI_OnLoad is exported.  The -s (symbols) command and the name of the .so file in your libs folder should do it.

A: In older releases of Android, the library was linked directly into the VM (libdvm.so linked against libnativehelper.so which linked against libjavacore.a).  In recent releases this changed to always load the library at start time, using the internal native library load mechanism, so JNI_OnLoad will be called if present.
If I run adb shell dalvikvm Foo (where "Foo" doesn't exist), I see this in logcat:
D dalvikvm: Trying to load lib libjavacore.so 0x0
D dalvikvm: Added shared lib libjavacore.so 0x0
D dalvikvm: Trying to load lib libnativehelper.so 0x0
D dalvikvm: Added shared lib libnativehelper.so 0x0
D dalvikvm: No JNI_OnLoad found in libnativehelper.so 0x0, skipping init

So it loaded libjavacore.so and apparently found and ran JNI_OnLoad (no news is good news).  It loaded libnativehelper.so and didn't find a JNI_OnLoad, so it logged a message to tell you so in case you were expecting otherwise.
If you replace the libjavacore.so in /system/lib (on a rooted device), and run the dalvikvm command, you should see your message in the log file, mixed in with messages like I've shown above.  If you restart the system, you should see your message during zygote startup, and not again unless something runs a Dalvik-based command (like am).


text:
Q: Nagios plugin gives "no output returned" using compiled perl I have a custom nagios plugin which is written in Perl. For complicated political reasons I am required to hide the source code of this plugin. The only way I found to do this was by using perlc (http://marginalhacks.com/Hacks/perlc).
In the words of author:
"Takes a single perl script, converts the block using a simple encoding with an optionally defined key. The script is decoded at runtime and fed to the perl library, to avoid it getting in the hands of the user."
The problem I am getting is that Nagios shows "No output returned from plugin" when I used the compiled version of the plugin. The raw perl source works just fine.
After debugging for a while I narrowed the problem down to using exit in perl. I.e
This works fine when compiled.
print "OK: Everything is working fine.\n";

This however does not work and results in ""No output returned from plugin"
print "OK: Everything is working fine.\n";
exit 1;

It doesn't matter how I exit (0 1 2 or 3) I still get the same problem.

A: According to the cross-posted PerlMonks thread, the issue was resolved by enabling autoflushing:
$| = 1;

From perlvar:

*

*HANDLE->autoflush( EXPR )

*$OUTPUT_AUTOFLUSH

*$|
If set to nonzero, forces a flush right away and after every write or
  print on the currently selected output channel. Default is 0
  (regardless of whether the channel is really buffered by the system or
  not; $| tells you only whether you've asked Perl explicitly to flush
  after each write). STDOUT will typically be line buffered if output is
  to the terminal and block buffered otherwise. Setting this variable is
  useful primarily when you are outputting to a pipe or socket, such as
  when you are running a Perl program under rsh and want to see the
  output as it's happening.

See the article Suffering from Buffering? for more details.