text:
Q: Forcing sound output through speaker in Android Is there a way in Android to force output through the phone speaker, even if a headphone is plugged into the jack? I know there has to be a way because when you are talking on the phone, you can put someone on speaker phone, even if there is headphones plugged into the jack.

A: You can change this system-wide using the AudioManager.setSpeakerphoneOn method.
I don't believe you can set this for a particular MediaPlayer/AudioTrack/SoundPool instance, but depending on your use case, you might actually be looking to set your audio stream type using MediaPlayer.setAudioStreamType or an equivalent for other audio playback classes.

A: This worked for me
First, I Added permissions in Manifest.xml
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

Then, I used this code
AudioManager m_amAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

    m_amAudioManager.setMode(AudioManager.MODE_RINGTONE | AudioManager.MODE_IN_CALL);
    m_amAudioManager.setSpeakerphoneOn(true);

A: Sound output through speaker
AudioManager m_amAudioManager =
        AudioManager)getSystemService(Context.AUDIO_SERVICE);

m_amAudioManager.setMode(AudioManager.MODE_NORMAL);
m_amAudioManager.setSpeakerphoneOn(true);


text:
Q: Computing a matrix to convert an (x,y) point on an ellipse to a circle I have an ellipse defined by its semi-major axis, inclination, and position angle.  The ellipse is centered on the origin.
I would like to solve for a matrix that converts this ellipse to a circle.
Hence if I have (x,y) on this ellipse, I need to convert it to (x', y') on a circle.
It is not straightforward to set x' = x and y' = y cos (inclination) because the ellipse semi-major and semi-minor axes are not collinear with the X- and Y- axes but are inclined by the position angle.

A: "Inclination" here seems to be connected with the angle $i$ at which a cone is intercepted by a plane to produce the ellipse, but I'm not familiar with the term.  At any rate the OP says (see Comment above) that the semi-minor axis can be expressed as $b = a \cos i$.  In what follows, we assume this has been done.
Confusion arises from the subsequent wording that "the ellipse semi-major and semi-minor axes are not collinear with the X- and Y- axes but are inclined by the position angle."  Notation for this position angle is not provided in the Question, so let's supply it here, and in doing so let's refer instead to it as the angle of rotation $\alpha$.  Specifically, since the ellipse is "centered on the origin", we define $\alpha \in [-\pi/2,\pi/2]$ to be the angle between the semi-major axis and the positive X-axis.
More concretely: the endpoints of the major axis, centered as they are on the origin, are expressed by:
$$ \pm a (\cos \alpha, \sin \alpha) $$
The first step is then "unrotation" by this angle of rotation, a linear transformation on Cartesian coordinates expressed by the following matrix multiplication:
$$ \begin{bmatrix} \cos \alpha & \sin \alpha \\ -\sin \alpha & \cos \alpha \end{bmatrix}
    \begin{bmatrix} X \\ Y \end{bmatrix} $$
Clearly applying this transformation to the endpoints of the major axis (see above) will map them to $( \pm a, 0)$, thereby putting both major and minor axes in line with the $X$- and $Y$-coordinate axes, respectively.
In this "standard position" the ellipse can easily be transformed into a circle by scaling the X- or Y-coordinate or both.  E.g. the mapping $(X,Y) \rightarrow (bX,aY)$ will produce a circle of radius $ab$ by scaling both coordinates.  Combining these operations gives a matrix multiplication:
$$ \begin{bmatrix} X' \\ Y' \end{bmatrix} =
   \begin{bmatrix} b\cos \alpha & b\sin \alpha \\ -a\sin \alpha & a\cos \alpha
   \end{bmatrix} \begin{bmatrix} X \\ Y \end{bmatrix} $$
Optional: Further equal scaling of both coordinates by a nonzero factor will change the radius accordingly (but preserve circularity) and might be desirable if a particular radius is desired.
Finally this circle may itself be rotated around the origin through any angle, using a linear transformation similar to the "unrotation" described above.  However this step is unnecessary if the goal was merely to map the original ellipse to a circle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: lowest value for given number I recently gave a codility test. There was a this question which I couldn't solve. Now that I'm trying at home, I would like to get help. I don't remember the complete question language, but I do remember the output how would the program respond. Here we go.
"write a java program, for a given number N, need to find the lowest number for the given N. N could be a billion number too."
{this may not be the exact one, Sorry about that}
For Example:

*

*N=1 then o/p is 0.

*N=123 then o/p is 100

*N=1234 then o/p is 1000 and so on.
My Solution: --just a workaround, this isn't actual logic.
class Solution {
    public int solution(int N) {
        int pointer=0;
        if (N == 1) {
            return 0;
        } else {
            String digitsCount = Integer.toString(N);
            for(int i = 0; i < digitsCount.length(); i++) {
                pointer++;
            }
            StringBuffer subString = new StringBuffer();
            int count=0;
            while(count < pointer-1) {
                subString.append("0");
                count++;
            }
            subString = subString.insert(0, "1");
            return Integer.parseInt(subString.toString());
        }
    }
}

A: Your solution seems to work fine. The only thing it doesn't take into account is the fact that N can be a very large number. int only has a max value of about 2 billion.
Here is my solution:
public static long getLowestNumberWithSameNumberOfDigits(long input) {
    if (input < 10) { // special case
        return 0;
    }

    long trial = 10;
    while (input / trial >= 10) {
        trial *= 10;
    }
    return trial;
}

A: Using math library, should be good for about 16 digits.
long getLow(long in) {
    if (in <= 1) return 0; // see note below
    return (long)(Math.pow(10, Math.floor(Math.log10(in))));
  }

The calculation is undefined for in < 1; we return 0. For in = 1 we return 0 per original code, though returning 1 would surely be more consistent: 2,3,...9 return 1, so why not 1 returns 1?

A: Thank You! Guys. All the suggestions were helpful. Infact, every suggestion has a learning. Here is the updated code. Please accept if you think its good enough.
private static long solution(long N) {
        if (N == 1) {
            return 0;
        } else {
            String digitsCount = Long.toString(N);
            int pointer=digitsCount.length();
            StringBuilder subString = new StringBuilder();
            subString.append("1");
            for(int i=0; i<pointer-1; i++) {
                subString.append("0");
            }
            return Long.parseLong(subString.toString());
        }
    }


text:
Q: How to insert a " Please Select " item into MVC dropdown list without it causing validation Ok dokey, I have the following set up.
Model
public class SupplyType
{
    [Key]
    public int SupplyTypeId { get; set; }
    public string SupplyTypeName { get; set; }

}

public class Supply
{
    [Display(Name = "What type of supply is this from?")]
    public int SupplyTypeId { get; set; }
    public IEnumerable<SupplyType> SupplyType { get; set; }
}

Controller
  public ActionResult (Guid id)
    {
            var model = Model(id);
            model.Supply.SupplyType = db.SupplyTypes.ToList();
            return View(model.);
    }

I now have a View of the following
 //Good view

                @Html.LabelFor(model => model.SupplyTypeId, "SupplyType")

       @Html.DropDownListFor(x => x.SupplyTypeId, new SelectList(Model.SupplyType, "SupplyTypeId", "SupplyTypeName"))
          @Html.ValidationMessageFor(model => model.SupplyTypeId)

This works fine and dandy, if I don't pass touch it, then validation does not fire and I can click on post buttons on my page.
However, when I try and implement a " -- Please Select -- " item in the list, the validation strikes and I'm stuck, can't click on one of my post buttons..boo!!
 //Bad view

            @Html.LabelFor(model => model.SupplyTypeId, "SupplyType")

   @Html.DropDownListFor(x => x.SupplyTypeId, new SelectList(Model.SupplyType, "SupplyTypeId", "SupplyTypeName"), " -- Please Select -- ")
      @Html.ValidationMessageFor(model => model.SupplyTypeId)

I still require a " -- Please Select -- " item in the drop down but I don't want the validation to strike if this hasn't been set.
Any ideas of how I can get around this without turning validation off completely? The reason for this is that the drop down lists will be conditionally shown and therefore might not need to be populated.
Any help greatly received.

A: For your specific requirement like this, I think the simple way is to add -- Please Select -- as a new List Item with SupplyTypID value as 0.
public ActionResult (Guid id)
{
        var model = Model(id);
        model.Supply.SupplyType = db.SupplyTypes.ToList();
        model.Supply.SupplyType.Add(new
                   {
                     SupplyTypID=0, SupplyTypeName=" Please Select"
                   });

        return View(model);
}


text:
Q: Why are oscilloscope input impedances so low? My question is two-fold:
Where does the input impedance come from?
I'm wondering where the input impedance of your average multimeter or oscilloscope comes from? Is it just the input impedance to the device's input stage (such as an amplifier or ADC input stage), or is it the impedance of an actual resistor? If it is the impedance of an actual resistor, then why is there a resistor at all? Why not just the input circuitry?
I measured the input impedance of my oscilloscope with a DMM. When the scope was turned off, the DMM measured about \$1.2\mathrm{M\Omega}\$. However, when the scope was turned on, the DMM measured pretty much exactly \$1\mathrm{M\Omega}\$ (I could even see the 1V test input applied by the DMM on the oscilloscope screen!). This suggests to me that there is active circuitry involved in the scope's input impedance. If this is true, how can the input impedance be so precisely controlled? Based on my understanding, the input impedance to active circuitry will depend somewhat on the exact transistor characteristics.
Why can't the input impedance be much higher?
Why is the input impedance of an oscilloscope a standard \$1\mathrm{M\Omega}\$? Why can't it be higher than that? FET input stages can achieve input impedances on the order of teraohms! Why have such a low input impedance?
I suppose one benefit of a precise standard \$1\mathrm{M\Omega}\$ is it allows 10X probes and the like, which would only work if the scope had a precise input impedance that wasn't unreasonably large (like that of a FET input stage). However, even if the scope had a really high input impedance (e.g., teraohms), it seems to me that you could still have 10X probes just by having a 10:1 voltage divider inside the probe itself, with the scope measuring across a \$1\mathrm{M\Omega}\$ resistor inside the probe. If it had an input impedance on the order of teraohms, this would seem to be feasible.
Am I misunderstanding the input circuitry of a scope? Is it more complicated than I'm making it out to be? What are your thoughts on this?
The reason I thought of this is that I've recently been trying to measure the common-mode input impedance of an emitter-coupled differential pair, which is much larger than the scope input impedance, so it made me wonder why the input impedance can't be larger.

A: Actually, it is ridiculously high for a wideband input.
There is no practical connector or cable that actually has an impedance (from a transmission line view. Resistance, but for coaxial cablers, gold platers, and waveguide plumbers. RF dudes.) of 1 megaohms, leaving the input utterly mismatched - even worse, a 15-45pf capacitor across an 1 megaohm (transmission line impedance) input would mismatch it to oblivion.
The reason it is 1 megaohm is for supporting standard 10:1 probes, which you indeed need to not overload the kind of circuit carrying audio frequency signals at high impedance and with high DC offset (think audio vacuum tube circuits, the probe designs are from just that era).
However, once you are dealing with RF or fast digital circuitry, the parallel capacitance of the scope input (which you can't make too small, again because of probes, cables, connectors) will dominate ... and bring the actual input resistance of that input down to 5 to 10 kiloohms once you reach one megahertz, 500 to 1000 ohms once you reach 10 megahertz. Reach VHF (hint: ACMOS or F-TTL circuitry is VHF stuff even if you don't clock it at VHF) and you would be better off with a matched 50 Ohm input, since you could connect a (within reason) long 50 Ohm cable and still have a 50 Ohm input on the circuit end, instead of an even bigger capacitive burden.
With the conventional kind of probe and input, you will overload RF circuitry easily. RF optimized oscilloscopes tend to have inputs that can be switched to 50 Ohm input impedance (any oscilloscope input can, with a parallel/through terminator) - which is, interestingly, BETTER suited, since now you can use probes (eg Z0 probes or active FET probes) that actually can be made to present much higher effective input impedances at the probe point. Or just provide a reliable 50 Ohm connection to your circuit with any old RG58 cable.

A: Most scopes have a compensated input attenuator to set the input signal to a voltage in the range of the input stage which will usually have the highest sensitivity of the scope.
This attenuator is usually designed assuming a 1 megohm input impedance - so the input impedance seen at the input connector usually is a result of  physical resistor.
If the measured impedance changes when the scope is powered it probably means that there are relays controlling the input attenuator that are not activated in the unpowered state.
There may be a higher sensitivity selection with reduced bandwidth that is handled by increasing the gain of the amplifier. The gain selection may also be controlled by a combination of varying the gain of the amplifier and the input attenuator.
In the attached schematic section the resistor R108 provides the 1 megohm input resistance when the highest sensitivity is selected. The input JFET Q101 has essentially infinite input resistance. the stray capacitances form the capacitance seen at the input in the highest gain position.
At lower gains the resistors R102, R103 and R104 (together with R105, R106 and R107) that make up the input attenuator determine the input resistance.
Trimmers C107, C108 and C109 are used to adjust the input capacitance in lower sensitivity selections to be the same as in the high sensitivity setting.

A: I would say a combination of a few factors.

*

*The input stages of an osciloscope are a difficult compromise. They need to be have a wide range of gains/attenutations, they need to be tolerant of user errors, and they need to pass high bandwidths.  Adding a requirement for a very high DC resistance would just further complicate matters. In particular attenuators needed to handle the higher end of the scopes input level range would get much more complex/sensitive if they needed to have a very high DC resistance.

*It's a de-facto standard, changing to something else would lead to incompatibilities with existing probes etc.

*There wouldn't be much benefit anyway.

To further explain point 3, at moderate frequencies (from a few kilohertz upwards) the 1 megohm DC resistance of the scope input is not the dominant factor in the overall input impedance. The dominant factor is the capacitance, with the cable making probably the largest contribution.
(in fact at UHF/microwave frequencies it's common to reduce the scope input impedance to 50 ohm, so the inductance in the cable can balance out the capacitance and the cable becomes a properly matched transmission line)
What this means is if high input impedances are desirable then it's much better to deal with that at the point of probing than at the scope. The typical compromise of cost/flexibility/input impedance for general use is an x10 passive probe.
If you need a really high DC resistance then the solution is to add a FET based amplifier in front of the scope, preferably as close to the point of measurement as possible.

A: A lot of things are the way they are because of history, and de facto standardisation.
A general purpose oscilloscope input is a difficult compromise between not loading the circuit, not being damaged by high voltage, having reasonably low noise, and being able to maintain a decent bandwidth.
1 MΩ in parallel with 15 pF to 30 pF satisfies a lot of people for a lot of applications. There's little incentive for manufacturers to build a general purpose oscilloscope with a different input, to address tiny parts of the market.
When you do need better noise, or a differential input, or a higher input impedance, then you use a custom pre-amp. When you need wider bandwidth, you switch to a 50 ohm input impedance.
There are special purpose oscilloscopes made at high prices that do address niche applications.

A: Addendum, from a DC view, also about multimeters:
There are bench multimeters/voltmeters that have much, much higher DC input resistance (still, not much higher input impedance at RF). Using such a device will actually prove to be extremely confusing to the "average" user (it would certainly to someone working on house wiring, vehicles, machinery rather than component-level electronics projects): When the test leads are connected to nothing or to an open circuit, any capacitance in the test leads, input circuits etc will be charged by whatever electric field is nearby, leading to a display of completely random values rather than zero volts (try working with a 100GOhm input resistance bench multimeter, you will see just these effects in practice...).
Also, a device with an input resistance in the teraohms will need to be extremely rugged against static electricity, since it can NOT just inherently dissipate the charges of potentially thousands of volts easily found in the environment - and ESD protection circuitry that reliably does not introduce leakage resistances or even worse leakage current sinks that would compromise the high input resistance appears to be difficult to make...
Btw, in addition, most hand multimeters (not all bench ones do) use quite sophisticated tricks (eg using an ADC clock that has a relationship to the mains frequency of the region they are sold in) to filter mains hum out of the results, which would otherwise again lead to unstable and random results even at "low" 1MOhm or 10MOhm (compare an open circuit oscilloscope probe...however, on a DMM, there is much more potential for misinterpretation).

A:
Why is the input impedance of an oscilloscope a standard 1MΩ? Why
can't it be higher than that? FET input stages can achieve input
impedances on the order of teraohms! Why have such a low input
impedance?

The reason for it being 1 MΩ rather than the much higher value a FET can achieve is that oscilloscopes originally used vacuum tubes. The maximum tube grid bias resistance was generally set at ~1 MΩ to minimize the effect of grid leakage current, which is typically in the region of 0.1 μA. By the time FETs became available the 1 MΩ standard was already well established.
Since a 10x probe is usually used (more to reduce probe capacitance than to increase resistance) this 'low' input resistance isn't usually a problem. If higher input resistance without attenuation is required then an 'active' probe can be used.


text:
Q: ReSharper's effect on coding interviews Anyone who has used R# or CodeRush knows how fast you can put together simple constructs (and refactor complex ones) with a simple keyboard shortcut.  However, do these productivity plugins cause a false evaluation of ability during interviews?
Part of being a productive code writer (and making a good first impression in an interview) is writing good code - fast.
If I had two candidates:

*

*Doesn't use plugins.  She thinks about the problem, sits down at a stock IDE at the interview PC that looks exactly like hers and types out the code in a minute or two, as usual.  Done.  Pass.

*Uses plugins.  He thinks about the problem, sits down at a stock IDE at the interview PC and realizes "fe + tab" no longer writes a foreach loop automatically, and all the shortcuts are gone.  He then bumbles around the keyboard hitting his normal hotkeys and popping up strange windows and getting flustered.  It takes him 3 minutes to write what normally would take 30 seconds.  Done.  Looked like they didn't know their way around the IDE at times.  Must be new to this IDE and thus not had much experience with it or maybe the language.  Pass, but a 'meh' mark beside their name.
In your experience, how do you handle plugins during interviews as the interviewer or interviewee?  What are the best practices to getting what the candidate really knows?  There can be candidates who don't understand code, and use R# as a crutch.  There can also be candidates who know the code in and out and use R# because it's just plain faster than the built in VS or Eclipse templates.  Is it best to just not use an IDE at all?  Let them bring their own PC?  Others?

A: I'd argue that tools like ReSharper actually make you a better candidate over all.
For one, something like ReSharper is going to teach you about language constructs you might not have known about, as well as better ways to organize your code toward thinking about a problem or structuring it for readability.  ReSharper, in a sense, keeps you sharp with the best practices for slinging code, rather than letting you fall back to bad or obsolete habits, or worse the bad kind of laziness.
A good coder needs to understand basic constructs, but not manually type them in. The good kind of lazy lets the tools do the borning grunt work, and the extra time saved is instead spent thinking about the problem.  This makes one a better developer overall.
I'd complete the line of reasoning by stating that if the interview process is favoring sticks and stone knives, it's fundamentally broken.

A: I was a candidate 2 in an interview very recently. I was given a vanilla install of the IDE on a PC with a non-standard keyboard and unfamiliar testing framework, and I was asked to write a simple Fizz-Buzz app with unit tests. I fluffed it. I must have looked like a complete noob, stumbling around in the dark trying to hack out code. Needless to say, I wasn't offered the position.
What I learned is that I rely very heavily on my plugins. They don't just get code typed faster - they actually shape the way I think about code and the way I go about coding. For example, I used to think very carefully about variable names because they could be a pain to change after the fact. Now, in contrast, I just make a half-baked guess about how I'll use the variable, hack out some code, let the variable tell me what it is for, and then hit Refactor->Rename to call it something more appropriate.
Does this make me the less capable candidate? In some ways, I think it does. Someone who can write code in Notepad and have it compile and run correctly has certain advantages over someone like me who needs all the IDE goodness he can get. From that point of view, I perfectly understand why any company would choose not to hire a toolhead like me.
On the other hand, I'm still a talented and capable Senior Developer. I've learned what works for me, and I practice the sort of laziness that makes me productive, given my own weaknesses and limitations. In short, I'm the kind of programmer that could really benefit a company like the one who turned me away.
Interestly, I had another interview a couple of weeks ago. Following my previous experience I made a point of asking about additional tools or budget for buying them. Discovering that there were neither gave me one more reason for turning down to the (rather generous) offer that they made to me.
So, to paraphrase Groucho, "I would not join any company that would have someone like me for an employee."
Not unless they let me use ReSharper, anyway.

A: Let them (candidates, that is) use whatever they want. The old, build a Wal-Mart with a Swiss army knife just to show you can approach is so old. They are going to use whatever it takes in their daily work (well, I certanly hope so) so let them use whatever they want in an interview. The final result is all that matters. And I'll much more gladly hire a candidate who knows what tools are available on the market, and how to use them efficiently, then the one who does it all manually. This is a killer industry.
p.s. As an example, think of Vim (or Emacs) - would you like to use it without any customized settings, plugins, etc.?

A: That's one of the reasons I ask people to code at the whiteboard, not in the IDE. It levels the playing field. And people do say "oh dear, resharper handles this for me usually". Heck, the built in snippets handle for loops and such, which the whiteboard can't give you. In that case saying something like "I hope the punctuation is right there; I'm a R# guy" is probably all you need to keep me from holding some syntax issues against you.
I need some ability to write understandable code on the whiteboard so we can have a meeting in which we work out how we're going to do things. And of course, I want to see if you have ever actually written code in your life or not. Your interviews may vary.

A: Great question BTW - I've often pondered this.
Mastery of tools is a skill that is central to being a good developer. I have always felt alarm bells ring when a developer claims he prefers coding in notepad to using an IDE. It suggests he's more interested in the process than the product.
It's like preferring to till the soil with a hoe vs a tractor - fine if you're a hobby gardener, but insupportable as an industrial farmer in a competitive economy.
However, we do become dependent on our tools. People do seem to freak out about how we would cope in the hypothetical situation where our tools were suddenly taken away. There was the same argument about allowing calculators into exams.
The reality is that tools get better and better and cheaper and cheaper each year and there is no reason why you should ever suppose you will be without them. And tools are great at doing repetitive things with a high degree of quality - which means we can focus the full force of our incredible homo-sapien intellects on the difficult (and interesting) parts.
ReSharper is an awesome addition to Visual Studio. My current company didn't have ReSharper when I was interviewed - but I was so evangelical about it in my interview that they bought me a copy when I accepted the position as well as one for the developer who interviewed me. It is now being rolled out across the company. Good tools pay for themselves in no time at all.
So to answer the question: your dependency on tools may cause a false evaluation of your abilities in an interview, but they will always give a correct evaluation of the interviewer's abilities. If a company doesn't recognise the value of tool support in your interview - you've got to show them the light. And if they still won't see it, then I'd be very concerned about accepting a position there.


text:
Q: Aptana auto format I'm trying out Aptana (standalone version) for PHP editing. Like its parent Eclipse, it has a lot of settings for code formatting. Unlike Eclipse, it doesn't seem to have an option for actually doing code formatting automatically or even by manual trigger. Is there a nonobvious option for this that I'm missing?

A: Right click > Format
Works fine for me. Make sure you have the PHP plugin installed if it isn't working for you

A: Shift+Ctrl+F is also the default keyboard shortcut for this.

A: Install Aptana PHP, info available here:
https://aptanastudio.tenderapp.com/discussions/problems/605-php-formatting


text:
Q: No output on the codepen after render my component I am using codepen.io to start with reactjs for the sample program. Below are my complete code. Not sure why the RenderDOM is not rendering the component correctly
HTML

 Raj

 Age 27

CSS
    .person{
    margin: 10px;
    border: 1px solid #eee;
    box-shadow: 0 2px 2px #ccc;
    width: 200px;
    padding: 20px;
    }

JS (Babel)
    function Person()
    {
    return
    (

 Nandhi

 Age 27

    );
    }

    ReactDOM.render(<Person />,
    document.querySelector('#p1'));

Attached the screenshot here:

A: The problem is the return statement inside Person:
return
(
)

Change it to:
return (
)

JavaScript returns undefined if there is nothing at the end of return indicating that the expression is running to the next line.


text:
Q: Set width to Iframe's parent div tag I have an iframe within a div(as popup) whose height and width can be variable.I tried to set the height and width in all possible ways but I was not succeeded.
I am unable to understand the reason.
Can somebody helpe me out.Here is a jsbin
Here is the code that I guess should work:
<!DOCTYPE HTML PUBLIC>

  <button onClick="showIrmNPopup('Window Title','http://www.w3schools.com',200,200)">W3 Schools</button>

X

A: If I understand your problem correctly, you have to set the "irmNPopupContent" height and width first of setting the iframe src.
Start your script with:
$('#irmNPopupContainer').css({width:_width+"px",height:_height+"px"});
Look at this jsbin: jsbin.com/oxemet/4


text:
Q: Access a VPN through Hamachi I am trying to solve a problem I have with a Cisco VPN.
Basically, when I work from home, I now use Remote Desktop through Hamachi to work directly with my computer at the office.
Hamachi works fine for this, because no ports need to be opened in the company's firewall.
Only problem is, Hamachi connection is often too slow and because of this, I am now working on my home PC and using Dropbox to get all the changes synced almost in real time on my work PC.
This is OK, but unfortunately there still is something for which I need to RDP to the work PC... which is what I'd like to avoid. Every now and then I need to access some servers through a VPN which I can access from my work PC, but not for home.
Is there anyway I could access the second VPN (a Cisco) from my home PC, through the Hamachi connection to the work PC?
Say
- Hamachi assigns, for example, the IP 5.1.1.1 to my HOME PC
- Hamachi assigns, for example, the IP 5.1.1.2 to my WORK PC
- Cisco VPN assigns the IP 10.0.1.1 to my WORK PC
- One compute I want to access through the Cisco VPN has IP 10.0.0.20
How do I proceed?
I have tried with
route add 10.0.0.0 mask 255.255.255.0 5.1.1.2
on my HOME PC, but nothing changes. I still can't ping any of the 10.0.0.x.
Any ideas?
Thanks in advance!

A: You could try using OpenVPN instead of Hamachi.
With OpenVPN, you can:
tunnel any IP subnetwork or virtual ethernet adapter over a single UDP or TCP port,
configure a scalable, load-balanced VPN server farm using one or more machines which can handle thousands of dynamic connections from incoming VPN clients,
use all of the encryption, authentication, and certification features of the OpenSSL library to protect your private network traffic as it transits the internet,
use any cipher, key size, or HMAC digest (for datagram integrity checking) supported by the OpenSSL library,
choose between static-key based conventional encryption or certificate-based public key encryption,
use static, pre-shared keys or TLS-based dynamic key exchange,
use real-time adaptive link compression and traffic-shaping to manage link bandwidth utilization,
tunnel networks whose public endpoints are dynamic such as DHCP or dial-in clients,
tunnel networks through connection-oriented stateful firewalls without having to use explicit firewall rules,
tunnel networks over NAT,
create secure ethernet bridges using virtual tap devices, and
control OpenVPN using a GUI on Windows or Mac OS X.

A: Adding the route 10.0.0.0 to 5.1.1.2 simply forwards the packets over a specified interface. The machine on the other side of that interface needs to know what to do with the packets it receives.
So, on your middle machine, it needs to know that when it gets a request FROM 5.1.1.1 asking for 10.0.0.20 to send it over the VPN. By default, Windows machines will just drop the packet.
To fix this, your windows machine in the middle needs to act as a(nother) router. The simplest way of doing this in Windows XP is to enable IP Forwarding, as noted in this KB.
HOWEVER - I have very serious doubts that what you're trying to do will work with just IP forwarding. What you're wanting to do is connect three disparate networks over two node-to-node VPNs, different subnets and consumer level software. This is not an easy task to do, and don't be surprised if there's no (easy) way you can get it working. Plus, I'm not sure your work would be too pleased if they knew you were doing this (otherwise they would just give you a VPN client for your home as well).

A: suggest logmein if you just need remote desktop every so often


text:
Q: Widgets when given inline-block in css stay on seperate lines Using a footer sidebar call as theme did not have a widgetized footer. When I go to apply styling to the widget areas (at this point just to inline them) I get this.
Css:
/*footer styling*/
#footer-widget-area {
    display:inline-block;
}

Result:

HTML and PHP for footer widgets

<?php

    /* The footer widget area is triggered if any of the areas
    * have widgets. So let's check that first.
    *
    * If none of the sidebars have widgets, then let's bail early.
    */
    if (   ! is_active_sidebar( 'first-footer-widget-area'  )
        && ! is_active_sidebar( 'second-footer-widget-area' )
        && ! is_active_sidebar( 'third-footer-widget-area'  )
        && ! is_active_sidebar( 'fourth-footer-widget-area' )
    )
        return;

?>

 <?php if ( is_active_sidebar( 'first-footer-widget-area' ) ) : ?>

                                                 <?php dynamic_sidebar( 'first-footer-widget-area' ); ?>

 <?php endif; ?>

 <?php if ( is_active_sidebar( 'second-footer-widget-area' ) ) : ?>

                                                 <?php dynamic_sidebar( 'second-footer-widget-area' ); ?>

 <?php endif; ?>

 <?php if ( is_active_sidebar( 'third-footer-widget-area' ) ) : ?>

                                                 <?php dynamic_sidebar( 'third-footer-widget-area' ); ?>

 <?php endif; ?>

 <?php if ( is_active_sidebar( 'fourth-footer-widget-area' ) ) : ?>

                                                 <?php dynamic_sidebar( 'fourth-footer-widget-area' ); ?>

 <?php endif; ?>

Footer.php is below

<?php
/**
 * Template for displaying the footer
 *
 * Contains the closing of the id=main div and all content
 * after. Calls sidebar-footer.php for bottom widgets.
 *
 */
?>

Our Satisfaction Guarantee

Not 100% satisfied? Send it back! Within 30 days









Our Satisfaction Guarantee

Not 100% satisfied? Send it back! Within 30 days









<?php
 /*
  * A sidebar in the footer? Yep. You can can customize
  * your footer with four columns of widgets.
  */
 get_sidebar( 'footer' );
?>

<?php
 /*
  * Always have wp_footer() just before the closing
  * tag of your theme, or you will break many plugins, which
  * generally use this hook to reference JavaScript files.
  */

 wp_footer();
?>

The right and centre alignments of the widgets are from properties within the widget themselves.


text:
Q: Using Multiple "Layered" SQL Server queries with parameters in Access I have tried to find answers to this question on the net but am not really getting anywhere.
I tried to do screen shots but don't have enough rep. Anyway.
Here is my current query structure.
Tables:

*

*tblInventoryItems(intSerial, intItem, intStyle) -This is the list of current items that are on inventory(built or unbuilt)

*tblLocations(intLocationID, chrLocationName, intLotType)

*tblItemStyles(intItemStyleID, intBasic Style)

*tblItemList(intItemID, intType, intSubtype, intStyle)

*tblCommissions(intBuildEvent, intItemType, intItemSubtype)

*tblBuildEvents(intSerial, intBuildEventType, dtEventDate)

First Set of Queries
qryCompletedBarns:
SELECT dbo.tblInventoryItems.intSerial,dbo.tblBuildEvents.dtEventDate
FROM dbo.tblItemList
INNER JOIN dbo.tblItemStyles ON
           dbo.tblItemList.intStyle = dbo.tblItemStyles.intBasicStyle
INNER JOIN dbo.tblInventoryItems ON
           dbo.tblItemList.intItemID = dbo.tblInventoryItems.intItem AND
          dbo.tblItemStyles.intItemStyleID = dbo.tblInventoryItems.intStyle
INNER JOIN dbo.tblCommissions ON
           dbo.tblItemList.intSubType = dbo.tblCommissions.intItemSubtype
AND dbo.tblItemList.intType = dbo.tblCommissions.intItemType

INNER JOIN dbo.tblBuildEvents ON
dbo.tblBuildEvents.intBuildEventType = dbo.tblCommissions.intBuildEvent AND
dbo.tblInventoryItems.intSerial = dbo.tblBuildEvents.intSerial
WHERE        (dbo.tblCommissions.ynCompletesBarn = 1)

So First we select all items that have a build event that qualifies them as completed. An item can have multiple build events but there is only one that qualifies it as completed
qryCompletedBarnDateFilter:
SELECT qryCompletedBarns.intSerial, qryCompletedBarns.dtEventDate
FROM qryCompletedBarns
WHERE (((qryCompletedBarns.dtEventDate)<=InventoryDate()));

Then we jump to Access and filter those results by a UDF that pulls the criteria for the build date of the item(Saved report definitions are stored in a table).
Now, we have a list of all Inventory items that meet the first criteria, which is that they must be built on or before the Inventory Date that the user selects.
Second set of queries:
qryInventoryLogDateFilter:
SELECT tblHaulLogs.*, tblHaulLogs.dtmHaulDate
FROM tblHaulLogs
WHERE (((tblHaulLogs.dtmHaulDate)<=InventoryDate()));

Get all the Haullogs (or you could call them inventory transactions) that are equal to or older than the InventoryDate criteria.
qryLastLogForBarn:
SELECT t1.intSerial, t1.intHaulType, t1.intDestinationSource, t1.intDestination
FROM qryInventoryLogDateFilter AS t1
LEFT JOIN qryInventoryLogDateFilter AS t2
ON (t1.intLogID < t2.intLogID) AND (t1.intSerial = t2.intSerial)
WHERE t2.intLogID IS NULL;

Get the last inventory transaction for each Inventory Item. This query is actually very fast when executed on the server natively.
qryInventoryCurrentCustomer:
SELECT tblSales.intSerial, tblCustomers.chrFirstName + ' ' + tblCustomers.chrLastName
AS chrCustomerName, tblSales.dtSaleDate
FROM tblSales INNER JOIN tblCustomers ON
tblSales.intCustomer = tblCustomers.intCustID
LEFT OUTER JOIN tblHaulLogs ON
tblSales.intSaleID = tblHaulLogs.intOrigon
WHERE (tblHaulLogs.intHaulType IS NULL) AND (tblSales.bolSaleCancelled = 0)
      OR (tblHaulLogs.intHaulType <> 3) AND
         (tblSales.intOrderType <4) AND (tblSales.bolSaleCancelled = 0)
GROUP BY tblSales.intSerial, tblCustomers.chrFirstName + ' ' + tblCustomers.chrLastName,
tblSales.dtSaleDate, tblSales.intOrderType;

This query does not actually return an "Inventory Item" but rather checks the sales table and returns a customer name if the inventory item was sold.
Now we finally join the two "sections" and the "Current Customer Query":
SELECT qryCompletedBarnDateFilter.intSerial, qryLastLogForBarn.intHaulType,
       IIf(IsNull([intDestination]),7,[intDestination]) AS Location,
qryInventoryCurrentCustomer.chrCustomerName,
qryInventoryCurrentCustomer.dtSaleDate, qryCompletedBarnDateFilter.dtEventDate
FROM (qryCompletedBarnDateFilter
LEFT JOIN qryLastLogForBarn
     ON qryCompletedBarnDateFilter.intSerial = qryLastLogForBarn.intSerial)
LEFT JOIN qryInventoryCurrentCustomer
     ON qryCompletedBarnDateFilter.intSerial = qryInventoryCurrentCustomer.intSerial
WHERE (((qryLastLogForBarn.intDestinationSource)=1
Or (qryLastLogForBarn.intDestinationSource) Is Null));

Then we join to the "Locations" table to get the name of the inventory item's location,  and also filter out a certain type of location.
qryRetailBarnsOnInventory:
SELECT qryBarnsOnInventory.intSerial, qryBarnsOnInventory.Location,
tblLocations.chrLocationName, qryBarnsOnInventory.chrCustomerName,
qryBarnsOnInventory.dtEventDate, qryBarnsOnInventory.intHaulType
FROM tblLocations
INNER JOIN qryBarnsOnInventory
ON tblLocations.intLocationID = qryBarnsOnInventory.Location
WHERE (((tblLocations.intLotType)=1));

The Final Query:
SELECT tblItemStyles.chrItemStyle, tblInventoryItems.intSerial,
        tblItemSizeList.intItemSize, tblItemPrices.ccyPrice,
       tblInventoryItems.txtOptions, qryRetailBarnsOnInventory.chrCustomerName,
       qryRetailBarnsOnInventory.dtEventDate, qryRetailBarnsOnInventory.intHaulType,
       qryRetailBarnsOnInventory.chrLocationName, tblItemList.intType,
       tblItemList.intSubType, tblItemList.intStyle, tblItemSizes.intItemSizeID,
       tblItemStyles.intItemStyleID, tblItemPrices.intPriceSheet,
       tblInventoryItems.bolinTransit
FROM tblItemSizeList INNER JOIN (tblItemSizes INNER JOIN
      (qryRetailBarnsOnInventory INNER JOIN (((tblItemList INNER JOIN
      tblItemPrices ON tblItemList.intItemID = tblItemPrices.intItemID)
    INNER JOIN tblItemStyles ON tblItemList.intStyle = tblItemStyles.intBasicStyle)
    INNER JOIN tblInventoryItems
    ON (tblItemList.intItemID = tblInventoryItems.intItem)
    AND (tblItemStyles.intItemStyleID = tblInventoryItems.intStyle))
    ON qryRetailBarnsOnInventory.intSerial = tblInventoryItems.intSerial)
    ON tblItemSizes.intItemSizeID = tblItemList.intSize)
    ON tblItemSizeList.intItemSizeID = tblItemSizes.intSize
WHERE (((tblItemList.intType) Like ItemType())
    AND ((tblItemList.intSubType) Like ItemSubType())
    AND ((tblItemList.intStyle) Like BasicStyle())
    AND ((tblItemSizes.intItemSizeID) Like ItemSize())
    AND ((tblItemStyles.intItemStyleID) Like SubStyle())
    AND ((tblItemPrices.intPriceSheet)=1)
    AND ((tblInventoryItems.bolinTransit)=False)
    AND ((IIf(IsNull([intHaulType]),2,3)) Like NewUsed())
    AND ((IIf(IsNull([chrCustomerName]),2,3)) Like IsSold())
    AND ((qryRetailBarnsOnInventory.Location) Like LotID()));

Summary:
In plain English, here is what I want to happen:
Get all Inventory Items from the inventory items table that were completed on or before the date criteria, then get the last inventory transaction on or before the date criteria for each of those items. And then filter by additional criteria that the user provides
I have the correct results but it is SLOW! Like 10-15 seconds. And we do a tremendous amount of queries every day.
What my idea was is to put this all on SQL Server in sprocs or views. If I do this all with views on SQL server and type manual criteria in, it's blazing fast. The problem I have is that every query requires a parameter. Not just the last one. I can pass parameters for the last query all right with a passthrough query but how do I pass the date criteria parameters for the first query?
EDIT:
Would it be possible to get the date criteria from another table? The criteria is stored in another table in the DB. If I could perform some kind of lookup to get that value and use it as the criteria that would make life really simple.


text:
Q: Is AWS Data Pipeline scalable exporting DynamoDB Table? Here are the following things I did,
Increased read units to 10000 for the table that need to get exported. I did wait for the capacity to get setup before creating pipeline.
In the pipeline set the ReadThroughputRatio to 75%.

Initiated the export using AWS Data Pipeline, It was fast in the beginning and then going very slow.

You can clearly see the read unit is increases and data pipeline is not using the maximum read. Maximum it used only 2500 read units.
It is only using average of 250 reads and progress is very slow.

What am I missing the process of setting up the pipeline to use the maximum read capacity?
Screenshot for Capacity:


text:
Q: ValueError at /category/ The 'image' attribute has no file associated with it I am building an Ecommerce website in Django for the first time. Some how despite following the YT tutorial, I am not able to render image that are uploaded from my Django Admin Panel.
Here are my codes:

*

*Models.py

class Product(models.Model):
    name = models.CharField(max_length=200, null=True)
    price = models.FloatField()
    image = models.ImageField(null=True, blank=True, upload_to='image/')

    def __str__(self):
        return self.name

*Views.py

def category(request):
    products = Product.objects.all()
    context = {"products":products}
    return render(request,'store/category.html', context)

*category.html

{% for product in products %}

New

{{product.name}}

${{product.price|floatformat:2}}

{% endfor %}

*settings.py

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

Error I get:

Please Help. Thank you.
I tried to render images in django by following along a Youtube Tutorial.

A: Django shows an error when the file is not associated with the image field. While saving the object of Product model, make sure to add an image file to the field.
You can use the following snippet :


text:
Q: Change initial view controller swift I need to change the initial view controller based on whether voiceover is on or not. I have tried multiple ways but I always get the same error: "Value of type 'AppDelegate' has no member 'window'"
This is what I have in my didFinishLaunchingWithOptions.
    print("voiceover: \(voiceOver)") // prints if voice over is on

    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let initialViewController = storyboard.instantiateViewController(withIdentifier: "voiceoverViewController")

    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()

Value of type 'AppDelegate' has no member 'window'

A: You have to declare a window property manually:
var window: UIWindow?

UIApplicationDelegate is just a protocol, it doesn't declare any properties for you.

A: You don't have to declare window variable manually
It is available in SceneDelegate file in your project
It will have pre defined method :

func scene(_ scene: UIScene, willConnectTo session: UISceneSession,
  options connectionOptions: UIScene.ConnectionOptions)

Example
func scene(_ scene: UIScene, willConnectTo session: UISceneSession,
 options connectionOptions: UIScene.ConnectionOptions) {

    if let windowScene = scene as? UIWindowScene {
        self.window = UIWindow(windowScene: windowScene)
        let initialViewController =
            storyboard.instantiateViewController(withIdentifier: "voiceoverViewController")
        self.window!.rootViewController = initialViewController
        self.window!.makeKeyAndVisible()
    }
}


text:
Q: Call a function after an interval when the page is accessed As the title says, I want to call a function every time a page is accessed but only if a specific interval has passed.
To be more precise: One user access the page and the function is called. After x minutes, when the first user accesses the page, the function is called again (no matter if or how many users accessed the page in between or how much time passed, if it's at least x minutes).
I'm using Wordpress and my function is in functions.php
A specific page from the website is calling the function.
I have tried to place a timer in my functions.php to call the function but it breaks my site or make it load forever (I have tried multiple codes and variations)
$status=TRUE;
do {
   myFunction(){
      //code here
   }
   sleep(60); //Sleep 60 seconds
} while($status==TRUE);

I think another method is to check the time (server time or set timezone date_default_timezone_set('UTC');) and call the function after a specific time (IE: xx:00, xx:30) but this will require to check if the function was called before.

A: For this purpose, you can use the Wordpress transient API (https://codex.wordpress.org/Transients_API). A transient is a piece of temporary key-value data with a timeout. On each page load, you test whether your transient exists. If not, set it up with an x minute expiration (or any expiration time you want) and execute your code. If another user visits the page within the expiration time, the transient is still there and the code will not be executed:
define('TRANSIENT_MY_INTERVAL'); // 5 minute interval for expiration

add_action('wp_loaded', 'do_this_regularly');

function do_this_regularly()
{
  $trans_timeout = 5 * MINUTE_IN_SECONDS; // define your timeout here
  $trans_lock = get_transient('my_transient_lock');
  if (! $trans_lock) { // will be false if expired or not set
    set_transient('my_transient_lock', true, $trans_timeout); // set the lock

    // <- perform your every x minutes action here!
  }
}

This code will only execute if people are actually visiting the page, just like with WP cron (https://developer.wordpress.org/plugins/cron). This could be used as well for the same exact purpose - just a matter of preference which one to use.


text:
Q: Combine data if they have the same host First of all, I'm sorry in advance for my English.
If I have a table likes this (2x5)

Shop A | orange
Shop A | apple
Shop A | mango
Shop B | orange
Shop B | apple

And I want to reference them into this (using formulas) (2x2)

Shop A |     orange, apple, mango
Shop B |     orange, apple

Thank you

A: This isn't easy via code to my knowledge. You can get the result with a bit of work but it's messy and manual.
I am assuming your data is in columns A and B.
First, I would create two headings in D1 and E1, called "Shop A" and "Shop B"
Next, I would type just 1 apostrophe (the ' symbol) into D2 and E2. This will not display but it stops excel putting a 0 in each empty result later on.
Then I would put the following formula in D3:
=IF($A1=D$1,D2&" "&$B1,D2)

What this does is the following:

*

*If column A for a given row contains the same "Shop" as the row
we're looking at, then...

*Join the string from the result above, place a space after it, and then add the value from column B

*Else, just carry over the previous result value from the row above.

I would then drag this across to E3, which for it becomes:
=IF($A1=E$1,E2&" "&$B1,E2)

I can then drag these two cells down (that is, highlight D3 and E3 and drag them down).
Drag it down as long as you need to completely cover the original number of rows (in this case, 5). The last entry will be the concatenated string of each column. For your case, you end up with:
 orange apple mango | orange apple

Copy these two strings and paste value them into another cell. You can then copy these again and transpose them if you want them one above the other rather than side by side, i.e.:
orange apple mango
orange apple

Then just enter the original columns (or copy D1 and E1 and transpose them).
Note that the strings will have a space at the start of them due to the ' we put in the first cell. If you want to trim this, just use the TRIM() function on the result to remove leading and trailing spaces.
Hopefully this helps. As I said, it's very labour intensive but I have never found a good way to concatenate strings conditionally in excel without diving in to writing VBA.
Note, I do not use the CONCATENATE() function because it does not insert the space. You could if you did:
=IF($A1=D$1,CONCATENATE(D2," ",$B1),D2)

It works out the same as just merging them as I did.


text:
Q: recreate excel .xlsx file from unzipped xml folder I'm trying to convert a folder of xml that was created by unzipping an excel file back into an excel .xlsx. But I get the error

The workbook cannot be opened or repaired by Microsoft Excel because it is corrupt

A minimal reproducible example to generate this error:

*

*Create a new blank spreadsheet in Excel

*Enter "test" in cell A1

*Save as test.xlsx

*Rename file to test.zip

*Unzip test.zip as a folder named test

*Compress test into test_new.zip

*Rename test_new.zip as test_new.xlsx

*Open test_new.xlsx with Excel

For zipping and unzipping I have used 7zip, WinZip and PeaZip, all with the same result. What am I doing wrong, and how can I turn unzipped excel workbooks back into their original form?

A: I managed eventually to find the solution to this myself.  The key is that when creating the new zip file, it is necessary to only add the contents of the unzipped folder into the archive. Not the whole folder itself!

A: After struggling with this for a few hours the solution I found that worked using WinRAR (v. 5.71 64-bit) and Office 2019 (16.0.13426.20270 32-bit) was:

*

*create a new excel file (e.g. .xlsm)

*change it's extension to .zip

*extract the contents to whatever folder you want

*add the contents (as dww suggests) to a new WinRAR archive. I did this by selecting all the contents, right-click, and selecting "Add to archive...".

*In the WinRAR menu and General tab, under Archive format select ZIP

*In the WinRAR menu and General tab, under compression method select "fastest"

*I did not change any other parameters but here are some defaults that I have (in case your defaults are different). Dictionary size: 32 kB, Split to volumes, size: blank, Update mode: Add and replace files, Archiving options: none are selected

*Pick whatever name you want for your new .zip file

*Click Ok

*Change the extension from .zip to .xlsm

*Open your new .xlsm file in excel


text:
Q: Badge for being included in the newsletter? A "Published" badge for being a "question/answer of the week" in the weekly newsletter.
It should be at least silver, and maybe gold since there are only 52 per year.
To be awarded retrospectively, of course.
Yet another badge? Maybe not - it would promote the newsletter, which many don't realise exists. I can recall congratulating a 150K+ user on being this week's best answer, and he replied "what newsletter?" - he had no idea.
At least if there's a badge for it, folks would be more likely to take an interest in it.

A: You already get a badge for a good question or answer.
I do agree it's an obscure feature. I can't find anything about it on the help pages and you only seem to be able to subscribe to a newsletter by visiting your own network wide profile.


text:
Q: Testing if Boost library was compiled correctly Does the Boost library have a test suite that tells if the Boost library installation is correct?

A: Unit Test
at boost source's directory
pushd tools/build/test; python test_all.py; popd
Regression Test
pushd status; b2 --toolset=intel; popd
http://www.linuxfromscratch.org/blfs/view/svn/general/boost.html


text:
Q: Access to the root controller from area i have area in my project Admin , User .
i Admin i create a signout buttom . i need when click in signout button go to root and AccountController and use logOff Action .
i using this but it search in area looking to AccountController and logOff Action .

@Html.ActionLink("خروج","LogOff","Account")

how can i solve this ?
Edit
i used exit code in index view :
@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
                {
                @Html.AntiForgeryToken()

خروج

.
                }
public ActionResult LogOff()
        {
            AuthenticationManager.SignOut();
            return RedirectToAction("Index", "Home");
        }`

A: Use [HttpPost] before action. For Ex. this.
[HttpPost]
public ActionResult LogOff()
{
    AuthenticationManager.SignOut();
    return RedirectToAction("Index", "Home");
}

and in view part it seems Ok. but just make submit button, like this.
@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
                {
.... Your Code .....
<input type="submit" value="Submit">
}

This is true answer if you meaned same i understand from your english.

A: For the area:
Url.Action("actionName", "controllerName", new { Area = "areaName" });

If you have some areas in the project then to get "root" controller you might need to do domething like that:
Url.Action("actionName", "controllerName", new { Area = "" });

So for example:
link text


text:
Q: A bounded everywhere defined operator that is affiliated to a von Neumann algebra is in the algebra A possibly unbounded operator $T$ on a Hilbert space $\mathcal H$ is (in my source) defined as affiliated to a von Neumann algebra $M$ if for each unitary element $u$ of $M^\prime$, $u^*Tu=T$ (or moreover, $u$ commutes with $T$). For $T \in B(\mathcal H)$, this should imply that $T \in M$, or by the bicommutant theorem, that $T$ commutes with all $x \in M^\prime$ and not just its unitary elements.
This seemed easy, but I am not seeing how this is true right now. I've also messed around with trying to prove that $T$ is in the WOT-closure of $M$, again without success. Can anyone help me out here?

A: Every element $x$ of a C*-algebra is a linear combination of unitary elements of the algebra.  To see this, note that $x = \frac12(x+x^*)+i\left(\frac{1}{2i}(x-x^*)\right)=\mathrm{Re}(x)+i\,\mathrm{Im}(x)$ is a linear combination of self-adjoint elements, so it is enough to show it for the case where $x=x^*$. We may rescale and assume that $\|x\|\leq 1$.  Then $x=\frac12(x+i\sqrt{1-x^2})+\frac12(x-i\sqrt{1-x^2})$ is the average of the unitary elements $x\pm i\sqrt{1-x^2}$.
Since $M'$ is a C*-algebra, if an operator commutes with every unitary element of $M'$, then it commutes with every element of $M'$.


text:
Q: Defining type of function depending on special conditions I want to ask, which is the right and neat way to declare a function, which's returntype depends on a condition.
That's how I solved this problem at such a bad situation (without creating a function):
const QAudioFormat::SampleType signalSampleType;
typedef decltype(signalSampleType == QAudioFormat::Float ? float() : (signalSampleType == QAudioFormat::SignedInt ? int() : unsigned int())) sampleType;
std::vector<sampleType> rawSignalData;

Would that be fine, or is there a better way to do such things?

A: This is a use case for std::conditional
using sampleType = typename std::conditional<
                     signalSampleType == QAudioFormat::Float,
                     float,
                     typename std::conditional<
                       signalSampleType == QAudioFormat::SignedInt,
                       int, unsigned int>::type
                   >::type;

Which can be made a bit less ugly with c++14:
using sampleType = std::conditional_t<
                     signalSampleType == QAudioFormat::Float,
                     float,
                     std::conditional_t<
                       signalSampleType == QAudioFormat::SignedInt,
                       int, unsigned int>
                   >


text:
Q: Gradle append zip archive I need to add file to existing zip archive. I tried to use Gradle Zip Task but it overwrite my archive.
I have now solved the problem as follows
import java.nio.file.FileSystem
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Paths
import java.util.function.Consumer

task AddToZip() {
  doLast {
    FileSystem fs = FileSystems.newFileSystem(Paths.get("$pathToZip"), null)
    Files.walk(Paths.get("$rootDir/dir")).forEach(new Consumer<java.nio.file.Path>() {
      @Override
      void accept(java.nio.file.Path path) {
        java.nio.file.Path dest = fs.getPath(path.toString().substring("$rootDir".length()))
        if (path.toFile().isDirectory()) {
          Files.createDirectory(dest)
          return
        }
        Files.copy(path, dest)
      }
    })
    fs.close()
  }
}

Is there any other way to solve this problem?

A: You could use Project.zipTree(...) to create a FileTree from the original zip. This can then be passed to Zip.from(...)
task addToZip(type:Zip) {
   from zipTree('path/to/original.zip')
   from 'path/to/additional/file.txt'
   archiveFileName = "updated.zip"
   destinationDirectory = file("$buildDir/zips")
}

*

*See Project.zipTree(...)

*See AbstractCopyTask.from(...)


text:
Q: Issue with fullpage.js (section fp-section fp-is-overflow active fp-completely) I want to have my container in this section with height 100% insted of that my container only takes one little percentage of the sreen and the rest is taken by (section fp-section fp-is-overflow active fp-completely) and I cannot change it, please help.
This is how I have it, That's the only space available for my div
This is the space i want to have
Here you can see I have my div with height 100% as I want it
In the second section the div is perfect as well, just as i want it
 .container-general {
    display: grid;
    justify-content: center;
    grid-template-columns: 1fr 1fr;
    overflow: hidden;
}

.container-general-2 {
   height: 100%;
   display: grid;
   justify-content: center;
   grid-template-columns: 1fr 1fr;
   overflow: hidden;
   gap: 30px;
  box-sizing: border-box;
 }

.container-3{
    height: 100%;
    display: flex;
    justify-content: center;
    grid-template-columns: 1fr 1fr;
    overflow: hidden;
    gap: 30px;
    box-sizing: border-box;

first two containers working fine, Third one is not

A: You can replace your height: 100%; for height: 100vh.
That, or use the option scrollOverflow: false if you do not plan on having scrollable sections.
.container {
    background: red;
    height: 100vh;
    display: flex;
    vertical-align: middle;
    align-items: center;
    justify-content: center;
}

Online demo


text:
Q: When we use d3 with rails 6 with webpack it thwos below error Using ruby 2.7.3
Rails 6.1.3
I am using d3 but it throws the below error on console -
TypeError: setting getter-only property "format" using
Ie https://d3js.org/d3.v4.min.js:2
<anonymous> https://d3js.org/d3.v4.min.js:2
<anonymous> https://d3js.org/d3.v4.min.js:2
<anonymous> https://d3js.org/d3.v4.min.js:2

On the view page, I have added the below code -
   <script src="https://d3js.org/d3.v4.min.js">
   </script>
   <%= javascript_pack_tag "home/index" %>

Below line added app/javascript/packs/application.js -
 import * as d3 from "d3"
 window.d3 = d3

Please give suggestions on these.


text:
Q: SharePoint CSOM, retrieving site collections. Limited to 300? I am trying to retrieve the site collections list from a SharePoint Online domain.
I am using C# and client object model.
The following code returns only 300 site collections.
var tenant = new Tenant(ctx);
spp = tenant.GetSiteProperties(0, true);
ctx.Load(spp);
ctx.ExecuteQuery();

Any idea on how to retrieve ALL site collections with CSOM ?
Thanks

A: I found the answer to this question,
the first parameter of the method GetSiteProperties is the index from which site collection retrieval starts.
I tried the the following command
    spp = tenant.GetSiteProperties(300, true);
which returned site collections from index 300.
So here is my code to get all site collections from sharepoint online
SPOSitePropertiesEnumerable spp = null;
var tenant = new Tenant(ctx);
int startIndex = 0;

while (spp == null || spp.Count > 0)
{
    spp = tenant.GetSiteProperties(startIndex, true);
    ctx.Load(spp);
    ctx.ExecuteQuery();

    foreach (SiteProperties sp in spp)
    siteCols.Add(new SiteCol(sp.Title, sp.Url));

    startIndex += spp.Count;
}

By the way, site collections are currently limited to 10000.

A: I guess NextStartIndex didn't exist at the time this was asked, nowadays you can do:
SPOSitePropertiesEnumerable sites;
List<string> allSites = new List<string>();
int startIndex = 0;

do
{
    sites = tenant.GetSiteProperties(startIndex, false);
    ctx.Load(sites);
    ctx.ExecuteQuery();

    allSites.AddRange(sites.Select(s => s.Url));

    startIndex = sites.NextStartIndex;

} while (sites.NextStartIndex > 0);


text:
Q: Why does calling random() inside of a case statement produce unexpected results? https://gist.github.com/anonymous/2463d5a8ee2849a6e1f5
Query 1 does not produce the expected results. However, queries 2 and 3 do. Why does moving the call to random() outside of the case statement matter?

A: Consider the first expression:
select (case when round(random()*999999) + 1 between 000001 and 400000 then 1
             when round(random()*999999) + 1 between 400001 and 999998 then 2
             when round(random()*999999) + 1 between 999999 and 999999 then 3
             else 4
        end)
from generate_series(1, 8000000)

Presumably, you are thinking that the value "4" should almost never be selected.  But, the problem is that random() is being called separately for each when clause.
So, the chance the it fails each clause is independent:

*

*About 60% of the time a random number will not match "1".

*About 40% of the time a random number will not match "2".

*About 99.9999% of the time a random number will not match "3" (I apologize if the number of nines is off, but the value is practically 1).

That means that about 24% of the time (60% * 40% * 99.9999%), the value "4" will appear.  In actual fact, the first query returns "4" 23.98% of the time.  To be honest, this is very close to the actual value, but given this size of data, but it is a bit further off than I would expect.  However, it is close enough to explain what is happening.


text:
Q: Flutter Admob Interstitial Ad overwrites system bottom navigation bar color to white I have admob in my flutter app. My system bottom navigation color is set to a custom color by the following flutter code:
PlatformApp(
      material: (_, __) => MaterialAppData(
        themeMode: ThemeMode.dark,
        theme: ThemeData(
          splashFactory: InkRipple.splashFactory,
          applyElevationOverlayColor: true,
          accentColor: Color(0xffe22249),
          colorScheme: ColorScheme.dark(
            primary: Color(0xffe22249),
            brightness: Brightness.dark,
            background: Color(0xff090909),
            surface: Color(0xff090909),
            onSurface: Color(0xffffffff),
            onBackground: Color(0xffffffff),
          ),
        ),
      ),
    );

In my page I use:
AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle(
        statusBarBrightness: Brightness.dark,
        statusBarColor: Theme.of(context).colorScheme.surface,
        statusBarIconBrightness: Brightness.light,
        systemNavigationBarColor: Theme.of(context).colorScheme.surface,
        systemNavigationBarIconBrightness: Brightness.light,
        systemNavigationBarDividerColor: Theme.of(context).colorScheme.surface,
      ),

Here is how I show interstitial ad:
InterstitialAd interstitial = InterstitialAd(

        adUnitId: InterstitialAd.testAdUnitId,
        targetingInfo: MobileAdTargetingInfo(
          testDevices: ["MY_SECRET_PHONE_ID"],

        ),
        listener: (MobileAdEvent event) async {
          if (event == MobileAdEvent.loaded) {
              interstitial
                  .show(
                anchorType: AnchorType.bottom,
                anchorOffset: 0.0,
                horizontalCenterOffset: 0.0,
              )
                  .catchError((e) {
                //TODO: Log error to analytics
                print(e);
              });

          }
        });

    interstitial.load();

The ad shows fine. I get the test ad.
My problem is for some reason, whenever an ad is shown it overwrites my system bottom navigation color to white which makes it seem odd and ruins the continuity of my apps style. Here is what happens:

As you can see the system bottom navigation is overwritten to white. This looks odd. I want to keep my apps custom color that I set with the flutter code while showing interstitial. Is this possible? Why is the system bottom navigation bar color overwritten?
Here is my manifest file:
<application
        android:name="io.flutter.app.FlutterApplication"
        android:icon="@mipmap/ic_launcher">

        <activity
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            >
... REST OF MANIFEST IS IRRELEVANT...

A: You can override the color property of the navbar using SystemUiOverlayStyle like this.
const mySystemTheme= SystemUiOverlayStyle.light
.copyWith(systemNavigationBarColor: Colors.red);

Use AnnotatedRegion widget on your screen where you show adds like this.
Widget build(BuildContext context) {
return new AnnotatedRegion<SystemUiOverlayStyle>(
value: mySystemTheme,
child: new MyRoute(),
 );
}

A: for this, you can set margin bottom to the main layout that you set (Admob Interstitial) layout.
like this,
 @override
  Widget build(BuildContext context) {
    return Container(
          margin: const EdgeInsets.only(bottom: 50),
          child: yourAdmobLayout(...)

after this your Admob widget takes margin to the bottom, and not overlapping to bottom navigation bar.
New update regarding style
Try this demo
https://gist.githubusercontent.com/akshatapp/6b6993ed7b7c10063ffb522461134d03/raw/03887b465405943ca58d4ec0d6462416d0db5de0/main.dart


text:
Q: MacOSX Bash App Bundle as Sudo I am working on a simple little mac application which runs a bash script when opened. My problem is, the bash script requires that sudo commands be called! Unfortunately, the app simply crashes when I try to do any sudo commands in the bash.
My app/bundle hierarchy is very simple:
myapp.app
--Contents
----MacOs
------myapp (the bash script)

That's it.
Seeing as using sudo is obviously not going to work, is there a way for me to make the application ask the user for a password, and then run its bash script AS sudo? Then I could remove the sudo prefixes and everything would theoretically work fine.

A: It seems that with sandbox, authorization under Mac become difficult (https://developer.apple.com/library/mac/#documentation/Security/Conceptual/authorization_concepts/01introduction/introduction.html)
Maybe you can find some informations here:
https://developer.apple.com/library/mac/#documentation/Security/Conceptual/AppSandboxDesignGuide/AboutAppSandbox/AboutAppSandbox.html


text:
Q: knockout js change the bindings with jquery or javascript I have problem with knockout binding, i'm trying to change the value of the viewmodel by jquery but i can't do that!
i'm learning knockout,
mi.data = {
    title: ko.observable("Page Title")
};

mi.data.title = "Some New Value"

html >

and here is a link on jsFiddle from what i have tried. what i'm missing?
what i have tried

A: Each observable is a function so to assign value to it you should pass value as a parameter:
mi.data.title("Some New Value");

To get value from observable you should call it:
var value = mi.data.title();

Here is working fiddle: http://jsfiddle.net/TRHFb/2/

A: Observable is a function not variable.
So you have to pass in value like:
i.data.title(Math.random().toString());
in your case.


text:
Q: Why do few people say "How is your today?"? My mom asks me "How is your today?" every day. I have been trying to tell her that nobody ever says that, and that most people say,

*

*"How is your day?" (somehow, using the noun day is more acceptable than using the noun today here)

*"How is your day going?" (now the question is about the going of the day, rather than the day itself)

*"How are you today?" (using today as an adverb to describe the verb are, and now the question is about you rather than about the day)

But I am having trouble articulating why exactly so few people say "How is your today?", and whether it is even wrong to say that.
I am reading https://www.dictionary.com/browse/today and https://en.wiktionary.org/wiki/today and it appears to be a noun like any other. If it is okay to say "How is your [noun]?" like the following examples:

*

*"How is your dog?"

*"How is your day?"

*"How is your Monday?"

...then why can't we say, "How is your today?"?
If there really is something special about the noun "today" which precludes it from being used in this way, then oughtn't dictionaries make a note of these unique restrictions?

A: The phrase is correct, just unusual. People use it to be unique, and to make mundane questions like "how are you today" become a little more interesting. And clearly it worked, since you asked this question.
Don't discourage your mom from saying this phrase. It's good that people use phrases like this, because it makes a question that should truly be asked wholeheartedly stand out more. I don't really give the question "how's your day going?" much thought. I just automatically say "fine". But a phrase like "how's your today?" turns on the thinking machine, and my answer is sincere. It's also a much more lighthearted approach to the daily question.
I know I did a lot more than answering your core question, with a lot of opinion-based stuff, but I actually think it's something one should consider. Using sprighty and unusual phrases instead of the grey, mundane and regular phrases we've become so accustomed to. Give it a try.


text:
Q: "System" spamming files on my drive I have Windows 10 running on an 60GB SSD. Most of the other files are on a separate disk.
When I boot my system I have about 2GB free space on the SSD. Within minutes, it ticks down to completly full. If I restart my PC, I have 2GB free space again and it ticks down again.
Here's a picture of the resource monitor:

Sorry it is in german. Lesen means Read,Schreiben means Write.
I don't know why this is happening. I have to restart my PC everytime because nothing works anymore when the drive is completly full (thumbnails disappear, etc.). I am not sure if it is because of "System" or because of "SearchIndexer".
How can I stop this?

A: Use SpaceSniffer to see what files/folders use up all your space. It could very well be that your hibernation file is taking up all your space.
http://www.uderzo.it/main_products/space_sniffer/


text:
Q: The variables from the form is not passed to php I have this form with which I am trying to take some user entered variables and pass them to calculate.php for counting and showing the result.
calculate.html

<TITLE>Calculation Form</TITLE>

<FORM METHOD="POST" ACTION="calculate.php">

Value 1: <INPUT TYPE="text" NAME="vall" SIZE=10>

Value 2: <INPUT TYPE="text" NAME="val2" SIZE=10>

Calculation:

<INPUT TYPE="radio" NAME="calc" VALUE="add"> add

<INPUT TYPE="radio" NAME="calc" VALUE="subtract"> subtract

<INPUT TYPE="radio" NAME="calc" VALUE="multiply"> multiply

<INPUT TYPE="radio" NAME="calc" VALUE="divide"> divide

<INPUT TYPE="submit" NAME="submit" VALUE="Calculate">

calculate.php:
        <?
if (($_POST["vall"] == "") || ($_POST["val2"] == "") || ($_POST["calc"] =="")) {
    header("Location: http://localhost/calculate.html");
exit;
}

if ($_POST["calc"] == "add") {
   $result = $_POST["vall"] + $_POST["val2"];
} else if ($_POST["calc"] == "subtract") {
   $result = $_POST["vall"] - $_POST["val2"];
} else if ($_POST["calc"] == "multiply") {
   $result = $_POST["vall"] * $_POST["val2"];
} else if ($_POST["calc"] == "divide") {
   $result = $_POST["vall"] / $_POST["val2"];
}

?>

<TITLE>Calculation Result</TITLE>

The result of the calculation is: <? echo $result; ?>

can anybody say where is my mistake as I get only the: The result of the calculation is:

A: You missed "s in array index in all the $_POST[], so you need to add "".
<?
if (($_POST["vall"] == "") || ($_POST["val2"] == "") || ($_POST["calc"] =="")) {
    header("Location: http://localhost/calculate.html");
exit;
}

if ($_POST["calc"] == "add") {
   $result = $ POST[vall] + $_POST[val2];

} else if ($_POST["calc"] == "subtract") {
   $result = $_POST["vall"] - $_POST["val2"];
} else if ($_POST["calc"] == "multiply") {
   $result = $_POST["vall"] * $_POST["val2"];
} else if ($_POST["calc"] == "divide") {
   $result = $_POST["vall"] / $_POST["val2"];
}

?>

A: These $_POST[vall] need to be $_POST['vall']. The string literal vall is the key.

A: You have a mistake on line 8 in your calculate.php:
$result = $ POST[vall] + $_POST[val2];

should be:
$result = $_POST["vall"] + $_POST["val2"];

And take into account previous answers

A: Could just a mistype here, but - besides all that everyone else said, you forgot to close the </form> tag
<INPUT TYPE="radio" NAME="calc" VALUE="divide"> divide

<INPUT TYPE="submit" NAME="submit" VALUE="Calculate">

</FORM>

I would also check for a POST request before processing:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
   // do your stuff
}


text:
Q: How can I get the selected value from dropdownlist in edit mode of a gridview? In my application, when I edit a row in the gridview I choose some new data from a dropdownlist.
I am populating the dropdown like this:
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                DropDownList emailsListDL = (DropDownList)e.Row.FindControl("emailsDL");
                emailsListDL.DataSource = allUsersEmails;//list of strings with the emails of the users
                emailsListDL.DataBind();
            }
        }
    }

But when I press the 'Update' button from the template and enters in the 'RowUpdating' event, the selected value from the dropdownlist is every time the first value from that dropdownlist.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        DropDownList emailsListDL = (DropDownList)GridViewAdvertisers.Rows[e.RowIndex].FindControl("emailsDL");
        string email = emailsListDL.SelectedValue; //the selected value is every time the first value from the dropdownlist
    }

Does anyone have any ideas?
I've tried many ways to set the selected value in the 'RowDataBound' event, but with no luck. I tried this:
1. emailsListDL.SelectedIndex = emailsListDL.Items.IndexOf(emailsListDL.Items.FindByValue(DataBinder.Eval(e.Row.DataItem, "OwnerMail").ToString()));
2. emailsListDL.SelectedValue = GridViewAdvertisers.DataKeys[e.Row.RowIndex]["OwnerMail"].ToString();
3. emailsListDL.SelectedValue = GridViewAdvertisers.Rows[e.Row.RowIndex].Cells[1].Text;
//ownerMail is a string (object) from the list of objects that I put as datasource to the gridview

Thanks,
Jeff
Update
My Item template from the aspx page is:
 <asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle"
                ItemStyle-Width="150px" HeaderText="Owner Email" HeaderStyle-HorizontalAlign="Left"
                HeaderStyle-BorderWidth="1px" HeaderStyle-BorderColor="#e1e1e1">
                <ItemTemplate>
                    <asp:Label ID="LabelEmail" runat="server" Text='<%# Bind("OwnerMail")%>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:DropDownList ID="emailsDL" runat="server" Width="150">
                    </asp:DropDownList>
                </EditItemTemplate>
                <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Font-Bold="True"></HeaderStyle>
                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="180px" BorderWidth="1px"
                    BorderColor="#e1e1e1"></ItemStyle>
    </asp:TemplateField>

A: The SelectedIndex will always default to 0 if you don't define it in your DropDownList definition.
Edit:  @Tim Schmelter should add his comment as an anwer.  In the meantime, I'll paraphrase for other readers:  You need to check for postback (see comments above).

A: You can declare a ComboBox mainBX = new Combobox();
and you can declare an event
private void onSeletedIndexChange(object sender,EventArgs e)
{
        mainBX = (ComboBox)(sender);
}

and next you should iterate foreach ComboBox in GridView and Add this Event .
Than all you should do is ,take the mainBX.seletedItem();
I think this is what you need ,if not apologise .

A: To set the Selected Value in the RowDataBound-Event, you should do it like this:
(DropDownList)e.Row.Cells[/*index*/].Controls[/*index, or use FindControl*/]).Items.FindByValue(((DataRowView)e.Row.DataItem).Row.ItemArray[/*columnnumber*/].ToString()).Selected = true;

FindByValue finds the current Textvalue of the Field in the "normal" Viewmode and sets the DropDownList with the value.
Of course this needs to be encapsulated in
if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
}

As for your "getting the Value at Update"-Problem, I must honestly say I've got no clue, since your approach is exactly like mine, only difference: mine works.
Here's my code if it's any help:
 protected void gridVariables_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

        string control = ((DropDownList)gridVariables.Rows[e.RowIndex].Cells[3].Controls[1]).SelectedValue;
        gridVariables.EditIndex = -1;
        this.gridVariables_DataBind(control, e.RowIndex);
    }

private void gridVariables_DataBind(string control, int index)
    {
        DataTable dt = (DataTable)Session["variableTable"]; //features a DataTable with the Contents of the Gridview
        dt.Rows[index]["ControlType"] = control;
        gridVariables.DataSource = dt;
        gridVariables.DataBind();
    }

A: I had the same problem with a different solution, I had implemented custom paging on the GridView with a custom pager, and in the process added the RowCommand method, which was rebinding the grid with a new page index. As it happens though the RowCommand method is also called during Updating.
So be sure to check any other locations you may be binding anywhere in your code.
Hope this helps somebody else.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    string commandName = e.CommandName;

    switch (commandName)
        {
            case "Page1":
                HandlePageCommand(e);
                //binding should happen here
                break;
        }

        //this line is in the wrong location, causing the bug
        BindGrid1();
}


text:
Q: Update validation for unique attribute I have this function update in my controller :
public function update(Request $request, $id){
    $siswa = Siswa::findOrFail($id);
    $input = $request->all();

    $validator = Validator::make($input, [
        'nisn'=>'required|string|size:4|unique:siswa,nisn'.$request->input('nisn'),
        'nama_siswa'=>'required|string|max:30',
        'tgl_lahir'=>'required|date',
        'jns_klmin'=>'required|in:L,P',
    ]);

    if ($validator->fails()) {
        return redirect('siswa/'.$id.'/edit')->withInput()->withErrors($validator);
    }

    $siswa->update($request->all());
    return redirect('siswa');
}

Where nisn is an unique attribute. Yet when I run it I always stumble in this screen written :
QueryException in Connection.php line 729:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'nisn1007' in 'where clause' (SQL: select count(*) as aggregate from siswa where nisn1007 = 1007)
Any help appreciated. Thanks in advance

A: You forgot about , here:
'nisn'=>'required|string|size:4|unique:siswa,nisn'.$request->input('nisn'),

should be like this:
'nisn'=>'required|string|size:4|unique:siswa,nisn,'.$request->input('nisn'),

after: siswa,nisn


text:
Q: v2v of RHEL5 box - issues with retaining MAC address For the last week we have been troubleshooting a customer's Red Hat Virtual Machine running on ESXi. We've been using Veeam to try to create a replica off-site and have been having getting it to work on a decent schedule and recently we noticed that there were issues with orphaned snapshots while looking at the datastore. You can see several snapshots in the same folder and it's causing issues with replication and backup, so we decided the cleanest way was to v2v the machine to another datastore so that we had a clean single-vmdk setup to work with, this is where our trouble started.
We first started off with a v2v using vmware converter and connecting to the powered on machine as we were having issues doing an offline v2v. This copied fine but when I tried to set a static MAC using this article http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=507 the new VM wouldn't take the address, it simply obtained a new MAC, received a dhcp lease and then would only boot up to a blank red screen, never the login screen.
So the next step was to do an offline v2v, once we finally got it working. Same thing, followed the kb to the letter and still it wouldn't take the MAC. I then tried it again and upon completion I compared both old and new VMX file, copying every identifier and variable possible, then unregistered both VMs, uploaded the new VMX file and booted, only to see the same results.
Finally I did the same as above but I copied the disk using DD to a second attached vmdk and then attached this to the new VM, and still no luck.
After downloading the modified VMX file after the first boot and comparing it to the original I created I found that the bios uuid had changed from the one I typed in manually, so I'm assuming this may be the snagging point, but I have no idea.
I've never had this issue before on a P2V and I'm just wondering if someone could shed some light on this, maybe it's to do with RHEL licencing?

A: This may or may not resolve your problem:
Most ethernet cards -- including the virtual ones provided by VMware
-- have a software programmable MAC address.  You can take advantage
of this by inserting something into your startup sequence to set the
MAC address of the card early in the boot process.
You would run a command like this:
ifconfig eth0 hw ether c0:ff:ee:fa:ca:de

This is obviously not The Right Way to solve this, but it may provide
enough of a workaround to get you moving forward.

A: I used to have similar issues. I'd usually scratch my head wondering why settings didn't take and it was almost always because the VM had to be unregistered and not just started/stopped. I know you said you did that, but give the following a try (in order):

*

*Stop (not pause) the new VM

*Unregister the new VM

*Set the following (in .vmx file):

ethernet0.addressType="static"
ethernet0.address = YO:UR:MA:CA:DD:RS

*Re-register the VM and boot it.


text:
Q: Years and months output not formatting properly When I try to implement this function of no_payment() in my python script:
import math
import argparse

parse = argparse.ArgumentParser(usage='Differential calculator that calculates the per month payment on a decreasing'
                                      'principal amount')
parse.add_argument('--type', '-t', type=str, required=True, help='diff = differential, annuity = standard, fixed payments') #error code
# cant compute with diff argument selected, as payment each month is different
parse.add_argument('--payment', '-p', type=float, required=False, help='monthly payment amount')
parse.add_argument('--principal', '-P', type=float, required=False, help='principal amount of the loan')
parse.add_argument('--periods', '-m', type=int, required=False, help='number of payments required to pay the loan')
parse.add_argument('--interest', '-i', type=float, required=True, help='interest rate (as integer, not converted)') #error code
args = parse.parse_args()

def no_payments():

    i = args.interest / (12 * 100)
    month_no = math.log(args.payment / (args.payment - i * args.principal), 1 + i)
    overpayment = args.principal * args.interest
    year_count = math.ceil(month_no // 12)
    month_count = math.ceil(month_no % 12)
    if 1 < month_no <= 12:
        print(f'It will take {month_count} months to repay this loan!')
    elif month_no == 1:
        print(f'It will take 1 month to repay this loan!')
    elif month_no == 12:
        print(f'It will take 1 year to repay this loan!')
    elif 12 < month_no < 24 and month_count == 1:
        print(f'It will take {year_count} year and 1 month to repay this loan!')
    elif 12 < month_no < 24 and month_count > 1:
        print(f'It will take {year_count} year and {month_count} months to repay this loan!')
    elif month_no >= 24 and month_count == 1:
        print(f'It will take {year_count} years and {month_count} month to repay this loan!')
    elif month_no >= 24 and month_count > 1:
        print(f'It will take {year_count} years and {month_count} months to repay this loan!')

    print(f'Overpayment = {overpayment}')

# error codes thrown if interest and type are not inputted

if args.interest is None:
    print('Incorrect Parameters')
elif args.type is None:
    print('Incorrect Parameters')

if args.type == 'annuity' and args.payment is None:
    ann_calc()
elif args.type == 'diff' and args.payment is None:
    diff_calc()
elif args.type == 'annuity' and args.principal is None:
    princ()
elif args.type == 'annuity' and args.periods is None:
    no_payments()

With a given argument of --type=annuity --principal=500000 --payment=23000 --interest=7.8.
The output should be 2 years but it comes out to be 1 year and 12 months. What do I have to change to make the output as 2 years?

A: on line 8m, your configuration states:
 month_no = math.log(args.payment / (args.payment - i * args.principal), 1 + I)

using the arguments you stated in your question, this results in a value of 23.513122662562726
This is the reason why you are receiving 1 year and 12 months in your response, because technically it's 23 months, then converted to 24 months when rounded.
you have two options:

*

*round up to 24 months, if the business logic states

*remove the math.ceil, and allow the number of months to be shown as fractions.

This answers your immediate question.
For the long term solution, I would recommend a reducing classification method with your date calculations. For example:
month_no = 24 (for your example)
years = math.floor(month_no / 12). -> 2
months = (month_no - (years * 12)) -> 24 - (2 * 12) -> 0

another example:
month_no = 26 (for your example)
years = math.floor(month_no / 12). -> 2
months = (month_no - (years * 12)) -> 26 - (2 * 12) -> 2

from there you can use string injection to push your print statement
yr = '{} years'.format(years) if years > 1 else '1 year' if years = 1 else ''
mo = 'and {} months'.format(months) if months > 1 else 'and 1 month' if months = 1 else ''

print('It will take {years}{months} to repay this loan!'.format(years,months))

here's my example:
import math
import argparse

#--type=annuity --principal=500000 --payment=23000 --interest=7.8
def no_payments(args):

    i = args['interest'] / (12 * 100)
    month_no = round(math.log(args['payment'] / (args['payment'] - i * args['principal']), 1 + i))
    overpayment = args['principal'] * args['interest']
    year_count = math.ceil(month_no // 12)
    month_count = math.ceil(month_no % 12)

    print("month no")
    print(month_no, month_count, math.ceil(24 % 12))
    years = math.floor(month_no / 12) #-> 2
    months = (month_no - (years * 12)) # -> 26 - (2 * 12) #-> 2
    yr = '{} years'.format(years) if years > 1 else '1 year' if years == 1 else ''
    mo = 'and {} months'.format(months) if months > 1 else 'and 1 month' if months == 1 else ''

    print('It will take {}{} to repay this loan!'.format(yr,mo))

args = {
    'type': 'annuity',
    'principal': 500000,
    'payment': 23000,
    'interest': 7.8
}
no_payments(args)


text:
Q: Math paper translation Does anybody know if Bruno de Finetti's paper, Sul significato soggettivo della probabilità, has been translated into English?  I am teaching myself Italian, but for some reason de Finetti doesn't mention a boy eating an apple or a woman reading a book or any of the other phrases I know yet. ;-)
The citation would be:

de Finetti (1931), "Sul significato soggettivo della probabilità", Fundamenta Mathematicæ, 17, pp 298 – 329


text:
Q: Android Map Application is Crashing I'm trying to create a simple Map View Application. I went through android developers documentation and copy-pasted MyActivity.java class and activity_main.xml layout. The app is crushing when i start on my real device (Android v2.3.6). The package explorer, manifest file, and logcat errors are below.

MainActivity.java:
package com.timur.mapapplication;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.MapFragment"/>

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.timur.mapapplication"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name="com.timur.mapapplication.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyDQ4pnYq3on6WFJsE..." />

</manifest>

LOGCAT ERRORS:
12-18 00:03:05.626: E/AndroidRuntime(18591): FATAL EXCEPTION: main
12-18 00:03:05.626: E/AndroidRuntime(18591): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.timur.mapapplication/com.timur.mapapplication.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.os.Looper.loop(Looper.java:130)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.app.ActivityThread.main(ActivityThread.java:3693)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at java.lang.reflect.Method.invokeNative(Native Method)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at java.lang.reflect.Method.invoke(Method.java:507)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at dalvik.system.NativeStart.main(Native Method)
12-18 00:03:05.626: E/AndroidRuntime(18591): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:581)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.view.LayoutInflater.inflate(LayoutInflater.java:386)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:215)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.app.Activity.setContentView(Activity.java:1663)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at com.timur.mapapplication.MainActivity.onCreate(MainActivity.java:11)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
12-18 00:03:05.626: E/AndroidRuntime(18591):    ... 11 more
12-18 00:03:05.626: E/AndroidRuntime(18591): Caused by: java.lang.ClassNotFoundException: android.view.fragment in loader dalvik.system.PathClassLoader[/data/app/com.timur.mapapplication-1.apk]
12-18 00:03:05.626: E/AndroidRuntime(18591):    at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.view.LayoutInflater.createView(LayoutInflater.java:471)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.view.LayoutInflater.onCreateView(LayoutInflater.java:549)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:66)
12-18 00:03:05.626: E/AndroidRuntime(18591):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568)
12-18 00:03:05.626: E/AndroidRuntime(18591):    ... 19 more

Thanks for help.

A: You are using MapFragment when your minSdkVersion is set to 8. You should use SupportMapFragment instead like so:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.SupportMapFragment"/>

Also, just a suggestion, do not post your API key, it should be kept private to whomever is developing the app.

A: As Emmanuel suggested, change MapFragment to SupportMapFragment.
Adding to it, extend FragmentActivity instead of Activity in your java class. See if it works now.