Using `selfdestruct()` to send back funds to stakers

Question: Currently, I deploy a contract via a Factory contract for staking. Think of it like UniSwap pools without swapping, short term contracts that I want to destroy after their use is done. But I also want to reimburse the original stakers and distribute the rewards post staking. What is the logic I should be using here? The one idea I had was use a specific reimburse function - and then destroy the contract. Any better ideas?
Comment: Maybe relevant for this https://ethereum.stackexchange.com/questions/91453/using-selfdestruct-in-constructor
Answer: In general it's much safer to let the users pull the rewards (and their stakes), instead of you pushing them.
I don't also see much point in destroying the contract. Just leave it there and users can come and claim their assets whenever they want - maybe tomorrow or maybe in 10 years.


Speedlite 430EX II & Canon 60D

Question: I have a Canon 60D and a Speedlite 430EX II.  Does anyone know if I can fire the speedlite remotely without firing the built in flash as well?  So far I have only been able to fire them both.
Answer: The 430EXII supports Canon's now older method of remote flash triggering, which uses flash pulses from the commanding unit to trigger the remote unit (430EX in this case). The newer system, based on radio, is supported by the 600EX-RT, and ST-E3-RT units.
Your system uses flash pulses, which fire BEFORE the shutter opens. So, even though you are seeing the flash on your 60D fire, it isn't necessarily contributing to lighting the scene, depending on how you have things configured.
The newer 600EX-RT system does not use flash pulses, so this problem does not exist. It can, and is supported by camera models that do not have a built-in flash, such as the 5DMkIII and 1DX.
Comment: @MikeV: Don't know Nikon that well, but Imaging Resource says the D3100 does NOT support Commander mode, the similar system to Canon's. FWIW, Nikon provided this feature in many cameras years before Canon. http://www.imaging-resource.com/PRODS/D3100/D3100FLASH.HTM
Comment: @MikeV, however, even without a CLS commander in the D3100's pop-up, the SB-700 does have SU-4 mode, which is a "dumb" optical slave mode. If you set the D3100's pop-up flash into M (vs. iTTL), and the SB-700 into SU-4, firing the pop-up will fire the SB-700. However, you'll have to set the off-camera SB-700's power level manually. The only thing communicated is the sync ("fire") signal.
Comment: Does this apply to a setup like a Nikon D3100 and a SB700 flash as well?
Comment: Actually, you can configure your external flash settings so that the on camera flash does, or does not contribute to the picture.
Comment: @Thanks guys... I have used it the way inkista has mentioned but I was wondering if there was a way to set it so it would pulse the flash prior to opening the shutter.  At the moment I am only able to make the SB700 go off when the on-camera flash goes off and although I set it to a negative compensation, it still affects my front light in the picture.
Answer: No, the pop-up flash on your camera has to fire to be a wireless master for the off-camera 430EXII.  The camera body and the flash communicate with light pulses ("pre-flashes"), so there will always be some firing of visible light pulses from the master.  You can set the pop-up flash not to contribute light to the image.  But light pulses are needed to set the remote flash's power, to perform any metering preflashes for eTTL, and, of course, to communicate the sync signal itself.
There's a little argument about whether or not the pop-up flash in master mode will fire during the exposure--some people say you can see it at macro distances or in mirror-selfie shots.  But for normal subject distances, whatever light is coming from the master is low enough not to register in the image. With Nikon, the commander definitely fires during the exposure, even when set to "--" (don't contribute); again, it won't register at normal subject distances, but Nikon also sells an IR filter to put over the pop-up flash if it becomes an issue.
However, there are limitations inherent in any optical triggering system. Typically this type of system works better indoors in lower light conditions.  The red sensor panel on the front of the flash (or side if you shoot Nikon) must be able to "see" the mastering light pulse. Indoors, with bounce surfaces, this requirement isn't particularly stringent. And in lower light, the mastering signal will register clearly. However, outdoors in bright sunlight, the story changes and range and reliability tend to decrease.  This is why radio triggering is so popular, and why Canon built it into the 600EX-RT and ST-E3-RT.
There are a wide variety of radio triggers these days that cover all kinds of functionality and price ranges--you don't have to get a 600EX-RT to wirelessly trigger a Canon flash over radio. Just keep in mind that you can typically only have two of the following three things with radio triggers: low cost, a lot of features, and reliability. :)
Answer: I don't have the 60D, but I had a T4i which also has a built in flash like the 60D. Yes, you are able to use the built-in flash to trigger an off-camera flash while NOT having the built-in flash contribute to the scene. You need to look in the camera flash settings - not the off-camera flash unit.  There is a setting there where you can choose to have the built-in flash to contribute, or alternatively, have it NOT contribute.
Answer: One thing I did while doing some off-camera flash work before I had the radio transcievers was to use optical triggering, but with a very low flash power relative to the flash power of the output units. It could possibly be a little unreliable, but optical triggering tends to be unreliable anyway, hence the recommendations for radio triggering systems.
Actually, you can buy radio transceiver pairs fairly cheaply - one sits on the bottom of the external flash, and one in your hotshoe. You lose all E-TTL functionality, but you lost that anyway when you took your 430EX-II off-camera.
I should also point out that generally, the bridge flash of such cameras are not so high output compared to dedicated speedlites. So even if your speedlite is at 1/16 and your bridge is at 1/16, there's probably already 2-3 stops difference (varying with the distance of the camera from the subject with respect to the distance of the flash to the subject).

Speedlite 430EX II & Canon 60D


Why is Krishna often addressed by his father's name - Vasudev?

Question: Why is Krishna often addressed by his father's name - Vasudev ? Is Vasudev also some kind of post , title or anything like that ?
Answer: According to Sanjaya -

From that, as far as I can make out, Keshava cannot be measured. Because he clothes all beings, because he is the womb of all the gods, he is known as Vasudeva."

731 (68), Yana-Sandhi Parva, Mahabharata.

According to lord Krishna himself -

"Assuming the form of Surya, I envelop the world and the universe with
my rays. Since I am the dwelling of all creatures, I am Vasudeva. O
descendant of the Bharata lineage! I am the destination of all
creatures and subjects."

Chapter 1656 ( 328), Moksha-Dharma Parva, Mahabharata
Answer: Though the name Vāsudeva also means Antaratma. Lord Krishna is called Vāsudeva mostly due to his father's name Vasudeva.
ŚB 10.51.39-40.:

Nonetheless, O friend, I will tell you about My current birth, name and activities. Kindly hear. Some time ago, Lord Brahmā requested Me to protect religious principles and destroy the demons who were burdening the earth. Thus I descended in the Yadu dynasty, in the home of Ānakadundubhi. Indeed, because I am the son of Vasudeva, people call Me Vāsudeva.

Note.: Lord Krishna's father is called Vasudeva (वसुदेव), whereas Lord Krishna is called Vāsudeva/Vaasudeva (वासुदेव).
Even Lord Rama and Lord Parshurama are called by their father's name.
Valmiki Ramayana.:

On receiving the deference paid by the sage Vashishta, that inexorable Rama of Jamadagni (jāmadagnyo) started to talk to Rama of Dasharatha (dāśharathim). [1-74-24].

I hope this clarifies all your queries. Prd..


Question about Shemitah years etc

Question: 20/01/15  Trying to find out- --I know a "shemitah" is a 7 yr. period. What confuses me is this: how do we know what specific years are the "shemitah" (e.g. Sept./07 to Sept./14
or Sept./08 to Sept./15. Then, is a "shemitah year" the 7th year of a "shemitah" or is it
the 8th year - e.g. the first year AFTER a "shemitah"?  I thought a "shemitah year" is the 7th year- e.g. Sept./13 to Sept./14. So then what year is the Jubilee year (This now being 50 years since the last Jubilee)- is it 2014-2015 or sept./15-Sept./16 ??
  I'm trying to nail down exactly (Gregorian) what are the 7 year periods*, the shemitah year, and the Jubilee year.  ---*I mean what year is the first year and what year is the 7th year (7th year being 2013 to 2014  OR 2014 to 2015, and is 2015 0r 2016 the Jubilee year. Know what I mean?  ----T Y V M
Answer: The Sabbatical year, "sh'viis" begins at Rosh Hashanah and actually occurs in years divisible by 7, such as the current year 5775. This isn't because they are counted since creation, but there was a tradition passed down since the time the 2nd Temple was destroyed as to when this year was.
Remember that during the Temple period the cycle was still used to determine years of Maaseh Sheini etc.
The actual regulations are a bit more complex. There are 3 issues: produce from the ground, produce from trees and recovery of debt. Produce from the ground is generally based on when it is reaped (although it is still forbidden to work the ground during the year), whilst fruit trees is when it budded and then I think Tu Bishvat (coming in 2 weeks time) is the start of the year for budding. Thus there is an issue with Shviis fruit well into next year.
With regards to recovering debt, the normal Minhag is that the Pruzbul document is written just before the end of the Shmitta year although there are a few who write one at the start.
The Yovel does not apply anymore and didn't apply during the 2nd temple period either.
With regards to the "Gregorian" calendar, the year before one divisible by 7 is a Shviis year (i.e. January up to Rosh Hashanah) and of course the few months before it. So 2016 is divisible by 7 and 2015 is such a year. An easier way to remember now is to ignore the 2000 part and know that if the last 2 digits are divisible by 7, a Sh'viis year will start at Rosh Hashanah on that year (e.g. 14 is divisible by 7 and 2014 had such a year start in it).

Question about Shemitah years etc


Solving stochastic dynamic problem by space state MATLAB program

Question: I have a maximization problem as shown in the picture below. The output has a common shock z that follows a two-state Markov chain with a transition matrix Π. Does anyone know how I would go about solving this by discrete-state-space dynamic programming?
Answer: Best I know as I used in my own paper is MDP toolbox which proposes functions related to the resolution of discrete-time Markov Decision Processes: backwards induction, value iteration, policy iteration, linear programming algorithms with some variants.
Can be downloaded from Toolbox page: http://www.inra.fr/mia/T/MDPtoolbox or the following address:(Marie-Josee Cros (2023). Markov Decision Processes (MDP) Toolbox)
https://www.mathworks.com/matlabcentral/fileexchange/25786-markov-decision-processes-mdp-toolbox)


finding prediction interval for any type of regression

Question: I am working on a project where I need to estimate some real-valued values given some features in an online fashion. I evaluate various online learning methods. My estimations has to be bounded by a prediction interval. I know that not every regression model is suitable for coming up with prediction intervals. For instance, non-probabilistic models such as regression-trees are not good for this. I wonder if there is any technique which can help me find prediction intervals only from the predicted data and the error(response-prediction) regardless of the learning method used? If not, what regression techniques should I look at if I strictly need prediction intervals around my predictions?
Comment: Are you interested in confidence intervals for parameters or in prediction intervals for individual predictions?
Comment: confidence intervals for individual predictions
Comment: Hmm, it is no option to combine the two options in my comment...
Comment: I meant the latter..prediction intervals for individual predictions
Answer: If the data set is large, you can always get naive $(1-\alpha)\cdot 100\%$ prediction intervals by adding to the point predictions $\hat Y$ the empirical $\alpha/2$ and $1-\alpha/2$ quantiles $\hat Q_{\alpha/2}$ and $\hat Q_{1-\alpha/2}$ of the residuals.
They are naive

because you ignore the variability in the point prediction (viewed as an estimator of a population average) and
because the distribution of the residuals might differ depending on the input values.

Both issues can usually be mended in the concrete case (e.g. calculate the quantiles separately per leaf of the tree to allow non-homogenous residual distributions) but there is no general solution.
Here a quick illustration in R to compare such naive 50%-prediction interval with the "classic" one:
<code>fit <- lm(Sepal.Width ~ ., iris)

# Implemented prediction interval for first obs
predict(fit, iris[1, ], interval = "p", level = 0.5)

#       fit      lwr      upr
# 3.446357 3.263315 3.629399

# Naive prediction interval described as above
predict(fit, iris[1, ]) + quantile(resid(fit), c(0.25, 0.75))

#      25%      75%
# 3.298499 3.631797
</code>
In this example, the "classic" interval almost agrees with the naive one based on empirical quantiles.


How do you update your production codebase/database schema without causing downtime?

Question: What are some techniques for updating a production server's code base / database schema without causing any downtime?
Comment: This would be a great question for http://dba.stackexchange.com/, which goes into public beta in a few hours.
Comment: Good question because I see so many people overlook this. Time is money and downtime never looks good to end-users, regardless of how legit the reason.
Comment: @Dan McGrath: which suppose you actually can have a downtime, I work for a system that is (normally) down only 4 times a year (quarter outage) and for 15 minutes maximum each time (during which time the traffic is queued)... database changes are heavily scrutinized :)
Answer: Generally, the websites I've worked on that had this sort of requirement were all behind load-balancers, or had separate failover locations. In this sample, I'll presume that you've got a single load balancer, 2 web servers (A & B) and 2 database servers (M & N - usually DB servers are linked via logshipping - at least in the SQL Server world).

Webserver A to be disconnected from load balancer (so all incoming traffic goes to B).
Log shipping is stopped (DB Server M is going to get updated first).
Update Webserver A. Point the configuration to DB Server M.
Test and verify that the update worked (usually folks are hitting the IP address directly).
Set the load balancer so that existing sessions continue to go to B. New sessions go to A.
Wait for all sessions on B expire (might be a half hour or more, usually we watch traffic and have a 1 hour break scheduled).
Update B and N.
Test and verify that the update worked.
Set up log shipping again and test it works.
Set the load balancer to regular operation.

In a very complicated web applications, what is described as steps 1-5 might take all night and be a 50 page Excel spreadsheet with times and emergency contact numbers. In such situations, updating half the system is scheduled for 6pm to 6am while leaving the system available to users. Handling the update for the DR site is usually scheduled for the following night - just hope nothing breaks the first day.
Where uptime is a requirement, patches are tested first on the QA environment, which ideally is the same hardware as production. If they show no disruption, they can then be applied on the regular schedule, which is usually on the weekend.
Comment: How do you propose merging new data from DB M and DB N?  They will both have new, updated and deleted records that the other doesn't have.
Comment: @Tangurena , can you answer the above comment ?
Comment: @sixtyfootersdude You can use SQL Server Replication Technologies like High Availability (HA) or  Group Replication(mySQL)
Answer: For typical databases (Oracle for example) it's possible to alter the database schema while still running queries in parallel. It requires some forward planning though.
Their are some constraints for the change to be applied:

it should work with the existing code, meaning that the code should deal with both the old and new versions of the schema
it should not incur such load on the DB that transactions would screech to a halt (I am looking at you CREATE INDEX)
it should not incur the loss of data (you cannot drop and re-create a table)

In order for the schema to be backward compatible, you usually can ADD or MODIFY a column, you can only DROP something if the existing code does not use it any longer.
If your code cannot handle the change transparently, then change the code before changing the database.
Simple advice on forward planning: always explicit the column names in your DB requests (don't use SELECT * FROM). This way you won't have new columns showing up in old requests.
Comment: Actually, for forward planning and adaptability, select * from is infinitely better than listing columns manually. Using explicit column names results in a lot of technical debt in most cases. If your code breaks from new columns, your code is already broken.
Comment: @Morg.: Not really. For security you need to use bind variables, which in the framework I use (at least) requires providing the variables to write to, and there needs to be exactly as many variables as there are output columns, thus `select *` means that the code breaks if a new column is added (for lack of a variable to write it to). Of course, this may be the result of using a strongly typed language.
Comment: Yes really, there is no added security in avoiding select *. It has nothing to do with strongly typed languages and everything to do with very bad design. If your framework cannot handle change seamlessly, it's useless. When I change a column, my application never stops working. When you do it breaks. I don't think there's any question as to which one is more reliable or secure.
Comment: @Morg.: I fail to see how `select *` is more reliable and secure. If you used to have `select one, two from ...` then you were only using `one` and `two`; if `third` is added to the table, then you have no use for it (here), so there is no reason to retrieve it. And if you need to suddenly use it, then you will modify the code, so you might as well modify the query at this point!
Comment: @Morg.: Well, it seems we are talking past each others, probably because our experiences differ. I work on products where performance is a paramount property, and this means that `select` need be as selective as possible (and covered by an index) otherwise I am toast (even before the obligatory joins). I am sorry to say, but the approach you are describing was an utter failure on those products.
Answer: Not all systems can, it has to be set up in a manner that supports it.
For example, one of our major systems I helped upgrade a few years ago should be available 24/7. It consisted of multiple tiers, including a pure communication tier between the off site User Interface Layer and Business Layer. Due to the way the communication layer was coded, any future changes to the Business Layer or DB schema could be implemented without a real outage. In the worst case scenario, a user would experience a 10-30 second pause as the changes took effect.
If the changes were purely code changes to the business layer, they could be queued up and 'cycled in' with only milliseconds delay.
It could do this because:

The communication layer could hold messages. This allowed us to have an actual outage on any of the tiers other than the UI Layer without needing to to bring down the UI.
The Business Layer handled by the MVDB called UniData. This holds all code in memory. After compiling code, you can use a command to force the new object code into memory, replacing the old.

Other techniques involve replication of transactions to another mirror of the existing system. By applying the update to one, switching over and replaying all transactions done between the update and switch. YMMV depending on your systems though.
Answer: Here's a different perspective, from the world of embedded database systems and embedded systems.  Embedded systems include various network/telecommunications infrastructure equipment, and in this realm they often talk about 99.999% (five 9s) uptime.
We (McObject) are the vendor of the eXtremeDB family of embedded database system products, including eXtremeDB High Availability.
First, understand that "embedded database" means that the database system is a library that is compiled and linked in with your application code; in that sense, it is "embedded" in your application.
With eXtremeDB High Availability, there is a MASTER instance of your application (which might be one or several processes) and one or more REPLICA instances of your application.  When a replica establishes a connection to the master, it receives a copy of the master's database through a process called "initial synchronization". This can be done while the master application continues its work.  Once syncrhonized, it receives the master's transactions through replication. Therefore, a replica always has current data and can take over (through a process called failover) in the event the master fails.
One feature of the initial synchronization is called "binary schema evolution."  In plain English, this means that the process of populating the replica's database will accommodate differences between the replica's database schema and the master's database schema.
In practice, this means that you can build a newer version of your application (with new/dropped tables, new/dropped/changed fields, new/dropped indexes), attach that new version of your application to a master, and then cause that newer replica to become the new master (i.e. force a failover to the new replica so it becomes the master and the old master shuts itself down).  Voila, you have migrated your application from version N to N+1, without interrupting the availability of your system.  Now you can go about upgrading the old master and any other replicas to version N+1.


For a linear system, why is direction "stored" in the variables when considering it as linear equations, but in vectors when its as a vector equation?

Question: Given an arbitrary system of equations, why is direction in space "stored" in the variables when considering the system as linear equations, but "stored" in vectors when considering the system as a vector equation? For example suppose we have a system of three equations in three variables where each equation is of the form (a_i)x + (b_i)y + (c_i)z = d_i. Lets also suppose they represent three distinct planes in R^3.  In the context of the system representing planes in space, it seems to me that dimension/direction is sort of "stored" in the variables x, y and z. Considering the system as a linear combination of vectors, the coefficients associated with any one variable make a column vector; for example, for variable x lets call the vector v_1 = . The vector equation associated with the system would then be xv_1 + yv_2 + zv_3 = . In this context it seems as though dimension/direction is stored in the vectors, and the variables x,y, and z now just scale them. I realize that both contexts have the same solution set, and both take place in R^3, but is there a more intuitive explanation for this relatedness?
Answer: You have stumbled upon the principle of duality in projective geometry, and Dual Theorems. Basically You define a plane as $$\mathbf{P}\cdot \mathbf{x} = 0$$
where $\mathbf{P}=(a,b,c,d)$ are the plane coordinates and $\mathbf{x}=(x,y,z,1)$ are point coordinates. The equation is then $ax+by+cz+d=0$.
It can interpreted as either

All the points $\mathbf{x}$ that pass through a fixed plane defined by the coordinates $\mathbf{P}$.
All the planes $\mathbf{P}$ that pass through a fixed point defined by the coordinates $\mathbf{x}$.

So for this construction, either $\mathbf{P}$ are coordinates and $\mathbf{x}$ are arbitrary, or the other way around. The caveat is the which ever is the coordinates in cannot contain all zeros. So either $\mathbf{P} \neq (0,0,0,0)$ or $\mathbf{x} \neq (0,0,0,0)$. It is said than in $\rm R^3$ points are dual to planes and vise versa.
What this allows to define is that

for every point in $\rm R^3$ there is corresponding unique plane (through the point, with the normal away from the origin)
and for every plane there is a corresponding unique point (closest to the origin)

So I can define a plane using the point coordinates $\mathbf{x}=(\vec{r},1)$ such as $\mathbf{P} = \left( \frac{\vec{r}}{\| \vec{r} \|}, -\vec{r}\cdot\vec{r} \right)$
Or I can define a point using the plane coordinates $\mathbf{P}=(\vec{a},b)$ such as $\mathbf{x}=(-\vec{a} b,\vec{a}\cdot\vec{a})$
Example
A plane has coordinates $\mathbf{P}=(\vec{a},b)=((2,1,3),-5)$ has equation $2x+y+3z-5=0$. The unique point closest to the origin is $\mathbf{x}=\left((-(-5)(2,1,3),(2,1,3)\cdot(2,1,3)\right)=(10,5,15,14)$.
The Cartesian coordinates of $\mathbf{x}$ are $x=\frac{10}{14}=\frac{5}{7}$, $y=\frac{5}{14}$ and $z=\frac{15}{14}$.
Lets prove these coordinates satisfy the plane equation $$ 2 \frac{5}{7} + 1 \frac{5}{14} + 3\frac{15}{14} - 5 =0\;\checkmark$$
So either $(2,1,3,-5)$ are the plane coordinates of this construction, or $(10,5,15,14)$ are the point coordinates of this construction.
Comment: PS. I am not a mathematician. I am just a user of this stuff so I probably didn't do a very good job of explaining the interpretation of coordinates and the role of duality in geometry.
Comment: You did an excellent job, thank you. I will be sure to give you plus 1 when my reputation is high enough.  When does one typically first encounter projective geometry and dual theorems in their mathematical education?
Comment: I was introduced to it as part of my Graduate Research in multi-body dynamics (robotics). There is geometrical connection that goes like this `Algebraic or Projective Geometry -> Screw Theory -> Dynamics` and the duality of Projective Geometry manifests itself in Dynamics also.


Optimization techniques in C#

Question: I am wondering what kind of optimization techniques people often use nowadays. I have seen people do caching all the time with dictionary and all. Is the trading space for speed the only way to go?
Comment: Can you be any more specific about the scenario you have in mind?  "Optimization" is a terribly broad category.
Comment: Yeah, way to broad.  Do you have a specific question?
Comment: Just wondering if there is any way to optimize the code other than using caching with dictionaries.
Answer: Really it's about your choice in algorithms. Usually there is no "silver bullet" for optimization.
For example, using a StringBuilder instead of concatenation can make your code significantly faster, but there is a tradeoff. If you aren't concatenating huge sets of strings, the memory and time it takes to initialize StringBuilder is worse than just using regular concatenation. There are a lot of examples of this throughout the framework, such as dictionary caching as you mentioned in your question.
The only general optimization you can really learn and apply to your coding throughout your day is the performance hit from boxing/unboxing (heap vs. stack). To do this you need to learn what it's about and how to avoid, or reduce the need to do it.
Microsoft's MSDN documentation has 2 articles on performance that give a lot of good general purpose techniques to use (they're really just different versions of the same article).

http://msdn.microsoft.com/en-us/library/ms173196.aspx
http://msdn.microsoft.com/en-us/library/ms173196(VS.80).aspx
Comment: StringBuilder is an awesome easy to implement optimizer when working with iterative building.
Answer: I will suggest below
1. Knowing when to use StringBuilder
You must have heard before that a StringBuilder object is much faster at appending strings together than normal string types.
The thing is StringBuilder is faster mostly with big strings. This means if you have a loop that will add to a single string for many iterations then a StringBuilder class is definitely much faster than a string type.
However if you just want to append something to a string a single time then a StringBuilder class is overkill. A simple string type variable in this case improves on resources use and readability of the C# source code.
Simply choosing correctly between StringBuilder objects and string types you can optimize your code.
2. Comparing Non-Case-Sensitive Strings
In an application sometimes it is necessary to compare two string variables, ignoring the cases. The tempting and traditionally approach is to convert both strings to all lower case or all upper case and then compare them, like such:
str1.ToLower() == str2.ToLower()
However repetitively calling the function ToLower() is a bottleneck in performace. By instead using the built-in string.Compare() function you can increase the speed of your applications.
To check if two strings are equal ignoring case would look like this:
string.Compare(str1, str2, true) == 0 //Ignoring cases
The C# string.Compare function returns an integer that is equal to 0 when the two strings are equal.
3. Use string.Empty
This is not so much a performance improvement as it is a readability improvement, but it still counts as code optimization. Try to replace lines like:
if (str == "")
with:
if (str == string.Empty)
This is simply better programming practice and has no negative impact on performance.
Note, there is a popular practice that checking a string's length to be 0 is faster than comparing it to an empty string. While that might have been true once it is no longer a significant performance improvement. Instead stick with string.Empty.
4. Replace ArrayList with List<>
ArrayList are useful when storing multiple types of objects within the same list. However if you are keeping the same type of variables in one ArrayList, you can gain a performance boost by using List<> objects instead.
Take the following ArrayList:
ArrayList intList = new ArrayList();
intList.add(10);
return (int)intList[0] + 20;

Notice it only contains intergers. Using the List<> class is a lot better. To convert it to a typed List, only the variable types need to be changed:
List<int> intList = new List<int>();

intList.add(10)

return intList[0] + 20;

There is no need to cast types with List<>. The performance increase can be especially significant with primitive data types like integers.
5. Use && and || operators
When building if statements, simply make sure to use the double-and notation (&&) and/or the double-or notation (||), (in Visual Basic they are AndAlso and OrElse).
If statements that use & and | must check every part of the statement and then apply the "and" or "or". On the other hand, && and || go thourgh the statements one at a time and stop as soon as the condition has either been met or not met.
Executing less code is always a performace benefit but it also can avoid run-time errors, consider the following C# code:
if (object1 != null && object1.runMethod())

If object1 is null, with the && operator, object1.runMethod()will not execute. If the && operator is replaced with &, object1.runMethod() will run even if object1 is already known to be null, causing an exception.
6. Smart Try-Catch
Try-Catch statements are meant to catch exceptions that are beyond the programmers control, such as connecting to the web or a device for example. Using a try statement to keep code "simple" instead of using if statements to avoid error-prone calls makes code incredibly slower. Restructure your source code to require less try statements.
7. Replace Divisions
C# is relatively slow when it comes to division operations. One alternative is to replace divisions with a multiplication-shift operation to further optimize C#. The article explains in detail how to make the conversion.
REFERENCE
Answer: There are often problems with algorithms as well, usually when something expensive is done inside of a loop. Generally, the first thing you do is profile your application, which will tell you the slowest part(s) of the application. Generally, what you do to speed up your application depends upon what you find. For example, if your application mimics a file system, it may be that you're calling the database recursively to travel up the tree (for instance). You may optimise that case by changing those recursive calls into one flattened database call that returns all of the data in one call.
Again, the answer is, as always, 'it depends'. However, more examples and advice can be found in Rico Mariani's blog (browse back a few years, as his focus has shifted):
Comment: Profiling you specific application is probably the only good advice.  Profile, see what's slow (or memory hogging), and try to cut it down.
Comment: I am actually looking for good examples. People use memoization (caching again) for recursions. +1 for database example.
Answer: Depends on a lot of things, really.
As an example, when memory becomes an issue and a lot of temporary objects are being created I tend to use object pools. (Having a garbage-collector is not a reason to not take care of memory allocation). If speed is what matters then I might use unsafe pointers to work with arrays.
Either way, if you find yourself struggling too much with optimization techniques in a c#/.net application you probably chose the wrong language/platform.
Answer: In general, make sure you understand the time complexity of different algorithms, and use that knowledge to choose your implementations wisely.
For .NET in particular, this article goes into great detail about optimizing code deployed to the CLR (though it's also relevant for Java, or any other modern platform), and is one of the best guides I've ever read:
http://msdn.microsoft.com/en-us/library/ms973852.aspx
To distill the article into one sentence: Nothing affects the speed of a .NET application (with sensible algorithms) more than the memory-footprint of its objects. Be very careful to minimize your memory consumption.
Answer: I would recommend Effective C# by Bill Wagner (first edition and second edition). He goes through a number of language constructs and techniques and explains which ones are faster and why. He touches on a lot of best practices as well.
More often than not, however, optimizing your algorithm will give you far better results than using any kind of language / optimization technique.
Comment: Exactly what I would have said-- this is where I'd go on my first pass.

Optimization techniques in C#


How can I show h(n) = O( √ n)?

Question: Is there any way to make recursion tree that satisfies the height
$h(n) = h(n−\sqrt{n}) + 1$ to show $h(n) = O(\sqrt{n})$?
Answer: Hint: Suppose that $n = 2^{2^k}$. Hence:
$$h(n) = h(2^{2^k} - 2^{2^{k-1}}) + 1 = h((2^{2^k} - 2^{2^{k-1}}) - \sqrt{2^{2^k} - 2^{2^{k-1}}}) + 1 + 1 = h(2^{2^k} - 2^{2^{k-1}} - 2^{2^{k-2}}\times \sqrt{2^{2^{k-1}}-1}) + 1 + 1$$
From the expansion, the order of $2^{2^{k-1}} = \sqrt{n}$ times is the length of the tree.
Answer: Consider the following sequence: $a_0 = n$, $a_{t+1} = a_t - \sqrt{a_t}$. You are interested in the minimum $t$ for which $a_t$ falls behind some arbitrary constant $C > 0$ (this corresponds to the base case of your recursion).
Here is the basic idea. As long as $a_i \geq n/4$, the sequence is decreasing at a rate of at least $\sqrt{n}/2$. Therefore after at most $(n-n/4)/(\sqrt{n}/2) = \alpha \sqrt{n}$ steps (where $\alpha = 3/2$), you dip below $n/4$. After at most $\alpha \sqrt{n/4}$ steps, you dip below $n/4^2$. And so on. It takes at most $\alpha \sqrt{n/4^r}$ to dip below $n/4^{r+1}$. The total number of steps to reach $C$ is thus at most
$$
\alpha\sum_{r=0}^\infty \sqrt{n/4^r} = \alpha\sqrt{n} \sum_{r=0}^\infty 2^{-r} = 2\alpha\sqrt{n}.
$$
With more effort, you should be able to determine the constant in front of $\sqrt{n}$.
Note also the trivial $\sqrt{n} - O(1)$ lower bound, which follows from the fact that the sequence decreases by at most $\sqrt{n}$ each step.

How can I show h(n) = O( √ n)?


International Wire Transfer Problems

Question: I have an international wire transfer that needs to be recalled. A month ago, I sent a wire transfer from the US to a Japanese Bank of America branch.  It looks like it was supposed to go to a US Bank of America branch instead. Basically, I provided a SWIFT code rather than a routing number.  The account number was correct for the intended recipient. That person has told me that they don't have an BoA account at that branch or in that country (but they do have a US BoA account).
I started a recall from the sending bank and they've informed me that the receiving bank acknowledged the recall but hasn't provided a status update yet.  It's been about a week.
BoA's customer service has repeatedly stated that for wire transfers to be successful, the receiving account number AND account holder name must match the information entered on the wire transfer order.  The chance of someone else having that account number and name would be extremely small.  Even if the name is disregarded, the account number is 12 digits: it's also very unlikely that another person has that same account number.
So, my question is.. what are my chances of getting the money back?  I feel like the money must be sitting in a holding account at the receiving bank and they are reluctant to release it because of fraud concerns/regulations.
Comment: Any guesses about your chances of getting the money back are speculation. It's unlikely this question and its associated answers are really general enough to be widely applicable to subject of personal finance.
Comment: Perhaps someone with intimate knowledge of the banking industry (specifically international) might be able to give an answer that goes beyond speculation given the details I've provided.  I don't believe my case is too unusual and it's likely that someone who has sent by wire transfer to the wrong branch/bank could provide a description of their personal experience.
Answer: tl;dr: Be patient, money is probably sitting somewhere, and it will eventually be credited back to your account.
I had a similar problem about 10 years ago.  I sent an international wire transfer, from my own bank account in Germany to my bank account in Central America. I had done this before, and there had been no issues, but in this case, even though all the information was correct, the bank rejected the wire because it was above $10K, and in that case, the bank needs written proof from the owner of the receiving account (me) , and so didn't know where the funds were coming from.
I had to call the local Sparkasse bank in Germany, as well as an intermediary bank in London to sort it all out, and in total, had to wait about 3-4 weeks to get the money back in my Sparkasse bank account.  At one point I thought I may never see that money back, especially since there was an intermediary bank to deal with, but it all worked out in the end.
Answer: Be patient, I think it's virtually guaranteed you'll get your money back. As you said it's probably "sitting" somewhere but it might take a while for the transactions to clear.
Answer: Behind the scenes of banking are a lot of very manual processes especially when something goes wrong. These take extra time not only because it involves people reviewing what went wrong but also because the bank will take extra steps to reduce human error (e.g. technical jargon about maker/checker, dual controls).
Something like this can easily get held up for a month and the best way to jump the queue is to start complaining a lot, calling customer service frequently, asking to talk to management and otherwise pestering the bank until someone senior gets your problem fast-tracked so you stop giving them a headache.

International Wire Transfer Problems


How to quickly know the dimensions of an image?

Question: I am looking for a nice and quick way to display the dimension of an image from OS X 10.9. Presently, I have to open the image in photoshop and then enter a menu to know the dimensions. The process is too slow when I have to browse through dozens of pictures and get those with dimensions big enough.
Comment: It's not clear (from the answers given, at least), whether you mean "resolution" or "size". The Resolution of an image is how many pixels per inch it contains, e.g 72dpi. The Dimensions, or size, is how many pixels it contains in total.
Comment: When you say *"display the dimensions... from OS"*, do you mean GUI option/plugin, command-line, or either? The title is too vague. The existing answers mostly assumed you meant 'GUI option/plugin'.
Answer: The simplest way from the command line is to use the built-in file command:
file ping-pong.png

Outputs:
ping-pong.png: PNG image data, 380 x 343, 8-bit/color RGBA, non-interlaced

More metadata will be displayed if available.
This will also work on Linux systems.  See: https://superuser.com/questions/275502/how-to-get-information-about-an-image-picture-from-the-linux-command-line
Comment: This is nice in that it doesn't require to install any software, but it'll return a variable number of fields (at least in my case with a mix of JPEG, PNG, GIF, WEBP), making the results a pain to parse. `magick identify "$1" | cut -d' ' -f1,3` from @SztupY's answer is better in this respect.
Answer: Get Info
You can get the resolution from Get Info menu. Select the image and press ⌘ CMD+i, or right click on that image and choose Get Info menu item.

Image from cultofmac.com
QuickLook plugin
If you weren't on 10.9 - this lightweight QuickLook plugin called qlImageSize which can be found on GitHub lets You check the image size on the quicklook window title. I don't have any that work on 10.9, but perhaps this will help you if you wish to search for a similar one or report 10.9 compatibility to that project for improvement.
Comment: This option does not appear in macos Catalina.
Comment: this works on big slur
Comment: Unfortunately, this plugin does not work for 10.9
Comment: Ups, just read the bottom of the README. You're right.
Comment: I couldn't find it again so anyway thanks! I am sure it will help other users.
Comment: @jalone which option? I have Catalina and under "Get Info" I can see the image dimensions. Make sure your file is on your local storage and not in iCloud.
Answer: From the command line, if you have Imagemagick 7.x installed (for example through homebrew or the installer), then you can use the following command to quickly display the resolution and similar information of multiple images in a directory (if you are still on the older Imagemagick 6.x, then the command is just identify instead of magick identify):
$ ls
a.jpg
b.png
c.png
$ magick identify *
a.jpg JPEG 550x309 550x309+0+0 8-bit sRGB 29.4KB 0.000u 0:00.000
b.png[1] PNG 1912x827 1912x827+0+0 8-bit sRGB 2.17MB 0.000u 0:00.009
c.png[2] PNG 311x262 311x262+0+0 8-bit sRGB 185KB 0.000u 0:00.000

Or if you only need the resolution:
$ magick identify * | cut -d' ' -f1,3
a.jpg 550x309
b.png[1] 1912x827
c.png[2] 311x262

Specifying -verbose will give you even more quick information which you can grep in case it's needed:
$ magick identify -verbose c.png
Image: c.png
  Format: PNG (Portable Network Graphics)
  Mime type: image/png
  Class: DirectClass
  Geometry: 311x262+0+0
  Units: Undefined
  Type: TrueColor
  Endianess: Undefined
  Colorspace: sRGB
  Depth: 8-bit
  Channel depth:
    red: 8-bit
    green: 8-bit
    blue: 8-bit
  Channel statistics:
    Red:
      min: 0 (0)
      max: 255 (1)
      mean: 154.515 (0.60594)
      standard deviation: 66.9006 (0.262355)
      kurtosis: -0.83131
      skewness: -0.468887
    Green:
      min: 0 (0)
      max: 255 (1)
      mean: 148.544 (0.582527)
      standard deviation: 77.5386 (0.304073)
      kurtosis: -1.18136
      skewness: -0.438364
    Blue:
      min: 27 (0.105882)
      max: 255 (1)
      mean: 176.548 (0.692343)
      standard deviation: 62.2995 (0.244312)
      kurtosis: -0.971188
      skewness: -0.584194
  Image statistics:
    Overall:
      min: 0 (0)
      max: 255 (1)
      mean: 159.869 (0.626937)
      standard deviation: 69.2078 (0.271403)
      kurtosis: -0.754397
      skewness: -0.568073
  Rendering intent: Perceptual
  Gamma: 0.454545
  Chromaticity:
    red primary: (0.64,0.33)
    green primary: (0.3,0.6)
    blue primary: (0.15,0.06)
    white point: (0.3127,0.329)
  Background color: white
  Border color: srgb(223,223,223)
  Matte color: grey74
  Transparent color: black
  Interlace: None
  Intensity: Undefined
  Compose: Over
  Page geometry: 311x262+0+0
  Dispose: Undefined
  Iterations: 0
  Compression: Zip
  Orientation: Undefined
  Properties:
    date:create: 2015-02-11T15:20:41+00:00
    date:modify: 2015-01-28T10:04:15+00:00
    png:iCCP: chunk was found
    png:IHDR.bit-depth-orig: 8
    png:IHDR.bit_depth: 8
    png:IHDR.color-type-orig: 2
    png:IHDR.color_type: 2 (Truecolor)
    png:IHDR.interlace_method: 0 (Not interlaced)
    png:IHDR.width,height: 311, 262
    signature: 35b3a0e9c50c785bece1ceff5a202823922cc78c2740cf9e0ff30d6143c89fdf
  Profiles:
    Profile-icc: 3276 bytes
  Artifacts:
    filename: c.png
    verbose: true
  Tainted: False
  Filesize: 185KB
  Number pixels: 81.5K
  Pixels per second: 2.716MB
  User time: 0.000u
  Elapsed time: 0:01.029
  Version: ImageMagick 7.0.10-34 Q16 x86_64 2020-10-09 https://imagemagick.org

Comment: Why, its built in?
Comment: @JW_: it wasn't a criteria in the original post to be a built in
Comment: Damn! That's a bunch of great info about images.
Answer: The fastest way is to have the resolution details visible all time ;)
Check out the step below:

*COLUMN VIEW
Comment: Does it work in the list mode?
Comment: @Colas no, but if you just select one file in a list view you get all the info in the column to the right..
Comment: Post is updated.
Comment: @Colas I mistakenly compared column view with list view. Sorry about that. If you want the resolution in list view you may need to hack.
Answer: Not the smoothest, but the following workflow might get you out of trouble:

on run {input, parameters}
    set filename to POSIX path of input
    set h to do shell script "sips -g pixelHeight '" & filename & "' | tail -n1 | cut -d' ' -f4"
    set w to do shell script "sips -g pixelWidth '" & filename & "' | tail -n1 | cut -d' ' -f4"
    display alert (h as text) & " x " & (w as text)
    return input
end run

You can also add a keyboard shortcut if you like:

… but the biggest problem is thinking of a good shortcut that isn't already being used by something else.
Answer: This is a trivial task. I have written a c++ program which can display on terminal. I could post if you are interested. It would also be trivial to write a Service to display the result.
//
//  Display  Comment, size of JPEG image
//

#include <iostream>
#include "../jpeg.h"

int main (int argc, const char * argv[])
{
    Cjpeg Jpeg1;

    switch(Jpeg1.OpenJpeg(argv[1]))
    {
        case INVALID_JPEG:
            std::cerr << "Invalid JPEG" << std::endl;
            return INVALID_JPEG;
        case NOTFOUND_JPEG:
            std::cerr << "File Not Found" << std::endl;
            return NOTFOUND_JPEG;
        case NOT_JPEG:
            std::cerr << "Not JPEG" << std::endl;
            return NOT_JPEG;
        default:
            std::cout << Jpeg1.Comments <<  " " <<  Jpeg1.Width <<  " * "  <<  Jpeg1.Height << std::endl;
    }
    return 0;
}

// jpeg.cpp: implementation of the Cjpeg class.
// ANSI version
//////////////////////////////////////////////////////////////////////

#include "jpeg.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

Cjpeg::Cjpeg()
{
    Height = Width = 0;
    Comments[0] = '\0';
}

Cjpeg::~Cjpeg()
{

}

//--------------------------------------------------------------------------
// JPEG markers consist of one or more 0xFF bytes, followed by a marker
// code byte (which is not an FF).
//--------------------------------------------------------------------------

#define M_SOF0  0xC0            // Start Of Frame N
#define M_SOF1  0xC1            // N indicates which compression process
#define M_SOF2  0xC2            // Only SOF0-SOF2 are now in common use
#define M_SOF3  0xC3
#define M_SOF5  0xC5            // NB: codes C4 and CC are NOT SOF markers
#define M_SOF6  0xC6
#define M_SOF7  0xC7
#define M_SOF9  0xC9
#define M_SOF10 0xCA
#define M_SOF11 0xCB
#define M_SOF13 0xCD
#define M_SOF14 0xCE
#define M_SOF15 0xCF
#define M_SOI   0xD8            // Start Of Image (beginning of datastream)
#define M_EOI   0xD9            // End Of Image (end of datastream)
#define M_SOS   0xDA            // Start Of Scan (begins compressed data)
#define M_JFIF  0xE0            // Jfif marker
#define M_APP1  0xE1            // Exif marker
#define M_COM   0xFE            // COMment
#define M_DQT   0xDB
#define M_DHT   0xC4
#define M_DRI   0xDD

// Process a SOFn marker
void Cjpeg::process_SOF (unsigned length)
{
    int data_precision, num_components;
    unsigned char Data[128];
    unsigned long   cb; // count of bytes read

    cb = fread(&Data, 1, length, fp);   // read JPEG

    data_precision = Data[0];
    Height = Get16(Data+1);
    Width = Get16(Data+3);
    num_components = Data[5];
}

// Process a COM marker.
void Cjpeg::process_COM (unsigned length)
{
    unsigned nch;
    unsigned long   cb; // count of bytes read

    nch = 0;

    nch = (length > MAX_COMMENT) ? MAX_COMMENT : length;    // Truncate if it won't fit in our structure.
    cb = fread(&Comments, 1, nch, fp);  // read JPEG

    Comments[nch] = '\0'; // Null terminate
    if(cb<length)
    {
        fseek(fp, length - cb, SEEK_CUR);   // point to next JPEG marker
    }
}

void Cjpeg::process_APP1(unsigned int length)
{
    fseek(fp, length, SEEK_CUR);    // point to next JPEG marker
}

int Cjpeg::OpenJpeg(const char *JpegFile)
{
    int count;
    unsigned long   cb; // count of bytes read

    fp = fopen(JpegFile, "rb");
    if(fp == NULL)
    {
        return NOTFOUND_JPEG;
    }
    cb = fread(&JpegMarker, 2, 1, fp);  // read JPEG
    if(JpegMarker[0] != 0xFF || JpegMarker[1] != M_SOI)
    {
        fclose(fp);
        return NOT_JPEG;    // Not JPEG File
    }
    while(cb != 0) // Stop if EOF reached
    {
        cb = fread(&JpegMarker, 2, 1, fp);  // read JPEG marker
        if(JpegMarker[0] != 0xFF)
        {
            fclose(fp);
            return INVALID_JPEG;    // Invalid File
        }
        switch(JpegMarker[1])
        {
            case M_SOS: // stop before hitting compressed data
            case M_EOI: // in case it's a table only JPEG stream
                fclose(fp);
                return 0;   // Normal exit
        }
        cb = fread(&JpegSecCount, 2, 1, fp);    // read length of field
        count = Get16(JpegSecCount);
        count -= 2; // value includes length bytes
        switch(JpegMarker[1])
        {
            case M_COM: // Comment section
                process_COM (count);
                break;

            case M_SOF0:
            case M_SOF1:
            case M_SOF2:
                process_SOF (count);
                break;

            case M_APP1:
                process_APP1 (count);
                break;

            case M_JFIF:

            default:
                // Skip any other sections.
                fseek(fp, count, SEEK_CUR); // point to next JPEG marker
                break;
        }
    }
    fclose(fp);
    return INVALID_JPEG;    // Possible Invalid File
}

Comment: Congrats on taking a "trivial task" and providing an overly complex solution.
Comment: It's just complex if you can't code. ;) Guess what all the other solutions have in the background...
Answer: There are two simple methods for accomplishing this via the command line:

sips - macOS built in tool for image identification and manipulation
GraphicsMagick gm identify - FOSS utility similar to ImageMagick but smaller and much more efficient.

Sips
The command to get the image dimensions is as follows:
sips -g pixelWidth -g pixelHeight images_file(s)

What is really convenient here, besides being a native tool included with macOS, is that you can specify which dimension you want (i.e. just the height).  It will also accept multiple files at once.
sips -g pixelWidth Logo.bmp Logo.png

Users/allan/Demo/Logo.bmp
pixelWidth: 225
/Users/allan/Demo/Logo.png
pixelWidth: 1141

GraphicsMagick
GraphicsMagick is a cross platform (macOS, FreeBSD, Linux, Windows, etc.) image processing utility designed to be a smaller and more efficient alternative to ImageMagick (referenced in another answer). It's available via MacPorts and Homebrew.
gm identify foo.bar

Example:
gm identify Logo.bmp
Logo.bmp BMP 225x200+0+0 DirectClass 8-bit 175.9Ki 0.000u 0m:0.000003s

To customize the output, you can use the format flag:
gm identify -format "%wx%h" Logo.bmp
225x200

gm identify -format "My image width is:  %w" Logo.bmp
My image width is:  225

Answer: If you have Photoshop, you probably also have Bridge. If you have Bridge, you can point it at a folder of images (with the ability to have it display the images in sub-folders of that folder) and then sort the images by a number of ways including by the dimensions of the image in pixels. Clicking on an individual image will show more information including the pixel dimensions. You can also choose the "View -> As Details command" and the list of images will include information that includes the pixel dimensions.
Answer: In macos 13 Ventura I was able to see dimensions (Image size) after opening file in Preview, then clicking (i) button
Comment: https://apple.stackexchange.com/a/171470/489896


Does TCP/IP prevent packet replays?

Question: Does TCP/IP prevent multiple copies of the same packet from reaching the destination? Or is it up to the endpoint to layer idempotency logic above it?
Please reference specific paragraphs from the TCP/IP specification if possible.
Comment: mm... this looks like a college exam question...
Comment: No, I'm curious whether I need to add extra logic to my application layer to protect against replays.
Answer: It's the TCP stack's job to recover from duplicate packets:

The TCP must recover from data that is
  damaged, lost, duplicated, or
      delivered out of order by the internet communication system.  This
      is achieved by assigning a sequence number to each octet
      transmitted, and requiring a positive acknowledgment (ACK) from the
      receiving TCP.  If the ACK is not received within a timeout
      interval, the data is retransmitted.  At the receiver, the
  sequence
      numbers are used to correctly order segments that may be received
      out of order and to eliminate duplicates.  Damage is handled by
      adding a checksum to each segment transmitted, checking it at the
      receiver, and discarding damaged segments.

-- RFC 793 - Transmission Control Protocol, Section 1.5
However, if they're the same packets with new sequence numbers, then no.
Comment: One part of your answer says the endpoint must recover from duplicate packets, while another part says that TCP must recover from duplicate packets. Don't these two contradict one another?

Perhaps you meant that it's the endpoint's job must recover from duplicate *requests*? Please edit your answer
Comment: It's the TCP stack's job to deal with duplicate packets.  This is why packets have a sequence number, so you can tell which ones are from the same request.  However, there's nothing preventing a device from sending "duplicates" with a different sequence number.
Comment: Right, which is why I wrote your reply should maybe should have read: "It's the TCP stack's job to recover from duplicate requests (not packets):"
Answer: TCP uses sequence numbers to detect duplication in the case of retransmission, which will also prevent trivial replay attacks.
From RFC 793, Section 3.3 - Sequence Numbers:

A fundamental notion in the design
  is that every octet of data sent
  over a TCP connection has a sequence
  number. Since every octet is
  sequenced, each of them can be
  acknowledged. The acknowledgment
  mechanism employed is cumulative so
  that an acknowledgment of sequence
  number X indicates that all octets up
  to but not including X have been
  received. This mechanism allows for
  straight-forward duplicate detection
  in the presence of retransmission.
  Numbering of octets within a segment
  is that the first data octet
  immediately following the header is
  the lowest numbered, and the following
  octets are numbered consecutively.

The duplicate detection will ensure that the same packet cannot be trivially retransmitted. Sequence numbers will also ensure that insertion (rather than replacement) of data in the data stream will be noticed, as further legitimate packets following forged packets will have duplicate sequence numbers, which will disrupt the data flow. This will likely cause those packets to be dropped as duplicates, which will likely break the protocol being used.
More information about the original (1981) TCP/IP specification can be found in RFC 793, and the many other RFCs involving extensions or modifications to the TCP/IP protocol.
Answer: Yes, the TCP layer prevents duplicate packets. The IP layer below it does not.
Details in RFC 1122.
Answer: You seem to be concerned about two different things:

What guarantees does the TCP reliable delivery provide
Can an attacker affect my server process with a replay attack

Answer to 1:
TCP guarantees reliable, in-order delivery of a sequence of bytes.  What ever data the client application send to TCP via write() will come out exactly the same during the server's read() call.
Answer to 2:
Replay attacks do not work well with TCP, since every connection depends on two random 32 bit numbers generated by the client and server respectively.  For a replay attack to work, the attacker must guess the sequence number generated by the server for the fake connection it is initiating (theoretically, the attacker has a a 1 / 2**32 chance to guess correctly).  If the attacker guesses incorrectly, she will at worst cause some buffering of data in your OS.
Note that just because a replay attack doesn't work, nothing prevents an attacker from forming a legitimate connection with your server and transmitting whatever data stream she wants to your application.  This is why it's important to always validate input.
Answer: Layers below TCP can experience multiple packets or dropped packets.  Layers above TCP do not experience repetition or dropped packets.
Answer: I don't know about packet repitition, but I've never encountered it using TCP/IP and I know that it does guarantee that the packets all arrive and in the correct order, so I can't understand why it wouldn't.
Answer: It really depends on how you are receiving your data - although technically the protocol should not give you duplicates (i.e. packets with the same tcp checksum), other factors could cause you to see duplicates - for example, the network hardware you are using; also if you are using sniffers to look at tcp streams, rather than just reading an open socket in your application, it's possible to get dup packets from the sniffers even if the actual tcp streams they were monitoring did not have dup packets.
To give a real world example - At the moment I'm working on some tcp analysis of internal networks for a major stock exchange, and the data I'm looking at is coming in from multiple sniffers and being spliced back together. So in pulling in the data, I've found that I need to do a number of pre-processing steps, including finding and removing duplicates. For example, in a stream I just read in, of approx 60,000 data packets, I have located and removed 95 duplicate packets.
The strategy I take here is to keep a rolling window of the 10 most recent tcp checksums, and to ignore packets that match those checksums. Note this works well for PSH packets, but not so well for ACK packets - but I'm less concerned with those anyways.
I've written a special collection for the purpose of tracking this rolling window of tcp checksums, which might be helpful to others:
///
/// Combination of a double-linked-list and a hashset with a max bound;
/// Works like a bounded queue where new incoming items force old items to be dequeued;
/// Re-uses item containers to avoid GC'ing;
/// Public Add() and Contains() methods are fully thread safe through a ReaderWriterLockSlim;
///
public class BoundedHashQueue<T>
{
    private readonly int _maxSize = 100;
    private readonly HashSet<T> _hashSet = new HashSet<T>();
    private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
    private readonly Item _head;
    private readonly Item _tail;
    private int _currentCount = 0;

    public BoundedHashQueue(int maxSize)
    {
        _maxSize = maxSize;
        _head = _tail = new Item();
    }

    private class Item
    {
        internal T Value;
        internal Item Next;
        internal Item Previous;
    }

    public void Add(T value)
    {
        _lock.Write(() =>
            {
                if (_currentCount == 0)
                {
                    Item item = new Item();
                    item.Value = value;
                    _head.Next = item;
                    item.Previous = _head;
                    item.Next = _tail;
                    _tail.Previous = item;
                    _currentCount++;
                }
                else
                {
                    Item item;
                    if (_currentCount >= _maxSize)
                    {
                        item = _tail.Previous;
                        _tail.Previous = item.Previous;
                        _tail.Previous.Next = _tail;
                        _hashSet.Remove(item.Value);
                    }
                    else
                    {
                        item = new Item();
                        _currentCount++;
                    }
                    item.Value = value;
                    item.Next = _head.Next;
                    item.Next.Previous = item;
                    item.Previous = _head;
                    _head.Next = item;
                    _hashSet.Add(value);
                }
            });
    }

    public bool Contains(T value)
    {
        return _lock.Read(() => _hashSet.Contains(value));
    }
}}

Answer: You don't fully understand the problem.
See this link:
http://en.wikipedia.org/wiki/Transmission_Control_Protocol
On this page is write:
"TCP timestamps, defined in RFC 1323, help TCP compute the round-trip time between the sender and receiver. Timestamp options include a 4-byte timestamp value, where the sender inserts its current value of its timestamp clock, and a 4-byte echo reply timestamp value, where the receiver generally inserts the most recent timestamp value that it has received. The sender uses the echo reply timestamp in an acknowledgment to compute the total elapsed time since the acknowledged segment was sent.[2]
TCP timestamps are also used to help in the case where TCP sequence numbers encounter their 2^32 bound and "wrap around" the sequence number space. This scheme is known as Protect Against Wrapped Sequence numbers, or PAWS (see RFC 1323 for details)."
Regards,
Joint (Poland)

Does TCP/IP prevent packet replays?


What are the basic ingredients in the Standard Model (SM) of particle physics?

Question: What are the basic ingredients of the standard model (SM) and their applications?
Comment: In what sense would you have the standard model, without the assumptions of the standard model? What does that mean? ... Anyway, it all follow from the choice of symmetry groups and their representations, working in the context of relativistic quantum field theory.
Comment: Thank You. I want to list out all the essential requirements like gauge invariance and symmetry breaking. Anything more?
Comment: The SM explains experimental results. That has _implications_, but I'm not sure what you mean by _assumptions_. Could you say a bit more, for example why you think symmetry breaking is an assumption?
Comment: You may want to reduce your question to something a bit less broad.  I mean, if you ask something like, **"_What assumptions is the Standard Model (SM) based on?_"**, that'd be a pretty big question already.  Probably best not to add anything else to that, e.g. also asking for applications.
Answer: The basic ingredients that make up the standard model are the following :
(i) A local (gauge) symmetry $SU(3)\times SU(2)\times U(1)$
(ii) Three fermion generations , consisting of the following representations:
$$Q_{L_i}(3,2)_{\frac{1}{6}},U_{R_i}(3,1)_\frac{2}{3},D_{R_i}(3,1)_{-\frac{1}{3}},L_{L_i}(1,2)_{-\frac{1}{2}},E_{R_i}(1,1)_{-1}\ \ \ \ \ i=1,2,3$$
where the $i$ represents the three generations, the numbers in the parentheses $(X,Y)_Z$ denotes the fact that the field sits in the $X,Y,Z$ representations of the $SU(3),SU(2),U(1)$ symmetry groups respectively, $L,R$ denotes the chirality.
(iii) A single scalar multiplet $\phi(1,2)_\frac{1}{2}$
(iv) It exhibits the following SSB,
$$SU(3)\times SU(2)\times U(1)\rightarrow SU(3)\times U(1)_{EM}$$
Now, once you bring in the gauge fields and write the most general renormalisable Lagrangian, you will end up with the SM Lagrangian, after SSB.


How to manually add a point to document outline in Google Documents?

Question: Google Docs has not automatically put all my headings into the document outline (this may be because the heading that is not included is right after the title).  Is there a way to manually add a heading/point to the document outline?
Answer:
Click on the heading you'd like to add to outline
Right click
Select "Add to outline" from the popup menu

Source: https://support.google.com/docs/answer/6367684#remove_headings
Comment: I can't find "Add to outline" though
Answer: As of 2018, it's not possible to modify Outline. It is created by "best guess" algorythm, and there is no option to change the way it selects content for Outline.
Source: https://productforums.google.com/d/msg/docs/BANAbgbZ1qY/qTRrcNFpBgAJ
Answer: While you can't edit the outline itself, if you reapply a heading style, it will get added back, even if you delete a heading from the outline.
e.g. if you have an H3 which is missing, making it an H4 then back to H3 again will add it back to the outline. With the keyboard shortcuts this is quite quick.
Personally I'd prefer a "all headings only" mode (sidebar table of contents) and get rid of the flaky algorithm, but this is not possible at present.
Answer:
Highlight what you want to be a heading or sub-heading
Click the drop down menu where it says "Normal Text" in the top ribbon
Select which level of heading/sub-heading you want it to be


Weight Loss, help!

Question: I am 20 and have been going to the gym for a few months now, and haven't seen much result. I find it very hard to diet, as I have a limited variety of food that I can stomach and like, I have quite unpleasant IBS which is why I attend the gym. I need advice on how to loose weight and tone up quickly, without having to jump through to any 'diet hoops' please help?
Comment: You need to tell us a *whole lot more* if you want answers to be at all useful. See [this](http://meta.fitness.stackexchange.com/questions/516/what-must-be-included-if-you-want-to-get-individualized-help) for what to include.
Answer: Well this may or may not help. But I am a huge advocate of Intermittent fasting.
I have come to find that I also had IBS for years, not knowing the true cause of it or any way to fix it. I started intermittent fasting, and it gave my digestive system a break. I use a 16/8 Lean gains protocol. You can google it up. I have proceeded into my adventure by testing my body and discipline with not only 16 hour fasts, but 24 hour, and my longest went into today at 36 hours.
Now, I also spent several months in the gym at 185lbs with no weight loss, just muscular transformations. I also never liked to diet, but I started counting my calories, which led to counting my macro nutrients which led to me getting tired of eating all day long. So I watched the Hodgetwins and Low Carb Cory on youtube, and they were sharing information they previously researched and learned called Intermittent Fasting.
I started at 185lbs 23-25% Body fat. Overall stocky build, with a lot of bad fat around my midsection.
I am now 168lbs 13% Body fat. V Shape Back to waist look, nice traps and a strong core.
I can't chalk it all up to Intermittent fasting, but I followed a rigorous 4 day split workout schedule and intermittent fasted my last 3 months or so, from which I have received the best results of my life.
Here is some reference for you:
This is my eating schedule protocol
http://www.leangains.com/2010/04/leangains-guide.html
This was my initial training protocol
http://www.bodybuilding.com/fun/get-swole-cory-gregory-muscle-building-trainer.html
This is what I do now, with lean gains in between.
http://stronglifts.com/eat-stop-eat-brad-pilon-fasting-review/
and I am on week 2 of this program
http://www.bodybuilding.com/fun/shortcut-to-size.html
Keep in mind. People will call you stupid, people will think you're crazy, but people will also want what you have. They will want to look like you. Don't downplay it. Do your research. Work hard, Stay dedicated. When it's all done. Pass it along to a friend or family member who can also benefit from this lifestyle.
PEACE
Comment: I admit - fasting is good. You can loose ~10pounds in 5 days. Of course you do not have to fast for 5 days. One day a week is great. Moreover I find it easier not to eat at all than eat but less.
Comment: You're so right my dude, it's much easier to just NOT eat, than it is to tease yourself with mini-meals 6 times a day...but yes weight loss is extreme with intermittent fasting...
Answer: You need to understand the difference between different types of workout. The only fat burning workout is an aerobic workout. To loose weight you have to choose between few known aerobic workouts: long distance running, cycling, swimming, rowing and cross country skiing. The most of the workouts in the gym are anaerobic and help to build muscle mass and as side effect build fat in the body too. The aerobic exercises in the gym are extremely boring and ineffective.
Get some fresh air!

Weight Loss, help!


I am having problems with the app when leaving Wi-Fi and connecting to cellular via mobile router on a samsung tablet

Question: I am using a Samsung tablet for an application to manage a fleet of transportation vans. Inside the van we have a wireless router (Pepwave), when in the parking lot the Pepwave has priority to connect to the yards access point. This is to upload any surveillance video needed from the van.  I am trying to get rid of the data plan on the tablet and run off of the data plan on the Pepwave via Wi-Fi entirely.  It works great... for the most part.  The problem I am having is that when leaving the yard the Pepwave switches from Wi-Fi to cellular when the Access point is out of range.  The application does not refresh when this data provider transfer takes place.  All other apps like YouTube or internet browser for fine after connection reestablishes. The only solution so far is to toggle the Wi-Fi on the tablet on and off. Any suggestions would be greatly appreciated.
Answer: I would use an automation assistant such as Tasker or Automate.
You can set these to detect the WiFi change of state and then toggle your tablet's WiFi setting off then on automatically.
It may only be a workaround for the problem but it may be the simplest fix.
Comment: Thanks, i'll give it a shot.


how to create custom id in sql server with sequence

Question: How can I create a table with custom ID like BK-0001001 with a sequence. Sorry I'm a newbie with databases. All help will be appreciated thank you!
Answer: You can use a mix between a SEQUENCE and formatting a DEFAULT CONSTRAINT:

CREATE SEQUENCE MySequence
AS int
START WITH 1
INCREMENT BY 1;
GO

CREATE TABLE MyTable
(
    MySeq varchar(20) CONSTRAINT [DF_MyTable_MySeq]
                      DEFAULT FORMAT((NEXT VALUE FOR MySequence), 'BK-000000#'),
    Foo   int,
    Bar   int,

    CONSTRAINT [PK_MyTable] PRIMARY KEY (MySeq)
);
GO

INSERT INTO MyTable (Foo, Bar)
VALUES (1,2),(2,3),(3,4),(5,6);
GO

SELECT * FROM MyTable;
GO

MySeq      | Foo | Bar
:--------- | --: | --:
BK-0000001 |   1 |   2
BK-0000002 |   2 |   3
BK-0000003 |   3 |   4
BK-0000004 |   5 |   6

db<>fiddle here
Comment: I'm glad to help
Answer:
... a table with custom ID like BK-0001001 ...

Why do you feel the need to?
To me, this looks more like two bits of data - "BK" & "0001001" - mashed together into single field.
Or even three bits of data - "BK", "0001" & "001"!
Either way, it's a Bad Idea.
Databases are really good at finding little bits of stuff and putting them together.  They're quite rubbish at finding things and pulling them apart again.
Storing different things in different fields will make your life a lot easier.
If you want to "present" this composite field to users, consider providing Views that do the composition:
create or replace view view1 as
select item_type
   || '-'
   || format( category_num, 0000 )
   || format( item_num, 000 )
   as item_id
from table1 ;


Flex SDK installer fails to download https://github.com/swfobject/swfobject/archive/2.2.zip

Question: I am trying to install Apache Flex SDK 4.16.1 + AIR 31.0 or AIR 32.0 with the latest Apache Flex installer - tried it on both Win 7 and Win 10. Starting it with administrator rights.
At some point the installer just stops with this message, nothing happens after that.
Downloading 2.2.zip from: https://github.com/swfobject/swfobject/archive
I can open https://github.com/swfobject/swfobject/archive/2.2.zip  in the browser just fine, it downloads the file.
Full install log contents:
<code>Installer path: C:\Users\Myuser\AppData\Roaming\org.apache.flex.installapacheflex\Local Store\Win64
Installer version 3.3.2 (windows)
Available Memory: 49291264 (64-bit)
Using Locale: de_AT
Fetched the SDK download mirror URL from the CGI.
SDK version Apache Flex SDK 4.16.1
AIR version 32.0
Flash Player version 32.0
Creating Apache Flex home
Creating temporary directory
Downloading Apache Flex SDK from: https://mirror.klaus-uwe.me/apache/flex/4.16.1/binaries/apache-flex-sdk-4.16.1-bin.zip
Verifying Apache Flex SDK MD5 Signature
The Apache Flex SDK MD5 Signature of the downloaded files matches the reference. The file is valid.
Uncompressing: C:\Program Files (x86)\Adobe\Adobe Flash Builder 4.6\sdks\4.16.1 AIR 32\temp\apache-flex-sdk-4.16.1-bin.zip
Finished uncompressing: C:\Program Files (x86)\Adobe\Adobe Flash Builder 4.6\sdks\4.16.1 AIR 32\temp\apache-flex-sdk-4.16.1-bin.zip
Downloading 2.2.zip from: https://github.com/swfobject/swfobject/archive
</code>
Besides of that every second time it aborts with the following message, but that's another story
Installation aborted: http://flex.apache.org/track-installer.html?failure=true&label=Apache Flex SDK 4.16.1&version=4.16.1&os=windows&installerversion=3.3.2&info=Error #2031
Thank you for any help!
Answer: It looks like there is an issue with the installer, after some links where changed/expired. Try downloading with AIR 31 or 30 then update air by replacing files from either AIR32 from adobe (doesnt work for mobile any more) or AIR33 from Harman.


There is nothing good or bad, but thinking makes it so. Are these words of Shakespeare,inspired by Marcus Aurelius, true?

Question: This question is not about ethics. It is about our perceptions of positive and negative value. I take the original meaning of the great emperor to be that we have control only of our own thinking, and can choose to see anything as positive or negative. So we can choose to be downcast or inspired, happy or sad, accepting or frustrated. Is this the will to power as Nietzsche conceived it, in the stoic rather than egoistic sense?
Comment: "There is nothing good or bad, but thinking makes it so" can be understood in ways that do not imply "we have control... and can choose..." "Good" and "bad" may be constructed by thinking, but construction by thinking isn't necessarily free and unconstrained.
Comment: i will tell you that, unless i have misunderstood you, i agree that what you say is the meaning of beyond good and evil. i suspect that certain buddhists are able to, given a condition of absorbtion, take any state of mind freely and at will, and it is well known that zazen has an amoral sheen to it
Answer: The quote expresses the idea of a (morally) blank or neutral world which is colored in "good" or "bad" by our thinking.
Not sure you could call that "true" or "false" as it's more of a statement of an opinion. You might for example also take the perspective that there is an absolute and objective definition of the terms "good" and "bad", that is not tied to the subjective impression of the individual.
Now sure Nietzsche seems to have taken that perspective, rejecting the classic moral supremacy of the Christian Church and afterwards finding himself confronted with moral nihilism and so took up the quest to define a new moral. Where he radically affirms the agency of the individual which needs to make up a new moral that goes beyond good and evil and instead declares what is "good" and "bad" by what is serving and hindering their own goals.

I take his meaning to be that we have control only of our own thinking, and can choose to see anything as positive or negative. So we can choose to be downcast or inspired, happy or sad, accepting or frustrated.

If you take that quote in isolation the scope of possible interpretation is pretty wide, however if you see it in it's context it seems to be more narrow:
https://poemanalysis.com/shakespeare-quotes/there-is-nothing-either-good-or-bad/
So apparently Hamlet feels imprisoned within Denmark by the knowledge that the current king is the murderer of his father and that he has control over him. Despite that in reality Hamlet is free to move, he is not actually imprisoned and he is aware of that. He asserts that what imprisons himself is the feeling of his own imprisonment and that he just needs to let go of the thinking of his negative perception of the situation. Though at the end of the day it's not really his choice to make, like he cannot not process the world through the lens of his self and he cannot unknow or unfeel how he interprets things so what he wishes for is akin to insanity to literally "losing his mind".
Comment: "To die—to sleep,
No more; and by a sleep to say we end
The heart-ache and the thousand natural shocks
That flesh is heir to: 'tis a consummation
Devoutly to be wish'd. To die, to sleep;
To sleep, perchance to dream—ay, there's the rub:
For in that sleep of death what dreams may come" He must reconcile with his conscience, with the past, to enter the future with equanimity. His freedom is to work on that, not simply to change where & who he is, & what future is destined by his choices.
Answer: The inspiration:

"You have power over your mind – not outside events. Realize this, and
you will find strength."
―Marcus Aurelius, from his Meditations

Comparable, but very different in intent. In Act 2 Scene 2, Hamlet speaking continues:

"Oh, God, I could be bounded in a nutshell and count myself a king of
infinite space, were it not that I have bad dreams."

Here are a few I think comparable statements to Aurelius':

"The mind is its own place, and in itself can make a heaven of hell, a
hell of heaven."
-from 'Paradise Lost', by John Milton

"The Great Way is not difficult for those who have no preferences.
When love and hate are both absent everything becomes clear and
undisguised. Make the smallest distinction, however, and Heaven and
Earth are set infinitely apart.
If you wish to see the truth then hold no opinions for or against
anything. To set up what you like against what you dislike is the
disease of the mind.
When the deep meaning of things is not understood the mind's essential
peace is disturbed to no avail.
The Way is perfect like vast space where nothing is lacking and
nothing is in excess. Indeed, it is due to our choosing to accept or
reject that we do not see the true nature of things. Live neither in
the entanglements of outer things, nor in inner feelings of emptiness.
Be serene in the oneness of things and such erroneous views will
disappear by themselves."
-from the poem Hsinhsinming, by the Third Patriarch of Zen, Seng Tsan.

"Mind precedes all mental states. Mind is their chief; they are all
mind-wrought. If with an impure mind a person speaks or acts suffering
follows him like the wheel that follows the foot of the ox.
Mind precedes all mental states. Mind is their chief; they are all
mind-wrought. If with a pure mind a person speaks or acts happiness
follows him like his never-departing shadow."
-opening lines of The Dhammapada, a collection of sayings of the Buddha Siddhartha Gautama

Aurelius and the Stoics, Milton in what has become an important Christian text, and these Buddhist texts, are talking about a spiritual recognition. Not of infinite liberty, in the way you seem to imply:

we have control only of our own thinking, and can choose to see
anything as positive or negative

We don't have control of our bad dreams. We don't have control over the past: even Enlightenment in the Buddhist tradition can only liberate us from creating bad karma, not from facing the consequences of the karma we have already made. The Stoic injunction is not that you are responsible for whatever situation you find your mind in. What Aurelius is talking about is cultivation, of inner qualities like equanimity. A lot of his Meditations are subjects to think about, comparisons to be drawn in your own life. It's not intellectual ideas being declared true, but practices to engage in to come to knowledge about your own life.
What Hamlet says is not true, and it doesn't accurately represent Aurelius. And that theme is covered in Hamlet. Will he be puppeted by the ghost demanding vengeance? It's not simply a matter of his deciding to become a cheerful optimist who forgets how his father died. He must grapple with the past, and how he does so is his freedom. His freedom does not extend to changing the past, only to what work he does with his mind, which will change how and who it is that meets the future.
In spiritual terms the focus tends to be on cosmology, on how we situate ourselves towards the world, how we assemble and narrate what we know. I would draw a comparison in this to theory-making, where we can never know what better theory awaits us and there is no simple algorithm to get us to it (Popper is good on this). This should be contrasted to experimental results, to phenomena, and evidence. Our thinking cannot change that kind of knowledge, and to believe it can is the route towards propaganda and delusion. Like, dislike; love, loathe; desire, abhor; these are situational. But is having enough oxygen, enough water, enough food to live, something to simply decide how to situate ourselves towards? We need some things as prerequisites, to even have the luxury of continuing, in which to do inner work. Thinking alone cannot change that.
You know Nietzsche loathed the Stoics right?

"You desire to LIVE "according to Nature"? Oh, you noble Stoics, what
fraud of words! Imagine to yourselves a being like Nature, boundlessly
extravagant, boundlessly indifferent, without purpose or
consideration, without pity or justice, at once fruitful and barren
and uncertain: imagine to yourselves INDIFFERENCE as a power—how COULD
you live in accordance with such indifference? To live—is not that
just endeavouring to be otherwise than this Nature? Is not living
valuing, preferring, being unjust, being limited, endeavouring to be
different? And granted that your imperative, "living according to
Nature," means actually the same as "living according to life"—how
could you do DIFFERENTLY? Why should you make a principle out of what
you yourselves are, and must be? In reality, however, it is quite
otherwise with you: while you pretend to read with rapture the canon
of your law in Nature, you want something quite the contrary, you
extraordinary stage-players and self-deluders! In your pride you wish
to dictate your morals and ideals to Nature, to Nature herself, and to
incorporate them therein"
-from Beyond Good and Evil

You might like this answer on what Will To Power means: What was Nietzsche all implying-and-not-implying by what would make him "holy"? The TLDR is that it's about shifting from fitting ourselves into a metanarrative recieved from society, towards a rich inner life that generates a narrative that enriches the lives of others and draws them into it, in the direction of 'lifeliness' which is not just of power, but of laughter, of dancing:

"And we should consider every day lost on which we have not danced at least once. And we should call every truth false which was not
accompanied by at least one laugh."
-from Thus Spake Zarathustra

And, of not turning away from tragedy, if that is part of the best story.

"Man is no longer an artist, he has become a work of art."
―Nietzsche, from The Birth of Tragedy
Answer: Answer is quite simple,
What Shakespeare said was fact. Good and Bad are relative terms. Nor there is universal measure of good or bad. They are result of our comparison or analysis, which is at the end act of thought.
If you ask what Nietzsche said was same or not, my answer would be no. Reason being I don't find comparison of them would be worth it. Since they belonged from different times and also there interests were different, comparison will create unnecessary trouble.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Resizing logical volume with no free extents but with free disk space

Question: I have a 7.9 TB logical volume formatted with XFS filesystem. I have 8 1 TB RAID devices as physical volumes, and 1 volume group that contains all of these devices. I have 2.5 TB free space on my logical volume. I'd like to remove 2 of the 1 TB devices from the volume group since I don't "need" them anymore. Reading the man page of pvmove, it seems like I would need to create at least 5.5 TB of space and pvmove everything from the current 1 TB volumes onto the new volumes, and then remove all 8 of the original volumes from the logical volume. This seems onerous. Any suggestions?
Answer: There's no problem on the LVM side. Use lvreduce to shrink a volume group; obviously, if there's a filesystem on it, you mustn't shrink it below the size of the filesystem. Then use pvmove to shuffle extents around: pvmove /dev/sdz42 removes extents from the physical volume /dev/sdz42 to other physical volumes in the same volume group, after which you can decommission the physical volume with vgreduce.
However this is moot since you have an XFS filesystem, and XFS does not support shrinking. I'm afraid you'll have to move the data off and remake the filesystem (and thus you can be completely unsubtle with LVM).
Comment: Gilles, excellent, I just did not get the correct workflow! lvreduce does exactly what is required... and now I see that I have really hurt myself with XFS.


How to run 2 different processes with python at the same time?

Question: I have a looping script , to get infos on a french site. It looks like this :
def getInfos(a,b,c)

def MyLoop(filename)

in which i call getinfos via
def MyLoop(filename)
    values = getInfos()

And It works well. But sometimes, the script slows down and finally stops.
So i tried several modules with different ideas in mind.
The first module ; Signal. But (subjectively) interesting functions are not avalaible on windows.
However, i tried to stimulate execution when it's frozen:
def reboot(signal, frame):
    print '??FROZEN??'
    time.sleep(1)
    #sys.exit(0)
signal.signal(signal.SIGINT, reboot)

As you can see i tried sys.exit(0), but too abrupt, and i'm not sur of what's really done. Anyway... after a two-hour loop, i get no answer with this transformed "keyboard interrupt" function.
Then i tried to limit execution time.
So i found : Multiprocessing, pp, signal (~5%avalaibleOnWindows).
The first one opened 30 or 40 other brackgrounded python processes.
The second one, pp, do not allow to paralelize two differents function. No it does ?
Do you have something that could work for me ? or at least, something i can try, to figure me out where the first step is ?
14 months later...
Finally, surely by lack of experience, i decided to use multiprocessing. Making some bots as executors, and 1 of them as checker/killer of the possibly frozen external process.
First, the multoprocessing approach:
#my_mp.py
import multiprocessing as mp
import actions as ac
bot_ids = list('ab')
if __name__ == '__main__':
    jobs = []
    for bot_id in bot_ids:
        p = mp.Process(target=ac.Act , args=(bot_id,))
        jobs.append(p)  ;  p.start()

Then, what is multiprocessed:
#actions.py
import time,random,glob,os,psutil
#________________________
def check_or_kill(eXe,bTm):
    age_max = 900
    if time.time() - bTm > age_max:
        for proc in psutil.process_iter():
            if  (proc.name == eXe):proc.kill()
    return
#________________________
def Act(bot_id):
    checker = random.choice(list('ab'))
    if bot_id not in checker:
        f = open('stTime_%s.txt'%bot_id , 'w')  ;  f.write('%s'%(time.time()))  ; f.close()
        #launch the execution file and then, when it's done :
        os.remove('stTime_%s.txt'%bot_id)
    else:
        #get their inner birthtime.
        while glob.glob('localfolder_path','stTime_*.txt') != []: check_or_kill('soft.exe',birthtime)
    return

Answer: For asynchronous programming try twisted
Here is a good book for beginners: Twisted Introduction
Comment: Thank you warwaruk. But according to this "Twisted Introduction" : "Windows is a strange, murky place and, if you are hacking in it, I can't offer you much more beyond my heartfelt sympathies."
Comment: Still, `twisted` works on Windows, regardless of this author's opinion on it :)
Answer: Is your process getting hung on a web request?  In the standard library urllib2 there is a function urllib2.urlopen which takes in an optional timeout parameter.  If that is what you are using, try setting the timeout parameter and handling the case where your request fails.
Comment: I'm too new of a user (I think?) to add comments to posts that are not mine.  I think having a better understanding of the problem you are trying to solve would be helpful.  As you've stated, `multiprocessing` would let you run multiple processes, but that's a complicated solution that might just disguise a simpler problem.  Can you post more of your code?
Comment: Thanks for your comments. No i was not using urllib2, but external processes called from my functions.


Negative balance effect credit score

Question: I have an saving account in Oriental Bank. I am not using this account for last 1.5 year. Currently the balance is negative.
I am staying in Bihar since last two year. It is not possible to go Delhi account home branch and close account.
Please suggest what to do. It may affect my credit score.
Answer: You can go to the local branch and complete the formalities, pay the charges and close the account.
It can also be done remotely by writing a registered letter to the Delhi branch.

Negative balance effect credit score


GNU screen version confusion

Question: I try to use mousetrack on in screen in Debian Jessie, and it is supported from version 4.1 Mouse in screen(1) on the Linux console?
But there are some confusion in the screen version.
dpkg -s screen: "Version: 4.2.1-3"
screen -v: "Screen version 4.02.01 (GNU) 28-Apr-14"

How to run screen 4.2 instead of 4.02?
Answer: Seems the GNU screen project itself inserts leadings zeros into the version numbers reported. Probably to avoid confusion between version numbers like x.11 and x.2 - which one is newer then? x.11 could be the next version after x.10 or just a minor version number bump from x.1 and older than x.2.
Have you actually tried to use this feature?
For me adding mousetrack on to my ~/.screenrc changed behavior for Ctrl-A : windowlist. With it I could move the selection of the window with my mouse, without the mouse had no effect. Did no further experiments with it, though.
I did this with Debian Jessie, exactly the same version of screen you have and Konsole as terminal. Might work different for other terminals, though.

GNU screen version confusion


Can I embed my Picasa video to play on my website?

Question: Is it possible to embed my Picasa videos (not the whole album) on my website so it plays directly on the website without redirecting back to Picasa (kinda like youtube embedded videos)? I've seen this done on another website but can't seem to get mine to work. Picasa keeps giving me the links and embedded code for a photo even tho the file I'm currently viewing is a video. Also, you can give suggestions for both google+ photos or picasaweb.google.com (they are the same thing), I don't mind.
Any help would be greatly appreciated, thanks.
Answer: You can upload your video to YouTube and use their method.  Picasa has a direct upload link to YouTube. For more details check following link:-
https://productforums.google.com/forum/#!topic/picasa/PMc9U3y5Iy8
Comment: thanks for the reply. Ive tried this method before but it means I have to upload my videos twice. But the main reason why i cant use youtube is because my videos have copyright music that will get them taken down in minutes. Thanks anyway.
Comment: @JumpMan247 there is no need to say thanks.            http://stackoverflow.com/help/accepted-answer


Screenshots for AppStore - do I combine into one image?

Question: ITunes Connect has different buttons for uploading screenshots (e.g. one for 3.5 inch retina)
Can I use each button more than once to upload more than one screenshot - or will a second upload overwrite the first? I know it says "screenshots" (plural) but it is not clear whether that is because I need to combine several screenshots into one image and upload it. Especially since the available sizes seem to be larger than the default screenshot size that XCode produces.
Comment: If sizes is the issue, try appscreenies.com . They provide screenshots for all sizes
Answer: OK. Found the answer by taking a plunge and just trying it. Yes, you can add a number of screenshots under each category. They are displayed for you, and it seems that you can change them later as well. So it is really easy.