C++ class identification question

Question: I'll phrase this in the form of an example to make it more clear.
Say I have a vector of animals and I want to go through the array and see if the elements are either dogs or cats?
class Dog: public Animal{/*...*/};
class Cat: public Animal{/*...*/};

int main()
{
vector<Animal*> stuff;
//cramming the dogs and cats in...

for(/*all elements in stuff*/)
//Something to the effect of:  if(stuff[i].getClass()==Dog) {/*do something*/}

}

I hope that's sort of clear. I know about typeid, but I don't really have any Dog object to compare it to and I would like to avoid creating a Dog object if I can.
Is there a way to do this? Thanks in advance.
Comment: You can't do that, it needs to be a vector or Animal *, not Animal.
Answer: As others has noted, you should neither use the typeid, nor the dynamic_cast operator to get the dynamic type of what your pointer points to. virtual functions were created to avoid this kind of nastiness.
Anyway here is what you do if you really want to do it (note that dereferencing an iterator will give you Animal* . So if you do **it you will get an Animal&):
for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) {
    if(typeid(**it) == typeid(Dog)) {
        // it's a dog
    } else if(typeid(**it) == typeid(Cat)) {
        // it's a cat
    }
}

Note you can apply the typeid operator to types itself too, as shown above. You don't need to create an object for this. Also note the typeid way doesn't work if you pass it a pointer like typeid(*it) . Using it like that will give you just typeid(Animal*) which isn't useful.
Similar, dynamic_cast can be used:
for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) {
    if(Dog * dog = dynamic_cast<Dog*>(*it)) {
        // it's a dog (or inherited from it). use the pointer
    } else if(Cat * cat = dynamic_cast<Cat*>(*it)) {
        // it's a cat (or inherited from it). use the pointer.
    }
}

Note that in both cases, your Animal type should be polymorph. That means it must have or inherited at least one virtual function.
Comment: Thanks a lot, very informative. I have some dynamic casts some other places in my program, but I just made it into a virtual function. It was in an area evaluating collision detection and I can't afford the performance hit. I'm still going to use typeid as in your example, because it's constant time
Answer: You can use dynamic_cast, as long as the vector contains Animal pointers.
vector <Animal *> stuff;

for(int i=0;i<stuff.size();i++) {
    Dog *pDog = dynamic_cast <Dog *> (stuff[i]);
    if(pDog) {
        // do whatever with the dog
    }

    Cat *pCat = dynamic_cast <Cat *> (stuff[i]);
    if(pCat) {
        // and so on
    }
}

but you should be aware that this is generally not the best practice. You should try to work with polymorphism, not against it. In other words, try to write a virtual Animal function that Dog and Cat override, and let the compiler automagically call the right one.
(Also, dynamic_cast is relatively slow, so too many of them will hinder performance; whereas a virtual function call is general just a single instruction.)
Comment: The one potential performance advantage of the dynamic cast is that it allows the "do whatever" to make non-virtual calls which can be inlined. It's not that the vcall is slow, itself, it's that it won't be inlined. But you'd have to measure to know which was faster in a given case.
Answer: Are you sure you want to do that? What you're going to do is the exact contrary of polymorphism, and polymorphism is the best thing in object-oriented programming.
Loosely speaking: Don't do something if you animal is a Dog; let the Animal hierarchy know what to do when one of its objects is a Dog! :)
Answer: If you really need your application-level to identify Dogs vs non-Dogs, you should avoid using RTTI (dynamic_cast and typeid), and make that knowledge explicit in your class hierarchy.
for (size_t i = 0; i != v.size(); ++i) {
    if (v[i]->isDog()) { v->cleanupPoop(); }
}

There are some minor performance benefits, but the primary benefit is exposing the necessary behavior in your class interface to maintenance programmers.  RTTI (being as limited as it is) should not be required in order for a class hierarchy to function.
Now, along with what other people have said, it's likely that the isDog() function could be refactored into something that doesn't require knowledge of the entire hierarchy up-front (such as needsPoopCleanup()).   Like everyone else said, you're losing the benefits of polymorphism if your application logic conditionally executes based on object type anyhow.
Comment: A base class shouldn't need to know its derived classes for the hierarchy to function. I totally agree that needsCleanup is better if that's possible, but isDog, isCat methods on Animal are just a home-brewed, inferior version of RTTI. If you can't do better you may as well use the real thing IMO.
Comment: It's only inferior in the sense that it is redundant with compiler-supported RTTI.  If the distinction is required from a "business logic" level, it's still marginally more useful to provide a sort of "executable documentation" for maintenance programmers (rather than making them "figure it out").
Answer: You can use the typeid operator to do this, e.g.
if (typeid(stuff[i].getClass())==typeid(Dog))

This can't catch if it's a derived class of Dog, though. You can use a dynamic_cast for that. However, any use of typeid or dynamic_cast is often indicative of a design flaw. Usually, you don't need to know what your derived types are, and there's probably a better way that involves polymorphism. It's hard to give the right advice without a real example, though.
Answer: using virtual functions:
As indicated by others responses, using virtual functions will often actually be sufficient enough, and is the "C++" way of thinking. Here is an example of using virtual functions:
#include<iostream>
#include<vector>
using namespace std;

/////////////

class Animal {
  public:
    virtual void move() { cout << "animal just moved" << endl; }
};
class Dog : public Animal {
  public:
    void move() { cout << "dog just moved" << endl; }
};
class Cat : public Animal {
  public:
    void move() { cout << "cat just moved" << endl; }
};

void doSomethingWithAnimal(Animal *a) {
  a->move();
}

/////////////

int main() {
  vector<Animal*> vec;
  vector<Animal*>::iterator it;

  Animal *a = new Animal;
  Dog *d = new Dog;
  Cat *c = new Cat;

  vec.push_back(a);
  vec.push_back(d);
  vec.push_back(c);

  it = vec.begin();

  while( it != vec.end() ) {
    doSomethingWithAnimal(*it);

    it++;
  }

  return 0;
}

If this will not be sufficient, then others have already posted answers which actually use conditional logic instead of polymerized logic.
Answer: The accepted answer is correct, but you should know that there is another option as well that hasn't been mentioned. You could have a virtual function in the Animal class called "type()" which could return an int or a string (or any type that is comparable).
So for example:
class Animal {
    /*...*/
public:
    virtual std::string type() const { return "animal"; }
};

class Dog: public Animal{
    /*...*/
public:
    virtual std::string type() const { return "dog"; }
};

class Cat: public Animal{
    /*...*/
public:
    virtual std::string type() const { return "cat"; }
};

This way you could just do:
if(array[i]->type() == "dog") { }

The type function could return anything (an int unique to each derived type would work too, but strings illustrate it better).
Simply another option.
Comment: Useful when your compiler can't do RTTI, or your system so constrained that you've switched it off in general and just want it for one small part of the hierarchy. If your hierarchy is small enough, you can use an int (bitset) allowing fast inheritance-checking with a mask and compare.

C++ class identification question


Boolean Not Rendering in Cycles - Blender 3.4

Question: I have a character setup with the "lighting boy studio" boolean based mouth rig. The booleans visibility is connected via driver to some control bones, but the boolean isn't rendering in cycles. It does render in Eevee however. These meshes arent using toon shading, and I've checked on alot of things like shader settings. Here's a screenshot of my render settings.
Another strange thing is that sometimes when I switch modes, like from edit to pose mode the boolean stops rendering in the viewport and i need to switch to pose mode for it to reappear.
System specs:
Processor: 12th Gen Intel(R) Core(TM) i7-12700   2.10 GH
RAM:16GB 3200 MHz DDR4
GPU: NVIDIA® GeForce RTX™ 3060 (LHR); 12 GB
Blend file: https://drive.google.com/file/d/1f8SIwBYt0uaI5lh6MLV6_WbdYeioSbOs/view?usp=share_link
Answer: I think you Disabled Boolean modifier in render


Get Plugin Information from Multiple Sites Externally

Question: I'd like to create a dashboard of sorts of plugins I'm using on multiple sites. I'm able to use get_plugins() to gather the information I want within each site, but how can I make that data accessible from the outside? Is this possible? What would be the best way to go about it?
Answer: Before anything else:

Be really sure that your endpoint to retrieve this information is reasonably secure. (e.g. using SSL and some authentication like a password) Leaking the information which plugins are installed
  on a site might offer a point of attack for hackers.

I am not going to offer you a ready-made solution but outline two different approaches how to tackle this: Push and Pull.
Push means that your sites report their plugins to the dashboard, while pull means your dashboards actively gets this information from your sites.
Also I am only going to show you the WP side of things. How you handle stuff for your dashboard is a completely separate issue and also probably not a good fit for this site.
So here we go:
Push
By using a WP-Cron you can schedule a site to do something in regular intervals. In our case we could for example schedule a task that gets the list of installed plugins and reports them to your dashboard (code hugely simplified):
<code>// Add the action that does the actual reporting
add_action( 'hourly_report', 'report_plugins' );

// Schedule this action hourly
wp_schedule_event( time(), 'hourly', 'hourly_report' );

// This function does the actual work
function report_plugins(){

    //Get plugin data
    $plugins = get_plugins();

    //create the data you want to send using $plugins
    $args = ...

    // Post the data to your dashboard
    wp_remote_post( $dashboard_url, $args );
}
</code>
Pull
Another option is to create an AJAX endpoint to actively get the plugin-data from a site. This would roughly go along those lines (again code hugely simplified):
<code>// Add the AJAX handler
add_action( 'wp_ajax_nopriv_plugin_data', 'return_plugin_data' );

function return_plugin_data(){
     //Again I want to emphasize that you need to ensure the user has the right to access this data.

     //Get plugin data
     $plugins = get_plugins();

     //Encode and return the plugin data
     echo json_encode($plugins);
     die();
}
</code>

I hope this helps to get you started, let me know if anything is unclear conceptionally.
Comment: hello and good day dear kraftner .- I'm currently working on a parser to fetch metadata on the newest plugins in wordpress.
https://stackoverflow.com/questions/61679425/parse-and-process-html-in-php-fetching-wordpress-plugin-metadata-with-a-scraper
your approach is much simple - many thanks

btw see also: https://wordpress.stackexchange.com/questions/345095/using-custom-code-how-can-i-fetch-data-from-the-wordpress-plugin-repo/345361#345361


What effect is seen when the extracellular concentration of sodium is increased?

Question: I can't seem to figure out how this would effect the cell since sodium is not very permeable.
Comment: Welcome to Bio. What cell? A human neuron behaves very differently than a bacterium at the bottom of the sea.
Comment: Don't expect tags to provide question background; they are basically not more than search terms. The answer below is likely not what you are after, but it answers your question perfectly. Vote to close.
Answer: The membrane isn't sodium permeable but it is water permeable.  Water will move from areas of high concentrations to low.  So when you increase the extracellular concentration of sodium, water will move out of the cell and into the extracellular matrix.  This causes the cell to shrink.
Comment: The question is closed, so answers can't be added, and existing answers generally should not be edited to add material.  Welcome to Biology stackexchange Patricia; try adding an answer to an open question instead of this closed question.


Where is it best to install a Windows program in the Ubuntu Operating system?

Question: I'm planning to install Microsoft Office on my Ubuntu 14.04. I was wondering if there is a location which is best to use for installing programs made for Windows.
I'd like to keep my office when upgrading to a newer version of Ubuntu, so I guess I shouldn't put it in the root partition, in order not to get it overwritten?
Answer: I would advice against this.
When using another operating system use the software included in that operating system. In case of Microsoft Office there is a perfect solution: Libre Office. It has close to 100% compatibility and supports xls(x) and doc(x). It is different yes and will need you to relearn using office (since LO does things a bit different).

if there is a spot, which is best to use for installing programs, made for windows.

Software from 3rd parties should be installed in /opt/ but this is for Linux software. There is no place to install Windows software in Ubuntu/Linux since that software is not made for it. We do not have a Windows runtime environment in Linux itself.
If you need to use Windows software you can do this using a tool called WINE. It is an attempt to mimic Windows but it is difficult to set up, hard to get working perfectly. It will make you cry if you want to use it for anything than the basic tools. Experience is important when dealing with WINE.
If you need Windows software and can not do without use Windows for it. Optinally you can do this with a dual boot (Windows side by side with Ubuntu) or with virtualization (Windows installed in virtualbox installed in Ubuntu).
But if I was you I would start with Libreoffice. You can even install it in Windows, get used to it and then decide to fully switch to Ubuntu. Same goes for other software: most of our software also is available on Windows.
Answer: Good luck!  Most MS programs will not run in Ubuntu directly.  You can try Wine, PlayOnLinux a virtual machine such as VMPlayer or VirtualBox, or a dual boot.
Additionally, if you are just looking for the MS Office suite, you can run them online in a browser in a manner similar to google docs.
Answer: your home directory? during and after upgrade files in your home directory are not touched
You will need Wine program to install Windows applications and by default it keep all installed windows programs in your home directory
(not a part of this answer but, LibreOffice is good, free alternative to Windows Office)
Answer: Microsoft Office works through the wine subsystem, which translates Windows system calls to native ones on-the-fly.  If you are not experienced with using it, I think it would be a good idea to use PlayOnLinux as a frontend to wine.  PlayOnLinux can be installed from the software center or by sudo apt-get install playonlinux.
Once PlayOnLinux is installed, perform the following steps.

Lower your expectations.
Run PlayOnLinux from your menu.
Pick Install a program from actions at top right.
Click Office at the top and choose your version of Microsoft Office from the list.
Click Install and follow the prompts.

At this point, PlayOnLinux will create the location to which Microsoft Office will be installed; during the process, accept the default install location (probably something starting with C:\Program Files...).  This will be mapped automatically to a directory under your user directory.
Assuming all goes well (not a foregone conclusion), you'll be able to run your Microsoft Office applications from your menu.
This same/similar procedure can be used to install almost any wine-compatible Windows application.  That step one above is always the most important.


Boiler Heat -3 Zones, 1 won't shut down when reaches temperature

Question: I have a tri-level home, 3 zones with 3 individual thermostats. This is a pretty old school system.  The home was built in 1969.
The mid level seems to run constant, even when the thermostat is turned completely down where it shouldn't be running.  Temps have exceeded 80.
I thought it might be time to switch out the old mercury t-stat to a digital one.  I purchased a honeywell programable one that I thought would work.
Behind the old switch were 2 green wires twisted together and around one terminal (I think W) and a green and white wire twisted together and around the R terminal   What I am getting from the instructions is that I need to connect to the Rh and W terminals.  Since I don't have air, fan and it's not a smart t-stat, where do I connect the remaining 2 wires?  I assume they don't stay twisted together and in the same terminals.  Any help would be appreciated.
Also, if this isn't the solution to maintain a regular temperature on our main floor zone, what can I do to fix it?
Thank you!
Comment: Did removing the thermostat make the heat stop running?
Comment: Weirdly, it did not.  It only stops when we flip the switch at the unit
Comment: I'd troubleshoot at the unit then before replacing the thermostat
Comment: Is the pump running when the thermostat is off and the other zones are not calling for heat? If so, you have an electrical problem - if not, it's thermosyphoning.
Answer: Most likely (since removing the thermostat didn't stop it) you have thermosyphoning causing heat delivery with no pump running. That's a pretty common installation defect for boiler systems. Hot water from the boiler in the basement rises into whichever zone is "easiest" and cold water falls from there back to the boiler.
Typically this means you need some sort of heat trap to stop the thermosyphoning while permitting pumped flow. Spring check valves and deep U bends are two common types of heat traps.
Alternatively, you have a pump running and/or a zone valve open when they should not be, but that's more unusual and requires an electrical defect.
Comment: Thank you very much.  This is officially over my head...lol.  I think I am going to just hook the old t-stat back up with the 2 green wires on top and the white and green on the bottom since I don't know where to put the 2 extra wires on the new t-stat.  Attaching a pic of new t-stat available connections for extra 2 wires if anyone knows what to do with them.
Answer:
Pic is of the available connections on the new t-stat.  I think that I only need the R and W, but have 4 wires.
Comment: This should be edited into the Question, it does not belong as an Answer.


What does it mean: "Everything looks OK but loss won't decreases!"

Question: I have written a LSTM network. It seems all the things are OK but when I train the network, I get the same loss amount about 4.9e-4 for every iterations! What is the problem? Why my network can't decrease the loss amount?
Answer: IF EVERYTHING ELSE IS OKAY then ideally, your loss should decrease every epoch which means your model is learning and updating weights accordingly.
Steady loss might mean that your model has over-fitted data. Your model has memorized data and there is no room for improvement. Maybe

1) You have less data with very complex LSTM. Try having very simple LSTM.
2) Apply regularization layer in between.


Transition Matrix eigenvalues constraints

Question: I have a Transition Matrix, i.e. a matrix whose items are bounded between 0 and 1 and either rows or columns sum to one. I would like to know if it is possible that in any such matrices the eigenvalues or eigenvectors could contain an imaginary part. Thanks in advance.
Answer: The matrix
$$
A=\left(\begin{array}{ccc} 0&1&0\\ 0&0&1 \\ 1&0&0 \end{array}\right)
$$
has row and column sum equal to one, but has complex eigenvalues. The characteristic polynomial is
$$
det(\lambda I-A)= \lambda^3-1.
$$
Answer: I think it is worth pointing out that, having daw's fine upon which to build, we can easily construct a family of irreducible transition matrices which also have a pair of complex conjugate eigenvalues, where by "irreducible" I mean there is a non-zero probability of any state transiting to any other state in one step, that is, all matrix entries lie strictly 'twixt $0$ and $1$.  (Not sure if this terminology is standard, but I know the underlying concept is important and useful.)  For if we let
$A = \begin{bmatrix} p_1 & 1 - p_1 - q_1 & q_1 \\ p_2 & q_2 & 1 - p_2 - q_2 \\ 1- p_3 - q_3 & p_3 & q_3 \end{bmatrix} \tag{1}$
with the $p_i, q_i$ sufficiently small albeit nonvanishing positive real numbers, the the resulting $A$ will still have a pair of complex conjugate eigenvalues, by virtue of the well-known fact that the zeroes of a polynomial depend continuously on its coefficients.  The polynomial in question here is of course the characteristic polynomial $p_A(\lambda)$ of $A$.  Since the complex eigenvalues in the case $p_i = q_i = 0$ are distinct, they remain so for small $p_i, q_i$.  Of course, $1$ remains a real eigenvalue of $A$, since
$A\begin{pmatrix} 1 \\ 1\\ 1 \end{pmatrix} = \begin{pmatrix} 1 \\ 1\\ 1 \end{pmatrix} \tag{2}$
for any $A$ the row sums of which are $1$.
Hope this helps.  Cheerio,
and as always,
Fiat Lux!!!
Comment: Though it is confusing terminology, transition matrices with all $p_{ij}>0$ are typically called "ergodic", because they satisfy the "ergodic theorem" (i.e., there exists an invariant measure and any initial measure will converge to it). "Irreducible" typically means that any state is accessible from any other state with positive probability (but possibly in more than one time step).
Comment: OK, thanks . . . it's been awhile since I worked on Markov chains, so my recollection of the terminology is perhaps a little rusty.  I guess I can save my posterior in this case by pointing out that I pointed out what I meant by "irreducible" in the post . . . must have been a little uncertain!  Thanks!


Possible to parallel PC power supplies & increase voltage to 14 VDC?

Question: I'm in need of 14 VDC @ 100 amps. Switching power supplies are available but too costly. I have enough supplies left over from various desktops to assemble such a beast it's just how? This is to power a 500 Watt HF amplifier so solid voltage regulation and excellent filtering is a must. I've found projects to convert a PC power supply as a multi-voltage bench supply but nothing found to increase the 12 volt rail to 14 volts and then parallel for greater current.
Comment: P(watts) = E*I, 311 volts at 100A works out to 31.1 KW, far more than the output of my amp!
Comment: I'm not AN EE, but how about this: rectify 230V -> 325V DC. Minus 14V = 311V. Use a 3.11 ohm series resistor to create a 311V drop at 100A. This has to be a power resistor ;-)
Comment: Yeah, I know, I told you you'd need a power resistor :-) (I was just kidding!)
Comment: If you are asking these questions, I don't think it is safe for you to try to power a 500 W HF amp. Apart from you needing a license in most, if not all, countries.
Comment: Data sheet for the amplifier? It should tell you the noise requirement on the power supply, if any.
Comment: I built the amp from plans, so no idea on noise requirements.
Answer: No, you can't generally parallel multiple supplies and get higher voltage.  Each supply will regulate to a specific voltage.  Even if all are rated the same, some will be a little higher and some a little lower.  The ones set a little higher will take most of the load.  There may also be oscillations as the multiple supplies try to fight each other.  In no case does this have anything to do with making more voltage.
It is possible to parallel some supplies to achieve higher overall current.  However, the supplies need to be designed or rated for this.  Switchers are often easier to design for paralleling.  Some even have a current sharing signal.  This signal is connected between the supplies, which is used to level the amount of current each supply produces.  Some supplies achieve this instead by having a somewhat soft current limit.  Even if one supply is set a little higher than the others, it will hit its current limit and its output voltage will drop a little.  This causes other supplies to kick in and start producing current to hold up the bus.  This is generally not considered as good as deliberate current sharing, but it can work with the right design.
In any case, you're going to need switchers one way or the other.  You want 1.4 kW out, so dealing with waste heat is going to be a major design issue.  Even at 90% efficiency you still have 156 W of heat to deal with.  That's not trivial.  You say switchers are too costly, but what you want to do is not trivial and doing it right will cost.  If you think switchers are too expensive, take a look at the total cost of the alternatives!
Answer: It may be possible if you have done this before, otherwise your power cable will become a 1 kW CB noise jammer. I've seen it happen many times from Mainframes with current shared PSU's to towers we made at Unisys in Rancho Bernardo with OEM PSU's that were designed for current sharing with cross feedback of current. The fix implemented was fine tuning of each supplies voltage and 10% of rated power dummy resistor. When you do not have symmetrical rate of change of voltage in a no-load condition, it is non-linear and the PSU's will oscillate at low RF frequencies at full power.
I have never seen a 1.4 kW HF radio designed for 14.0 V but certainly spec'd at 14V with a range of 10~18V or 12~15 etc. I agree switching noise or humm must be avoided, but how low is required?
This is what I recommend;

Test your radio on your vehicle after confirming the voltage is within spec.  Cars are typically 14.2V +/- 0.2
Use welder's cable or starter cable and connect to radio.
Test for noise levels on transmit and receive with another radio.
Put in a remote starter for your vehicle and run it when you need to power your radio.
If you really need it 24x7. bring a car battery inside to power the radio and make sure it has low ESR = good specific gravity in each cell. ( very important )
Use a regulated battery charger to maintain voltage at 14V then add essential Ferrite filters for CM choke on twisted pair power cables with low ESR (1 mΩ ) plastic caps ( I prefer Panasonic)

Please report on each step of your test results and specs for power source noise acceptable levels and ensure you use 50 Ω method for measuring noise.
Comment: Don't forget to add a stove type suitable rated fuse or magnetic breaker (household type) and allow for voltage drop on cables, connectors & fuse. 0.1V max if done right ( <1mΩ), >0.4V if not. This requires some effort to regulate, so please get specs.
Comment: Well 1-3 have been done in the past in a Dodge 2500 diesel, check my profile for my website to read about that install. I no longer own the Dodge but do the amp. The rig is an Icom 7000 powered by a separate supply. 4 is simply too far away to work. You did give me an idea, how about using one of those very large capacitors normally used on high powered car audio amplifiers?  The main mode is single sideband, so the amp can draw up to 75 amps on voice peaks.
Comment: SuperCap or even better UltraCap's can help a  bit on AC ESR but battery may have lower ESR.  Long cable inductance from front to rear of car is reason for SuperCaps help audio amps. But Battery connected close to supply such as  1000 CCA battery means ~ 5mΩ ESR.  If you get acquainted with the ESR of each component and report back, I can tell you what will help the most.  V vs I with ∂V/∂I = ESR.  Car batteries should have Spec. Grav.= 1.26g/cc to 1.29g/cc and matched within +/-1.5%  same for voltage per cell.  Also Battery open rested voltage = (S.G. + 0.84 )*6 otherwise not charged or bad
Comment: I just checked Super CAP-XX specs... 150F at 14V, and an ESR of 4.5 milliohms, the CAP-XX module offers the best power density available today  ( Those are expensive 150 Farad Caps not the ones you are thinking of for audio systems) so not much hope there.
Comment: BTW... 1000 CCA means current at 7.5V @ -18'C from fully charged battery. i.e. from 13 to 7.5 = 5.5V so ∂√=5.5V  and if ∂I=1000A then ESR is 5.5mΩ but ESR can be measured at much lower currents too.
Answer: Yes, is possible to increase voltage up to 14.5V for a PSU and to parallel two or more to increase oputput current (power). Some server PSU have a pin (RETURN) that alow to increase otutput voltage to about 14.5V; regarding paralleling, need to have care that each PSU share about same current as each others.


MLP conv layers

Question: When should MLP conv layers be used instead of normal conv layers? Is there a consensus? Or is it the norm to try both and see which one performs better? I would love to better understand the differences between the two.  Also which deep learning libraries support MLP conv layer?  They are used in this paper Network in Network
Comment: Would you put a citation to `MLP conv`? I've not seen them.
Comment: added a paper that used them
Answer: The term normally used to refer to "MLP conv layers" nowadays is 1x1 convolutions.
1x1 convolutions are normal convolutions, but their kernel size is 1, that is they only act on one position (i.e. one pixel for images, one token for discrete data). This way, 1x1 convolutions are equivalent to applying a dense layer position-wise. The term "MLP convolutional layers" used in the network-in-network paper is a reference to this fact.
While normal convolutions use the spatial information and therefore they can detect local patterns (spatial locality inductive bias), 1x1 convolutions do not, as their window of action is a single position. They are simply used to change the dimensionality of representations, specifically to change the number of channels in images, or to change the embedding dimensionality in discrete data. For instance, if at some point of a 2D convolutional network we have a tensor of width $w$, height $h$ and $c$ channels, we can use a 1x1 convolution to obtain a tensor of width $w$, height $h$ and $c'$ channels, where $c \neq c'$.
Answer: In normal convolutional layers, ReLU activation function is used. ReLU is fixed and cannot be trained in itself. MLP Conv Layer is combination of Convolution operation and Multilayer Perceptron Network. If you use MLP after Convolution, you can learn much more complex function(mapping input to output).
It increases capacity of your model as well, and can fit more data.
For comparison you have to try it yourself. Some comparison is shown in the paper itself.
There is also another paper that does a similar thing. Check: Learning Activation Functions to Improve Deep Neural Networks
You can make your own MLP conv layer in deep learning frameworks like Tensorflow and Pytorch. Someone might have already built it as well.

MLP conv layers


Can a weak entity type be involved in an "is-a" relationship?

Question: Considering the scenario depicted in the diagram below, as the title says, can a weak entity type take part in an "is-a" relationship?
Answer: When I've modeled databases, I would use a isType description where you have isA.  You appear to have two types of Specs; labelSpecs and itemSpecs.  Common data belongs in Specs entity, with type specific data in the appropriate subtype record.  Normally subtypes are exclusive, so a Spec would be either a labelSpec or an itemSpec.


Touch iPhone/iPod/iPad Transactions

Question: I heard that there are applications that allow people to do transactions by just touching there iPhones to each other. How is that archive via code in Objective C?
Answer: I beleive each phone has to detect the "bump" (using UIAccelermeter) and send an immediate notification of the event ot a server (perhaps with a timestamp and some geolocation info too?). Then the server matches up events that occur at the same moment, to determine the two devices involved. Then the server facilitates the transaction by sending each phone's info to the other.
Answer: take a look at the Bump API http://bu.mp/api.html as used in the Bump iPhone application. I haven't used it myself so I cannot say how easy it is to integrate but they claim it only requires you to add ten lines of code.
Answer: The way I would do it would be to have each device send the other their UID over bluetooth and then have them both send a message containing the other devices UID and their own UID to the server with a timestamp, then have the server handle the transaction.

Touch iPhone/iPod/iPad Transactions


Equivalence relations and the axiom of choice

Question: Let $X,Y$ be two sets and  $f:X\rightarrow Y$ a function. If we  define an equivalence relation $\sim$ on $X$ and we assume that if $x_1\sim x_2$ then $f(x_1)=f(x_2)$, we can define a function
$\overline f:X/_\sim\rightarrow Y$ such that $\overline f([x]):=f(x)$. Practically if we have a set of representatives $R$ for the relation $\sim$, then we completely "know" the function $\overline f$. But if we don't assume the axiom of choice, the set $R$ can be empty, is it right?
Comment: "algebra-precalculus" seems an odd tag for a question about the Axiom of Choice.
Comment: edited, many thanks.
Comment: Are you trying to define $\bar{f}$ without the Axiom of Choice?
Comment: Yes I'm asking if $\overline f$ exists without assuming the axiom of choice.
Comment: @Galoisfan: my answer explains that it does
Answer: We may not have a set of representatives without the axiom of choice. That doesn't mean the set of representatives is empty, it just means it does not exist - there is no set that satisfies the definition of a set of representatives for $X/\sim$.
But we do not need a set of representatives to define the function $\bar f$ in ZF. It can be defined as follows:
$$
\bar f (C) = y \Leftrightarrow (\forall x \in C)[f(x) =y]
$$
In other words, $\bar f$ is the set of pairs $(C,y)$ where $C \in X/\sim$ and $(\forall x \in C)[f(x) = y]$. That definition of $\bar f$ works in ZF without the axiom of choice. Rather than using representatives for the equivalence classes, we can just use the equivalence classes themselves.
In case you are worried about $X/\sim$ itself, it is definable as
$$
\{ C \subseteq X : (\exists z)(\forall y)[y \in C \leftrightarrow (y \in X \land y \sim z)]\}$$
Comment: I don't know if the following remark is helpful: by adopting a more "functional" perspective one could say that to give a set of representatives is to give a function $r \colon X/{\sim} \to X$ right inverse to the projection $X \to X/{\sim}, x \mapsto [x]$. One can then define $\bar{f} = f \circ r$ and check that $\bar{f}$ is independent of the choice of $r$. You show that the detour back to $X$ is unnecessary for establishing the existence of $\bar{f}$.
Answer: This is essentially as saying that every $f\colon X\to Y$ can be restricted to some $R\subseteq X$, and the restriction is an injective function with the same range as $f$.
The above is equivalent to the axiom of choice, so whenever the axiom of choice fails this principle must fail somewhere as well.
It should be pointed out, however, that the set of equivalence classes still exists. The set of representatives (to which you want to restrict the function to) does not. For example $\mathbb{R/Q}$ always exists, but if all sets are measurable then you cannot define a Vitali set, which is that system of representatives.
Comment: And this marks my 200th answer on [axiom-of-choice].
Comment: Congrats. How long did that take?
Comment: I started meddling seriously about topics of choice two years ago. I may have gathered a couple of answers before that, but roughly two years ago I began taking it more seriously.
Comment: Congrats on the gold! Too bad Brian got his bronze badge a while ago.
Comment: @Arthur: Yeah... Good luck to Vera/congratulation to you both, by the way.
Comment: Thanks, Asaf.  We're still waiting... less and less patiently as the days pass.
Answer: Yes, if you have a function $f:X\to Y$ then you completely know the function if you define the equivalence relation $x~x'$ if $f(x)=f(x')$, choosing a representative from each equivalence class and recording the value of $f$ on each representative (notice that this is slightly more accurate than the original statement in the question). Without the axiom of choice, or some extra knowledge of the domain of $f$ and/or $f$ itself, there is no guarantee that the set of all representatives exists.


"ristretto" slideshow in fullscreen

Question: I am using xubuntu atm and my biggest issue is, that ristretto show pictures in 100% zoom.
When I run a slideshow, I want it to expand to full screen.
I can only enable that for one picture at a time, and this gets reset if I switch to antother picture.
Comment: My absolutely preffered kind of answer is, how to enable that within ristretto. An alternative would be an image viewer with few depencies but nice integration.
Answer: I do not use Ristretto (a little at my Linux life start only) and people often suggest "eliminate this utility" (quote). And despite this fact if I right figure out you need to know where exist such checkbox alike first at Ristretto Menu > Edit > Preferences:

I think more settings for Ristretto you can find at Settings Editor (xfconf GUI), and you can see ristretto exists at settings channels list:

Alternatively I do not know what to suggest.
If I'll needed to use XFCE I'll chosen Feh which also lightweight also image also viewer however Feh it is "barebone" image viewer and can be a bit difficult for plain user.
So, look if interesting Feh
Hope it help you.
Comment: The first suggestion doesn't work  on my xfce 4.12, it just opens risettro in full screen, with a tiny image in the middle. I can zoom to fit, but the next image doesn't work. #2 didn't have any options of risettro. @didn't try the third.
Answer: OK, I was looking for this in ristretto, but I gave up. Don't know how to set stretching image to screen without clicking it at every image. Shotwell also was beyond my skills.
However, I may found satisfying solution for your needs.
To create presentation with stretched and fitted images simply run vlc (which I consider to be basic video player on every computer) hit ctrl+shift+O and add image files you want to be in slide show.
Tricky thing is duration of single slide: hit ctrl+P mark Show settings ⇒ All and then go to: Input/Codecs ⇒ Demuxers ⇒ Image ⇒ Duration is seconds (by default 10 seconds).
If you want to infinitely repeat presentation, just hit loop button.
Hope it helps.
Comment: Thanks, this worked well for me. Shotwell has removed the slideshow feature. At least, I can't find it in 16.04. And EOG can only delay for up to 90 seconds between images.
Comment: If you haven't found another solution, the package mirage is a huge upgrade over rissetro, with the same ui.
Answer: Settled on mirage; it has features of risttreto plus a lot more customizability, including remembering last settings - both on next image, and on next open.
package-manager install mirage

Tried viewnoir, but it no thumbnail preview is a dealbreaker.

"ristretto" slideshow in fullscreen


ASP.NET or Ruby on Rails for someone new to web development?

Question: I have experience in client-server application development in C/C++ on Windows platform. I would like to get into web based application development. I have an understanding of web application development concepts in general. Which web application development framework would be the quickest to learn/master? I am currently learning .NET and C# but the current Microsoft web application development stack appears to have a steeper learning curve with its myriad technologies like ASP.NET, MVC, SilverLight and WCF. On the other hand I keep hearing about Ruby and Rails and it appears that Ruby is much easier to learn and Rails inherent use of MVC is the most natural way to develop web applications & is also much quicker to develop. I am leaning more towards Ruby but I am worried that I may slowly move away from the Windows platform into some unchartered territory.
Answer: Try web2py framework: http://www.web2py.com/. It uses Python and in my opinion is very easy.
Answer: It's not that Ruby-on-Rails is bad stuff - in fact, it's awesome!
Yet everything is about trying out and especially your own preference.
You have experience with C# and .NET (I guess you have also experience with Windows Forms).
The concept of Windows Forms and C# as the "code behind" you'll have no big issues adapting to WebForms or Silverlight.
Except there are some web specific things but there is an amazing learning opportunity at http://www.asp.net
I have had the same learning curve as you have and learned basic ASP.NET development in less than a month. (Things that I couldn't do, either in PHP / Symfony nor JS out of the box).
ASP.NET MVC is a great framework that has a similar functionality to Ruby-on-Rails/Symfony - yet it is a little bit different and has some MS specific features which are also amazing.
I would suggest you to get the following book: Professional ASP.NET MVC 1.0
Answer: If you would like to stick with with c++, try wt: http://www.webtoolkit.eu/wt .
From my limited experiance, php and certain frameworks built on it are the easiest to jump into.
Web2py is a nice portable python framework (I'm told that code works in google appengine without modification), which you could look into as well.
But it boils down to personal preferance. Try on all the shoes that you can find, pick the one that fits you best.
Answer: First off you should know that moving to web based application development from client-server stuff can be a learning curve in and of itself. I recommend learning at least the basics of HTML, CSS and JavaScript as well as your programming language of choice.
Try out 2 or 3 different languages to start with and go through at least a basic tutorial on each to get an idea of what your likes and dislikes are. When I started the first 3 I tried were ASP, PHP and Perl. I went with PHP for many reasons which I won't get into here but the point is you just have to try it out for yourself. Since then I've learned Ruby, Python, Java and want to learn Scala soon. For starters I usually recommend trying Ruby or PHP. If you try PHP be sure to also look into CakePHP or another MVC framework to get you going faster.


What types of challenging atmospheres might exist on an ice planet?

Question: We know that Venus has a poisonous carbon dioxide and hydrochloric acid atmosphere at a temperate of over 800 °F, but what about an ice planet? Mars is mostly freezing with a trace atmosphere, we have Titan with its nitrogen-rich atmosphere, and there's Triton with its ice vents, but I'm thinking about an ice planet with an actual, fairly thick atmosphere. What chemicals might exist and what acidic or otherwise challenging atmospheric conditions might exist on an ice world?
Comment: Just to clarify, are you asking for acidic atmosphere at <270K that might coexist with a planet covered in ice, irrespective of plausibility?
Comment: Ice planet as in "water ice"? If you want a real challenge, try having a planet with a surface including frozen oxygen.
Comment: Thanks for the questions. This planet would have an acidic or otherwise corrosive atmosphere, perhaps something thick and soupy, one that would provide a materials challenge for anyone wanting to don a suit and walk on its surface. I see it as having large seas or oceans that are either largely frozen water or some other fluid (perhaps one with a much lower freezing point, so the seas could be liquid at the freezing temp). And yes, irrespective of plausibility.
Comment: Just so you know, [Titan's atmosphere is 45% thicker than Earth's](https://en.wikipedia.org/wiki/Atmosphere_of_Titan).
Comment: A large amount of water would dilute any acid, as water is pretty much neutral.  Unless you have seas of sulfuric acid or whatever acid in the atmosphere. I am not sure how that relates to low temperature though.  Maybe water freezes but the acid dosn't, that's beyond my pay grade.
Comment: The atmosphere would be *very* dry, since all the water vapor would precipitate out.  One must also ask where all the hydrogen chloride and/or nitrogen oxides (the gasses which dissolve in water to make the relevant acids) come.
Comment: Thanks for the answers, everyone. Very helpful. Could the hydrogen chloride, nitrogen oxide, and carbon dioxide gases come from sort of subterranean vents and then by some other means subsumed back into the system (acid hail?).
Answer: Those who are a bit familiar with chemistry know that the reaction rate of any reaction is strongly dependent by the temperature.
The dependence goes like an exponential of the absolute temperature, therefore lowering the temperature to the realm of icy planets really lowers to the point of almost nullify the chemical aggressiveness of any compound.
But the extremely low temperature is a risk by itself: materials become extremely brittle when they are at cryogenic temperatures (see what happens to a rose in liquid nitrogen)

Besides brittleness, any lubricant would become pretty ineffective, and proper motion of mechanical parts would become a nightmare for the engineer daring to design for those conditions.
So, if you are looking for challenging environments, the cold is already enough.
Answer: The ice planet regions of earth are already very challenging.  An increase in atmospheric pressure and / or wind velocity would make them even more challenging.

http://www.wondermondo.com/Countries/An/Antarctica/Antarctica/Commonwealth.htm

The chief meteorologist of Douglas Mawson's expedition to Commonwealth
  Bay C.T.Madigan wrote in 1913:
"For nine months of the year an almost continous blizzard rages, and
  for weeks one can only crawl about outside the shelter of the hut
  unable to see an arm's length owing to the blinding snow drift..."

The Antarctic has strong winds, freezing cold, and ice.  Windborne ice particles can abrade and eventually destroy anything in their path.
That is already pretty harsh.  Increasing the kinetic energy of the wind (and with it the mass of airborne ice particles impacting your hapless explorers) would make it harsher.  You can increase kinetic energy of wind 2 ways.

Higher wind speed.  Kinetic energy of anything is 1/2mv2 and so kinetic energy of your moving air mass will increase with the square of the velocity.
Increase atmospheric pressure.  This works on the m side of 1/2mv2 : increased atmospheric pressure means increased mass of gas that comprises the wind.  Gas is already denser the colder it is.  You can increase atmospheric pressure by just having more atmosphere (so a higher column of gas above you pressing down), or incorporating heavier gases.  CO2 and NO2, for example,  are bigger molecules than O2 or N2 and because all gases are the same volume at equivalent temperature and pressure, a gas mix containing these big molecules will have greater mass than one without.


What is there in learning to ride a bicycle?

Question: Why do we need to learn to ride a bicycle? We just need to pedal and move the handle. I don't think balancing needs to be learnt. What is the thing we need to learn to ride a bicycle or is it just telling the brain that it is ok? And why do we not forget cycling? Thank You.
Comment: You should do some research on how balancing works. It is not just about holding your head straight. You can start here: [Balance (ability)](https://en.wikipedia.org/wiki/Balance_(ability))
Comment: Can you walk on your hands and walk on a cord? Can infants walk the moment their legs can hold them physically? They're just balancing acts according to your reasoning...
Answer: Riding a bicycle is the clasical example of procedural memory.

Procedural memory guides the processes we perform and most frequently
  resides below the level of conscious awareness. When needed,
  procedural memories are automatically retrieved and utilized for the
  execution of the integrated procedures involved in both cognitive and
  motor skills, from tying shoes to flying an airplane to reading.
  Procedural memories are accessed and used without the need for
  conscious control or attention.
Procedural memory is created through procedural learning or, repeating
  a complex activity over and over again until all of the relevant
  neural systems work together to automatically produce the activity.
  Implicit procedural learning is essential for the development of any
  motor skill or cognitive activity.

When we learn to ride a bicycle, the brain is learning the motor movements necessary to maintain balance. This learning occurs mostly at the unconsious level, and this is probably the reason why you have the illusion that nothing is learnt.

Motor control is the process by which humans and animals use their
  brain/cognition to activate and coordinate the muscles and limbs
  involved in the performance of a motor skill.

The procedural memory is a type of long term memory which has a long lasting effect.


What Minerals are used in crafting?

Question: It appears that minerals and artifacts are mainly used to donate to the museum. But some, like Earth Crystals, are used in crafting recipes. What other minerals need to be saved for crafting purposes and what can just be sold after the first one has been donated?
Answer: Cross-referencing the Crafting and Minerals pages of the Stardew Valley Wiki, the minerals that can be used in crafting are:

Aquamarine (Marble Brazier)
Diamond (Ring of Yoba)
Quartz (refined quartz for numerous recipes)
Fire Quartz (Slime Egg Press)
Frozen Tear (Warrior Ring)
Earth Crystal (Mayonnaise Machine, Sturdy Ring)
Marble (Marble Brazier)
Coal (20 crafting recipes, use in furnace for refining ore and quartz)
Copper Ore (Cherry Bomb, Flute Block, Drum Block, Furnace, copper bars for numerous recipes)
Iron Ore (Bomb, iron bars for numerous recipes)
Gold Ore (Mega Bomb, gold bars for numerous recipes)
Iridium Ore (iridium bars for numerous recipes)

Artifacts seem to have very little use in any crafting. According to the Artifacts page:

Artifacts aside from the Ancient Seed are not used for Crafting or
  requested by Villagers for quests.

Minerals can also be used for Bundles in the community center:

Aquamarine (Dye Bundle)
Quartz (Geologist's Bundle)
Fire Quartz (Geologist's Bundle)
Frozen Tear (Geologist's Bundle)
Earth Crystal (Geologist's Bundle)
Frozen Geode (Field Research Bundle)
Copper/Iron/Gold Bar (Blacksmith's Bundle)
Comment: Minerals can also be the object of a fetch quest, so it's worth keeping one of each type around, whether they're useful for crafting or not.
Comment: @Nathan This is true, I didn't add them here because the question specifically asked about ones used in crafting. I suppose the bundles technically aren't about crafting either... but some are, and some help further crafting. But you're correct, it'd be advantageous to keep at least one or two of each for the `Gathering` quests from Clint, and the `Delivery` help wanted quests (described on the [Stardew Valley wiki page](http://stardewvalleywiki.com/Quests#Gathering) under those same headings).

What Minerals are used in crafting?


Open source code posting. Is a license required?

Question: I recently came across this question which had a portion of Chromium code in it. At the bottom they put the license for the code(which is BSD style). Is this actually required? How is the snipplet of code actually licensed since they put it on SO which demands CC? Is it legal to even post such code?
Answer: I am not a lawyer, but...
The posting of the text of the original license is not required; the OP could have just mentioned that it was a BSD license.  If the source of a snippet is mentioned, it's straightforward to go find out what the license is, and anyone who wants to use code (regardless of source) should do this, and abide by the original license terms.
The cc license cannot, and does not, override the terms of an existing license.
It goes without saying that, if the license does not permit you to post snippets of code (i.e. a proprietary license), you should not post it on SO.
Comment: Does the fair use doctorine apply to code?
Comment: @Casebash: If you are referring to the ability to reuse code in another application, most licenses require you to follow the terms of the license to do that, even if it's a relatively small part of the code. In general, you can publish small parts of open-source code on forums like SO, unless the license specifically prohibits it.
Comment: Well I don't plan on seeing someone attack SO for allowing open source code to be put on here without the appropriate license so..
Comment: "Fair use" is the exception to copyright protection for fragments of protected works in a critical or academic context; in parody; and a few other situations. Ask a lawyer for certainty and for a discussion of the limits of fair use, but I would imagine that it applies.
Comment: @Robert: As dmckee said, the fair use doctorine is an exemption from copyright. So copyright laws generally can't be used to enforce terms of a license that would prevent fair use, but contract laws on the other hand can. So snippets of some proprietary code may be allowed depending on whether the license is protected by copyright laws or contract laws. As always, the law is complex and depends on jurisdiction, so talking to a lawyer is the only way to know for certain.
Comment: @Casebash, See here: http://cyberlaw.stanford.edu/packets002733.shtml
Comment: @Robert: Interesting. SO copyright law may sometime preempt contract law, but whether it will seems unclear.


When can I farm a boss?

Question: When farming a boss, do I need to do all of my farming before turning in the related mission, or, after turning in the mission, can I later go back to farm said boss?
Comment: I've edited your question to what I think you meant. If I'm incorrect, feel free to roll it back to the original question.
Answer: A boss can be farmed at any point after you have reached it. Once you have beaten it, you can turn in the related quest, then save and quit, or even just leave the area and enter it again, and the boss will have respawned, ready to be farmed.
Comment: Bring friends mayhem awaits.

When can I farm a boss?


camera shutter works only with live view shooting

Question: i have a canon EOS 550D but when it's time to use it, the shutter stopped clicking. but when i used the live view shooting, the shutter works. did i clicked on something? or do i need some settings to reset?
Comment: It is very difficult to say, what is happening without any information about the settings you use while you try to take a photo. Can you supply more information? What have you tried? Did you try to factory reset your camera?
Answer: Sometimes with the earlier rebel series cameras, when going in and out of live view, the shutter can act sticky. Make sure you are in a photo mode (PASM) and that you are not using live view. If it is stuck open, try turning off the camera, switching modes, and turning back on. Let us know if this solves it.


Can my apartment management stop me having visitor friend with pet? not overnight

Question: We do not have anything mentioned in the lease about pets. I have moved in this apartment from 2015 and just last year they sent out pet policy changed and , no pets allowed.
My friend visited me with her small dog for few hours and the manager contacted me directly with the pet removal notice. I am not sure if he is doing that to charge me for extra money or something? because few hours dog was just sleeping and there is none property damage. I just need to know what Can I do if he do want me to charge fees. If it's legal for him to do or not.
Comment: This depends on where you live.  Laws are different in New York, Texas, Paris, etc.
Answer:
Can my apartment management stop me having visitor friend with pet?
not overnight

Absent a local statute or ordinance to the contrary, or Americans with Disabilities Act (ADA) considerations (e.g. for seeing eye dogs), yes, your apartment management can stop you from doing this if the lease authorizes them to do so.
It sounds like the original lease from 2015 that didn't prohibit pets was changed at the time of a lease renewal in this case, which landlords are usually allowed to do.


Technical review article on black hole thermodynamics?

Question: Can anyone recommend a resource on black hole thermodynamics for physicists who are not familiar with this area? I'd like to see a rough sketch of the derivations of black hole entropy and Hawking radiation, for example. Something at the level of a review article or informal collection of notes aimed at physicists or grad students would be ideal.
Comment: Expositions on Hawking radiation in particular can be found in Wald or even Carroll
Comment: Like Nihar said, QFT in curved spacetime is what you need for the derivation of Hawking radiation. Carroll covers it pretty nicely. More broadly, if you're interested in the quantum aspects of thermodynamics of blackholes, I personally like these notes by Atish Dabholkar a lot: https://arxiv.org/abs/1208.4814.
Answer: Ted Jacobson's "Introductory Lectures on Black Hole Thermodynamics" (1996) give a rather didactic introduction into the topic, discussing the physics with as little advanced mathematics as possible. It is very useful, in my opinion, for getting a feeling of the the main ideas, and seeing a bigger picture behind them.
A more recent review by Aron Wall provides succinct bits of more up-to-date "memes" of the field. It is not designed to be a thorough course, but can serve as a nice gateway to current research literature.
Answer: Bob Wald's Living Review, The Thermodynamics of Black Holes, is 20 years old, so it is missing the most recent developments.  It touches on the big topics of classical BH thermodynamics, Hawking radiation, and BH entropy, and it is well referenced.
It is a relatively high level summary, outlining arguments without presenting detailed calculations.  It does assume the reader has familiarity with the technical vocabulary of general relativity.  For more technical detail the reader can follow the references.


what is the cheapest way for sending ethereum from 10 account addresses to 10 account addresses?

Question: What is the cheapest way to send ether to 10 addresses? By using smart contract or using externally owned account to send one by one...? I know that the gas limit of a normal transaction is 21,000...so 10 of this transaction costs 210,000 gas. I think send ether to 10 addresses by using smart contract has cost more than 210,000 gas, correct?
Answer: 10 transactions from an EOA will cost 210,000 gas.
The most efficient way to do this would be to deploy a contract that accepts funds in the constructor and subsequently distributes the funds to 10 different addresses. This will cost the initial 21,000 gas, plus the cost of the transfers, which is maybe ~100,000.
Comment: thanks for your answering...the contract that you described transfer the funds In an instant? or  contract can hold funds until 10  address send ether to contract and then transfer them to 10 address?
Comment: if you have a good refrence for this type of contract please share with me @Shane Fontaine


How much speed is maintained in a 90 degree turn?

Question: How much speed is maintained in a 90 degree turn? Is there an equation for this? I was recently driving and took a 90 degree turn while coasting at 25 mph and it did not seem like I lost very much speed. Which made me wonder what the equation was for this, does it depend on the momentum of the object?
Answer: Here what i think from a layman's point of view

Let us assume that you were driving your car in an ideal situation that is their is no friction or any other force to reduce your velocity. So when you make a turn or change the direction of the velocity of the car you apply a force on the car to do this, it should be an external force, so when you apply the force to do this the direction of the velocity of the car changes, but their is no change in the speed of the car. However in your case the decrease in the speed of the car was due to friction force between tires and roads and various other forces acting on it from the surrounding and due to the fact that the power to drive the car and turn the car was apllied from same power source however i am not sure about my last line.


Derivative of Composite Natural Logarithm

Question: What is the derivative of $\ln\left(\left(\frac{1-x}{1+x}\right)^2\right)$ with respect to $x$? I used chain rule and my answer was $-4\frac{1-x}{1+x}$. But the answer should be $\frac{-4}{1-x^2}$. Is that right?
Comment: Use the chain-rule. https://en.wikipedia.org/wiki/Chain_rule
Comment: Welcome to math.SE: since you are new, I wanted to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level. Also, many find the use of imperative ("Find", "Solve", etc.) to be rude when asking for help; please consider rewriting your post.
Comment: You accepted my answer, but I calculated the derivative of a "wrong" function, because I interpreted your notation like that. But your edit makes clear it is an other function. See user534382.
Comment: @Cornman, I apologize for that. I typed it wrongly the first time.
Comment: You are welcome. I should have asked before editing.
Answer: I assume you meant $y=\ln\left(\left(\frac{1-x}{1+x}\right)^2\right)$?
Then $y = 2 \left[ \ln(1-x) - \ln(1+x) \right]$.
With chain-rule:
$$\frac{\mathrm dy}{\mathrm dx} = 2 \left[ \frac{-1}{1-x} - \frac{1}{1+x} \right] = -2\cdot\frac{2}{1-x^2} = \frac{-4}{1-x^2}$$


Saving and retrieving information from wordpress database

Question: I am trying to create a wordpress page on the admin area where the user can set his twitter, facebook,..., addresses. It is my first time trying something like this and I am finding it quite complicated.
Searching the net, reading here and there, I have put this code together on my function.php:

BUNT THEME SETTINGS

1. Social Media Icons

Here you can set the addresses for your Social Media pages. The buttons will automatically show up on your blog.

    <form method="post" action="options.php">
        <?php wp_nonce_field("update-option") ?>

1.1 TWITTER:
            <input type="text" name="twitterid" size="70" value="<?php echo get_option('twitterid'); ?>" />

<input class="button button-primary" type="submit" name="submit" value="Save changes" />

        <input type="hidden" name="action" value="update" />
        <input type="hidden" name="page_options" value="twitterid" />
    </form>
</wrap>

This creates a submenu on the Settings Menu with a field to insert a twitter address and a "Save Changes" button
When I type an address and click "Save Changes" I get sent back to the options.php showing:
"Are you sure you want to do this?
Please try again."
("Please try again" is a link that will take us back to my new settings page, with the field again empty).
My goal would be that the user inputs the twitter address, which would then later be added to the twitter button on the blog. So I thought the way to to this would be to store the adress and then retrieve it for the button. Is this the way to do it?
Why isn't this working? How can I fix this?
Thanks!
Answer: You'd be better looking into the Options Framework. It makes this whole process a lot simpler.
https://github.com/syamilmj/Options-Framework


Weird lines on mesh after exiting sculpt mode

Question:
Hey there, does anyone know why i get these weird lines all over my mesh after exiting sculpt mode? Shading is set to smooth and normals are facing outwards. I also tried to put a subsurf modifier on top of it. Nothing helped. :/
Answer: Simply the multires modifier wasn't set high enough. Another level and an overall smooth fixed it. Still strange tho since i set preview and sculpt to the same level.


When using a search field on a website, is there a way to open the search result in a new tab in Firefox?

Question: For example, I go to http://en.wikipedia.org, I enter something into the search field, and I would like to see the search result in a new tab.
Answer: Consider using the search box next to the address bar in Firefox to search on Wikipedia directly without explicitly having to go to the search box within a Wikipedia page. Within the Firefox search box, change the provider to Wikipedia

For subsequent searches, click Alt+Enter after you enter a keyword within the search box instead of just Enter, to view results in a new tab.


How to install Synaptic Package Manager?

Question: I tried to install Synaptic Package Manager but I get the following error message:
Package dependencies cannot be resolved.
This error could be caused by required additional software packages which are missing or not installable.
Furthermore there could be a conflict between software packages which are not allowed to be installed at the same time.

Comment: Well does not your synaptic pacckage manager is installed? It seems you have your package already installed you are searching for. Goto System > Administration > "Synaptic Package Manager" and see if there is the thing you are searching here for
Comment: possible duplicate of [How do I resolve unmet dependencies?](http://askubuntu.com/questions/140246/how-do-i-resolve-unmet-dependencies)
Answer: On the terminal type in the following commands (one line at a time) >>
sudo apt-get update
sudo apt-get install synaptic

Comment: i prefer not to do the upgrade
Comment: I'd add `-f` to the update and upgrade commands if I was having problems.
Comment: why the upgrade?
Answer: Just go here and install offline way if this helps.
Synaptic packages for 12.04
Comment: why would you need any instructions if you got a .deb file already? Its the most simplest thing to install a deb file on ubuntu I guess
Comment: @ObsessiveSSOℲ: the link isn't a link to some instructions, it's a link to `.deb` files.
Answer: If this is happening then you either have a package version that is lower than the required dependency version or one of your packages is broken.
You can try fixing the packages by running your update manager and checking for updates and installing them.


Why do 0v have to be connected when using two power supplies and ULN2803A?

Question:
The other day I was playing with a ULN2803a and a stepper motor. I spent ages trying to work out why it wasn't working and why i was reading ~14V as an output on the PIC I was using. So why did I have to connect the 0V of both supplies together?
Thanks in Advance,
Dean
Answer: Just because two different supplies both have a terminal labeled 'ground' doesn't necessarily mean that those nodes are at the same voltage. In fact, if you have two supplies that have isolated output, you could have almost any potential between their ground lugs, unless you strap them together. You could find a DC offset or even significant AC between the grounds of two isolated supplies. To establish a proper relative voltage levels within your system, each component needs to have a common voltage reference, and usually that's the ground node, so you connect them for that purpose.
Comment: "Ground" is just a label.  Another word for "voltage" is potential difference.  It's the difference in potential between two points.  For convenience, we choose a point in the circuit and call it ground (0 V), and measure all other voltages relative to that point.  That point is conventionally chosen in a specific way, but you could really choose any point and measure all voltages relative to it.
Comment: I had a very similar problem when using transistors to switch power components off an Ardurino's TTL output. On a hunch I connected all the grounds and it worked. I understand the concept on a practical level, but it's still kind of odd theoretically. Has anyone got a good link explaining the "relativeness" of voltage?
Comment: For starters, all the power you have in your house comes from the AC plugs in your wall.  AC doesn't have a 'ground' as a common reference.  On top of that, many power supplies to convert AC to DC are completely isolated from the wall power, so even if there was a 'ground' reference for AC, you wouldn't have access to it from the DC (because of isolation).  And lastly, I can put 'ground' anywhere I want in a circuit it's just a reference.  It could at 5V or 1000V but as long as everyone IN THAT CIRCUIT agrees on what it is, it will work.


ubuntu installation from usb stick

Question: I have a machine which does not have a DVD drive. This machine does not have provision of booting from usb directly. Currently the machine is operating on ubuntu 9.04 version. I have downloaded ubuntu version 13.04 from the ubuntu site on to my usb stick. I have also made it a bootable disk as recommended in the ubuntu forums. The size is large and I cannot write it onto a CD and I do not have a DVD drive as I have brought out earlier. It's there any way to install ubuntu from my usb stick given the above conditions? If yes, can anyone guide me through the process as I am not very constant with the commands. Thanks
Comment: Welcome to AskUbuntu. Plugin your usb stick, setup the 1st boot to usb. After boot you will get two option, "Try Ubuntu" or "Install".
Comment: "This machine does not have provision of booting from usb directly", care to explain a little more about it?
Comment: Thanks for asking Mitch. I mean, my machine does not boot from USB even if i set the boot priority (to boot through USB) through BIOS...
Comment: @Scorpy - 1.) usb-stick needs boot-flag (can be set with gparted) - 2.) bootable usb-stick with iso-image of Ubuntu (for any machine to be bootable) can only be done with a tool like multisystem, unetbootin, Linux-live-USB-creator and else ...
Answer: Booting via GRUB
The easiest way to boot from a USB Drive is to boot via GRUB. To check if your BIOS is able to detect the USB drive and hand it over to GRUB, just run GRUB from your hard drive if it already installed, or from a GRUB boot floppy or CD. At the GRUB menu, hit the C key to enter command mode. Now search for your USB drive, using the root command to choose a drive/partition and the find command to see if you found the right one.
You can go through your devices like in this example:
grub> root (hd0,0)   # first harddrive, first partition
grub> find /[tab]    # type the slash then press [tab], and it will try to list files on this partition
Error 17: Cannot mount selected partition   # Oops no file system here
grub> root (hd0,1)   # first harddrive, second partition
grub> find /[tab]
 Possible files are: lost+found var etc media ...   # That was my hard drive with my linux install
grub> root (hd1,0)   # second hard drive usually is the USB drive if you have only one internal drive
grub> find /[tab]
 Possible files are: ldlinux.sys mydoc myfile mystick syslinux.cfg  # Bingo, that's the USB stick

Note: If you have two internal drives including your CD/DVD drive, the USB drive probably is hd2,0 and so on.
Boot the drive by entering:
chainloader +1
boot

For convenience, add these commands to your GRUB configuration (usually in /boot/grub/menu.lst):
# to boot from a USB device
title    Boot USB drive
root     (hd1,0)
chainloader +1
boot

You can check the documentation for more info : BootFromUSB
Unetbootin
Unetbootin can help you, but only if you have 2 hard-drives.
By using a hard-drive as a usb-key, you can install ubuntu directly from it !
But there's a catch : Ubuntu can't be installed on the disk who is running the live-session. So you need 2 drives.
So on your second hard-drive you need to create a new partition - for exemple at the end - with gparted.
Now with Unetbootin, you need to choose this partition : check the option "Show All Drive" and select the proper partition.
#BEWARE THIS ACTION WILL REWRITE THE BOOT SECTOR OF THE SECOND DRIVE
More Information about Unetbootin : From Ubuntu Wiki
Comment: Thanks Romain. Will try what you have said (although much of it seems greek and latin to me... :)) Never a bad time  to learn is there....  :)?

ubuntu installation from usb stick


html link to change the value of a textbox

Question: I'm trying to create text in html, that once clicked, the the value of a textbox residing near it, changes its value to be equal to that of the text clicked. Is there anyway I can do that?
In other words, I want the functionality of a button (the onClick event) for a link/text. For example: What's wrong with this?

    <input type="submit" name="submit" value=<%=text.toString()%>
        onClick="(<% TextBox1.Text=text.toString()%>)"
        style="background:none;border:0;color:#ff0000">

Answer: Assuming the input has an id attribute with value "foo":
onclick="document.getElementById('foo').value='bar';"

Frameworks like JQuery can make this slightly simpler:
$('#foo').attr('value', 'bar');

One could add this event to a span element, for example. It's best practice to use script to set these events and special styles to reflect how they act, so that without script their different (lack of) behavior still looks intuitive.
Answer: You can do it like that :
text
<input type="text" value="" id="myTextbox">

With JQuery :
text
<input type="text" value="" id="myTextbox">


Ignore certain changes for git commit

Question: Members of our team uses different version of visual studio, and VS seems to automatically update the sln file with code like:
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual C# Express 2010

or
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012

whenever we work with the solution. Can we configure git to ignore such changes? We're not interested in this line, but we are interested in other changes of the .sln file, e.g. adding of new csproj to the solution.
Answer: It's not possible to partially ignore a file. A simple solution would be to create two versions of the .sln file, and tell the team to open the one corresponding to their version.
Another solution would be a post-commit hook that rejects the commit if these lines are changed. Needs a bit of scripting, but it's feasible.
Answer: On your local side you can simply update git index to ignore changes in certain file like this:
git update-index --assume-unchanged SolutionFile.sln

The same thing can do any of your developers.
Another solution would be adding the file to .gitignore if you don't want to keep it under source control.
Answer: I would just ignore the .sln files for they are not relevant to building a project: Microsoft realized some time ago that project files must be versionable and novadays all building done by the Studio is carried out by msbuild engine which takes those .proj (and other .<whatever>proj, like .csproj, .vbproj etc) XML files and uses them to build a project.  Those files is actually everything which is needed to build a project, and the solution file just contains various bookkeeping information.
Answer: You can add a smudge/clean filter to git which calls a script to tweak the particular line to be consistent when committing. In "Can git automatically switch between spaces and tabs?", it shows how to implement a similar change, where spaces are converted to tabs on checkout, and back to spaces on commit.
You'll probably need to write the script to identify and modify the relevant line, whereas the linked example uses pre-existing unix commands for swapping between tabs and spaces.

Ignore certain changes for git commit


Madhura Kavi Alwar

Question: Madhurakavi Alwar wrote Kanninunn siruthambu. He adhered Nammalwar as his guru.
What made him to accept Nammalwar as his guru and apart from kanninuun sirutambu any scriptural works from him?
Comment: @TheDestroyer Pl read the second line again.What  instance made madurakavialwar to accept Namalwar as his guru. I think you are ot awae of kanninunn sirutambu. Just go thru the hyms composed.
Comment: Please reframe your question with proper title and explain the gist you want to know in body.
Comment: @TheDestroyer What are the questions Madurakavi asked and what was the reply from Namalwar? Here comes the instance part. I do not mind on negative voting but without giving proper answers rather not understanding the essence of the question commenting like opinion based etc is not a good thing. It is demotivation.
Answer: Kindly forgive me for the length of this answer.
Since his Avatharam in Bhulokam, Nammazhwar did not cry or ask for food like other babies of his age and hence was named Maran. He closed his eyes and entered the state of Samadhi (deep meditation) in the hollow of a tamarind tree for 16 years (this tree can still be seen at Thirukurugoor or Azhwar Thirunagari, which is the Avathara Sthalam of Swami Nammazhwar.

Sri Madhurakavi Azhwar was born earlier than Swami Nammazhwar at Thirukolur, about 2 miles north to Thirukurugoor. He was well-versed in the Vedas and Shastras and had a good knowledge of Sanskrit and Tamil. He had great devotion toward Sriman Narayana. To facilitate attaining Moksha, he thought of going for a Yatra towards the North Indian Kshetras like Ayodhya, Mathura, Kasi, Dwaraka etc. He converted this thought into action and started for the North Indian Sthalas. There, he worshipped all the Vishnu Sthalams and finally went to the Ayodhya temple and admired the beauty of Sri Raman along with Sita Piratti, Lakshmana and Hanuman. He stayed in Ayodhya for a while.
There, one night, he saw a strange light that was very brightly glowing like a forest fire in the South. Though the light looked strange, Madhurakavi considered it to be a normal phenomenon and went back to sleep. But he continued to see that light night after night and he decided to follow it. He left Ayodhya, going in its direction. He observed that bright object was a star which was travelling Southwards. He was following the star, when he finally reached Azhwar Thirunagari and the star merged with the luminous Nammazhwar sitting in the hollow of the tamarind tree.
Madhurakavi on seeing him could not believe that a child can live without eating or even moving a bit for 16 years. With great difficulty, Madhurakavi succeeded in drawing out Nammazhwar from his deep Samadhi. Finally, Nammazhwar slowly opened his eyes and smiled at Madhurakavi. Madhurakavi was still confused whether he could speak or not.
Wanting to test him, Madhurakavi questioned him as follows:

Setthathin Vayitril Siriyadhu Pirandhal Edhai Thindru Enge Kidakkum? literally meaning, "If in the womb of a dead, a small subtle thing is born, what does it eat and where does it reside?" The philosophical meaning is that "This body is made of lifeless material elements. What does the soul, which has life, eat and where does it stay in the body?"

Swami Nammazhwar replied as follows:

Adhai Thindru, Ange Kidakkum." literally meaning, "It eats that and stays there."

The philosophical meaning is that "The soul has to subsist on matter to sustain the material body and stay in this material world where spirit cannot be distinguished from body, and do good or bad actions, and hence be unable to attain Moksha."
On hearing this answer, Madhurakavi Azhwar realised that Nammazhwar is neither deaf nor dumb, but a person of great philosophical knowledge. He fell at Nammazhwar's feet and immediately decided to take Nammazhwar as his Acharyan.
Now, for the second part of your question, Sri Madhurakavi Azhwar is the only one out of the 12 Azhwars who has NOT performed Mangalasasanam to any of the 108 Divya Desa Perumals. He wrote ONLY Kanninun Siruthambu which is a collection of 11 Pasurams on his guru Swami Nammazhwar. This is his ONLY contribution to the Nalayira Divya Prabhandham. There are no other works attributed to him. He was elevated to the status of an Azhwar due to his great devotion to his Acharyan who was Swami Nammazhwar, even though he did not perform Mangalasasanam to any Perumal.
Comment: @ParthasarathyRaghavan sure! In fact Thiruvaimozhi is considered the essence of the Sama Vedam. And I belong to the Sama Vedam!!
Comment: Hello, welcome to HSE! You should add citations and references to support your answer, else it might get deleted by the community. Cheers!
Comment: Dear Arkaprabha, Kindly advise me on how to add citations and references as this is my first day at HSE. Thank you
Comment: @ArkaprabhaMajumdar There is no way of deleting this answer or addition of citation banner as it is clear and detailed answer. If the answer stands alone wihout needing sources, that is fine. However, this cites exactly what has happened along with original quotes of Nammalwar and Madhura Kavi Alwar. Nothing else needed in the answer.
Comment: @HayagreevRam Nice answer- I expected this detailed answer. Although I know the answer asked the question for the community to get a glimpse of the answer. Reciting Thiruvaimozhi for the past 10 years daily as advised by my father. Depending upon the time will recite one pathu or 2 or 3 or 4 or 5 pathus. My request is you start reciting Thiruvaimozhi and u will feel the peacefulness within you. Just mail me in case if you need any clarification on reciting.
Comment: @HayagreevRam   Gr8!! I belong to Yajur vedam. Have a look of my profile. Performing Homams.
Comment: How to highlight that yellow shade? I forgot that step.
Comment: Put this sign  >  before the paragraph you want to highlight
Comment: @HayagreevRam Jaya Jaya Sri Sudarshana! Welcome to H.SE!

Madhura Kavi Alwar


Solr facet division of 2 aggregation function

Question: I'm storing 2 type of data for each record in my Solr core. first one is the total number of tasks in each day (total)  and the second one is the total number of finished tasks in each day (finished). I want to compute how many percents of tasks was finished in each month using solr json facet query. Something like this:
{
  finishedRate : {
    type : range,
    field : date,
    gap : "+1MONTH"
    facet: "div(sum(finished),sum(total))"
  }
}

but it said

org.apache.solr.search.SyntaxError: Unknown aggregation
  agg_div

I test the following query to solve SyntaxError, but it gives me the maximum percentage of tasks that finished in a day for each month:
{
  finishedRate : {
    type : range,
    field : date,
    gap : "+1MONTH"
    facet: "max(div(sum(finished),sum(total)))"
  }
}

how can I implement this query?
Answer: Had a similar use case a while back. After searching through the official Solr documentation, I finally gave up the idea of dividing it in the query itself.
I took another approach of just calculating the two values in the Solr query and then handling the division in my code.
Something like this -
{
  finishedRate : {
    type : range,
    field : date,
    gap : "+1MONTH",
    facet : {
      "finished tasks" : sum(finished),
      "total tasks" : sum(total)
    }
  }
}


For an Xcode project, is it good to add .xcodeproj files to the source control as well?

Question: I am using Xcode 4.3.2 and realized that the project files are not added to the git repo, so I added them and committed:  (there are 6 files)
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   new file:   Proj01.xcodeproj/project.xcworkspace/contents.xcworkspacedata
#   new file:   Proj01.xcodeproj/project.xcworkspace/xcuserdata/jeremy.xcuserdatad/UserInterfaceState.xcuserstate
#   new file:   Proj01.xcodeproj/project.xcworkspace/xcuserdata/jeremy.xcuserdatad/WorkspaceSettings.xcsettings
#   new file:   Proj01.xcodeproj/xcuserdata/jeremy.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist
#   new file:   Proj01.xcodeproj/xcuserdata/jeremy.xcuserdatad/xcschemes/FlipCard.xcscheme
#   new file:   Proj01.xcodeproj/xcuserdata/jeremy.xcuserdatad/xcschemes/xcschememanagement.plist

but is it actually a good practice to do so?  (one time Xcode crashed and the folder .xcodeproj was gone).
Answer: As said your .xcodeproj is very important and should be included in your commit
I just want to add this link about using xcode with git which helped me a lot : http://shanesbrain.net/2008/7/9/using-xcode-with-git
Answer: It's important to add the project.pbxproj file, but nothing else in the .xcodeproj bundle needs to be under version control.
Answer: Well, since all the file references, build settings, target options are saved in the .xcodeproj file, yes, you should include it in your repository. I usually exclude most (if not all) user specific files, such as breakpoints, user interface state etc.


What do these IAR IDE icons mean?

Question: Quick and easy question - if you know the answer. I can't find it mentioned in the documentation. What do the icons circled in red mean?
Answer: Not sure about the icon itself, but the checkbox in that column indicates that a file (or folder) has an option override (source).
Answer: Found in the built-in help (Workspace window):
The column  that contains status information about option overrides can have one of three icons for each level in the project:
Blank There are no settings/overrides for this file/group.
Black check mark There are local settings/overrides for this file/group.
Red check mark There are local settings/overrides for this file/group, but they are either identical to the inherited settings or they are ignored because you use multi-file compilation, which means that the overrides are not needed.

What do these IAR IDE icons mean?


Xubuntu Terminal Cursor

Question: I am running Xubuntu 14.04 and the default Terminal Emulator (xfterm I think).  The terminal itself is fine but I want to change the cursor to a blinking underline rather than a solid block.  How do I do this?  Can't see anything in the settings.
Comment: It would be great, if the cursor shape would change according to `overwrite-mode` of Bash shell.
Comment: The `overwrite-mode` is shell specific, but the cursor setting is application specific, so it seems to be impossible to have this, if you use several windows/tabs.
Answer: You can change the cursor shape in XFCE terminal by editing ${XDG_CONFIG_HOME:-$HOME/.config}/xfce4/terminal/terminalrc (expressed partly as shell parameter expansion), just find the MiscCursorShapevariable and change it from TERMINAL_CURSOR_SHAPE_BLOCK to TERMINAL_CURSOR_SHAPE_UNDERLINE. In order to have a blinking cursor (any shape you defined) you must have MiscCursorBlinks=TRUE too.
System-wide defaults can be found under some of the colon separated directories ${XDG_CONFIG_DIRS:-/etc/xgd}, respectively.
See XDG Base Directory Specification for more information about which directories are used and in which order.
For details and additional options on available in the graphical configuration tool, see http://docs.xfce.org/apps/terminal/advanced
Comment: Found it!  The file in question was in ~/.config/xfce4/terminal
Comment: This did not work for me, I have already tried it.  In my case I didn't even have a ~/.config/Terminal folder, never mind any file called terminalrc.  I tried creating it but it did not work.

Xubuntu Terminal Cursor


Why is my army size halved?

Question: When my king died, the next king (oldest son) could only raise like half the army (levies) I could before.  What happened?
Comment: uhh ohmm... hmm... no, but like, it retained the big ones like 'king of poland' and 'king of lithuania' titles.  I've never played CK but played lots of EU3, and there you would keep your armies when a new king came. Is it different here?
Comment: oh crap, and I was giving away titles to keep people happy thinking as long as I kept the 'kingdom of...' I was good.  If you make it an answer I'll mark it.
Answer: I think the reason your levy decreased is due to your heir's vassal-leige relationship score being different than your original king's.  It could also be that your levy base providing buildings are not in your heir's personal demense.
The levy system is actually kinda complex but once you have a feel for it I suspect it'll make sense.
I originally said (in comments) that I thought this was related to titles, and it's not quite right.  There's a few things at play.
If you don't give your sons any land then you can end up with the "unlanded sons prestige penalty".  You need to give your first son some lands (but not the 2nd or 3rd as it'll increase a chance of war on inheritance).  This shouldn't affect your levy though, except as it may indirectly affect your relationship with your vassals.
I came across a pretty decent description of the levy system [here].1
If you lose any of the following, you'll see a bad drop:

Castles give 225 base Levy (150 HI, 60 LI, 15 LC)
Churches give 130 base Levy (45 HI, 45LI, 40A)
Cities give 115 base Levy (75LI, 40A)

Here's where you could be losing levy... especially note that if the castle isn't in your personal demesne you'll take a hit.

You raise 100% of the Levy in your own holdings. Since castles give the most and best types of troops you want to have castles in your demesne unless you don't want to use only mercenaries and vassal levy.

The following is what I was talking about with the V-L Relation

Relation with your vassal and Levy Laws determine how much of the vassal levy you can raise. Crown Authority sets the minimum levy you get and Levy Laws set the maximum:
Crown Authority → 0 min /10% min /20% min /30% min /40% min
  Feudal Levy Law → 60% max / 70% max / 80% max / 100% max (225)
  City Levy Law → 50% max / 65% max / 80% max / 95% max (115)
  Church Levy Law → 50% max / 60%max / 70% max / 80% max (130)
You always get the min levy set by crown authority but the actual amount up to the >maximum is determined by vassal-liege relation (VLR). Relation is transformed into >percentage value (P) according to the following formula:
P = ((25 + VLR) x 0.69)/100
Now when you apply P to the maximum levy set by law (MXL) you get the percentage of >troops (PT) you get from the holding:
PT = P x (MXL/100)
Multiply by the number of levy (NL) in the holding and you get the actual troops (AT) >you can raise:
AT = PT x NL

Hope this helps and good luck!  Sorry about any confusion!
Comment: good info thanks. So basically, I should only build forts in the provinces I'm owner for armies (and guess cities for money... not sure why I would want a bishopic). And not really do anything with provinces that are not part of my... demesne was it?
Comment: There may be tax reasons or other reasons to do these things, apparently once your demense becomes too large you will need to split it, and bishopics are probably the way to go, but for levies you're prefer to have them as your own.
Comment: Bishopics allow you to build 2 cheap buildings - church and cathedral school - which boost technology growth. Only for 240 gold you get +30% bonus, while univercity costs you 700 and gives +20%, it's upgrade costs 800 and gives another 20.
Comment: You can improve the holdings of counties you hold.  Ideally, as a (noble) ruler, you should not own any cities or bishoprics, because those give you the "wrong holding" penalty.  But you can still improve those cities and bishoprics if you hold the county title.
Answer: Since you don't mention whether it's your personal levies or your vassal's levies...
Your ruler's martial skill also makes a difference in the the number of levies you can raise. If your deceased father had a martial of 20+ and your new whelpling has a martial of 10 or less, you'll see a significant difference. Even though you always raise 100% of the available levy in any of your demense holdings, what that figure is changes based on your personal martial skill (and buildings built and county modifiers). Quoting from the CKII wiki:

Levy size modifiers is the sum of modifiers from:

Martial skill: 5% * (martial skill - 10). This significantly affects the levy size, e.g. -50% at 0 skill and +50% at 20 skill.

So if you went from 20+ to 0 martial skill, you would go from 150% to 50% personal levies, which is a 2/3rds reduction. If you have a large demesne and a low vassal count, this could be responsible for the bulk of the difference.
Also, the military tab (sword & shield icon, right of the ruler portrait) can show you what proportion of your levies come from your Demesne vs. your Vassals.

Below that part, there's a section that breaks down your vassal levies. If you hover over the green/red bar split, you get a summary of the math for that vassal. This should look roughly similar to the math in Tharius' excellent answer.

Why is my army size halved?


PHP MySQL - Find Row ID

Question: I have a table called "participants" that has 3 fields:
prt_id
prt_event_id
prt_participant_id
What I have is a select query with a where condition on event_id. The query returns let's say 20 rows (20 different participants). What I would like to do is to be able to figure out the row number for a given participant (prt_id).
SELECT *
FROM participants
WHERE prt_id = someinteger

Comment: RowID is a feature of Oracle only: http://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns008.htm
Comment: What do you need that for? The order of the rows is not the order you added the records, you know.
Comment: Of course... But I wanted to keep it simple for the post. Indeed I ORDER my select query based on a timestamp...
Answer: While you can't specifically find a row ID using MySQL, you could do something like the following:
$conn = new mysqli(/*dbinfo*/);
$res = $conn->query("SELECT prt_id FROM participants");

$rowids = array(); $currid = 1;
while ($row = $res->fetch_object()) { // this is using the mysqli library
  $rowids[$row->prt_id] = $currid;
  $currid++;
}

This would give you an array of ids associated with prt_id.
Comment: Hello Baez. I was looking for another solution than a while loop but as I see there is no such things as rowId or something like that. thks...
Comment: As I have pointed out, what happen if u inserted a row, next time you get this, you number will not match the previous.
Comment: @Churk As long as you don't specify an `ORDER BY prt_id` clause or delete a value then the ids should always stay the same.
Comment: If u don't delete. That is not something u can guarantee. Especially for the life of an application.
Answer: You could do something like:
<?php

$counter = 1; // Start at one for first entry

$res = mysql_query("SELECT * FROM participants WHERE prt_id = 12");

while( $array = mysql_fetch_assoc($res) )
{
    // Do something with the counter, store it into array with details
    $counter++;
}
?>

Answer: This should do what you want inside MySQL (ie assign a rownum in the order of prt_id), but the performance will be dependent on the number of rows in the table so it's not optimal.
SELECT * FROM (
  SELECT @tmp:=@tmp+1 rownum, p.*
  FROM (SELECT @tmp:=0) z, participants p
  ORDER BY prt_id
) participants
WHERE prt_id = 36;

Demo here.
Edit: This "doh level" rewrite uses an simple index range instead of a table scan, so should be much faster (provided prt_id is a PRIMARY KEY)
SELECT *, COUNT(p2.prt_id) ROWNUM
FROM participants p1
JOIN participants p2
  ON p1.prt_id >= p2.prt_id
WHERE p1.prt_id=36;

Demo here.
Comment: Great answer but like you said, this would be very slow with even a minimal amount of rows. +1
Answer: you could just add an index column in your database, set it as int, primary key and auto increment. then when retrieving the row you retrieve the index number.
Comment: That is the same idea as using one of the primary key column, just because u assign auto increment, if you delete a row and insert another, you would not be reusing the deleted row's id.
Answer: RowID is a feature of Oracle: http://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns008.htm.
MySQL does not have something like that, you can basically emulate that by assign number to an array inside php as you retrieve each row, but that doesn't guarantee you the same number next time you retrieve that results. You probably have to settle for using one of the primary IDs

PHP MySQL - Find Row ID


Why are there so many versions of the TEA block cipher?

Question: Why are there so many types of TEA, for example TEA, XTEA, and XXTEA? What are the differences?
Answer:
The original algorithm is TEA, which is a very lightweight Feistel cipher. However, its extremely simple key schedule has two weaknesses. The first weakness allows what's called a related key attack, which is not an issue if the keys are chosen randomly. The second weakness causes equivalent keys. This means that, for TEA, any given key is equivalent to three other keys. This effectively weakens the keyspace from 2128 to 2126, which is bad, but not terrible. This is not normally a major problem unless the cipher is used in ways it shouldn't, such as for a hash.
XTEA was designed to fix the weaknesses in the original algorithm, in particular by adding a more complex key schedule. However, it was found that XTEA introduces some related key vulnerabilities of its own and did not meet the intended security target. This lead to another revision called XXTEA. However XXTEA is also vulnerable, in particular to a chosen-plaintext attack requiring only 259 queries (although the attack is impractical). The wide-block variation which avoids the usual downsides of a 64-bit block cipher is highly vulnerable as well, negating yet another benefit of XXTEA. In the end, it turns out that TEA itself is still quite secure as a cipher. It remains secure as long as it is used correctly, i.e. as a block cipher with uniform random and unrelated keys.
Comment: Note: the two XXTEA attacks referred to in the answer are the same. Addition: one of XXTEA's feature is a block size parameter. However the algorithm's reduction in the number of rounds as the block size grows is too aggressive, making it vulnerable to differential cryptanalysis, with an attack for $2^{59}$ chosen plaintexts _when the block is widened from 8 to 212 bytes or more_. I know no published attack for less, and it would require a major advance to break XXTEA with a block size of 8 to 24 bytes, or if it was strengthened by replacing 6 with 12 in the formula for the number of rounds.
Comment: These [three](https://doi.org/10.1007/978-3-540-24691-6_30) [published](https://doi.org/10.1007/s10207-008-0059-9) [attacks](https://doi.org/10.1007/978-3-642-31410-0_8) on XTEA are for reduced round-versions, and require impractically much work. However these attack break more rounds for XTEA than for TEA, which (beside TEA having been more scrutinized) is reason why I would recommend TEA over XTEA _when equivalent keys are not an issue_.