Generic text in Short Description

Question: I have a generic line that I want to show in the short description of each product and at checkout (i.e. buy one and get one free). Is there a way to automate this rather than for me to enter in to each product?
Comment: Mean , update product short description pro-grammatically? magento version ?
Answer: There are multiple ways to do this. You could add the text in the phtml file and maybe add some variables here and there. That way, all products have an identical description. You could also do a check here: If a product has a value for the description, you could show that description. If not, show the default description. In that case you'll make the description attribute optional, so you'll need to change the required setting for the attribute.
Another option could be to use a custom variable here. That way, you can just add the custom variable in the product description and it will show the same text. Downside is that using product specific data, like product name, can't be shown in the description.
Final option might be to make this configurable. Create a custom extension where you make it possible to set the default description in the system configuration. You could develop this in a way where you can use variables within the text. You can show this by default and maybe still make it possible to create a custom description for a product as well, which will be used instead of the default description.
I hope this will help.

Generic text in Short Description


Can the browser invalidate (valid) cache item if it's disk cache is full?

Question: Is it possible that if user with a full browser cache comes to my website and some my resources required to be cached (via Cache-Control header), then browser will remove some old (but still valid, i.e. non-expired) items from the cache in order to make it possible to cache my resources?
If there is no outdated resources in user's cache, will the  browser ignore my cache policy?
Answer: If the cache is full the browser has to find room for new content somewhere.
A sane approach to this would be to
<code> 1) first remove all expired contents.
 2) second remove oldest (based on time since last visit) contents
</code>
But, to be honest with you I have never looked deep into this issue because I find it counter productive to rely on cached contents. Many browsers have a "delete all cache on exit" button. Or the users run programs like CCleaner to remove temporary files. Cache is basically considered temporary files.
I suppose you could try writing a server log analyzer that would determine whether specific resources are being reloaded at a time when companion resources are not being loaded. This would involve separating the header-only call that is used to determine "age" of the resource vs. the full download of the resource. Again mostly speculation since, I don't rely on cache being there AND I don't use cache as a tracking device.


Power supply for toothbrush motor

Question: I would like to connect an electric toothbrush motor (Braun Oral-B Type 4729) directly to external power supply. So far I have been trying at least 3 different DC power supply unit with appropriate voltage (1-5 V) but nothing happened. However motor works perfectly fine when connected just to a regular battery (AA, 1.5V)...what is happening? The only guess I have is some impedance mismatch between the source and the motor...can anyone confirm this and/or provide any solution how to connect this motor to regular DC power unit?
Thank you very much!
Comment: Does the motor still work on an AA battery? I tried to the the exact same thing you're doing, but I somehow destroyed it. I still don't know why. I had my supply set to 1.5V.
Comment: Yes, the motor is OK, I did not manage to destroy yet. It seems that it is really the problem this initial current consumption...not even regular phone charger (5V) cannot do it. At the moment it works on one of the power supply I have with the current limit pushed till the end (2 A)...but even in this case the performance is not smooth: time to time I need to give some initial push by hand that motor starts rotating. I will try now by putting this extra capacitor as suggested below.
Answer: If this motor runs when directly connected to a 1.5 V battery, then it will run when connected to any other 1.5 V source.
The reason it doesn't run with your other power supplies is probably because the motor demands more current than the supplies can supply, and they shut down or reduce their voltage.
Note that motors take more current when starting than when running.  Your supplies might be rated for the running current, but never get there because they shut down or collapse due to the starting current demand.
You can easily verify this.  Put a voltmeter across the supply and see what happens when you connect the motor.  You will see the voltmeter go to 0.
The solution is to get a supply that can handle the current requirements.  If a AA battery works, then a couple of amps should be good enough.  With a benchtop supply, you can set it to 1.5 V, then adjust the current limit to see what it takes to allow the motor to get going.
Another thing to try is to connect a large capacitor across one of your existing supplies before you connect the motor.  If the capacitor is large enough, it can source the initial current to get the motor going, then the supply can catch up and source the current to keep the motor running.  At this low voltage, you can get sufficiently large caps.  I'd try something like 10 mF or more rated for 10 V.
Answer: One thing I have seen in some toothbrushes is how the circuit is completed when the cap is fitted over the battery.
If, when you use the external supply, this connection is not completed then it will not work.
Comment: Perhaps also, but if I just connect the motor two pins with regular AA battery it works perfectly.

Power supply for toothbrush motor


Boats in Philadelphia Story

Question: Why do Katherine Hepburn and Cary Grant spend so much time talking about boats in The Philadelphia Story? I understand that the True Love, their yacht, is a metaphor for their relationship. What specific advantages does the boat metaphor have though?
Answer: It's a way to talk about their relationship, without talking about it directly. George would not take kindly if Dexter and Tracy started to rehash their marriage, but talking about the boat let's them skirt this.
It further allows Tracy to admit she wasn't very "yar" and for Dexter to admit his foibles.  It also allows the establishment of the fact that Ms. Imbrie was at their honeymoon sailing taking pictures until Dexter tossed her camera into the ocean. This in turn provides reinforcement that Dexter is at heart a stand-up guy because he paid for the camera (and for the others he destroyed).
But I think the biggest reason for the boat is Tracy's reaction to Dexter considering its sale.  She explodes and says won't stand for it.  If we take it as a metaphor, she's says she doesn't believe in exploiting their relationship for profit, which echoes Dexter's sentiment "I had the strange notion that our honeymoon was our own". Yet, Tracy's fiance, George, shows himself willing to treat their marriage as an asset to be used as needed. This is another signal that they may not be destined to be together.

Boats in Philadelphia Story


Color of an object as a Variable in Illustrator

Question: Is it possible to have the color of an object as a Variable?
In my particular case I want to change the color of a rectangle with my datasets.
Comment: @Ovaryraptor thanks for answering. Where do you put that switching statement? is it some kind of scripting? thanks
Comment: I didn't read your question correctly. https://helpx.adobe.com/illustrator/using/data-driven-graphics-templates-variables.html might help you in the right direction.
Answer: Please see my LinkedIn article here: https://www.linkedin.com/pulse/illustrator-variable-data-advanced-techniques-recoloring-vasily-hall/
It describes the usage of a menu-item script in the batch action which processes each dataset with a custom routine which colorizes shapes. The script called "Recolor.jsx" takes variable data from text frames associated with a variable field and uses it as a parameter for its function in setting document object colors. You can make creative uses of all the various application methods and their parameters.


Is vaping e-liquids halal?

Question: I quit smoking and am willing to vape 0 nocotine e-liquids, but I read a lot about e-liquids that they contain VG and PG in their ingredients. Can anyone confirm if PG is fine and not haram?
Answer: Aslamu Walaykum
Brother, do not use these cigarettes, all of them are haram. The PG ingredient is haram, and whatever it is even liquid. They are haram. It is better if you do not use these nicotine mysterious cigarettes which are harmful to your health and to your iman as well.

Is vaping e-liquids halal?


/sbin/nologin default PATH

Question: I want to add the PATH of the default for the user where a shell is set in /etc/passwd by /sbin/nologin.
I write PATH in /etc/csh.login or /etc/profile,csh in case of bash or csh is OK.
What about
/sbin/nologin?
Answer: If you set the shell for an account to /sbin/nologin (on my system it's /usr/sbin/nologin) then if someone tries to login under that account, they will get a message that says the account is unavailable. There is no PATH or /etc/csh.login or /etc/profile for that situation.
This is separate from the /etc/nologin file. If that file exists, no user other than root can login. The contents of that file will be displayed if they try. This is useful when the administrator is about to do a shutdown or otherwise change the runlevel of the system and doesn't want additional users logging in.
Answer: Using /sbin/nologin will refuse any kind of SSH login for that user.  This is useful for service accounts (i.e. apache, mysql) to prevent anyone from using them to login remotely.  Typically you could also set a user to /sbin/nologin if they are just an FTP user as well.
Comment: hi Brent, thanks for the response! But note that we don't allow signature blocks here. Feel free to put it in your user page profile though: http://serverfault.com/users/27299/brent-frye
Answer: Try changing the path in /etc/environment.   Put /opt/jdk6.0/bin in front of /usr/bin.  However, /usr/bin should be a symbolic link to an appropriate Java version. On Debain or Ubuntu you can use update-alternatives to modify then entry.  However, in that case you should consider installing the sun-java package and not run Java from /opt.

/sbin/nologin default PATH


Expected number of running heads in coin toss

Question: How to find the expected number of running heads of a specific length (say 'k' exactly) in 'n' tosses of a coin (fair/biased). For example, consider the output of a coin toss as follows "THHHTHTHHHTTTHHTHHT". The number of running head of length 1,2 and 3 are 1,2 and 2 respectively.
Answer: Index the tosses by $i=1,2,\ldots, n.$  Let $X_{i;k}$ be the indicator of the event "a run of exactly $k$ heads terminates at toss $i.$"  From the formula of expectation (as the product of values by their probabilities), the expectation of any indicator is its chance of being $1:$
$$E[X_{i;k}] = \Pr(X_{i;k}=1).$$
When the coin has a chance $p$ of heads (independently at each toss) and therefore a chance $q=1-p$ of tails, the independence assumption shows the chance that $X_{i;k}=1$ must be the chance of $k$ heads preceded and followed by either (a) a tails or (b) the terminus of the sequence.  Thus,

When $i\lt k,$ $\Pr(X_{i;k}=1)=0.$

When $i=k,$ $\Pr(X_{i;k}=1) = p^kq$ if $k\lt n$ and otherwise $\Pr(X_{i;k}=1)=p^k.$

When $k \lt i \lt n,$ $\Pr(X_{i;k}=1)=p^kq^2.$

When $i=n$ and $n\gt k,$ $\Pr(X_{i;k}=1)=p^k q.$

Let $N_{k;n}$ be the number of runs of exactly length $k$ in the sequence.  Since
$$N_{k;n} = \sum_{i=1}^n X_{i;k},$$
taking expectations gives
$$E[N_{k;n}] = \sum_{i=1}^n E[X_{i;k}]$$
yielding

$$E[N_{k;k}] = p^k,$$
$$E[N_{k;k+1}] = 2p^kq,$$
and generally for $n\ge k+2,$
$$E[N_{k;n}] = 2p^kq + (n-k-1)p^kq^2.$$
Comment: Thank you very much @whuber.


Should "in-cabin" be hyphenated in "the dogs must ride in-cabin on the airplane"?

Question: Would the term in-cabin be hyphenated or not? As in, the dogs must ride in-cabin on the airplane.
Comment: I say yes, but there are at least two other questions that address this https://english.stackexchange.com/questions/12494/when-is-it-appropriate-to-use-a-hyphen , which is a duplicate question itself.
Comment: @EdwinAshworth Could you provide a link to an example of non-hyphenated predicative usage? I know such examples must exist and would like to include them in my answer. But when I looked for them in the course of writing my answer, I was having trouble locating one.
Comment: I can't find a dictionary to validate this choice, but airlines (who one might well consider authoritative enough here) seem to hyphenate in-cabin used attributively but not predicatively. Which follows the usual rule of thumb.
Comment: [This is anecdotal but looks to be the writings of a competent Anglophone.](https://www.tripadvisor.co.uk/ShowTopic-g1-i26969-k9272414-Do_airlines_actually_weigh_pets_for_travel_in_cabin-Traveling_with_Pets.html) Of course, headlinese would look the same.[Another example](https://www.tripadvisor.co.uk/ShowTopic-g294262-i1747-k10867098-Strollers_policy_for_Singapore_Airlines-Singapore.html). /  I'd say that neither form is unacceptable; also, 'in[-]cabin' is a compound adverb / adverbial after 'carried' say.
Answer: If it is used like an adjective would be, then it should definitely be hyphenated. If used like an adverb would be, then either hyphenated or non-hyphenated is probably fine, though my impression is that the hyphenated use might be more common.
As Edwin Ashworth pointed out, dictionaries do not record in-cabin as a compound word, but there are plenty of attested examples where it is used like one. I will provide some below.
The key question is whether there is any alternative to interpreting in-cabin/in cabin as a compound word. The obvious one (which is really the only one) is that it might be better read as a prepositional phrase (PP). If it is indeed better read as a PP, then it shouldn't be hyphenated. But if there is no possibility to read it as a PP, then it definitely should be. And if it can be read as either, then either hyphenated or not hyphenated is fine.
When used like an adjective would be
Normally, PPs cannot function as pre-head modifiers in noun phrases (NPs), and so we must consider in-cabin as a compound adjective in such cases:
Take the amp on the plane as i͟n͟-͟c͟a͟b͟i͟n͟ luggage. (source)
aviation laws limiting the quantity of liquids permitted in i͟n͟-͟c͟a͟b͟i͟n͟ luggage. (source)
In the above, in-cabin is used attributively, but there are even instances where it is used as a predicative complement:
For a sound experience that is i͟n͟-͟c͟a͟b͟i͟n͟ but out-of-this-world. (source)
There are three ways for pets to travel by air. The first is i͟n͟-͟c͟a͟b͟i͟n͟ with the passenger as carry-on. (source)
When used like an adverb would be
PPs routinely function as adverbials: put it i͟n͟ ͟t͟h͟e͟ ͟c͟a͟r͟, traveled b͟y͟ ͟t͟r͟a͟i͟n͟, located o͟n͟ ͟y͟o͟u͟r͟ ͟l͟e͟f͟t͟. The only issue with in cabin is that cabin is a count noun in the singular, so we would normally expect a determiner in front of it, like this:
Pets up to approximately 5 kg are allowed to travel i͟n͟ ͟t͟h͟e͟ ͟c͟a͟b͟i͟n͟. (source)
However, there is precedent for dropping the determiner in PPs. For example, we say that we travel b͟y͟ ͟b͟u͟s͟, go t͟o͟ ͟c͟h͟u͟r͟c͟h͟, appear o͟n͟ ͟t͟e͟l͟e͟v͟i͟s͟i͟o͟n͟, talk b͟y͟ ͟t͟e͟l͟e͟p͟h͟o͟n͟e͟, etc. What is common to all these cases is that the noun doesn't refer to a particular object but to some generalized notion, a type: a type of transport, institution, media, and communication, respectively.
So perhaps we can say travel in cabin and mean a type of travel: one where e.g. a dog rides in the cabin as opposed to in the storage area.
There are attested examples of such usage:
He wished to ride i͟n͟ ͟c͟a͟b͟i͟n͟. (source)
On the other hand, there is also precedent for combinations preposition+noun becoming compound adverbs:
I'll do my best to stay o͟n͟-͟t͟o͟p͟i͟c͟. (source)
what a candidate does o͟f͟f͟-͟s͟t͟a͟g͟e͟ (source)
(Note however that there is also a PP version of the latter: occurring, as it does, o͟f͟f͟ ͟s͟t͟a͟g͟e͟ (source). But the OED does record offstage as an adverb, where some of the examples of such usage that it provides use the hyphenated form off-stage. Confusingly, however, some of its examples leave it as two non-hyphenated words. With all due deference to the authority of the OED, I would suggest these cases have been mischaracterized and that off stage is a PP rather than a single compund adverb there.)
And indeed, many sources do use in-cabin as a compound adverb:
Korean Air allows small pets to travel i͟n͟-͟c͟a͟b͟i͟n͟ for $200 a piece. (source)
Dogs who can comfortably fit under the seat are permitted to ride i͟n͟-͟c͟a͟b͟i͟n͟. (source)
Your furry friend is too large to travel i͟n͟-͟c͟a͟b͟i͟n͟. (source)
For animals that are not traveling i͟n͟-͟c͟a͟b͟i͟n͟, the ARK strongly recommends... (source)
Therefore, it seems that when in-cabin/in cabin is used like an adverb would be, both the hyphenated and non-hyphenated versions are OK.
Comment: "Normally, PPs cannot function as pre-head modifiers in noun phrases (NPs)" — Can they not? I can think of plenty of PPs that are quite happy to function as NP modifiers (normally hyphenated): an out-of-body experience, an on-the-spot solution, by-the-hour rentals, etc. It's not particularly _common_ for PPs to modify in this way, but it doesn't seem right to state that PPs normally _cannot_ act as such. The impediment seems more semantic than syntactic to me. (Nonetheless, +1. It's a good, authoritative answer, and I have no idea why anyone downvoted it.)
Comment: @JanusBahsJacquet: the second part of that sentence explains why your proposed counterexamples aren't, according to linguisticturn's analysis: "so we must consider in-cabin as a compound adjective". I assume linguisticturn would say that out-of-body, on-the-spot, and by-the-hour are likewise "compound adjectives" in the phrases that you mention.
Comment: @sumelic That's rather circular logic, though. PPs cannot be modifiers, so when we see PPs that act as modifiers, they must be compound adjectives; therefore, there are no PP modifiers. I have no problem calling them compound adjectives as such, but the statement that PPs cannot act as modifiers is at least unsubstantiated in this answer.
Comment: @JanusBahsJacquet: Yes, this answer doesn't seem to explain why these are considered to be "compound adjectives". I'd be interested in seeing more on that. I think "a very on-the-spot solution" feels acceptable. I'm not sure if it is impossible for "very" to modify PPs, though (a [related question](https://english.stackexchange.com/questions/83952/when-can-very-modify-a-prepositional-phrase) doesn't seem to give a clear answer; I think I remember seeing some other discussion of this somewhere in relation to a Safire article, but I forget where).
Comment: @sumelic  A question for both of you: I really disagree that this question is a duplicate, simply because one of the issues is the grammatical status of the word group. First of all, do you agree? And if you do, what would be the best way to challenge that marking?
Comment: @JanusBahsJacquet: I'm also not sure about whether it's true that "compound adjectives" are always hyphenated.
Comment: @JanusBahsJacquet: Oh, the "very" issue came up in my answer to a previous question by linguisticturn (I still am not sure about whether it has a satisfactory answer): [In the PP 'near here', why is 'near' the head?](https://english.stackexchange.com/questions/380113)
Comment: @JanusBahsJacquet Thank you both for the comments! I'm thinking about how best to answer them (without simply appealing to the authority of CGEL, which just states that PPs don't appear in that function, though some single prepositions like *downstairs* do). I may change my mind about some things int he process, too...
Comment: @sumelic I definitely plan to address the comments both of you have made, but it might take a bit of time.
Comment: There seems to be a difference in pronunciation between _He travels
in-cabin_ and _He travels in cabin._ The latter of which sounds wrong.


German Websites for Literature?

Question: Are there any German websites for literature, like Goodreads? Or for that matter German book shops like Amazon.
Comment: Goodreads supports multiple languages and German features prominently among them. I keep track of all my books there, regardless of language. There are German book shops, too, of course, starting with amazon.de, buch.de and buecher.de
Answer: If you're looking for classical (as in older) literature, give the Gutenberg Project a try, it has tons of Ebooks with texts in the public domain. You'll find lots of classical German texts from Authors like Goethe and Schiller.

German Websites for Literature?


Marking mail as spam in Thunderbird

Question: Is there an easy way to flag mail as spam within Thunderbird? I get heaps of spam and having to go deep within the menu to create custom rules and name them different things every time I want to block a string of messages is quite annoying. Gmail has a quick button, so does Thunderbird?
Answer: There's a flame icon in the list of mails received. Click on the small round button in that flame column, and it will mark it as junk/spam.
Comment: I've done that before but I don't know if it actually does anything? Do you know what it does? Will it prevent me from getting mail like that in the future?
Comment: It adds the post to a junk filter log, which I presume "learns" what is spam and what isn't. It isn't clearly told what it does: https://support.mozilla.org/en-US/kb/thunderbird-and-junk-spam-messages (search for: "Training the junk filter")
Comment: Ok, I had to set another filter to do something with the spam, otherwise all it does it mark it as junk and remains going to your inbox. I just redirect it to spam folder now.

Marking mail as spam in Thunderbird


Error handling from JS remoting

Question: We are using JS remoting.  Found this interesting race condition:

JS Remoting AJAX request made by user.
Before it completes the user moves to another page
When user moves browser to another page the js remoting ajax request is aborted.
The abort invokes the error handler and we have a generic error handler which pops up a dialog showing exception info.
In some cases, the dialog will flash up for a second because the page navigation away hasn't completed.

This looks ugly and we would prefer if the error handler knew there was a page unload happening and not show the error dialog if this was happening.
So, I tried adding a page unload listener and setting a flag in that which can be subsequently checked.
jQuery(window).unload(function() {
    unloadhappening = true;
});

This approach will work in most ajax designs but won't with JS remoting.  JS remoting, calls the error handler before the unload event.  Not sure why?
I tried the earlier beforeunload event:
jQuery(window).on('beforeunload', function() {
    unloadhappening = true;
    return '';
});

This won't work because this event just shows up another dialog.
So I tried to add a listener to all anchor tags that have a http(s) hyperlink
jQuery('a[href^=http]').click( function() {
    unloadhappening = true;
})

This won't work for relative URLs.
So I tried to adding a listener to all anchor tags that have a href
jQuery('a[href]').click( function() {
    unloadhappening = true;
})

This will filter out components that won't work because it won't filter out components that don't trigger a page unload such as:
   Advice

So before I go and write a selector to filter out anything with a fragment identifier, there are also some anchors that are coming form JQuery UI that do:
   Today

I am starting to think this is a more of a hack that will never work as opposed to a solution.  Do you have a good idea for this problem?
The only idea I can think of is to check the exception, error, event info returned by
JS remoting for an aborted request.  I see: Strings:
Unable to connect with Server

and
Communication Failure

But that error message is also used when a JS remoting ajax request is aborted because of network failure in the middle of an ajax request - not just because it is aborted because of navigation to another page.  If you want different error handling for the two it is impossible to differentiate between them.
Note I have to use JS Remoting here. Using forceTK etc is not an option.  So I am wondering has anyone else seen this and if so what is your solution?
Thanks
Comment: Have you tried a "native" `window.onunload=function(){ SomeJavaScriptCode };` javascript function? I have the problems with for example `jQuery(document).ready()` function. Then i've tried the `window.onload` iand it works in realy all cases.
Comment: I can confirm that I've run into this problem as well, and also have yet to find a solution.
Comment: Can you share the generic exception handler youve written?
Answer: Recently I have found out one problem in JS remoting in salesforce is that It doesnot work with the Enter key. For eg. If you hit any key apart from enter My JS script is calling. On every Event it is working but when I it enter it does not work. Then to verify the same I have put if statements to catch the key value == 13(Enter key Ascii code) to verify if it is Enter key issue only.
TO my observation I am correct the issue persists with enter keyevent. Normally JS remoting will listen until the response is returned from the apex class. But on hitting enter key it escapes every thing and just executes the complete code and exit. It will not at all listen for the response. Infact I have seen in the logs with enter key it is skipping the JS remoting call.
Please check if same is the case with your event your are trying.
Comment: You can use `event.preventDefault()` if you want to keep Enter from submitting the form (and thus cancelling your AJAX request).
Answer: Are the error handler invocation and the unload event are fired at almost the same time?
If so, you could add a css or js animation to introduce a slight loading delay to the error dialog and then hide it when the unload event fires.
If you still need a hand, it would be much easier to help you if you create a minimal example and post the code.

Error handling from JS remoting


How do I get my baby blue tongue skinks to get used to being held?

Question: When ever I try to pick them up they tend to run away. They have never hissed or bitten me, but I would like to be able to hold them.
Answer: I have no idea about lizards, but I would guess they end up being like any other pet or human in this regard.
Would you like a foreign person to grab you and put you on their lab or carry you somewhere else? No? Then what is with a child that even asks to be held by their parents? That's different.
With someone you trust, being held or pet or cuddled is a nice thing. That is not only because you know they won't harm you, but also because you know that they know and acknowledge your boundaries. Which means, if you want them to stop, they will stop.
For your lizards that means you will have to earn their trust. With rabbits you could feed them out of your hands, sit in the room while they run around and let them sniff and discover you at their pace.
I am sure there are some similar options for lizards. Just try to be close, but never intrusive.
Then you can try petting them, if you think they would be comfortable with it. As soon as they look uncomfortable, stop!
Bit by bit, both of you will get to know each other, earn each others trust and learn to read the signs given by each other. You will know that you won't be bitten (unless you don't read the signs and go on after your pet is uncomfortable) and your pet will know there is no reason to run away or bite (unless you behave strangely and carry that box with the veterinarian smell on it).


Quicksort with insertion sort

Question: Okay so I have implemented quicksort with insertion, where K is a value until which the recursion occurs and then rest of the array is sorted using insertion sort. Now I am comaparing 3 different algorithims for sorting (quick , merge and quicKInsert). My question is is there a scenario where quickInsert out performs quick sort and merge sort
running time for QuickInsert would be O(nK)+O(n log n/݇K)
I have to find out a combination of N(number of elements) and K value to outperform other two sorting algos
What I have tried is using k = log N did not work
I know insertion sort beats quick sort in small numbers but how do I find out combination based on that. Am I missing something here
Comment: It should possible to do an analysis of the number of comparisons. Would that suffice or do you need the actual running time?
Comment: @Michel: Comparisons and assignments. People often don't just sort integers. They might sort C++ objects (expensive to assign with a copy constructor, slightly better if you have a move constructor), or they might sort reference-counted pointers, also slightly expensive to move.
Comment: You can bind (as in upper bound) the number of assignments in terms of the number of comparisons and estimate what your actual data cost at most to move. But I assume you know that in any case.
Answer: The running time (and how it changes) of any algorithm implementation will vary across platforms (hardware, operating system, compiler etc) and the input data. So it looks hard to find a simple relation for the array size up to which insertion sort will perform better than quick sort (and that too for all inputs).
Perhaps what we can do is assume the platform factors would remain fixed and use some representative input arrays. Then test and measure time (avoiding other system noises) to find the threshold array size $K$ below which insertion sort becomes faster. Use this $K$ in the hybrid quick/insert sort to delegate to insertion sort.
Answer: Asymptotic complexity evaluations are not appropriate to decide which implementation is the fastest, and the best you can do is to rely on empirical evaluation.
This said, there will be no absolute answer because the running time of an algorithm is not a deterministic function of the problem size. On the opposite, it is a complete statistical distribution, which is uneasy to catch.
What you can do is

select running conditions which you think are typical in your use case(s). Usually this information is not available. You can rely on random arrays, which will give you an idea of the expected time. But better measure the standard deviation based on several runs with different data.

working on the same arrays, try increasing values of k. Compare the times to the standard version, and conclude which is better when the averages are significantly different (say to two sigmas).

Now you can plot the relation between n and k that gives the best results.
Answer: Big-O is only relevant for large values. It won't help you at all trying to find the optimal K.
For Quicksort, you obviously would stop recursing for a subrange of 1 number which will be already sorted. You may very well handle subranges of length 2 differently as well like
<code>if r ≤ l + 1
    if r > l and a [l] > a [r]
        exchange a[l], a[r]
    return
</code>
So now you just choose K = 3, 4, 5 etc., measure the time for the combination of quick sort with insertion sort, for a range of typical arrays, and decide depending on your measurements. It is entirely possible and actually likely that for different machines the optimal K is different. If the optimal K is not trivial in size you'd also try insertion sort with binary search to find the position where to insert.

Quicksort with insertion sort


What are the state-of-art techniques in capturing carbon dioxide and/or converting it to oxygen and their challenges?

Question: It seems there are multiple chemical reactions (from this question and internet in general) where $CO_2$ can be converted to $O_2$. If this is the case, can someone please explain the challenges (manufacturing, setup costs, raw material scarcity etc) we are facing in reducing $CO_2$ in atmosphere? Also, what are the state-of-the-art techniques used to reduce $CO_2$?
Answer: There may be potential in carbon capture using the carbon silicate cycle to our advantage. The carbon silicate cycle occurs on geologic timescales, but "enhanced rock weathering" seeks to speed up the process by finely grinding basalt or silicates, giving them greater surface area and greater exposure to air.
Scientists in the first article found using their model that

Applying a fixed rate of 10 tons of basalt dust per hectare on these sites sequesters 64 gigatons of CO2 over a 75-year period; when extrapolated to all agricultural land, ERW sequesters 217 gigatons of CO2 over the same time interval.

217 gigatons of CO2 is not trivial, although distributing 10 tons of basalt per hectare over all agricultural land is also not trivial. There is discussion on its viability because of cost of implementation, and the fossil fuels that will be used to mine the basalt or whatever type of substrate, and then distribute it.
edit: I feel compelled to add that of course, this is not a remotely viable solution itself. The only solution is a push towards complete decarbonization immediately.
Answer: Carbon capture and storage (CCS) and direct air capture (DAC) are massively energy intensive processes. So a large barrier to deployment is finding the energy to run the capture plants.
Since we emit so much CO2 from our power generation it's better to just turn off that power generation than use any of the resulting energy to then partly undo the process done in the power station. So in a world with any energy generation from fossil fuels, it basically makes no sense to use energy on capturing carbon, we should just turn off that energy generation.
There are some tiny carbon capture plants operating in Iceland since they have an abundance of geothermal energy.
After/if we transition to renewable energy it will still take energy/resources to build renewable energy infrastructure. Energy doesn't suddenly magically become free. So the massive energy bill of trying to capture carbon is still going to be a problem. As ever, the best solution is to stop emitting carbon dioxide. Carbon capture is pushed hard by oil companies for several reasons, and one of those is that it justifies them continuing to profit off destroying the atmosphere for decades more while they watch their delaying tactics play out.
Answer:
Also, what are the state-of-the-art techniques used to reduce $\text{CO}_2$?

That the easy part of the question to answer: Drastically reduce human use of fossil fuels, thereby drastically reducing the amount of fossil fuel based $\text{CO}_2$ into the atmosphere. Humanity is partway on the path toward achieving that. Multiple solutions do exist.
As for the rest of the question, there are no other viable solutions. Most proposed alternatives don't scale up well, most are ridiculously expensive, many have lots of nasty side effects, and many turn out to be not carbon neutral due to energy consumption (assuming energy production remains fossil fuel based).
Comment: Reducing the amount of fossil fuel used globally every year (something we have not achieved yet!) will most likely only reduce the annual *increase* of $CO_2$ in the atmosphere. Even if *all* emissions from fossil fuels stopped today, the amount of $CO_2$ in the atmosphere would be reduced only very slowly: the number I have seen is that it would require a full century of a zero-emission scenario to reduce atmospheric $CO_2$ back to pre-industrial levels.


Django Ninja API schema circular import error

Question: I have UserSchema:
# users/models.py
class User(AbstractUser):
    ...

# users/schemas.py
from typing import List
from tasks.schemas import TaskSchema

class UserSchema(ModelSchema):
    tasks: List[TaskSchema] = []

    class Config:
        model = User
        ...

...and TaskSchema:
# tasks/models.py
class Task(models.Model):
    ...
    owner = models.ForeignKey(User, related_name="tasks", on_delete=models.CASCASE)

# tasks/schemas.py
from users.schemas import UserSchema

class TaskSchema(ModelSchema):
    owner: UserSchema

    class Config:
        model = Task
        ...

But it throws:
ImportError: cannot import name 'TaskSchema' from partially initialized module 'tasks.schemas' (most likely due to a circular import) (/Users/myname/codes/django/ninja-api/tasks/schemas.py)

What I want to do is that I want to fetch:

GET /api/todos - a list of tasks with related owners
GET /api/todos/{task_id} - a task with owner
GET /api/users/{user_id} - a user with a list of owned tasks

Versions:
python = ^3.11
django = ^4.1.5
django-ninja = ^0.20.0

Answer: You can check if the name of the two models or file name is the same or not if that also does not work then tell them to make a model in the same file or add that one in the same file so circular data will not happen.
Hope this will help you.


What's the best new feature/change of iOS7.0.1, iOS7.0.2, and iOS7.0.3?

Question: One feature/change per post.  Please search the current answers before listing yours.  If it's difficult to explain with words, please use pictures.  Changes that can increase productivity of the user, consumption of media are likely to attract more votes.  The change could have been made in any current revision of iOS7, but has to still be available in iOS7.0.3.
Answer: My favorite new feature is the ability to 'reduce motion' via Settings > Accessibility > Reduce Motion.
When enabled, the animation for launching an app and going to the home screen are greatly reduced, which allows me to access the phone from its locked state more quickly, and is more valuable to me than having zooming animations.


How do I place a progress bar in AndEngine?

Question: I am developing game using AndEngine. I need to place a progress bar in my game to denote time remaining in the game. Is there a built-in method for doing this in AndEngine? My searches only turned up results for Android, not for AndEngine.
Answer: If you simply need to have a progress bar alongside your game you can use the LayoutGameActivity which was added for that purpose. LayoutGameActivity allows you to place the andEngine View into a standard Android layout which is loaded from XML, rather than using its default layout. As mentioned in the article, this is accomplished by overriding getLayoutID() and getRenderSurfaceViewID() in your game LayoutGameActivity class.
For example:
@Override
protected int getLayoutID() {
        return R.layout.xmllayoutexample;
}

@Override
protected int getRenderSurfaceViewID() {
        return R.id.xmllayoutexample_rendersurfaceview;
}

Code fragment from the linked forum post.
Answer: You could also just vary the width of a simple rectangle over time, or if you want to have it nicer, stitch together a couple of sprites.


Integrating the Office 365 and/or Windows Live credentials in to our website like FB and Twitter

Question: I have a requirements like this, Integrating the Office 365 logins or Windows Live logins in to our website, means like Facebook and Twitter I will show one button on login page, onclick of that button user needs to redirect to Office 365 login page and needs to fill the login details. After successful authentication user need to redirect back to the site and register to our site as a user. I tried to find API for Office 365 but couldn't able to find any.
This is for WordPress website, I found WPOffice 365, but I doubt that will it work for all Office 365 credentials?
One of my friend used this plugin, but he said, he tried many ways but he stuck with configuring the AAD APP and he is continuously getting this error with that plugin. And WPOffice 365 support is paid.

ERROR: Insufficient privileges to complete the operation.

And I found Auth0, but I didn't find Office 365 in their providers list.
Can any one have any idea to integrate Office 365 in to our application?
Thanks in advance and any help here is much appreciated.
Answer: I found the answer my self, this plugin and its working as expected with out any issues.


Where am I wrong in this reasoning?

Question: We know that $\log \det (X)$ is a concave function if $X$ is a positive definite matrix. Furthermore, we know that $\det (X^{-1})=(\det(X))^{-1}$ which means that $\log \det(X^{-1})$ is a convex function if $X$ is positive definite. However, we know that the inverse of a positive definite matrix is a positive definite matrix and therefore $\log \det(X^{-1})$ should also be a concave function for $X$ being a positive definite matrix. Where am I wrong in this reasoning?
Comment: Please learn to write an *informative* (not generic) title, so others can find the problem and solution later.
Comment: @Frank: How do you justify your last argument that $\log\det X^{-1}$ should be concave? Have you tried an analogous argument for $\log x^{-1}$ on the positive reals?
Comment: @NicNic8: You are mistaken, $\log\det X$ is indeed concave in $X$.
Comment: @NicNic8 I mean if the domain of this function is constrained to the positive definite matrices only then its a concave function. Surely if we fix the input then its a constant.
Answer: Your first argument is correct, for as you noted when $X\succ 0$,
$$
\log\det(X^{-1})=\log((\det(X))^{-1})=-\log\det(X),
$$
which is the negative of a concave function, hence convex.
Your issue with the second argument is you seem to be using the "claim" that if $f:C\to \mathbb{R}$ is concave, where $C$ is a convex set, then for any invertible map $\phi:C\to C$, $f\circ \phi$ is still concave because it has the same domain. But that clearly is not true: consider $f:\mathbb{R}_{>0}\to \mathbb{R}$ given by $f(x)=x$, and $\phi:\mathbb{R}_{>0}\to \mathbb{R}_{>0}$ given by $\phi(x)=1/x$. $f$ is concave on this domain, while of course $(f\circ \phi)(x)=1/x$ is well-defined and convex on the same domain, but your reasoning would suggest that it should be concave as well.
Answer: That "therefore" makes no sense. See what happens with the real numbers greater than $0$: $\log(x)$ is concave and $\log\left( x^{-1}\right)=\bigl(-\log(x)\bigr)$ is convex, not concave.

Where am I wrong in this reasoning?


Does the density of the brushes used in a DC motor increase efficiency?

Question: I'm doing a science paper about DC motors and efficiency and I need to test one part to see whether or not the efficiency increases or decreases. I think I will do the brushes and I'm wondering if the density of the brush affects the power outage/efficiency of a dc motor at all.
Comment: Density? Brush parameters would be material, force, contact area, thickness (amount of wear they can tolerate), maybe a few others, what do you mean by *density?*
Comment: By density, do you mean the density of the material the brushes are made from or the number of brushes in close proximity to each other?
Comment: By density I mean the... thickness of the brush?
Answer: Several aspects of brush design have some effect on DC motor efficiency. That would include friction, brush resistance, and contact resistance or contact voltage drop. Those items would be partly determined by brush dimensions and material. The effect would be influenced by armature voltage, current and operating speed and perhaps some other factors.
For carbon brushes, brush resistance is simply the resistance of the brush material. The resistivity is determined by the composition of the brushes, graphite, a binding additive and sometimes copper powder and other metal powders. Some very small motors have spring brushes made of metal alloys.
Comment: Could you elaborate on brush resistance a bit more? Thanks!


How to swap a specific weapon for a new weapon during a supply drop in MGSV: TPP

Question: I currently have two primary weapons equipped. I want to change one of these primary weapons for a different weapon. I order a supply drop, and this arrives. How do I specify which of my two primary weapons should be replaced by the new weapon?
Answer: The two primary slots are for different types of weapons. The first is for your rifles, shotguns etc. and the second is for your heavy weapons such as the sniper rifles, machine guns and launchers.
If your supply drop is a heavy weapon it will replace your current heavy, otherwise it will replace your primary in the first slot.
Comment: @Jim On a side note, you should take a look into alternate solutions for grenade launchers. If you don't use pistols much, the Zorn KP is a pistol that fires grenades, similar to a rifle grenade. And once you recover the Legendary Gunsmith, and get access to weapon customization, you can develop two of the single-shot grenade launchers to be mounted underbarrel on any weapon with an underbarrel attachment option.
Comment: Thanks for clarification: I was using a grenade launcher, which went in the first slot but meant I was a bit underequipped when dealing with enemy soldiers. Will see what suitable weapons I can develop that go into the second slot...


How difficult is Whimsyshire?

Question: I've never been to this place and I was wondering how difficult it was compared to the "real" game (at the same level of difficulty).
For instance I killed Diablo in Hell without much trouble, would Whimsyshire in Hell be a bigger challenge?
Answer: I have only experienced Whimsyshire on Normal difficulty, but the monsters there were on par with what you face in Act IV. I brought a level 24 friend along and he was getting stomped pretty hard (but not oneshotted). I, as a level 32ish wizard at the time, found the creatures appropriately challenging to my level.
I would assume that in higher difficulties, Whimsyshire is similarly scaled to be roughly equivalent to Act IV of that particular difficulty.
Comment: I can confirm this is the case for Normal, Nightmare, and Hell (still working on the Inferno staff), +1
Answer: If you can do the difficulty higher on Act I with minimal problems, I'd say you are ready for that difficulty of Whimsyshire.
So if you can take Nightmare Act I, you are ready for normal Whimsyshire.
Note that with a group of 4, this can change drastically. Soloing will not be a problem at this point however.
Answer: Also note that there are no ranged monsters in Whimseyshire, aside from possibly the Mortar mod on elites.  Depending on your character, this might make it significantly easier than similarly-leveled areas.

How difficult is Whimsyshire?


How much electricity can be produced by my thermoelectric generator?

Question: I am using a thermoelectric cooler from a pc's heatsink to produce electricity. Its size is 30mm by 30mm. I will cool it on one side at -10 degree Celsius and the other at 24 degree Celsius. Can anyone tell me how much electricity in watts will be produced. I'm using this heatsink cooler because it's the most easily available to me. Can anyone suggest an even better thermoelectric generator? Also how much electricity it would produce and how much it will cost?
Comment: "thermoelectric generator". All Engines work by using a hot and cold heat sink. You will probably get the best possible efficiency using Stirling Engine attached to a standard alternator. However, 34K/300K ~ 10%(approximately maximum efficiency not possible) the is hardly anything.
Answer: The details of how your particular device will perform is very much a function of how that device was constructed and how it will be used, but in general, the physical effect is called the Seebeck effect -- briefly, the conversion of a temperature difference across a device to a voltage.
Efficiency for such devices is actually quite low, with $\eta = 0.02$ (2% efficiency) being a typical value.
See this manufacturer's web site for many more details.  You may also wish to search for datasheets for particular devices (they're usually called Peltier coolers after the inverse physical effect and more typical application) to get more details about specific device performance.
Answer: You'd be lucky to even generate 1 Watt.  Compare yours to this much larger 10 Watt generator intended to operate off hundreds of degrees of temperature difference:
http://www.devilwatt.com/products/17-10-watt-camping-stove-thermoelectric-generator


FME Data migration for Feature class with Attachments

Question: I want to migrate data from one point feature class to another point feature class in same Database schema using FME job.  I can easily do this task without using any transformers.
But now both point feature classes (reader and writer) has attachment tables. Attachment table has created by using arc catalog. The feature class and its attachment table have some relations.
Can anyone please let me know how i can migrate data for attachment tables while I do data migration between feature classes?
Answer: This might be accomplished easier with a Python script using ArcPy.  However, you could create an FME Workspace to create the Match Table independent of using the Generate Attachment Match Table Geoprocessing tool, but I'm not entirely sure if Arc makes more than one table here.
To create an ArcPy script you can export a model from ModelBuilder using Model => Export => To Python Script.  Creating the model should be fairly easy:  Insert => Add Data or Tool... and select your data.  Then use that same menu to add System Toolboxes => Data Management Tools => Attachments => Generate Attachment Match Table.
To create the table from FME you'll add your reader(s) then you'll want to use the Matcher transformer to match your data together based on your Selected Attributes.  Then pass the Match ID Output Attribute along with the ObjectIDs to a writer for the Match Table.  UNfortunately I don't know the naming scheme for these Match Tables.  You'll want to name the table appropriately so Arc recognizes it.


Do teaching an advance course helps in evaluation and tenure?

Question: Do teaching an advance course helps in promotion or it does not matter?
Comment: Do you mean relative to not teaching at all or to teaching first-year undergraduate courses?
Comment: This is certainly a naive question, but it is inarguably natural, and touches on operational issues, I think, even if the asking is itself not particularly thought-through.
Comment: @schester relative to teaching first or second year courses
Answer: Within my U.S. math department, teaching a successful, energetic, research-oriented graduate "topics" course is a plus inside the department. It is also essential, within the department, to have demonstrated "acceptable" capacity to teach bread-and-butter courses, such as ... calculus.
The engineering departments that determine the course of the "college of science and engineering" (due, I imagine, to the size of external grant funding... and the concommitant "overhead") view math, physics, and chemistry fundamentally as "service" departments, and, indeed, the size of these departments is hard to justify on any practical grounds except for the hordes of freshman and sophomores taking filtering/weeding/service courses. In any event, when tenure cases reach the "college" level, demonstrated success in teaching those lower-division courses is considered essential ... research success is taken for granted, and considered of mostly internal interest to the department, not to the college... and minimal involvement or non-involvement with lower-division teaching can ... upset... the engineering faculty.
So, at that level, it would be unwise to have exclusively done advanced teaching, even if "only" at an undergraduate level.
Within the department, it shows a certain kind of energy, I think, because it may well require more psychological effort to do the best job with higher-level material than to do an acceptable job with low-level material aided by a phalanx of teaching assistants. But there seems to be a watershed in preferences about teaching graduate courses, so new faculty preferences in that regard are mostly construed as a matter of taste or opinion, not essential.
Comment: Clarification: I'm at a large "state" university, perhaps one of the better, but still subject to a different political weather than privates, etc.


Paragraphs : white space and left indent in the same piece

Question: I understand that I should not use white space in between paragraphs and indent on the left to separate the same paragraph. But is it alright to go in novel writing from one to another? For instance, to use the white space between paragraphs to show passage of time and left indent for everything else?
Comment: I certainly prefer both, when I'm reading someone else's work.  (As an amateur author I end up reading a lot of the works of others of a similar status, and the combo of spacing + about a 4 char indent is far easier to parse as you're scanning a page of choppy paragraphs.)
Answer: Are you self-publishing or submitting your novel to literary agencies?
If you're submitting to agencies, it's a tricky one because you will get a different answer to this depending on which novel formatting website you visit.  Some say indent every paragraph except the first, others say indent every paragraph.
When submitting to agencies, I was told to never use a book as a formatting guide for a submission, the two formats have nothing in common. The publisher lays out the book format, not you.
So, when submitting, I indented every line, including the first, and used white space to show passages of time. My submission (I'm UK based) was very well received with this formatting and my agents haven't asked me to change this before we submit to the publishers.
If you are submitting, the important thing to keep in mind when stressing about the formatting of your manuscript is that agents and in-house editors are human. As long as you have followed their submission guidelines to the letter, and your MS is in a clear, easy-to-read format, e.g. TNR font, 12 point, double spaced, they won't reject you if you don't indent the first line.
But, personally, I would indent every line.
HTH


Display Bundle Products in Category Listing When Bundle Options Not Set

Question: I create new bundle product in magento without any bundle option selection.
I assign category,store and inventory same as simple product.
I check that product not display in category products listing.
If I create bundle option than it's display there.
I want to display all bundle products in category listing even if bundle option not set because of display product information in website.
Answer: A bundle without options does not make sense, it's incomplete.
If you need a placeholder product that is not purchasable, for product information, it could be a simple product that's out of stock or gets a special attribute which you check in your template to hide price and "add to cart" button.
If for some reason it must be a bundle, you could create one option with one dummy simple product that's out of stock.


Will I really not come off as rude even if I don't say thanks in comments?

Question: Will I really not come off as rude even if I don't say thanks in the comments? The comment box prompts me to not write thanks, but I often see people with several 100 reps say thanks in their comments? Is upvoting or checking as solved without saying thanks really enough and is the norm here?
Comment: Thanks in comments are just noise. You don't need to do it, upvote instead.
Comment: Yes it is perfectly the norm to not say thanks here. It's not a continuous chatroom but a question and answer site. Feel free to flag all the other "thanks"-comments as "too chatty" or "obsolete", especially if the answer was accepted anyway.
Comment: see also http://meta.stackexchange.com/questions/198669/do-most-question-answerers-prefer-gratitude-or-reputation-more - your upvote does come to the attention of the answerer (though we may not know it's you) and expresses your gratitude
Answer:
Will I really not come off as rude even if I don't say thanks in their comments?

Yes.
That's how we do things here.
No thanks needed. If you want to thank an answerer - upvote/accept the answer.
Comment: Just wanted to add - I know I'm guilty of having done this since joining...but now having read this question I'll feel comfortable to just upvote now knowing that this is the community culture here. One point though: It could help to have an "introduction" page for members giving them a feel for how the community works
Comment: @Bendy: You mean, like [tour]?
Comment: @AlE.yes along those lines but something that would give new members an idea on the "culture" how to write questions/answers succinctly and that people don't want/expect 'noise' of comments just saying thanks etc


Is it haram to read about sex just for fun?

Question: When I had free time I would love to read, but due to COVID I can't access any 'real' library books, so I just started reading online books. After some time in reading though I started reading characters having sex, I didn't know what it was at first but after some research I started to realize what is it. I try not to read but it's just so addicting, I really am trying to stop because I don't know if it's haram and I want to stop but I just can't. Every time I try blocking that book it comes back into my mind and I read it again. After I read it I feel regret and ask for forgiveness. I always wish I hadn't read it but once again it'll come into my mind and I'll read it and therefore the cycle restarts. I don't know if it's good or bad and I don't know how to stop. What should I do?
Answer: Hadith
وعن أبي هريرة رضي الله عنه أن النبي صلى الله عليه وسلم قال:
كُتب على ابن آدم نصيبه من الزنا مدرك ذلك لا محالة: العينان زناهما النظر، والأذنان زناهما الاستماع، واللسان زناه الكلام، واليد زناها البطش، والرجل زناها الخطا، والقلب يهوى ويتمنى، ويصدق ذلك الفرج أو يكذبه"
 ((متفق عليه وهذا لفظ مسلم، ورواية البخاري مختصرة))
Abu Hurairah (May Allah be pleased with him) said:
The Prophet (ﷺ) said, "Allah has written the very portion of Zina which a man will indulge in. There will be no escape from it. The Zina of the eye is the (lustful) look, the Zina of the ears is the listening (to voluptuous songs or talk), the Zina of the tongue is (the licentious) speech, the Zina of the hand is the (lustful) grip, the Zina of the feet is the walking (to the place where he intends to commit Zina), the heart yearns and desires and the private parts approve all that or disapprove it."
[Al-Bukhari and Muslim].
This is the wording in Muslim; Al-Bukhari wording is a bit short.
Sunnah.com : Book 18, Hadith 112
Arabic/English book : Book 18, Hadith 1622
Riyad us Saliheen
Never go near this as it can lead you to zina which is an major sin.do act which Allah love e.g prayer fasting
Hadith
حَدَّثَنَا عَبْدَانُ، عَنْ أَبِي حَمْزَةَ، عَنِ الأَعْمَشِ، عَنْ إِبْرَاهِيمَ، عَنْ عَلْقَمَةَ، قَالَ بَيْنَا أَنَا أَمْشِي، مَعَ عَبْدِ اللَّهِ ـ رضى الله عنه ـ فَقَالَ كُنَّا مَعَ النَّبِيِّ صلى الله عليه وسلم فَقَالَ
 مَنِ اسْتَطَاعَ الْبَاءَةَ فَلْيَتَزَوَّجْ، فَإِنَّهُ أَغَضُّ لِلْبَصَرِ وَأَحْصَنُ لِلْفَرْجِ، وَمَنْ لَمْ يَسْتَطِعْ فَعَلَيْهِ بِالصَّوْمِ، فَإِنَّهُ لَهُ وِجَاءٌ "

Narrated 'Alqama:
While I was walking with `Abdullah he said, "We were in the company of the Prophet (ﷺ) and he said, 'He who can afford to marry should marry, because it will help him refrain from looking at other women, and save his private parts from committing illegal sexual relation; and he who cannot afford to marry is advised to fast, as fasting will diminish his sexual power."
Sahih al-Bukhari 1905
In-book : Book 30, Hadith 15
USC-MSA web (English) : Vol. 3, Book 31, Hadith 129  (deprecated)
Sahih Bukhari
Indulge in dhikr . there are many differnt dhikrs e.g for evening and morning which will rise our level in paradise.
Comment: While reading this hadith, we are still reading about that. isn't it?
Comment: What do u mean??i am sorry but i dont understand ur question.
Comment: Please mark your quotations as such to make them clearly distinguishable from your own words.
Answer: AoA,
I have experienced this, and reading sex stories is not explicitly haram, but it is definitely not halaal either.
The best way is to repent for any sins done, and to believe in god and pray for forgiveness with all true intention.
Hope this helped!
-Amber
Comment: please stop spreading lies
Answer: In this question, the expression "for fun" is the main criterion. In this case, the question is summarized in لهو and لعب:
(إِنَّمَا الْحَیاةُ الدُّنْیا لَعِبٌ وَ لَهْوٌ 47/36)
The (appearance of) life of the world is just palying and entertainment, while you were believed and Godwory, God will give you reward ... In this verse, God will reward who has Godwary (التقوی).
"لعب" is an action that has a kind of imagination to achieve a fantasy goal, and "لهو" is an entertainment job that is busy and deviate from the main gauls. So keeping a job that is not necessary will weaken faith.
On the other hand, being forbidden is a credit. For a person who is lost in the desert and is very hungry, eating a forbidden animal is also a solvent (albeit to survive). Means that only in certain conditions, forbidden actions could be done; Let's observe "for fun". In whole, whatever weakens faith, reduces man from the degrees of heaven and reduces his place. The less of "for entertainment", is the greater of the faith.


What is this insect in North Carolina?

Question: This insect is in my house in North Carolina, USA. I think it shares similar body features of that of a wasp, but it is far too narrow and has what appears to be a long stinger. What is it?
Comment: The long stinger is an ovipositor. (https://en.m.wikipedia.org/wiki/Ovipositor?wprov=sfla1)
Answer: This is some species of ichneumon wasp.
The ichneumon wasps are parasitoid wasps in the order Hymenoptera. They commonly parasitize other invertebrates, especially larvae and pupae of Coleoptera, Hymenoptera, and Lepidoptera.
Specifically, this appears to be Dolichomitus irritator.

 Photo credit:  Thomas wilson
Here's another specimen of the same species found in Weymouth Woods-Sandhills Nature Preserve, Southern Pines, Moore County, NC:

 Photo credit:  Dorothy Pugh
You can find additional high-quality images from Jeff Tome's Flickr page.
I could not find too many sources with good information about this specific species. Fontanelle Forests' Nature Search provided the most complete info:

Description: 7/8 inch long, not including the ovipositor.  The head and thorax are black.  The abdomen is red-orange.  The legs are yellow and orange.  The antennae are black.  The black ovipositor is at least as long as the body and head.
Ecology: Parasitoids of many woodboring insect larvae including long-horned beetles, weevils, metallic wood-boring beetles and some moths that are wasp look-alikes.
Taxonomy: In the subfamily Pimplinae, which has 180 species in 28 genera in North America.
Comment: Thank you very much, I thought it had to do something with wood
Comment: @Evander_C Some additional info: the long ovipositor has a purpose, but it isn't used for making holes in wood. Other species, like solitary bees lay eggs in existing or newly made holes. They make small walls between each egg (actually they also put eggs with females deeper into the wood). The longer your ovipositor, the more eggs the wasp can reach. A beautiful example of Ecology and evolution if you ask me.

What is this insect in North Carolina?


Find votes by current user on a post

Question: i'm building an application where users can submit posts and vote on them.
I need to find a way to allow users to delete their vote.
I started a private method called correct_user under my votes_controller, but I don't quite know how to pull the current user's vote id to a specific post. I figure once I have the ID I can pass it through to an instance variable where I can call the vote_path(@vote), method: :delete on it.
However, right now I don't quite know how to pull the proper id for a vote by a specific user on a specific post.
I did @vote = current_user.votes.find_by_id(params[:id]) in my current user method, but obviously that's not working. Not really sure how to pull this off. Any help would be great.
votes_controller.rb:
before_filter :correct_user, only: [:destroy]

def destroy
  @vote.destroy
  flash[:notice] = "Your vote has been deleted"
  redirect_to root_path
end

private

def vote_params
  params.require(:vote).permit(:user_id, :post_id, :up)
end

def correct_user
  @vote = current_user.votes.find_by_id(vote_params[:post_id)
  redirect_to root_path if @vote.nil?
end

and from my views:
<%= link_to "delete", vote_path(@vote), method: :delete %>

Answer: I ended up putting this in my delete link:
vote_path(link.votes.where(user_id: current_user).first)
I will have to refactor and clean this up a bit, but that's what answered this question.

Find votes by current user on a post


.NET C# running application from UNC results in error

Question: I have an application which does not read ANY files from the local disk or does not try to write anything.
It runs perfectly on the local filesystem, but it needs to run on a few 100 workstations, so I put it on a share on a Win2003 server.
But when I try to start it on a XP workstation from the UNC:
system.io.fileloadexception
What can be the issue here?
Answer: The issue is that the XP machine is likely running an earlier version of .Net 2.0.  Up until 3.5 SP1 it was a violation of CLR security policies to run a .Net application from an UNC share.  To do so you must tweak the CAS (Code Access Security) policy on the local machine.  Starting with 3.5SP1 this requirement was removed.
More Details:

http://geekswithblogs.net/robz/archive/2008/08/19/.net-framework-3.5-sp1-no-more-need-for-caspol-on.aspx
Comment: Thank's I suggested the sysadmin to upgrade to the latest .NET version, I hope this will solve the issue!
Answer: Only applications on the local file system have full trust to run. Try following the steps on this site:
http://dotnetdud.blogspot.com/2009/01/how-to-give-file-share-fulltrust.html
Answer: .Net code access security might be one of reasons. You can adjust it in thru control panel and change the settings for "Local intranet" zone. The best solution is to create a custom policy, however.
Answer: it is because of limited permissions. as far as i remember, if you go to explorer and find that exe, right click on it, you will see tab for extending permissions for app.


Time period of bar pendulum

Question: Why does the time period of a bar pendulum first decrease and then increase when the distance of the axis of rotation from the centre of gravity increases?
Answer: The period of a pendulum executing small angle oscillations is given by
$$T = 2\pi\sqrt{\frac{\mathcal{I}}{mgr}}$$
where $\mathcal{I}$ is the moment of inertia about the axis of rotation and $r$ is the distance from the center of mass to the axis of rotation.
For your situation, use $r$ as a variable. The moment of inertia can be found using the parallel axis theorem to be $$\mathcal{I}=m\left( \frac{\ell^2}{12}+r^2\right)$$, where $\ell$ is the length of the bar.
Plot $T$ as a function of $r$ and you'll have your answer. Arbitrarily choose a value for $\ell$ (1 or 2). Start $r$ at some small value. Mathematically, $\mathcal{I}$ is increasing in the numerator while $r$ is increasing at a different rate in the denominator.

Time period of bar pendulum


How do you watch a variable in pdb

Question: I'm debugging a python script, and I want to watch a variable for a change (much like you can watch a memory adress in gdb).  Is there a way to do this?
Comment: @WayneWerner: https://stackoverflow.com/questions/46822154/how-to-watch-a-variable-in-pudb
Answer: data breakpoints with pdb

...much like you can watch a memory address in gdb...

GDB uses data breakpoints, this is made easy with hardware support (hardware watchpoints), this typically involves marking the memory pages read-only which then trips an exception handler on memory access. When hardware watchpoints are not available it uses software watchpoints, these are only useful in single threads and are much slower.
PDB does not support data breakpoints, so the short answer is NO, you cannot do it with PDB out of the box.

printing variables when hitting breakpoints in pdb
For watching a variable when you are hitting a breakpoint, you can use the commands command. E.g. printing some_variable when hitting breakpoint #1 (canonical example from pdb doc).
(Pdb) commands 1
(com) print(some_variable)
(com) end
(Pdb)

Additionally, you can use the condition command to ensure the breakpoint is only hit whenever the variable takes a certain value.
eg:
(Pdb) condition 1 some_variable==some_value

other solutions
You can use tracing / profiling functions to examine things step by step using sys.settrace and checking out the opcodes being executed.
Here is some code to get you started:
import sys
import dis

def tracefn(frame, event, arg):
    if event == 'call':
        print("## CALL", frame)
        frame.f_trace_opcodes = True
    elif event == 'opcode':
        opcode = frame.f_code.co_code[frame.f_lasti]
        opname = dis.opname[opcode]
        print("## OPCODE", opname)
    return tracefn

watchme = 123

def foo():
    global watchme
    watchme = 122

sys.settrace(tracefn)

foo()

You will probably need to spy on all the STORE_* opcodes. https://docs.python.org/3/library/dis.html
Comment: While it can be useful, it doesn't directly answer the question, which wants to watch for changes to variables, and then break at those changes, not just view the state of a variable at preset breakpoints.
Comment: This should be the top answer. Easy, direct, teaches you a neat feature of pdb - the breakpoint commands.
Comment: some variable like `j` seem be used as abbreviation `jump`. I want to pring `j`, could I do that or change the variable name?
Answer: For Python 3:
you can use display functionality of pdb
Once you hit the breakpoint just type
ipdb> display expression
example:
ipdb> display instance
display instance: <AppUser: dmitry4>
ipdb> display instance.id
display instance.id: 9
ipdb> display instance.university
display instance.university: <University: @domain.com>

ipdb> display

Currently displaying:
instance.university: <University: @domain.com>
instance.id: 9
instance: <AppUser: dmitry4>
ipdb>

as you can see, each time you type display - it will print all of your watches (expressions). You can use builtin function undisplay to remove certain watch.
You can also use pp expression to prettyprint the expression (very useful)
Comment: If you are watching for changes in a loop, add a `break ` and every time you `c`ontinue you will get your display shown. Display is pretty handy.
Answer: Here is a really hacky way to do this with pdb. These commands can be put in your ~/.pdbrc for automatic loading every time you use pdb.
!global __currentframe, __stack; from inspect import currentframe as __currentframe, stack as __stack
!global __copy; from copy import copy as __copy
!global __Pdb; from pdb import Pdb as __Pdb
!global __pdb; __pdb = [__framerec[0].f_locals.get("pdb") or __framerec[0].f_locals.get("self") for __framerec in __stack() if (__framerec[0].f_locals.get("pdb") or __framerec[0].f_locals.get("self")).__class__ == __Pdb][-1]

alias _setup_watchpoint !global __key, __dict, __val; __key = '%1'; __dict = __currentframe().f_locals if __currentframe().f_locals.has_key(__key) else __currentframe().f_globals; __val = __copy(%1)

alias _nextwatch_internal next;; !if __dict[__key] == __val: __pdb.cmdqueue.append("_nextwatch_internal %1")
alias _stepwatch_internal step;; !if __dict[__key] == __val: __pdb.cmdqueue.append("_stepwatch_internal %1")

alias nextwatch __pdb.cmdqueue.extend(["_setup_watchpoint %1", "_nextwatch_internal"])
alias stepwatch __pdb.cmdqueue.extend(["_setup_watchpoint %1", "_stepwatch_internal"])

This adds two commands, nextwatch and stepwatch which each take a variable name varname as an argument. They will make a shallow copy of the current frame's local variable for varname if possible, and keep executing next or step respectively until what that name points to changes.
This works in CPython 2.7.2 but relies on some pdb internals so it will probably break elsewhere.
Comment: I copied the macros into my ~/.pdbrc file. However pdb tells me: NameError 'nextwatch' is undefiened. I Fall it like this: "nextwatch'(var)
Comment: I am use python 3.5, mac, and it seems `.pdbrc` is not working. Even when I paste the code above into `(pdb):` environment, when I run `stepwatch` or `nextwatch`, it says `__dict` and others are not defined. Could you update your code for python 3.5? thanks
Comment: As mentioned, this probably won't work in some other versions of Python. You are welcome to post a Python 3.5 version as a new answer.
Answer: A possible solution is to use pdb++:
pip install pdbpp

Then "mark" the object you want to watch with the decorator @pdb.break_on_setattr:
from pdb import break_on_setattr
@break_on_setattr('bar')
class Foo(object):
    pass

f = Foo()
f.bar = 42    # the program breaks here

Here pdb will break on any change of the attribute bar on any Foo-object.
Caveats
Only invocations of the underlying __setattr__-method will trigger the breakpoint. This means that f.bar = 'XYZ' and setattr(f, 'XYZ') will work, but manipulating the bar-object will not trigger the breakpoint:
f.bar = []
f.bar.append(7) # will NOT trigger breakpoint

f.bar = 2
f.bar += 5      # will trigger breakpoint

Note: @break_on_setattr is not part of the standard pdb-module. pdb is overridden/monkey-patched by the pdbpp-package.
You can also wrap an existing object (via its class) after pdb.set_trace():
(Pdb++) import pdb
(Pdb++) pdb.break_on_setattr('tree_id')(self.__class__)
(Pdb++) continue

Comment: This should be the accepted answer. Works like a charm, super simple.
Answer: Here is my version of Michael Hoffman's solution adopted for ipdb and python 3.7 (changes related to checking of class type and has_key for dict):
!global __currentframe, __stack; from inspect import currentframe as __currentframe, stack as __stack
!global __copy; from copy import copy as __copy
!global __Pdb; from IPython.terminal.debugger import TerminalPdb as __Pdb
!global __pdb_list; __pdb_list = [__fr[0].f_locals.get("pdb") or __fr[0].f_locals.get("self") for __fr in __stack() if ((type(__fr[0].f_locals.get("pdb")) is __Pdb) or (type(__fr[0].f_locals.get("self")) is __Pdb))]
!global __pdb; __pdb = __pdb_list[0]
alias _setup_watchpoint !global __key, __dict, __val; __key = '%1'; __dict = __currentframe().f_locals if (__key in __currentframe().f_locals) else __currentframe().f_globals; __val = __copy(%1)
alias _nextwatch_internal next;; !if __dict[__key] == __val: __pdb.cmdqueue.append("_nextwatch_internal %1")
alias _stepwatch_internal step;; !if __dict[__key] == __val: __pdb.cmdqueue.append("_stepwatch_internal %1")
alias nextwatch __pdb.cmdqueue.extend(["_setup_watchpoint %1", "_nextwatch_internal"])
alias stepwatch __pdb.cmdqueue.extend(["_setup_watchpoint %1", "_stepwatch_internal"])

To use it for python 3.7 and pdb change definition of __Pdb as given below:
!global __Pdb; from pdb import Pdb as __Pdb

Answer: Both existing answers have some essential trouble.
Directly doing it in pdb, or using some hacks to implement watchpoint, can ONLY work when you are in the same scope. It won't work when you get out of the frame.
def change(var):
    var.append(1)

a = []
change(a)

It can't catch what happens in the function, only knows after change(a), the variable a is changed. This works when the function is trivial, but in reality, the function could be so deep that what is valuable is inside. Or it could be worse, a could be returned and passed around, and never change in current scope. Then you'll never catch it.
The __setattr__ method works ONLY if you can create your own class. It can't deal with the simple situation I mentioned above. For many cases, having a new type of object is not acceptable. For example, if you are working with built-in dict or list.
I would recommend a library called watchpoints.
It is much easier to use than pdb(if you are not familiar with it already) and it covers way more situations than either of the solutions in this thread.
The only thing you need to do is to watch the variable you want to watch.
from watchpoints import watch

a = []
watch(a)
a.append(1)  # will print the changes

The output would be
> <module> (my_script.py:5):
>     a = 1
a:
0
->
1

It works with built-in types(including immutable ones), self-defined classes, and even attributes and index. For example, you can do watch(my_obj.my_attr) and it will just work.
You mentioned pdb so there might be something extra you want to achieve than simply knowing the variable is changed. watchpoints supports pdb pull up, as breakpoints() works.
You need to config watchpoints by
watch.config(pdb=True)

Then watch stuff as above. pdb will be brought up when the variable is changed. You can q(uit) the pdb and it will be brought up the next time the variable is changed.
You can refer to the github page for more usage for the library.

How do you watch a variable in pdb


What does Object... mean?

Question:
Possible Duplicates:
What does "…" mean in Java?
Java array argument "declaration" syntax

Can anyone confirm if I'm right in seeing the Object... parameter in the method call below:
public static void setValues(PreparedStatement preparedStatement, Object... values)
    throws SQLException
{
    for (int i = 0; i < values.length; i++) {
        preparedStatement.setObject(i + 1, values[i]);
    }
}

As an array of type Object? I don't recall seeing ... before in Java.
Comment: @Jigor Joshi: That one is closed itself as Duplicate.
Comment: Thanks to the respondents here. I had never seen ... before in Java.
Answer: It's equivalent to Object[], but allows the caller to just specify the values one at a time as arguments, and the compiler will create an array. So this call:
setValues(statement, arg1, arg2, arg3);

is equivalent to
setValues(statement, new Object[] { arg1, arg2, arg3 });

See the documentation for the varargs feature (introduced in Java 5) for more information.
Answer: From the Java Tutorial (Passing Information to a Method or Constructor):

Arbitrary Number of Arguments
You can use a construct called varargs
  to pass an arbitrary number of values
  to a method. You use varargs when you
  don't know how many of a particular
  type of argument will be passed to the
  method. It's a shortcut to creating an
  array manually (the previous method
  could have used varargs rather than an
  array). To use varargs, you follow the
  type of the last parameter by an
  ellipsis (three dots, ...), then a
  space, and the parameter name. The
  method can then be called with any
  number of that parameter, including
  none.

public Polygon polygonFrom(Point... corners) {
    int numberOfSides = corners.length;
    double squareOfSide1, lengthOfSide1;
    squareOfSide1 = (corners[1].x - corners[0].x)*(corners[1].x - corners[0].x)
            + (corners[1].y - corners[0].y)*(corners[1].y - corners[0].y) ;
    lengthOfSide1 = Math.sqrt(squareOfSide1);
    // more method body code follows that creates
    // and returns a polygon connecting the Points
}

You can see
  that, inside the method, corners is
  treated like an array. The method can
  be called either with an array or with
  a sequence of arguments. The code in
  the method body will treat the
  parameter as an array in either case.
Answer: What you are looking at is a varargs parameter.  The documentation on it can be found here.
Varargs are equivalent to an object array, but there is syntactic sugar to make calling that method easier.  So the old way was (this code is from the document above):
Object[] arguments = {
    new Integer(7),
    new Date(),
    "a disturbance in the Force"
};

String result = MessageFormat.format(
    "At {1,time} on {1,date}, there was {2} on planet "
     + "{0,number,integer}.", arguments);

With varargs you get to write:
String result = MessageFormat.format(
    "At {1,time} on {1,date}, there was {2} on planet "
     + "{0,number,integer}.", 7, new Date(), "a disturbance in the Force");

Note that autoboxing helps here to convert the int 7 to new Integer(7) without you having to explicitly declare it.

What does Object... mean?


Output video to both file and pipe: simultaneously using FFmpeg Libav

Question: I have been trying to output video (from my webcam) simultaneously to both a file ('out.mkv') and pipe:
The file gets filtered frames, and the pipe: gets unfiltered rawvideo.
My frame rate is 30 fps. However, I am getting a far lower framerate in my file output.
Attached is the while loop which reads packets and writes them to output:
while (1) {
    av_read_frame(ifmt_ctx, packet);
    stream_index = packet->stream_index;
    StreamContext *stream = &file_stream_ctx[stream_index];
    av_packet_rescale_ts(packet,
                     ifmt_ctx->streams[stream_index]->time_base,
                     stream->dec_ctx->time_base);
    avcodec_send_packet(stream->dec_ctx, packet);

    while (ret >= 0) {
        avcodec_receive_frame(stream->dec_ctx, stream->dec_frame);
        stream->dec_frame->pts = stream->dec_frame->best_effort_timestamp;
        ret = filter_encode_write_frame(stream->dec_frame, stream_index,file_stream_ctx,file_filter_ctx, file_ofmt_ctx);
        ret = av_interleaved_write_frame(pipe_ofmt_ctx, packet);
    }
}

'ifmt_ctx' is the AVFormatContext for the webcam.
'file_ofmt_ctx', is the AVFormatContext for the pipe for the output file, and pipe_ofmt_ctx is the AVFormatContext.
'file_stream_ctx' and 'file_filter_ctx' are the stream and filter contexts used for filtering and encoding the file output.
My guess is that writing to the pipe is taking too long and not allowing the next packet to be read on time - causing a lower frame rate. Does that make sense? If so - any suggestions on how to fix it? (I tried using AVFMT_FLAG_NONBLOCK but it doesn't seem to help).
Thanks
Hillel
Comment: Does your console output when you run this complain about missing packets / dropped packets?  I typically see those warnings from the library when packets are being dropped because I can't consume them in time.
Answer: It is hard to tell without any profiling, but you're probably correct given what you're seeing.  I'd be curious to know if you eliminate one of the write outs if you see better performance.
I always write the packets or frames (depending on the case) into a queue and have a separate thread do writing.  You might even want two threads - one for the video (packet queue) and one for the frames.
As an aside, I think the line avcodec_send_packet(stream->dec_ctx, packet); consumes the packet, so when you use it later in ret = av_interleaved_write_frame(pipe_ofmt_ctx, packet); that seems like it wouldn't work.  You could try copying the packet and see if that helps at all:
av_packet_ref(new_packet, packet);
Assuming you've allocated new_packet of course.  Doesn't sound like what your seeing is this, so it might be OK what you're doing.  But something you could also try.


Text processor that is capable of Arabic

Question: I want to create some documents with Arabic text in them. I already tried several programs, but not of them can satisfy my needs, which I think are quite basic.
I want:

Multi-column text layout
Numbered lists with Eastern Arabic digits (٠١٢٣٤٥٦٧٨٩)
Correct display of glyphs depending on context
Tashkil, since I write texts for beginner learners
Formatting styles, so that I don't have to do the formatting individually
A program that runs on Microsoft Windows 10

I tried Microsoft Word 2010, which gets the job almost done, it just causes the wrong glyphs to be displayed.
I tried Microsoft Word 2016, which doesn't get the spacing of the letters correctly (see the third screenshot).
I tried Scribus, which cannot display Arabic text properly at all.
I tried Microsoft WordPad, which lacks formatting possibilities like text in multiple columns.
I tried LibreOffice 5.2, which cannot format a numbered list so that the numbers appear in Eastern Arabic digits (no bug report yet for this one).
Any idea which other programs I could try?
Answer: I would suggest SummitSoft Arabic Editor as it handles Arabic in just about every way imaginable.


Heat flux over a surface

Question:
I was able to answer the question logically but could not account for the exact values of fraction of the total radiation, so please give some good way to exactly calculate the fraction of the total radiation as detected by detector.
Please help.
Answer:
The source of the radiation is above O. Construct 3 more squares which are identical to $OBCD$ as shown in the diagram.

Similarly, construct 6 big squares to form a cube. The source of radiation is at the center of the cube, right above O. So each face of the cube would get $\frac{1}{6}$ of the radiation.
Now go back to the first image. Each face consists of 4 identical squares. The radiation hitting each face is shared equally by each part of the face. Therefore, the square $OBCD$ gets $\frac{\frac{1}{6}}{4}$, i.e: $ \frac{1}{24}$ of the total radiation.
Comment: This is a really lovely answer!

Heat flux over a surface


Mobile Battery Charge

Question: I just wanted to ask whether it is possible to voluntarily discharge a mobile phone's battery and transfer it onto another battery?
Comment: Not all of it. Any other questions?
Comment: No, not without some intelligence in between.
Answer: It is possible to tranfer the energy stored in one batery into another.  However, this is not as simple as just connecting the two batteries together.  If the batteries are of the same type, then that will cause each to be about equally charged.
Assuming batteries of the same type, the voltage of the one that is to be fully charged will end up higher then the one that is to be drained.  It would take a active circuit to transfer the energy.  That is possible, but there are various inefficiencies along the way.  The circuit won't be 100% efficient, and the receiving battery will lose some energy in storing and retreiving.  As a rough guess, you'd probably get only 1/2 or less of the energy from the first battery eventually to come out the second at best.
Comment: ...and a battery's optimal charging characteristics are very often very different from its own discharge characteristics, so even 50% transfer is **extremely** optimistic.

Mobile Battery Charge


How can you tell whether a disk is spinning (without sound/touch)?

Question: Is there a "programmatic" way to determine whether a disk is spinning or not (spinning, not necessarily reading/writing)?
Comment: It's always spinning unless it's sleeping. Check if the drive is sleeping perhaps?
Comment: I don't see anything in the SMART attributes.  There may be a way, but it would depend on the specific drive and controller.  You would have to read the specifications to find out if it is possible.  I seem to remember some old drives that had a bit that would be on for spinning.
Answer: Whether a disk is spinning depends on its power mode; typically the spindle motor will be running in "Active" and "Idle" modes, and stopped in "Standby" and "Sleep" modes. (It gets a bit more complicated with drives with NV cache power management, which I don't know enough about to cover here.)
If a drive is asleep it's definitely not spinning (or doing anything else, including communicating with the host); otherwise you can interrogate it about its current mode.
For an ATA drive, the "Check Power Mode" command will do this. Send the value E5 in the command register, and it will return FF in the sector count register if the drive is active or idle.
Doing that programatically is venturing into Stack Overflow territory, but here's a snippet of C that will do it on Windows:
int isSpinning = -1;
HANDLE hDevice = CreateFile(TEXT("\\\\.\\PHYSICALDRIVE0"), GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
if (hDevice != INVALID_HANDLE_VALUE)
{
    DWORD cb = 0;
    ATA_PASS_THROUGH_EX cmd = {sizeof(ATA_PASS_THROUGH_EX)};
    cmd.AtaFlags = ATA_FLAGS_DRDY_REQUIRED; /*  Require drive to be ready  */
    cmd.TimeOutValue = 3;                   /*  Arbitrary timeout (seconds)  */
    cmd.CurrentTaskFile[6] = 0xE5;          /*  "Check Power Mode" in command register  */
    if (DeviceIoControl(hDevice, IOCTL_ATA_PASS_THROUGH, &cmd, sizeof(cmd), &cmd, sizeof(cmd), &cb, 0))
    {
        /*  FF in sector count register means the drive is
            active or idle (and therefore spinning)  */
        isSpinning = cmd.CurrentTaskFile[1] == 0xFF;
    }
}


View of the Shu"t Min HaShamayim

Question: The Shu"t Min Hashamayim was written by a Rishon who would receive answers in dreams from Heaven. Is there a difference in Torah views regarding how to weigh the halachic perspective of such a work? (i.e. The Chida (Yosef Ometz 82) seems to favor the sefer at times, but do others agree/disagree/neutral leaning)
Comment: Very related: https://judaism.stackexchange.com/q/14912/13438
Answer: Rav Reuven Margaliot presents a survey of sources from Chazal through Acharonim in the introduction of his critical edition of Shu"t Min HaShamayim, in which he makes a very strong argument that dreams play a pivotal role in deciding Halacha, peshat in a Pasuk, and more.
Rav Ovadia has a few Teshvuot (Yabia Omer vol. 1 Orach Chaim 40-42, vol. 5 Orach Chaim Siman 43, vol. 9 Orach Chaim Siman 103:5; Yechaveh Daat 1:68) where he argues with the Chida and rereads some of the aforementioned sources in disfavor of asking Halachic questions Min HaShamayim. In fact, according to the Rambam, asking questions min hashamayim might be tantamount to Navi HaSheker! (middle of Yabia Omer 1:OC:40)
Comment: "In fact, according to the Rambam, asking questions min hashamayim might be tantamount to Navi HaSheker! (middle of Yabia Omer 1:OC:40)" @MDjava you really should bring the actual text on this from Rav Yosef in addition to your citation. It would be a surprise that he would be making the statement that argues Sh"ut Min HaShamayim is considered to be equated with the din of a Navi Sheker even according to Rambam.
Comment: Yabia Omer is not Me'ever LaYam or Bashamayim that you should have to cross the sea to get itכִּֽי־קָר֥וֹב אֵלֶ֛יךָ הַדָּבָ֖ר מְאֹ֑ד בְּפִ֥יךָ וּבִֽלְבָבְךָ֖ לַעֲשֹׂתֽוֹ׃. The sefer is readily available in many Batei Midrashot around the world.
Comment: It isn't about my access to my set of Yabia Omer. It's about improving your answer. You are making a very big statement of your understanding of Rav Yosef's response with only a page citation. For him to be stating that as he understood Rambam the Shu't Min HaShamayim (something quoted by many poskim as authoritative) to be compared to a false prophet is out of character with Rav Yosef, in general. Not impossible, but unusual. It deserves more than a simple page citation.

View of the Shu"t Min HaShamayim


What's a "worker", or a "worker name"

Question: Using a "worker" or "worker name" is often an option when you do pool mining. It is often exemplified by "rig1". But how do you create one, and what is its use?
Answer: In pool mining context a worker is simply a machine that mines the blockchain.
A rig

A mining rig is a computer system used for mining bitcoins. The rig might be a dedicated miner where it was procured, built and operated specifically for mining or it could otherwise be a computer that fills other needs, such as performing as a gaming system, and is used to mine only on a part-time basis. wiki

The rig1
Its a name to identify your machines when you connect it to a pool with a miner address. You can use the same mining address on different rigs and identify them with rig name, some pools show the rig name on the status page.
Answer: The pool I mine on reflects activity for "miners" and, as a subset, workers. I have yet to figure out how to designate the individual devices (gpus) as workers.
Answer: Its ecosystem and computer mining system in pool mining context a worker is simply a machine that mines the blockchain.

What's a "worker", or a "worker name"


Is there any way to access the storage of another pallet in Substrate-based blockchain?

Question: I'm trying to transfer the collection ID from relay chain to a parachain. I am currently accessing the collectionId from its storage, and I am wondering if there's a way to access the storage of the pallet_nft on another chain in order to facilitate the transfer.
Answer: Between two pallets in the same chain you need coupling between them to access the storage. An example about this in the Substrate FRAME repository is  between pallets bounties and child-bounties which are tightly coupled.
See this specific example where in pallet child-bounties access the storage of pallet bounties.
let parent_bounty = pallet_bounties::Pallet::<T>::bounties(bounty_id)
            .ok_or(BountiesError::<T>::InvalidIndex)?;

To query another pallet storage from another chain you have to construct an XCM call using the instruction Transact. It has been proposed by the main XCM ideologues on a previous StackExchange question: XCM Transact for interfaces and in this Post on the Polkadot Forum: XCM Storage Query.
You can find a similar example about what you achieve in the XCM docs Examples.


How shall we read the Kafka topics in a given time range?

Question: I need to read the messages in a given time range out of a Kafka topic. The solution that I can think of is to first find out the largest offset for the beginning of the time range, and then continue consume the messages until the offsets on all partitions past the end of the time range. Is there any better approach for solving this problem? Thanks!
Answer: Well, you definitely have to first search for the first offset which fits the opening of the time range.
This can be done using the KafkaConsumer#offsetsForTimes method.
The method accepts a map of Map<TopicPartition, Long(timestamp)>, and returns a Map<TopicPartition, OffsetAndTimestamp> where the timestamp in OffsetAndTimestamp is of the first message with timestamp Equal to or greater then the one specified.
From there, you can assign your consumer to the offset returned, and iterate until the timestamp in the record exceeds the end of your time range.
Some pseudo code:
static void main(String[] args) {
    String topic = args[1];
    long timestampBeginning = Long.parseLong(args[2]);
    long timestampEnd = Long.parseLong(args[3]);
    TopicPartition partition = new TopicPartition(topic, 0);

    Consumer<Object, Object> consumer = createConsumer();

    long beginningOffset = consumer.offsetsForTimes(
            Collections.singletonMap(partition, timestampBeginning))
                    .get(partition).offset();

    consumer.assign(Collections.singleton(partition)); // must assign before seeking
    consumer.seek(partition, beginningOffset);

    for (ConsumerRecord<Object, Object> record : consumer.poll()) {
        if (record.timestamp() > timestampEnd) {
            break; // or whatever
        }

        // handle record
    }
}

Comment: It's funny, because answering you made me understand that I can use the same method to do something similar in something I'm writing.
Answer: What you mean by saying "time range"?
Time range of what of the messages in queue or time stamp in the messages? :-)
What I would consider is to use Kafka Streams and windowed stream and either take messages out of stream with assumption that current time stamp of take message is the one from the range, then consider message, otherwise just ignore it.
On the other hand if you consider time stamps within the message, then small extention to the streamming (in java DSL .filter() method) will really good filter out messages for you. You just need to formulate good predicate.
See: Kafka Streams (Confluent) and Kafka Streams (Apache)


How do I run chef recipe from inside ruby code?

Question: From the Rails app I need to provision, configure and manage servers on Amazon AWS. Some time ago I've been using chef-solo and knife to do that, but from the command line. Would that be possible to do the same from inside the code? Any pointers on how to start?
Answer: I would suggest taking a look at chef-zero, it supersedes chef-solo as the way forward for running Chef without a central Chef Serer.  It also has the advantage of having a Ruby API so you don't have to shell out.
From the description:

Chef Zero is a simple, easy-install, in-memory Chef server that can be useful for Chef Client testing and chef-solo-like tasks that require a full Chef Server.