Fastest Multithreading Sorting Method

Question: Currently, I am creating a multi-threaded sorter that reads in a bunch of CSV files and outputs a single large sorted CSV file consisting of all the data in the CSV files. Right now, I am planning on sorting each of the CSV's in their individual thread using mergesort and then sorting it one last time when all the data from the threads are concatenated together. I am just curious whether only using mergesort would be considered "fast". After the threads concatenate the sorted data together, the data is sorted in their individual sections but overall, it is still unsorted.
Comment: You should read about [adaptive sorting](https://en.wikipedia.org/wiki/Adaptive_sort).
Comment: I don't know about fastest, but [here](https://stackoverflow.com/a/11380649/315052) is an implementation.
Answer: I thought that merge sort would be memory bound due to relatively tight loops in the merge function until I made a multi-threaded bottom up merge sort. With 4 threads, it was about 3 times as fast as a single-threaded merge sort. In this example, the array is split up into 4 parts, each part is merge-sorted, then thread 0 merges quarter arrays 0 and 1, and thread 2 merges quarter arrays 2 and 3, then thread 0 merges the two half arrays.
https://codereview.stackexchange.com/questions/148025/multithreaded-bottom-up-merge-sort
gnu sort, which is a text file sort, does a multi-threaded merge sort on an array of pointers in the first pass used to create the initial temporary files (assuming the original file is larger than available memory). After the initial pass, it does a single threaded 16 way merge on the temporary files, since the bottleneck there is the disk I/O speed, not processor speed.
Comment: @codemonkey - You could use an array of pointers to the structures instead of using a linked list.
Comment: That sounds like a good solution. I was planning on concatenating the individually sorted arrays and mergesorting again but that is just wasting time because they are essentially on the last step of mergesorting, which is the merge part. Now I am just thinking on whether I should use a linked list or just another array to hold together all of the individual struct arrays of the files.
Answer: How large is your data? Sorting is O(n log n), and the final merge step which is inherently not parallelizable is of course O(n), so unless log n is utterly gigantic or the cost of comparisons is disproportionately large compared to the cost of moving data around, there's very little to be gained by multithreaded sorting.
If you still do want to try it, what's wrong with your approach is doing a final merge sort of the concatenated list. That's essentially going to be the same speed as doing the whole sort all over again. Instead, you want to merge the output from each pair of threads using a single merge operation rather than a whole merge-sort. Repeat this, halving the number of sorted lists you have each time, until the last step just merges 2 lists. You can break this work up into threads by setting up a hierarchical relationship between threads where, when two "sibling" threads in the hierarchy finish their jobs, one exits and the other "moves up" in the hierarchy and picks up merging its sibling's output.
Comment: Oh, I misread that as 5000 lines total. Still, even 5M lines is sufficiently small that it's unlikely to help. log is about 22.
Comment: I don't agree with the argument in your first paragraph. Each pass in a merge-sort takes roughly the same amount of time (because earlier passes have to do more merges whereas later passes have to do merges on larger lists), so even if `log n` is relatively low -- say, around 25 (meaning about 34M items) -- parallelizing early passes can have quite a large effect on the total time.
Comment: Each file has 28 columns and around 5000 lines. The amount of files can range from 1 - 1024.
Comment: You could sort 50000 lines (10x that many) in less time than it takes a thread to start. Multithreaded sorting is not even remotely going to make sense unless you have billions of lines.
Comment: 5,000 * 1024 is around the max amount of lines there can be, which is 5,120,000 lines.
Comment: This is a project for one of my classes so we have to use multi threading unfortunately. I would think multithreading would speed up the process overall if I am going through a directory and creating a new thread for every CSV file I see so that the sorting can begin while I am still searching for CSV files in the directory. Does a thread really take that much time to start?
Comment: A better question than "does a thread really take that much time to start?" is "does it really take that little time to sort thousands of objects?" and the answer is yes!

Fastest Multithreading Sorting Method


How to disable Parent Component Form Submit button if child component fields are not valid

Question: I am using Template Driven Form.
Parent Component HTML
<form #BasicForm="ngForm" (ngSubmit)="onBasicDetailsSubmit()" id="BasicForm">

  <app-input-text [(sharedVar)]="dashboardDetails.Text1" [isMandatory]="true" ></app-input-text>
  <app-input-text [(sharedVar)]="dashboardDetails.Text2" [isMandatory]="false"></app-input-text>

  <input type="submit" value="Save" [disabled]="!BasicForm.valid" class="btn btn-success">

</form>

Child Component
TS
@Input() sharedVar: number;
@Input() isMandatory: boolean;

@Output() sharedVarChange = new EventEmitter();

change(newValue) {
  this.sharedVar = newValue;
  this.sharedVarChange.emit(newValue);
}

HTML
<input type="text" class="form-control" [(ngModel)]="sharedVar" (ngModelChange)="change($event)" [attr.required]="isMandatory">

The Submit button is not getting disabled. I have tried writing required in child component as well as parent component selector, but it doesn't work. Please help.
Comment: No. I am trying it now
Comment: In parent component html you aren't accessing sharedVarChange no?
Comment: You could rather share the same `form` between parent and child. https://stackoverflow.com/questions/51281527/angular-5-form-validation-and-display-error-in-generic-component/51281984#51281984
Only difference is you have template driven forms. That should not be an issue. Once done, you can fetch form controls to validate in either of the components
Answer: As you are using Template-Driven-Form, the best way to validate Child components is to create a custom-Directivelike this that you will always add in each field that you want to validate in the Child-Component-Form:
You can use this one:

import {Directive, OnInit} from '@angular/core';
import {NgControl, NgForm, NgModel} from "@angular/forms";

/**
 * This attribute directive must be used to each input-field of a childComponent.
 * That input-field must contain a NgModel attribute, else the application must throw an error
 * Usage: (<input class="form-control" type="text" registerChildComponentToForm
 *          [(ngModel)]="testname" name="testname" required />
 */

@Directive({
    selector: '[registerChildComponentToForm]',
    providers: [NgModel]
})
export class RegisterTemplateFormModelDirective implements OnInit {

    constructor(private form: NgForm, private eltControl: NgControl) {
    }

    ngOnInit() {
        if (this.form && this.eltControl) {
            this.form.form.addControl(this.eltControl.name, this.eltControl.control);
        }
    }

}

Then register it into declarations and exports in your App-Module

declarations: [
        RegisterTemplateFormModelDirective,
        ...
],
exports: [
        RegisterTemplateFormModelDirective,
        ...
]

Suppose that your <app-input-text> is this HTML code, then you should just use the directive(registerChildComponentToForm) like this:

<input id="iban" name="iban" [(ngModel)]="bank.iban" #ibanRef="ngModel"
  [required]="isMandatory" registerChildComponentToForm/>
Comment: Thank you so much. This solution is working great. Just 1 problem. I am getting the following error in console. can you please help with it?                                                               ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ng-valid: true'. Current value: 'ng-valid: false'.
Comment: I have fixed it with `setTimeOut` , but I dont think its the right approach :     setTimeout(() => {
            if (this.form && this.eltControl) {
                this.form.form.addControl(this.eltControl.name, this.eltControl.control);
            }
        }, 1);
Comment: The approch with `setTimeOut ` is also correct. I use it too. Or use the approche with `ChangeDetectorRef` of Angular https://angular.io/api/core/ChangeDetectorRef
Answer: Parent Component HTML
<app-input-text [(sharedVar)]="dashboardDetails.Text1" (sharedVarChange)="sharedVarChangeHandle($event)" ...

Parent Component TS
sharedVarChangeHandle($event) {
    // by evaluating the value passed you can update a variable (ex: disableSubmit)
}

Parent Component HTML
<input type="submit" value="Save" [disabled]="!disableSubmit" class="bt .....

Answer: Child Component ts
valid // this is a public variable

change(newValue) {
  this.sharedVar = newValue;
  this.sharedVarChange.emit(newValue);
  // here conditioanally update the **valid** variable (true or false)
}


How can I hide interactive console in debug mode in PyDev Eclipse?

Question: How can I remove interactive console from debug logging in PyDev - it takes place and not helps. I normal run there is no such console and it is o.k.
Comment: Why people gives -1 for question still I have no idea - some feedback is need?
Comment: I don't know why the downvote. Hopefully my answer is helpful to you if not to them.
Comment: and how do I avoid getting those PyDev debugger logs of form `pydev debugger: warning: ...` in the eclipse console? I get a lot of them when I run code in debug mode.
Answer: You can turn it off by clicking the icon that looks like a console in the view toolbar, as the arrow below shows:
Comment: @user2361174 if you don't have the icon, you don't have the ability to open the prompt. Either this means you have too old version of PyDev or your console is not attached to a debug session?
Comment: I want to to open the prompt but I'm unable to find this icon on the menu bar, how can I open it?
Comment: You're right, I had PyDev 2.8.2, I updated it to 4.5.4 (later versions of it doesn't show up at all) and now I have it!
Comment: @user2361174 If you mean PyDev in its entirety does not show up see release notes: ["Important PyDev now requires Java 8 and Eclipse 4.5 onwards."](http://www.pydev.org/history_pydev.html)
Comment: and how do I avoid getting those PyDev debugger logs of form `pydev debugger: warning: ...` in the eclipse console? I get a lot of them when I run code in debug mode.


Application install but not displaying in Google Glass after KitKat Update

Question: After updating the OS to kitkat 4.4.2 in Glass, the application I am installing using glassware or via usb debugging are not visible in "OK Glass" -> Immersion. Even on the glass time-line the installed app via glassware are shown as facebook 2min ago, twitter 10min ago but when I was trying to access them using "Ok Glass" command they are not visible in the list of apps.
Comment: The method to set voice commands changed in XE16. See http://stackoverflow.com/questions/23097828/why-is-my-voice-command-missing-from-the-ok-glass-menu-in-xe16 for details.
Comment: have you used/insert voice based intent/launcher in the AndroidManifest.xml ??
Comment: yes, the same app is working fine for the previous version i.e. 4.0.4
Comment: Is there any kitkat specific setting for glass ?
Answer: The same problem with my GDK app was fixed by adding
<code><uses-permission
    android:name="com.google.android.glass.permission.DEVELOPMENT" />
</code>
to the manifest. This is new for XE16, but the change isn't well documented IMHO.


registerOnSharedPreferenceChangeListener Stops getting called after some time

Question: I have a sharedPreference that that gets updated continuously (around every second)from a Class which extends BroadcastReceiver.
The first few times, the registerOnSharedPreferenceChangeListener gets called, but after a while, it stops getting called(I dont even press any button on my emulator).
I know that the sharedPreference is still getting updated because I have seen my log. It is a problem with the registerOnSharedPreferenceChangeListener.
This is the code for the listener(using the suggestion from here)
My shared preference is getting updated almost once every second.
Here is the code for my listener:
SharedPreferences.OnSharedPreferenceChangeListener listener=new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                              String key) {
            // TODO Auto-generated method stub
            if(key=="TIME")
            {
                Log.v("Tagger","Value has changed");
                long L=-2;
                if(sharedPreferences.contains("TIME"))
                {
                    L=sharedPreferences.getLong("TIME", 0);

                    long  HH=(L/1000)/3600;
                    long MM=((L/1000)/60)%60;
                    long SS=(L/1000)%60;
                    MILLIS-=1000;
                    mainHH.setText(Long.toString(HH));
                    mainMM.setText(Long.toString(MM));
                    mainSS.setText(Long.toString(SS));
                }

                if(L<=0)
                {
                    Editor edit=sharedPreferences.edit();
                    edit.remove("TIME");
                    edit.commit();

                    Log.v("VALUE",Long.toString(454L));
                    Intent intent = new Intent(getApplicationContext(), TimerAlarmReceiver.class);
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
                    TimerAlarmReceiver.alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                    TimerAlarmReceiver.alarmMgr.cancel(pendingIntent);
                    start.setText("Start the Test?");
                    TimerOn=false;

                    edit.putBoolean("TimerOn", TimerOn);
                    edit.commit();
                }
            }
        }};
        sharedPreferences.registerOnSharedPreferenceChangeListener(listener);

I have provided the full code because something else might be the problem.
EDIT::
here is my BroadcastReceiver class
public class TimerAlarmReceiver extends BroadcastReceiver {
    public static long TIME;
    public static Boolean TimerOn=false;
    public static AlarmManager alarmMgr ;
    @Override
    public void onReceive(Context context, Intent intent) {

      //Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();

      /*  SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(context);
        Editor editor = sharedPreferences.edit();
        editor.putLong(key, value);
        editor.commit();*/

        SharedPreferences time = PreferenceManager
                .getDefaultSharedPreferences(context);
        long T = time.getLong("TIME",594554L);

        Editor editor=time.edit();
        editor.putLong("TIME", T-1000);
        editor.commit();

        Log.v("Tag", Long.toString(T));
       //this gets updated and i can see the new values of T
    }

    public static void setTime(long T)
    {
        TIME=TimerActivity.DMILLIS;
    }
}

Comment: So you are saying that your Log.x get printed, but your UI components don't get updated?  And that is why you know that the listener is firing?
Comment: no, I have not posted my broadcastreceiver class.
The log prints from there. Please see my edit
Comment: Well, key == "TIME" really should be key.equals("TIME") so that you are doing a character per character comparison instead of address space for a string.
Comment: okay, but why does it work for a few seconds in the first place?. I changed it to key.equals, it still stops
Comment: commit returns a boolean, perhaps a check to see if it stops committing at some point might be helpful.
Comment: that is only if L<0;
L is a long int
Comment: I had meant within your onReceive()
Answer: OnSharedPreferenceChangeListeners are registered via weak reference. Make sure you keep a reference to the listener by setting it to an instance variable.


how to access multidimensional array javascript

Question: var x = [{firstlevel: [{
        secondlevel: [{
            'fname': 'harsh',
            'lname': 'gupta'
        }]
    }]
}]

I want to access secondlevel array without loop-in. Is there a way to directly access the secondlevel array?
I could access it with .map()
x.map(function(item, index) {
   return item.firstlevel[index].secondlevel[index]
})

but still finding a better approach.
Comment: @HarshGupta—in that case, *map* is completely unnecessary and *index* will always be zero (0).
Comment: You have to map through one and then the other. The outer array could be bigger than a child and vice versa
Comment: In this particular instance, `var secondLevel = x[0].firstlevel[0].secondlevel;`. If the first and second level arrays can be of any size, then your `map()` solution seems pretty solid to me.
Comment: @Cᴏʀʏ magic numbers is rarely ever the answer
Comment: @Harsh, It's hard to know how to help with this because the example is too vague. Is that array `x` going to have many items all with `firstlevel` properties?  Is the `firstlevel` array going to have many items? With all those items have `secondlevel` or something else. Please give a more complete example.
Comment: The *map* solution is pretty wasteful. `x[0].firstlevel[0].secondlevel` gives you direct access to the array of objects, using *map* just makes another array of the same objects, you might as well do `x[0].firstlevel[0].secondlevel.splice()` and save the iterations. Also, the way you're using *item* means you'll get `firstlevel[0].secondlevel[0]`, then `firstlevel[1].secondlevel[1]`, etc. so a kind of diagonal filter.
Comment: @Mark_M `firstlevel[]` array will contain only `secondlevel[]` array. Both array's **.length** will always be 1.
Answer: Without loop in, this is the only solution:
var arr = x[0].firstlevel[0].secondlevel


Create one dictionary for each combination of list-values in a dictionary

Question: I have the following dictionary:
my_dict = {"A":0, "B":[1,2], "C":3}

I am trying to split this into a list of 2 dictionaries that encompass each possible value. For example:
#Desired result
[{"A":0, "B":1, "C":3}, {"A":0, "B":2, "C":3}]

I am able to get a list of each needed dictionary, in hopes I can then loop through the list and merge dictionaries using update(). This will overwrite the key "B"and only create a single dict.
Here is what I have done:
dict_list = []
my_dict = {"A":0, "B":[1,2], "C":3}

for k, v in my_dict.items():
    if type(v) == list:
        for i in v:
            dict1 = {k:i}
            dict_list.append(dict1)
    if type(v) != list:
        dict2 = {k:v}
        dict_list.append(dict2)

new_dict = {}
for d in dict_list:
    new_dict.update(d)

print(new_dict)

Output:
{'A':0, 'B':2, 'C':3}

This is overwriting the key 'B' and creating only one dictionary based on the last value.
Comment: you need to create a `defaultdict(list)`
Answer: It's pretty easy if your dict can have only one list.
>>> my_dict = {"A":0, "B":[1,2], "C":3}
>>> k, lst = next((k, v) for k, v in my_dict.items() if isinstance(v, list))
>>> [{**my_dict, k:x} for x in lst]
[{'A': 0, 'B': 1, 'C': 3}, {'A': 0, 'B': 2, 'C': 3}]

It's a bit trickier if your dict can have multiple lists.
>>> from itertools import product
>>>
>>> my_dict = {"A":0, "B":[1,2], "C":[3, 4]}
>>> lists_kv = ([(k, x) for x in v] for k, v in my_dict.items() if isinstance(v, list))
>>> [{**my_dict, **dict(x)} for x in product(*lists_kv)]
[{'A': 0, 'B': 1, 'C': 3},
 {'A': 0, 'B': 1, 'C': 4},
 {'A': 0, 'B': 2, 'C': 3},
 {'A': 0, 'B': 2, 'C': 4}]

Comment: Think I answered my own question. For anyone wondering see [What does **dict mean in python](https://stackoverflow.com/questions/21809112/what-does-tuple-and-dict-means-in-python)
Comment: Marked this as the correct answer as it is absolutely doing what I needed it to do, so thank you. Could you explain what [{**my_dict, k:x} for x in lst] is actually doing?  I am trying to step through but the **my_dict portion is throwing me off.
Comment: @EricT see also [How to merge two dictionaries in a single expression?](https://stackoverflow.com/a/26853961/3620003)


onmouseover onmouseout fadeIn fadeOut no jQuery

Question: Im looking for an elegant solution for a fade in and out of an HTML element onmouseover on mouseout without using jQuery (call me old fashioned).
In theory the below js solution should work however I am having problems with it working could someone point me in the right direction or offer an alternative solution??
My Js functions are and the HTML which is inserted is the same as which is on the page...
function fadeIn(element) {

   for (i = 0; i < 100; i++) {
      var value = 0 + i;

      element.style.opacity = value;
      element.style.filter = 'alpha(opacity=' + value + ')';
   }
}

function fadeOut(element) {

   for (i = 0; i < 100; i++) {
      var value = 100 - i;

      element.style.opacity = value;
      element.style.filter = 'alpha(opacity=' + value + ')';
      element.innerHTML = "

";

   }
}

Comment: >elegant solution
>fade in and out of an HTML element onmouseover on mouseout
>without using jQuery
Choose any 2
Comment: jQuery :-P libraries make life easier.
Answer: Your fadeIn/Out doesn't work right because you haven't done anything to control the rate of change. That will just execute immediately and show/hide the elements.
Try something like this:
function fadeIn(el) {
   var opac = 0;
   var i = setInterval(function() {
     opac += 10;
     if (opac >= 100) {
       clearInterval(i);
       opac = 100;
     }
     el.style.opacity = opac;
     el.style.filter = 'alpha(opacity=' + opac + ')';

   }, 20);
}

That should fade in over 200ms (20 * 100 / 10). Play with the numbers to adjust the speed.
As for mouseover/out, you can just bind the events like anything else.
Generally, attaching JS events like you have, using HTML attributes, is frowned upon. Usually you'd have a helper like this: https://gist.github.com/955642
You want to write your own method that will check which of the main methods, addEventListener or attachEvent your browser supports.


mvc passing model to action method

Question: I'm using MVC 5, and have a page where I will list out payments for a contract.  there are times when there are no payments associated with a contract.  my view brings in the model to list:
<code>@model List<MyProject.Models.PaymentViewModel>
</code>
the Action Method on the Payment view looks like:
<code>        [HttpGet]
    public ActionResult Payment(int id)
    {
        var payments = contractController.GetPaymentsForActiveContract(id);

        return View(payments);
    }
</code>
Now GetPaymentsForActiveContract returns a List and this works fine when I use
<code>@Html.Partial("partialviews/_Payments")
</code>
on my view.  but what i'm trying to do now is have another action method get called, which will return either a view which will display a table of payments, or another one which will write out there are none if no payments exists.
I have that action defined as:
<code>        public ActionResult GetPayments(List<PaymentViewModel> payments)
    {
        if (payments.Count > 0)
        {
            return PartialView("partialviews/_Payments", payments);
        }
        return PartialView("partialviews/_NoPayments");
    }
</code>
I'm not sure how to pass the Model into this Action from my view.  I'm looking through the @Html methods, but can't seem to find anything which would allow me to call the GetPayments method passing in the model and having it return either Partial View.
Answer: If you want to call controller action from view, you can use
<code>@Html.Action()
</code>
method and pass payments list as route value
<code>@{
    var paymentsList = new List<PaymentViewModel> {new PaymentViewModel(), new PaymentViewModel()};
}

@Html.Action("GetPayments", new { payments = paymentsList })
</code>
Comment: I just got it working, I was also able to do it passing it in the view with @Html.Action("GetPayments", new { payments = Model})

mvc passing model to action method


How to write Tricomi's confluent hypergeometric function in terms of Meijer-G function

Question: I am calculating a closed form expectation and I encountered the Tricomi's confluent hypergeometric function
(aka confluent hypergeometric function of the second kind) given by integral $U\left( a,b,z \right) = \frac{1}{\Gamma\left(a\right)} \int_{0}^{\infty} e^{-zt}t^{a-1}\left(1+t\right)^{b-a-1}$. I need to write this in terms of Meijer-G function
$G_{p,q}^{m,n}\left(z\left|\begin{smallmatrix}\mathbf{a}_n, \mathbf{a}_{p-n}\\
\mathbf{b}_m, \mathbf{b}_{q-m}\end{smallmatrix}\right.\right)$.
I used the "MeijerGReduce[HypergeometricU[a, b, z], z] in wolfram alpha and got the solution $U(a,b,z) = \frac{G_{1,2}^{2,1}\left(z\left|\begin{smallmatrix}[1-a], [] \\
[0,1-b],[]\end{smallmatrix}\right.\right)}{\Gamma\left(a\right)\Gamma\left(1+a-b\right)} = \frac{\frac{1}{2\pi i}\oint \Gamma\left(-s\right) \Gamma\left(a+s\right) \Gamma\left(1+a-b+s\right)z^{-s}ds }{\Gamma\left(a\right)\Gamma\left(1+a-b\right)}$
However in the book Handbook of Mathematical Functions: With Formulas, Graphs, and Mathematical Tables it is written in terms of Barnes type integrals as follow (equaion 13.2.10 page 506)
$U(a,b,z) = \frac{\frac{1}{2\pi i}\oint \Gamma\left(-s\right) \Gamma\left(a+s\right) \Gamma\left(1+a-b+s\right)z^{-s}ds }{\Gamma\left(a\right)\Gamma\left(1+a-b\right)z^a}$
In other words the second one has a $z^a$ term in the denominator! Which one is correct? I appreciate the hints and answers!
Answer: There is no issue at all, except that you made a mistake in expanding the Meijer-G function in your first assertion.
Both Abramowitz, Wolfram and Python are correct (and NIST, and Prudnikov et al....)
The wrong bit in your question is:
$$[^*]\; G_{1,2}^{2,1}\left(z\left|\begin{smallmatrix}[1-a], [] \\
[0,1-b],[]\end{smallmatrix}\right.\right)= \frac{1}{2\pi i}\oint \Gamma\left(-s\right) \Gamma\left(a+s\right) \Gamma\left(1+a-b+s\right)z^{-s}ds $$
By the very definition of the Meijer-G function (NIST handbook 2010 p.415 16.17.1):
$$G_{1,2}^{2,1}\left(z\left|\begin{smallmatrix}1-a \\
0,1-b\end{smallmatrix}\right.\right)=\frac {1}{2\pi i} \int_L \Gamma(-s)\Gamma(a+s)\Gamma(1-b-s) z^s ds$$
So now by using the obvious change of variables $s = -u-a$:
\begin{align}
G_{1,2}^{2,1}\left(z\left|\begin{smallmatrix}1-a \\
0,1-b\end{smallmatrix}\right.\right)&=\frac {1}{2\pi i} \int_L \Gamma(u+a)\Gamma(-u)\Gamma(1+a-b+u) z^{-u-a} du \\
&= \frac {1}{2\pi i}z^{-a} \int_L \Gamma(-u)\Gamma(a+u)\Gamma(1+a-b+u) z^{-u} du
\end{align}
so that
$$U(a,b,z) = \frac{G_{1,2}^{2,1}\left(z\left|\begin{smallmatrix}1-a \\
0,1-b\end{smallmatrix}\right.\right)}{\Gamma(a)\Gamma(1+a-b)} = \frac {\int_L \Gamma(-u)\Gamma(a+u)\Gamma(1+a-b+u) z^{-u} du}{2\pi i \Gamma(a)\Gamma(1+a-b)z^a} $$
QED.
Comment: $L$ is not closed. By definition the Meijer-G function uses a Bromwich integral so $L$ is a vertical line at some adequate place in the right half-plane. The change of variables leaves the integral invariant while causing $z^{-a}$ to appear as in standard Riemann integration over the real line. Hint: look at the sign of the exponent of $z$. I suspect you missed sth there.
Comment: Thank you for this answer. I'm confused now, is $L$ a closed contour? What changed by changing of variable? If both formula's are correct, then how it comes that they differ by a $z^a$ factor?!?
Comment: Hmmm, indeed! The exponent of $z$ in my formulation is wrong! Thank you! Finally, correct at last!
Answer: In the Wolfram website, it is claimed that
$$
U(a, b; z) = \frac{1}{\Gamma(a)\Gamma(a-b+1)}G_{1,2}^{2,1}\left(z\left|\begin{smallmatrix}1-a\\
0, 1-b\end{smallmatrix}\right.\right).
$$
I've checked with Python for a set of values and this looks correct:
<code>from mpmath import *

a = mpc(3, 2)
b = mpc(2, 3)
z = mpc(1, 1)

g = meijerg([[1-a],[]], [[0, 1-b],[]], z) / (gamma(a) * gamma(a-b+1))
u = hyperu(a, b, z)

print(g, u)
</code>
gives:
<code>(-0.0673314909897862 - 0.152245341184982j) (-0.0673314909897862 - 0.152245341184982j)
```
</code>
Comment: thank you for your answer. So you give more weight to Wolfram then, that means Abramowitz's handbook made a mistake, am I correct?!?
Comment: @K.K.McDonald I've checked with Python (see my updated answer) and this looks correct.
Comment: Ahhh, yes indeed! I forgot to check numerically! Got too tangled up with theory! Thank you!
Comment: @K.K.McDonald Abramowitz is definitely *not* mistaken. I am afraid *you* are...


Write greek in latex for ubuntu

Question: I'm totally new in ubuntu. I want to write mathematical papers in greek in latex.
From the synaptic package manager I downloaded texlive and texstudio.
Everything works fine in english, but i can't write in greek.
I wrote the following code.
\documentclass{article}
\usepackage[english,greek]{babel}
\usepackage{[iso-8859-7]{inputenc}
\begin{document}
ααα
\end{document}
\enddocumentclass{article}

And texstudio returned
''file babel.sty , unknown option greek...''

I tried that
\documentclass{article}
\usepackage[iso-8859-7]{inputenc}
\begin{document}
ααα
\end{document}
\enddocumentclass{article}

And it returned
''inputenc.sty :file iso-8859-7.def not found ''

Please tell me what to do to fix this problem.
If it's easy, give me some straight instructions if I have to use the terminal.
Comment: Did you install [`texlive-lang-greek`](http://packages.ubuntu.com/search?searchon=contents&keywords=iso-8859-7.def&mode=exactfilename&suite=trusty&arch=any)?
Comment: #muru no. may i write sudo apt-get install texlive-lang-greek?
Comment: Yes, that should do it.
Comment: #muru !!!!!It works perfectly!!!! You're my hero!!!
Answer: A quick search to see which package provides iso-8859-7.def turns up texlive-lang-greek. Therefore installing it might solve the problem:
sudo apt-get install texlive-lang-greek

Write greek in latex for ubuntu


Remote full system backup of a running system

Question: I have a system  where I would like to create a full system backup.
The backup should include all system settings, drivers, user data, etc. on the system storage drive.
The backup should be usable to restore the system drive for that specific PC, after exchaning the physical storage device, once the system drive crashes.
There is the situation, that I only have remote ssh access to create the backup. For restoring, I obviously have to (and can) get to the PC physically (to replace the drive, etc.).
In additon, the PC doesnt have direct access to the internet. I connect via internet to a jump host and have ethernet access from there to the PC.
With physical access I would boot the PC via a ventoy bootstick, to boot to a gparted live system and use dd to clone the system partitions to some image files. But this isn't possible by remote access.
Is there any alternative?
e.g.:
Is it possible to use backup strategies like
tar -cvpzf /backup.tar.gz --exclude=/backup.tar.gz --one-file-system

or
https://help.ubuntu.com/community/BackupYourSystem/TAR
or is this not suitable in my case? Or is this not possible or maybe not complete enough?
I could remotely move the backup from that PC to a NAS or to the jump host and download it from there (or directly generat the backup to the NAS), so it is really about how to generate a suitable backup and not about how to make sure that the backup file is preserved when the system crashes. And also I will be able to reduce the used disk space to less than 30% before creating the backup, if the current 48% is too close to > 50% (which could prevent any strategies that store the backup on the drive itself).
These are the relevant partitions:
/dev/sdf1        2048    1050623    1048576  512M EFI-System
/dev/sdf2     1050624 3705751551 3704700928  1,7T Linux-Dateisystem
/dev/sdf3  3705751552 3750748159   44996608 21,5G Microsoft Basisdaten
sdf
16,4T root  disk  brw-rw----
├─sdf1 vfat                  B687-437E                            /boot/efi
512M root  disk  brw-rw----
├─sdf2 ext4                  56aaa632-d318-4ca9-8094-f803b2237e44 /media/sdf2
1,7T root  disk  brw-rw----
└─sdf3 vfat                  30A8-C177
21,5G root  disk  brw-rw----
/dev/sdf2                       1822227568  817873716   911719948   48% /
/dev/sdf1                           523244       5360      517884    2% /boot/efi

Comment: Automated disk imaging/cloning? ... This might help(the concept can be done with even a mounted modified Ubuntu ISO): https://clonezilla.org/related-articles/009_Multiple_customized_Clonezilla_on_hard_drive/MultipleCustomClonezilla.html
Answer: "drivers" is not going to work. Those are kernels modules and need to be loaded. You can't copy them without backing up the whole kernel (and that would mean the WHOLE system)
I would suggest limiting this to your personal files and create a script for post-install update and consider the restore as installing a -new- installation (ie. lots of "sudo apt install/purge" and "gsettings" or "sed" commands you execute afterwards to get your preferences back) and not fixing the old system. That means this ALSO works if you want  to install a new version of Ubuntu.

Might I add a different approach ...
If I was you I would not use tar but rsync. You can use rsync on a running system plus you can use an external destination. Something like this:
sudo rsync -ahPHAXx --delete --exclude={/dev/*,/proc/*,/sys/*,/tmp/*,/run/*,/mnt/*,/media/*,/lost+found} / {user}@{host}:/backup/{date}/

(you could remove mnt and media from this list if you do incremental backups (see below); all the others are tmpfs so not suited for a backup) with the added benefit that restoring does it one file after another so no need to watch out for disk space. Plus you can restore one single file if need be.
If you want a full backup and have the space you can have more than one backup by adding a {date} to the destination. On the destination you could delete older backups using some kind of logic (keep 7, 14, 30 days and remove older backups)
rsync can also do incremental backups (so only copying the differences since the last backup) so this lowers bandwidth usage by a lot. How this works is: all backups get a timestamp, your 1st backup is a full backup , all other backups compare the latest timestamp with your current system and then create a backup of the differences. Benefit: you can tell rsync to restore a specific timestamp (ie. "make the system like it was on 13:00 2 days ago).
Comment: @Micka yes the rsync command does the whole system (see the / before the destination) except for mnt and media (as those are different partitions or disks anyways).  The benefit with rsync is the incremental backup: the 2nd and more backups only do the changes made saving a gigabytes of space.
Comment: is there any possibility to remote backup the whole system, while it is running?
Comment: One more thing: before running `rsync`, shut down as much of the software on the system to be backed up as you can.  In particular, shutting down any database servers is critical -- copying a database file while it's being updated is virtually certain to corrupt the database.
Answer: Tested on Ubuntu server 20.04 ... The following procedure will enable you to clone the entire disk of a remote machine after running the system from RAM and detaching all disks/disk partitions ... Risk included of course(but contained as much as possible).
References:

man pivot_root
man mount
man umount
man systemctl

Going to RAM

SSH to your server(Keep this SSH connection up all the time and don't close it until the end).

Then, become root:
sudo -i

Then, save the list of mounted file systems(reference) to a file mounted_fs:
df -TH > mounted_fs

Then, try to stop stoppable running services(excluding SSH):
systemctl list-units --type=service --state=running --no-pager --no-legend | awk '!/ssh/ {print $1}' | xargs systemctl stop

Then, unmount all that is unused:
umount -a

Then, prepare a system environment in RAM(will take around 2.2G) by running the following six commands one after the other in the same order:
mkdir /tmp/tmproot
mount none /tmp/tmproot -t tmpfs
mkdir /tmp/tmproot/{proc,sys,usr,var,run,dev,tmp,oldroot}
cp -ax /{bin,etc,mnt,sbin,lib,lib64} /tmp/tmproot/
cp -ax /usr/{bin,sbin,lib,lib64} /tmp/tmproot/usr/
cp -ax /var/{lib,local,lock,opt,run,spool,tmp} /tmp/tmproot/var/

Then, run:
mount --make-rprivate /

Then, change the system root to that environment:
pivot_root /tmp/tmproot /tmp/tmproot/oldroot

Then, mount some needed system parts:
for i in dev proc sys run; do mount --move /oldroot/$i /$i; done

Then, restart SSH:
systemctl restart sshd

Then, run:
systemctl list-units --type=service --state=running --no-pager --no-legend | awk '!/ssh/ {print $1}' | xargs systemctl restart

Then, run:
systemctl daemon-reexec

Then unmount the original system root(on the disk):
umount -l /oldroot/

Then, run df -h and unmount any mounted remaining disks/disk partitions like /boot.

Now the system on the server is totally running from RAM and the disks/disk partitions are totally detached and you are connected through SSH ... This is, more or less, like if you have booted from a live USB.
Imaging
You can now use dd(with great care) to clone your entire disk/s and either save the cloned image/s on a back up drive on the same server(mount the back up drive first) or on another server/NAS in the same network.
You can also save the image directly on your machine(direct and fast internet link required) like so:

Use dd(with great care) to image the entire disk and prepare to send the image from the server to your machine with an nc listener(Change /dev/sda to the disk you want to image on the server):
dd if=/dev/sda | nc -l 4444

Then, open a new terminal on your machine to receive the image and save it(Change 10.0.0.100 with the IP of your server):
nc 10.0.0.100 4444 > disk.img

Wait for this to finish ... You'll see a  message from dd on the server side something like this:
10737418240 bytes (11 GB, 10 GiB) copied, 500.935 s, 21.4 MB/s

Then, close the new terminal(or key in it CTRL+C)

Now, you have successfully cloned the server's disk/s.
Coming back from RAM
The easiest way to bring the server back to normal state(system root on disk) is to simply reboot(I strongly suggest rebooting as it's much safer) ... so, clean up:
rm mounted_fs

Then, reboot(No permanent file systems are mounted so, sending just b to /proc/sysrq-trigger should be fairly safe):
echo "b" > /proc/sysrq-trigger

If, on the other hand, you prefer not to reboot the server then:

Mount your original root partition(the one on the disk) or LV to /oldroot(Change device with your root partition or logical volume and refer to the previously saved mounted_fs file):
mount device /oldroot

Then, run:
mount --make-rprivate /

Then, change the system root back to the one on the disk:
pivot_root /oldroot /oldroot/tmp/tmproot

Then, prepare some important system parts by running the following three commands one after the other in the same order:
for i in dev proc sys run; do mount --move /tmp/tmproot/$i /$i; done

Then, unmount /tmp/tmproot:
umount -l /tmp/tmproot

Then, run:
rmdir /tmp/tmproot

Then, mount the original file systems:
mount -a

Then, restart SSH:
systemctl restart ssh

Then, start failed services:
systemctl list-units --type=service --state=failed --no-pager --no-legend | awk '!/ssh/ {print $2}' | xargs systemctl restart

Then, restart running services:
systemctl list-units --type=service --state=running --no-pager --no-legend | awk '!/ssh/ {print $1}' | xargs systemctl restart

Then, run:
mount --make-rshared /

Then, run:
systemctl isolate default.target

Then, open a new terminal and SSH connect to your server ... If things are working as expected from the new SSH connection, then you're done.

Clean up:
rm mounted_fs


How to prevent ProGuard from obfuscating a library imported from a JAR file?

Question: There is a library that I have imported using Android Studio's Import from JAR/AAR file dialog box. However, ProGuard is obfuscating this library, and hence the methods in those classes are not visible in my other modules.
I tried creating a file with name proguard-rules.pro beside the build.gradle file in the generated library directory. However, this file is not picked up by ProGuard, though it is what I expected could happen.
The library JAR that I'm importing has 4 classes in two sub-packages under the package com.merchant.lib. These are the ProGuard rues that I have added.
-keep class com.merchant.lib.** { *; }

The build.gradle file which is generated by Android Studio is as follows:
configurations.maybeCreate("default")
artifacts.add("default", file("merchant-lib.jar"))

I expect ProGuard to keep the classes in that JAR file intact, without any modifications. However still ProGuard is processing this JAR file, and I cannot access those classes.
How can I prevent ProGuard from obfuscating the library files?
Comment: @DeepakJoshi No Deepak. I've raised a ticket to DexGuard team and they said that wasn't supported as of then. We ended up buying a licence for the test app module too.
Comment: break the problem into smaller problem, first give qualified sub-package in proguard if it works then add more and then roll up
Comment: did you solve this?
Comment: @SriHarshaChilakapati, Is it possible to access the link to the ticket raised?
Comment: @DeepakJoshi I don't think so. Also, I've since moved to a new company, so don't have access to the link as well.
Comment: Thank you. I will try to find an elegant and simple way to do this.
Answer: get the package name from jar file and use -dontwarn
-dontwarn  com.sun.mail.**
-dontwarn  javax.mail.**

Comment: Don't warn is a different thing I believe. When I tried adding this to the app's build.gradle, Gradle was able to compile fine, but I started seeing errors in runtime.
Comment: add this line into proguard.pro file
Comment: Sorry for the typo, I meant I did add it to the app's proguard.pro file. It compiled fine but is throwing a noclassdeffoundexception
Answer: For me, I needed to include the jar file as an input instead of as a library in your proguard.pro file:
-injars jar-in-question.jar

not
-libraryjars jar-in-question.jar

All this in ADDITION to the -keep statement in your question.
Answer: consumerProguardFiles 'lib-proguard-rules.txt' should be set for libraries

To add the ProGuard rules to your library project, you must specify
the file's name with consumerProguardFiles property, inside the
defaultConfig block of your library's build.gradle file. For example,
the following snippet sets lib-proguard-rules.txt as the library's
ProGuard configuration file:

android {
    defaultConfig {
        consumerProguardFiles 'lib-proguard-rules.txt'
    }
    ...
}

Please, see the original doc for more details


Reader cannot continue after i've checked for records

Question: I have successfully checked that there are values in the database.
Here is the code:
if (!reader.Read())
{
    MessageBox.Show(" Can not find user!");
    reader.Close();
}
else
{
    int count = 0;
    while (reader.Read())
    {
        string user = (string)reader.GetString(0);
        string name = (string)reader.GetString(1);
        int roll = (int)reader.GetInt32(2);
        string phone = (string)reader.GetString(3);
        string address = (string)reader.GetString(4);
        string birthofdate = (string)reader.GetString(5);
        label1.Text = "" + roll;
        label2.Text = name;
        label3.Text = birthofdate;
        label4.Text = "" + phone;
        label5.Text = address;
    }
}

But the problem is that the while loop is skipped anyway.
Comment: did u check the visibility of label???
Comment: Do you really want the cast ?`GetString` will return `string` and `GetInt32` an int
Answer: Replace
if (!reader.Read())

with
if (!reader.HasRows)

Answer: I would just have the loop so you call Read in one place, and check count afterwards:
int count = 0;
while (reader.Read())
{
    ...
}
if (count == 0)
{
    MessageBox.Show(" Can not find user!");
}

I've removed the reader.Close() call - so long as your reader is in a using statement (which it should be) it'll be closed automatically.
Answer: You should not use reader.Read() twice, use it only once
if (!reader.HasRows)
                {
                    MessageBox.Show(" Can not find user!");
                    reader.Close();
                }
                else
                {
                    int count = 0;
                    while (reader.Read())
                    {
                        string user = (string)reader.GetString(0);
                        string name = (string)reader.GetString(1);
                        int roll = (int)reader.GetInt32(2);
                        string phone = (string)reader.GetString(3);
                        string address = (string)reader.GetString(4);
                        string birthofdate = (string)reader.GetString(5);
                        label1.Text = "" + roll;
                        label2.Text = name;
                        label3.Text = birthofdate;
                        label4.Text = "" + phone;
                        label5.Text = address;

                    }
                }


How to remove plastic film on window pane

Question: We live in a late-70s condo in California with some windows a few inches above ground level. On one of them, the previous owners placed some plastic film which is now cracking and unsightly. Clearly not for insulation because there's no plastic on the sash window above.
Was this an attempt to "kick-proof" the window? How can we remove the plastic and should we replace it?
Comment: That sure looks like tempered glass that has been shattered.  Are you sure it's the plastic film that is cracked?
Comment: If it's tempered glass, (likely, as it's apparently just about ground level) there should something etched into the glass on a corner stating that.
Comment: Whether you should replace it is a matter of prerogative & local building code. My guess is that you're right about it being a safety film installed in lieu of tempered glass, possibly to catch up to modern standards for windows low to the ground.
Answer: Unless it peels off, which it apparently doesn't, it's probably an adhesive-backed clear coat application. You don't mention if the window is glass or acrylic (Plexiglass). Assuming it's glass you might be able to get it off with a safety razor scraper. Any adhesive could possibly be dissolved with finger nail polish remover or a commercial product such as Goof Off.
If it's acrylic, any scraping or solvent application may damage the pane. In that instance, you may just want to replace it but if you're going to do that you might want to try scraping and solvent first. Nothing to lose.
Comment: Sometimes vinegar will dissolve those adhesives.
Comment: Doing some further research, I believe it is "safety film" and per comments above is in lieu of tempered glass, in case of impact or earthquake.  From what I can tell, safety film needs a professional installer so will probably have to hire someone for the new film.  When they remove the old film, I'll update this post on how they did it.


Binary search algorithm in python

Question: I am trying to implement the binary search in python and have written it as follows. However, I can't make it stop whenever needle_element is larger than the largest element in the array.
Can you help? Thanks.
def binary_search(array, needle_element):
    mid = (len(array)) / 2
    if not len(array):
        raise "Error"
    if needle_element == array[mid]:
        return mid
    elif needle_element > array[mid]:
        return mid + binary_search(array[mid:],needle_element)
    elif needle_element < array[mid]:
        return binary_search(array[:mid],needle_element)
    else:
        raise "Error"

Comment: May want to see [binary-search-in-python](http://stackoverflow.com/questions/212358/binary-search-in-python)
Comment: I would try to avoid creating lots of partial copies of the array, and pass in a lower and upper index instead. Then you simply stop if lower>upper.
Comment: If the purpose of this is academic understanding of binsearch, I can't really help, but if the purpose of this code is to actualy be used: never roll your own binsearch. Always use widly adopted, and prefereably old, library implementation, and even then be very careful, binseach is notoriously difficult to get right in all edgecases.
Answer: It would be much better to work with a lower and upper indexes as Lasse V. Karlsen was suggesting in a comment to the question.
This would be the code:
def binary_search(array, target):
    lower = 0
    upper = len(array)
    while lower < upper:   # use < instead of <=
        x = lower + (upper - lower) // 2
        val = array[x]
        if target == val:
            return x
        elif target > val:
            if lower == x:   # these two are the actual lines
                break        # you're looking for
            lower = x
        elif target < val:
            upper = x

lower < upper will stop once you have reached the smaller number (from the left side)
if lower == x: break will stop once you've reached the higher number (from the right side)

Example:
>>> binary_search([1,5,8,10], 5)   # return 1
1
>>> binary_search([1,5,8,10], 0)   # return None
>>> binary_search([1,5,8,10], 15)  # return None

Comment: You could do `x = (lower + upper) // 2`
Comment: This doesn't work. Try a list: [7,9,2,4,8,6,5,1,8,5,3].
Comment: @user1342336 Binary search is only expected to work on lists that are already in sorted order.
Answer: Why not use the bisect module? It should do the job you need---less code for you to maintain and test.
Answer: array[mid:] creates a new sub-copy everytime you call it = slow. Also you use recursion, which in Python is slow, too.
Try this:
def binarysearch(sequence, value):
    lo, hi = 0, len(sequence) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if sequence[mid] < value:
            lo = mid + 1
        elif value < sequence[mid]:
            hi = mid - 1
        else:
            return mid
    return None

Comment: @Shnatsel ad "large enough input array" - given we are talking about "binary" search and CPython has by default recursion limit set to 1000 (can be set to more by [`sys.setrecursionlimit`](http://docs.python.org/library/sys.html#sys.setrecursionlimit)) we are talking about arrays of sizes up to 2**1000, also know as ~10^300...
Comment: Not only recursion is slow - it will actually blow up in your face if the array is long enough, because Python has no tail recursion optimization and will run out of stack frames given a large enough input array.
Answer: In the case that needle_element > array[mid], you currently pass array[mid:] to the recursive call. But you know that array[mid] is too small, so you can pass array[mid+1:] instead (and adjust the returned index accordingly).
If the needle is larger than all the elements in the array, doing it this way will eventually give you an empty array, and an error will be raised as expected.
Note: Creating a sub-array each time will result in bad performance for large arrays. It's better to pass in the bounds of the array instead.
Comment: Good performance note; it is important for the OP to consider that
Answer: You can improve your algorithm as the others suggested, but let's first look at why it doesn't work:
You're getting stuck in a loop because if needle_element > array[mid], you're including element mid in the bisected array you search next. So if needle is not in the array, you'll eventually be searching an array of length one forever. Pass array[mid+1:] instead (it's legal even if mid+1 is not a valid index), and you'll eventually call your function with an array of length zero. So len(array) == 0 means "not found", not an error. Handle it appropriately.
Answer: All the answers above are true , but I think it would help to share my code
def binary_search(number):
    numbers_list = range(20, 100)
    i = 0
    j = len(numbers_list)
    while i < j:
        middle = int((i + j) / 2)
        if number > numbers_list[middle]:
            i = middle + 1
        else:
            j = middle
    return 'the index is '+str(i)

Answer: def binary_search(array, target):
    low = 0
    mid = len(array) / 2
    upper = len(array)

    if len(array) == 1:
        if array[0] == target:
            print target
            return array[0]
        else:
            return False
    if target == array[mid]:
        print array[mid]
        return mid
    else:
        if mid > low:
            arrayl = array[0:mid]
            binary_search(arrayl, target)

        if upper > mid:
            arrayu = array[mid:len(array)]
            binary_search(arrayu, target)

if __name__ == "__main__":
    a = [3,2,9,8,4,1,9,6,5,9,7]
    binary_search(a,9)

Answer: This is a tail recursive solution, I think this is cleaner than copying partial arrays and then keeping track of the indexes for returning:
def binarySearch(elem, arr):
    # return the index at which elem lies, or return false
    # if elem is not found
    # pre: array must be sorted
    return binarySearchHelper(elem, arr, 0, len(arr) - 1)

def binarySearchHelper(elem, arr, start, end):
    if start > end:
        return False
    mid = (start + end)//2
    if arr[mid] == elem:
        return mid
    elif arr[mid] > elem:
        # recurse to the left of mid
        return binarySearchHelper(elem, arr, start, mid - 1)
    else:
        # recurse to the right of mid
        return binarySearchHelper(elem, arr, mid + 1, end)

Answer: Using Recursion:
def binarySearch(arr,item):
    c = len(arr)//2
    if item > arr[c]:
       ans = binarySearch(arr[c+1:],item)
       if ans:
          return binarySearch(arr[c+1],item)+c+1
    elif item < arr[c]:
       return binarySearch(arr[:c],item)
    else:
       return c

binarySearch([1,5,8,10,20,50,60],10)

Comment: This doesn't handle if the item doesn't exist in the list.  It just throws exception.
Answer: If you're doing a binary search, I'm guessing the array is sorted.  If that is true you should be able to compare the last element in the array to the needle_element.  As octopus says, this can be done before the search begins.
Answer: You can just check to see that needle_element is in the bounds of the array before starting at all. This will make it more efficient also, since you won't have to do several steps to get to the end.
if needle_element < array[0] or needle_element > array[-1]:
    # do something, raise error perhaps?

Answer: It returns the index of key in array by using recursive.
round() is a function convert float to integer and make code fast and goes to expected case[O(logn)].
A=[1,2,3,4,5,6,7,8,9,10]
low = 0
hi = len(A)
v=3
def BS(A,low,hi,v):
    mid = round((hi+low)/2.0)
    if v == mid:
        print ("You have found dude!" + " " + "Index of v is ", A.index(v))
    elif v < mid:
        print ("Item is smaller than mid")
        hi = mid-1
        BS(A,low,hi,v)
    else :
        print ("Item is greater than mid")
        low = mid + 1
        BS(A,low,hi,v)
BS(A,low,hi,v)

Answer: Without the lower/upper indexes this should also do:
def exists_element(element, array):
    if not array:
        yield False

    mid = len(array) // 2
    if element == array[mid]:
        yield True
    elif element < array[mid]:
        yield from exists_element(element, array[:mid])
    else:
        yield from exists_element(element, array[mid + 1:])

Answer:
Returning a boolean if the value is in the list.

Capture the first and last index of the list, loop and divide the list capturing the mid value.
    In each loop will do the same, then compare if value input is equal to mid value.

def binarySearch(array, value):
  array = sorted(array)
  first = 0
  last = len(array) - 1

  while first <= last:
    midIndex = (first + last) // 2
    midValue = array[midIndex]

    if value == midValue:
      return True
    if value < midValue:
      last = midIndex - 1
    if value > midValue:
      first = midIndex + 1
  return False

Binary search algorithm in python


Why does a UICollectionViewCell with a UIButton have a monochrome/tinted image?

Question: I create a UICollectionView and add a single cell who's only subview is a UIButton.  That button has its title and image set.  I've verified that the image data is correct in the debugger.
When the button is drawn on screen I see the text and the image however the image looks as if it has been filled with the tint color, obscuring all of the image other than its shape.
What am I missing here to have this show up as a normal button should?
Update
It turns out this is not specific to UICollectionView but rather all UIButtons in iOS7.
iOS 7 makes all images in buttons behave as template images using the alpha channel of the image in concert with the tint color to produce the image (much like the images in a tab bar).  There's a new renderingMode property on UIImage which is defaulted to "automatic" which lets the context decide (which is template style for buttons)
This can be circumvented using the new imageWithRenderingMode: method on UIImage:
UIImage* myImage = [UIImage imageNamed:@"Foo.png"];
myImage = [myImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
[button setImage:myImage forState:UIControlStateNormal];

Answer: The easiest way to avoid this is to use a different UIButtonType. It's UIButtonTypeSystem on IOS 7 that has this behaviour, so you could use a custom button instead:
UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
[button setImage:myImage forState:UIControlStateNormal];

Answer:
When the UIButton's background color lightText in this way, it will not close the button image.

UIButton.backgroundColor = UIColor.lightText


How to mount a 1/2" UNF drill chuck on an angle grinder with M14 thread?

Question: I want to connect a drill chuck with 1/2"x20 UNF female thread to an angle grinder with a M14x2 male thread. How to?
Safety Warning: Do not use a drill chuck at higher speeds than it is designed for. Specifically, it is not designed for the 10-12000 rpm of a typical angle grinder. Using it in this way may result in serious injuries.
(This question is still meaningful because there are angle grinders with speed control, and running them on slow rpms will be ok with a drill chuck. Or, for that matter, the required adapter will also help building a DIY angle drive from a dead angle grinder, which is then used with a normal power drill.)
Answer: Make sure that your drill chuck is indeed a 1/2"-20 UNF thread. Because threaded drill chucks come in several variants (source):

3/8"-24 UNF thread
1/2"-20 UNF thread
5/8"-16 UNF thread (or maybe that should be 5/8"-19 UNF?)
M12x1.25

If it's indeed a 1/2"-20 UNF thread, here are several options, using varying amounts of commercial parts and DIY:

Buy the required adapter. They are rare though, but you can try your luck with one of these:

Milwaukee 4932430464 (also here) ("Winkelschleifer-Adapter M14 für Lochsägen-Gewinde 1/2"x20", GTIN/EAN 4002395381258)
Festool 484291 ("M14 Stirring Rod Adaptor 1/2", GTIN/EAN 4014549088500) Discontinued product, but still rarely found, like here.

Combine a male/male adapter and a nut. So, you buy a "M14 male to 1/2"x20 UNF male" and a long (40-50 mm) M14 nut. For the thread adapter, you can try get hold of any of the following:

Ruko 108115 ("Adapter mit Gewindeschaft M 14 für Bohrfutter mit Artikel-Nr. 108 116", GTIN/EAN 4007140077967)
Festool 769150 ("Adapter MA M14-1/2"x20")
Collomix Adapter 1/2" outside – M14 outside
Eibenstock Adapter 1/2" to M14
Make your own, by welding M14 and 1/2"-20 UNF bolts back-to-back, with their heads together.

Weld a 1/2" UNF bolt into a long M14 nut, and cut off the head of the bolt. But that could be difficult to get perfectly straight.
Cut off the M14 bolt from the angle grinder, and weld on a 1/2" UNF bolt instead. This could also be difficult to get perfectly straight when rotating, and "damaging" the angle grinder will not be acceptable in most cases. Except where you have one to spare, or it's just the angle gear from a broken angle grinder that you are building an adapter for your power drill from.
Or use your lathe. If you have one around :) to make the adapter.


Can $5^n+1$ be sum of two squares?

Question: I want to determine whether or not $5^n+1$ , $n\in\mathbb{N}$ can be written as sum of two squares.
Obviously, the real problem is when $n$ is odd. I am aware of the known results about numbers written as sum if squares, but I couldn't apply them here. We can see that when $n$ is odd, $5^n+1$ ia divisible by 6 and gives reminder 2 when divided by 4 which means that the two squares we would have to add must end in 1 and 9 or 5 and 5.
Comment: Don't you mean $n \in \mathbb N$?
Comment: Yes. I edited the question
Comment: How would you write $5^1 + 1$ as the sum of two squares. $6= 0+6;1+5; 2+4;3+3$ none of which work.
Comment: $5^4+1=1^2+25^2$, is an obvious example....similarly for all even $n>2$.  But, say, $5^3+1$ can not be so written.
Comment: Note:  if $n$ is odd, then $5^n+1$ is divisible by $3$.  That doesn't rule it out, of course, but you would need  an even power of $3$ to divide it...and then there are the other primes congruent to $3\pmod 4$.  Seems difficult to find an odd example.
Comment: I don't think it's possible for n odd but I can't find a proof
Comment: I would expect it to be difficult.  A quick search through the first 20 or so odd exponents shows, as expected, that there is always a prime congruent to $3\pmod 4$ which divides $5^n+1$ to odd order.  The prime $3$ works most of the time, but not always.  Seems hard to prove in general...and maybe it's not even true.  I stopped looking somewhere around $5^{37}+1$...not that deep a search, really.
Answer: Say $x^2 + y^2 = 5^n + 1$.
Looking mod 2, we get that $x^2 + y^2 = 0 \mod 2$, so $x$ and $y$ have the same parity, and looking mod 4, we get that $x^2 + y^2 = 2 \mod 4$, so $x$ and $y$ must both be odd.
Say $x = 2r + 1$ and $y = 2s+ 1$, so $$x^2 + y^2 = (2r + 1)^2 + (2s+1)^2 = 4(r^2 + r + s^2 + s) + 2 = 5^n + 1$$
or
$$4(r(r+1) + s(s+1)) = 5^n - 1$$
Now, the left side must be divisible by $8$, so $n$ must be even.
Comment: More briefly, for odd $n$, $5^n+1\equiv 6 \pmod 8$, but since squares can only be $0,1$ or $4 \pmod 8$, no two can add up to $6 \pmod 8$.
Answer: You say that you're "aware of the known results about numbers written as sums of squares". Let's try to apply them here (just for fun, because the solution by @Michael Biro is perfectly elementary). We have the classical theorem : $x\in \mathbf N$ is a sum of two squares iff, for all primes $p\equiv 3$ mod $4$, the $p$-adic valuation $v_p(x)$ is even. It's not perhaps superfluous to recall the principle of the proof : every $p\equiv 1$ mod $4$ is a sum of two squares, so, by multiplicativity, it remains only to study the divisibility of $x$ by the primes $p\equiv 3$ mod $4$. Such a prime $p$ is inert (i.e. remains prime) in the PID $\mathbf Z[i]$, so if $x=a^2+b^2=(a+bi)(a-bi), p$ divides both the factors.
Now $3$ is inert and $5$ splits as $(2+i)(2-i)$ in $\mathbf Z[i]$. But $ 5^{2m+1} = (6-1)^{2m+1}=6^{2m+1}- 6^{2m}+...+6-1$ by the binomial formula, so $ 5^{2m+1}+1=6(6^{2m}-...+1)$, whose $3$-adic valuation is $1$. This shows that the exponent in your problem must be even.
Answer: Partial observation
Let $n=2m+1$
$$5^n+1 \mod 3 = 3 \mod 3=0$$
So $3|5^n+1$. We can reduce the cases by observating that:
$$5^n+1\equiv 0 \mod 9 \Rightarrow n=6k+3$$
So if $n\neq6k+3$, it can't be expressed as sum of two squares because it contains $3^1$ in its factorization. In that case it may be useful:
$$5^{6k+3}+1=(5^{2k+1}+1)(5^{4k+2}-5^{2k+1}+1)$$
Improvement
Notice that :
$$5^{6k+3}+1\equiv 0 \pmod 7$$
So to be a sum of squares it must be:
$$5^{6k+3}+1\equiv 0 \pmod{49} \Rightarrow  k\equiv 3 \pmod 7 $$
So our new exponents are of this form $$n_2=6(7k+3)+3=42k+21=21(2k+1)$$
Now notice that:
$$ n_1=6k+3=3(2k+1) $$
$$ n_2=42k+21=3\times7(2k+1) $$
If we could prove that this process goes on infinitely than the thesis would be demonstrated. But i don't know how.
:/
Comment: I think you can finish now with an argument mod $43$, since $5^{21}\equiv-1$ mod $43$.

Can $5^n+1$ be sum of two squares?


Order of permutation

Question: I've run into this problem a while ago, and even though I've read lots of topics about it, I still don't seem to understand how order in permutations works. To be specific, I have to find orders of permutations: $$(16)(36) \text{ and } (135)(251)$$
I suppose that the way to do it is to check which power gives me 1 in the end. Sorry if this is confusingly written, I'm very tired. So, here's my attempt:

$(16)(36)^2 = 1$, so order of permutation should be two, since we're skipping a number, so we get $(1)(6)(3)$;
$(135)(251)^3 = 1$, so order of permutation should be three, since we're skipping two numbers, so we got $(1)(2)(3)(5) = 1$;

Please tell me if my understanding of the subject is incorrect. My lecture notes tell me that I should get swapped results (3 for the first example, 2 for the second), but I can't figure out why it should be like that. Any help is very much appreciated, thank you!
Comment: The "order" of a permutation is the least number of times that the permutation multiplied by itself will give the identity permutation.  For example, a transposition $(1\; 6)$ will give the identity if you multiply it by itself (second power), so a transposition has "order" two.  This terminology comes from group theory, as you are perhaps already aware.
Answer: Non-disjoint cycles do not necessarily commute, and in this case we have
$$
 ((16)(36))^2 \neq (16)^2 (36)^2  = 1
$$
and
$$
 ((135)(251))^3 \neq (135)^3 (251)^3 = 1.
$$
To fix this we have to write the permutations as the product of disjoint cycles. Then
$$
 (16)(36) = (163)
 \quad\text{and}\quad
 (135)(251) = (12)(35).
$$
Now you can apply your logic to the right hand side of the equations, because disjoint cycles do commute. Then $\mathrm{ord} (163) = 3$ and $\mathrm{ord} ((12)(35)) = 2$.
(More generally we have $\mathrm{ord} (a_1 \dotso a_n) = n$ for every cycle $(a_1 \dotso a_n)$, and if $c_1, \dotsc, c_n$ are disjoint cycles then $\mathrm{ord} (c_1 \dotsm c_n) = \mathrm{lcm}(\mathrm{ord}(c_1), \dotsc, \mathrm{ord}(c_n))$.)
Comment: thanks, I think I finally got it! Great, thank you! :)

Order of permutation


Should expansion tank be installed before or after water softener?

Question: I'm installing a water softener and expansion tank similar to the picture below. Does the expansion tank get installed before the water softener, or immediately before the HWT?
Comment: you want to keep the calc to minimum inside the expansion tank for prolonged life
Comment: External salt storage tank? Interesting!
Comment: @FreeMan  yes, they are common on water softeners.   Lowes (among others) sells salt for water softeners in 40 lb bags.  When I "stock up" for mine, I usually get about 400 lbs (10 bags).

https://www.lowes.com/search?searchTerm=salt%20for%20water%20softener&protectedQuery=true
Comment: Yes, @GeorgeAnderson, I'm quite familiar with buying salt & filling the softener -30+ years experience with that. My "salt storage tank" is the concrete ledge near the softener. This drawing _appears_ to have a secondary tank into which salt can be poured from the bag then, it either automatically feeds the salt into the softener or, perhaps, the "salt storage" tanks is also used for creating brine for the flush process. Maybe I'm misinterpreting the drawing, but I would never even think of drawing in the ledge & pile of bags as part of my plumbing system, so that's how I took it.
Comment: @FreeMan sorry if I offended you, your first comment made it seem like you weren't familiar with them, apparently you are, my apologizes.  In my system the salt storage bin not only stores lots of salt, but as you mentioned, it creates the brine for the flushing process.
Comment: No offense, just surprised. Had never heard of a system like that. I might be interested in looking into one when my softener next needs to be replaced. Much easier to dump salt in every 3 or 4 months instead of monthly...
Answer: You want the expansion tank immediately before the cold water inlet to the water heater.  The water in the tank expands due to heating and the hot supply side doesn't leave much room for expansion.  Putting the tank on the cold supply side gives that water a place to expand before it causes backflow into the utility.
In your case, it will also protect the softener from hot water backflow.


Email couldn't send to Ubuntu email server

Question: I have setup an email server at ubuntu. It was working fine. But last time when I send an email to my email server (firstname.lastname@example.com) from my yahoo email, I get the following error message at yahoo email.
188.8.131.52 failed after I sent the message.
Remote host said: 552 5.3.4 Error: message file too big

I could understand that in my email server there is not enough memory space. But I am very new to linux servers. I don't know how to fix this problem at my email server.
Comment: It would help if you said what exactly smtp server you use. My guess is Postfix - so have a look at message_size_limit and also mailbox_size_limit values and set them as required/wanted.
Comment: And of course spend some time reading Postfix manuals :)
Answer: Most email systems place a limit on the size of emails, and many times that limit is exceeded by email attachments. 10G is a typical limit. The error can come from your email server, or Yahoo's email server.
Assuming that you're running Postfix as your mail server, in terminal, go to /etc/postfix, and edit main.cf. Look for a line like mailbox_size_limit =, and message_size_limit=. These set limits for your email server. Zero means unlimited.
Or, using the postconf -d command in terminal will show your current settings. postconf -d | grep -i size will show the parameters that you're interested in. In my config (not a server), the defaults are:
mailbox_size_limit = 51200000
message_size_limit = 10240000

postconf -e 'message_size_limit = 10240000' sets it to 10G. Set it to something higher, if you wish.
You'll need to restart Postfix after changing these settings.
Comment: I checked that file. It says, mailbox_size_limit = 1073741824 (1 GB). Shall I raise this memory to 2 GB?
Comment: Please see my answer update. Cheers, Al
Comment: Great to see the one solution what you have suggested. But I think I could delete some older emails and put the deleted email into the archive and save it to another disk? How can I do this?
Comment: I changed message_size_limit = 20480000 to 30480000 and mailbox_size_limit = 1073741824 to 2073741824 and reloaded postfix using the command 'postfix reload'. But still, I am not able to receive any email from Yahoo or Gmail and Internally.
Comment: Even I deleted some Junk emails from my friend's emails who have an email account on my server.
Comment: **Any** email, or ones with large attachments? Same or different recipients? Same error message about "message file too big"? I'd reset your size limits back to Postfix default, by commenting out those two lines in main.cf, and reloading postfix. Then use the `postfix -d|grep size` to see what they were set to. Then try the mail again. Cheers, Al
Comment: I comment out that two line. But still, I couldn't receive the emails. I checked the result of the command 'postfix -d|grep size'. It shows, mailbox_size_limit = 51200000 and
message_size_limit = 10240000
I posted same question here. http://serverfault.com/questions/811822/sending-email-in-postfix
Comment: What about a different recipient? Does that have the same problem? Cheers, Al
Comment: Yes. I tried to send my friend's email. It has the same problem.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/47576/discussion-between-smith-dwayne-and-heynnema).
Comment: What may have happened is that originally when the mailbox_size was set so high (1,073,741,824) it caused a problem? My expertise is limited any further, but I'd love to hear the final outcome. Cheers, Al


Dark Souls PC FPS drops - can I fix that at all?

Question: My configuration: Mac machine using Win 7 with Bootcamp, ATI Radeon HD 6490m display adapter. And the game runs horribly, compared to what I see for consoles.
I tried different things, most notably installing catalyst control center and unchecking "Application Settings" for Anti-Aliasing and Anisotropic filtering in attempt to wake up the video card and boost the performance (was reading in some forums that the video card is running in idle speeds, that is why the frame drops).
No visible improvement of frame rate (especially Undead Burg, and other areas with fires, Blighttown is just awful).
Do you know any tricks?
Comment: Sounds like your video card meets the minimum spec.  Hard to tell if it meets the other requirements, though.
Comment: I'm also interested in this one. After upgrading to Win7, Dark Souls was the only game that lost FPS. Fiddling with DSFix (Linked in Shykin's mod) settings doesn't seem to help. The game's ported very poorly, in general, so without some very powerful hardware and/or a number of tweaks, it will always have major FPS drops in Undead Burg and Blighttown - the other areas are thankfully more merciful.
Comment: the only explanation i can come up with is the fact that the game does not have loading screens of any kind unless you quicktravel. and im fairly positive that undeadburg and blighttown are located geographically above/below other areas in the game, so it is probably possible that the game is having frame rate issues due to the increased activity in those areas. then again, this is just a guess at the general issue
Comment: DSFix actually made things a lot worse as framerate... But there are many factors, so probably the most important is that it is not helpful.
Comment: @Pvt.Grichmann, you say "after upgrading to Win7" - does this mean that on windows Vista (or XP) it was performing better?
Comment: @Danail Yes, I had Vista previously, and Dark Souls consistently performed significantly better before the upgrade. Now that you mention it, it may be related to DSFix settings: I updated that from 1.4 (I think) to 2.0.
Comment: hm, that is a good hint. I have been only trying with DSFix 2.0.
Comment: The latest game patch decreases CPU load. Maybe that is the issue.
Comment: Yeah I figured it was a long shot but technically it was an answer so I didn't want to place it in a comment. Usually it only increases framerate on machines being held back so to speak. I don't know what else I can suggest honestly, especially because I don't know mac/bootcamp
Answer: Dark souls has a mod/fix that allows you to run the game at a higher framerate/resolution than it was built for. However the same mod also can increase performance if you leave the resolution the same as it was (1024x768).
http://blog.metaclassofnil.com/?tag=dsfix
The mod is placed in the same place as the exe I believe. It comes with a readme. I'd like to point out the on the console blighttown and undead burg had a tendency to lag slightly.
Comment: I've tried before with DSFix 2.0, and the framerate was worse than normal installation. I'll try again - with 2.0, and some older version (1.4 maybe), and will see how the game handles it.
Answer: Use skyrim ENB with ENBoost. (it actually works)
http://enbdev.com/enbseries_skyrim_v0269.zip
http://www.nexusmods.com/skyrim/download/1000054383
1) Unpack the d3d9.dll, enbseries.ini and enbhost.exe out of theenbseries_skyrim_v0269.zip's injectorversion folder and enblocal.ini out of the ENBoost 5_0-38649-5-0.zip's folder corresponding to your graphics card manufacturer into DATA folder of the game.
2) Be sure to disable any kind of AA, including the SMAA and FXAA in DSFix.
3) For optimal performance changing the priority of DARKSOULS.exe in Windows Task Manager is suggested.
It runs constant 30fps in blighttown on laptop with i3 1.8ghz, Intel HD Graphics 4000 and 6gb of ram. (DSfix 900x720, ENBoost, High priority)


Can we find useful, standard search filters?

Question: Search filters
Having recently discovered the power of SE's relatively extensive Advanced Search feature, thanks to Jeromy, I want to ask what if any search filters you use regularly when browsing CogSci?
We all have a finite amount of time to spend here, so I think being able to efficiently find good questions to answers, and good answers to upvote, is an important piece of our community knowledge. It would be great if we could find a few standard search filters that are particularly diagnostic of different types of posts (e.g., new posts that need attention).
Which search filters do you use to help browse CogSci more efficiently? If you weren't aware them before, like I wasn't, can you think of any particularly useful or diagnostic ones?
Search filter examples

Questions without answers or upvotes. Obvious.
New answers with zero score. Obvious.
Favorites. Finally a use for favorites! I could never find them.
Comment: What about the default review queues?
Comment: @StevenJeuris I think most people already know about those.
Answer: I like questions with no votes and no answers that are neither duplicate nor closed.
Answer: Unanswered questions with at least 500 views. It's easy to adjust the # of views to be more or less strict.
Answer: Not-closed, not-duplicate questions with no answers within a tag (e.g., working-memory).


How to turn off bell sound in Visual Studio Code?

Question: I've got freshly installed Visual Studio Code on OSX with only Emacs Keymap extension.
When I'm trying to undo (ctrl + /) the bell sound occurs.
Any idea how to turn it off with this keybinding or for ever? I did not find any sound related settings in VSC configs.
Comment: I came here looking for this answer. I can only add that this setting for me did not change anything:`"terminal.integrated.enableBell": false`
Comment: I've posted the solution updating VS Code settings in [https://stackoverflow.com/a/66505279/7761396](https://stackoverflow.com/a/66505279/7761396)
Comment: for future, it worked, but only for a new terminal, so close all terminals and open it again without the annoying sound, also worth to take a look [here](https://superuser.com/questions/10575/turning-off-the-cmd-window-beep-sound)
Answer: For anyone stumbling on this question going crazy for an answer, the issue is related to this:
https://github.com/Microsoft/vscode/issues/44070
The bell sound actually occurs when you press Ctrl+/ on any text input box (try it in Chrome address bar and Stickies).
You'll need to rebind the shortcut through DefaultKeyBinding.dict.
Go to ~/Library/KeyBindings/DefaultKeyBinding.dict (you'll need to mkdir and touch the file if it doesn't exist).
Add this:
{
    "^/" = "noop:";
}

Then restart vscode.
Comment: Thank you so much; it was driving me crazy!
Answer: To add to the answer from mooncoder above... If you are on High Sierra or above (Mojave, Catalina), you'll need to use this as the contents of your DefaultKeyBinding.dict file, as posted in  this issue on gitHub.com.
{
    "@^\UF701" = "noop:";
    "@^\UF702" = "noop:";
    "@^\UF703" = "noop:";
}

Answer: The best way that I've found is to disable all bell sounds in the operating system's control panel. I'm not sure where that's found for Mac, though.
Answer: I did the following

CTRL+SHIFT +P
typeed settings, to open default visual code
settings.json
added "terminal.integrated.enableBell": false (in
the end of the file, before the closing })
closed all integrated terminals opened
started a new terminal
hit the backspace and no sound =)

also, if you want to turn off the sound of the system (Windows), you can take a look  here, but I tried and even without the sound, the beep (another even more annoying) still happen inside visual code.
Comment: As of v1.56, the bell status now shows in the terminal list. See these release notes:
https://code.visualstudio.com/updates/v1_56
Comment: that doesn't work for me
Answer: Just added "audioCues.volume": 0 in my user settings.json. It works for me \o/
Comment: This worked for me to mute audio cues from github copilot (every single suggestion produced a cue).
Answer: For mac users, the alert sound can be muted system-wide from System Preferences > Sound > Sound Effects. Lower the "alert volume" all the way.
Comment: This turns off sound for the system. Similarly strong answers would be to turn off the computer. Answers must be specific and relevant. The best solutions have minimal side effects.


QTableWidget, centering cellWidgets

Question: Is there a way to place QCheckBox as a cell widget of QTableWidget in the center of a cell, not at the left side, without additional QWidget and adding the checkbox to it's layout?
Answer: Use setCellWidget to add QCheckBox to table:
QWidget *checkBoxWidget = new QWidget(); //create QWidget
QCheckBox *checkBox = new QCheckBox();   //create QCheckBox
QHBoxLayout *layoutCheckBox = new QHBoxLayout(checkBoxWidget); //create QHBoxLayout
layoutCheckBox->addWidget(checkBox);     //add QCheckBox to layout
layoutCheckBox->setAlignment(Qt::AlignCenter); //set Alignment layout
layoutCheckBox->setContentsMargins(0,0,0,0);

ui->tableWidget->setCellWidget(0,0, checkBoxWidget);

Also use these line to resize to contents:
ui->tableWidget->resizeRowsToContents();
ui->tableWidget->resizeColumnsToContents();

setCellWidget: Sets the given widget to be displayed in the cell
  in the given row and column, passing the ownership of the widget to
  the table.

Reference: https://evileg.com/en/post/79/
Comment: This works.  However, it does not address the OP of aligning the `QCheckBox` in the table cell *without* using an additional `QWidget` as the parent of the `QCheckBox`.  I have not found anything better, though.
Answer: I have a simple solution without any additional layout if you want to use ui->tableWidget->resizeColumnsToContents():
Use checkBox->setStyleSheet( "text-align: center; margin-left:50%; margin-right:50%;" );
AFTER this, call ui->tableWidget->resizeColumnsToContents().
If the column is resized after this (eg. the table gets resized by the layout), you may have to call ui->tableWidget->resizeColumnsToContents() again.
It the widget is placed before the resulting column width is known, it retains its (wrong) position. Using resizeColumnsToContents() repositions it.

QTableWidget, centering cellWidgets


Dynamic arguments for Python functions

Question: I have a list of lists, and I would like to enter them into a function in such a way that each element of the main list is a different argument to the function.
squares = [[1,5,9,13], [2,6,10,14], [3,7,11,15], [4,8,12,16]]
print zip(squares[0], squares[1], squares[2], squares[3])
# displays [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

Is there a way to do something like print zip(arguments(squares)) so that the arguments can be entered dynamically?
Answer: This is what the * operator is for:
print zip(*squares)

Dynamic arguments for Python functions


AngularJS: How to make field read only inside directive

Question: For my website I have a custom directive for some fields, I would like to dynamically change in the directive whether a particular field should be read only or not based on some values.
Is this possible? and if so how?
Comment: what about [ngReadonly](https://docs.angularjs.org/api/ng/directive/ngReadonly)?
Answer: I don't think a directive is necessary for what you want to do as ng-readonly can take arguments, you would use it like this;
<input type="search" ng-readonly"variable===true"/>

Hope it helps!
Answer: If your custom directive can be used as class i.e,restrict :'C',then
ng-class="{className:[condition]}"

ng-class="{custom-directive:[value =='ABC']}"


How to find a Shelveset using information provided by a CodeReviewRequest

Question: If I have the name and the owner of the Shelveset, I can find it successfully using the following code:
 foreach (Shelveset shelveset in
     versionControlServer.QueryShelvesets(workItem.
         Fields["Associated Context"].Value.ToString(), "NW\\LFreeman"))

where workItem is an instance of a CodeReviewRequest workItem.
I can get the name of the CodeReviewRequest from workItem.Fields["Associated Context"]
If I set the owner to null as such, it returns an empty list.  It has been reported to me that this method will only work when the owner is specified as a string.
I am trying to figure out how to get the owner.
Using workItem.Fields["Associated Context Owner"].Value.ToString(), I am able to get the GUID of the owner.
The challenge is now how to convert the GUID to the expected owner which would be "NW\LFreeman".
When I print out the workItems.Fields["Associated Context Owner"].Value.ToString(), here's what I see:
c3741a78-1a44-4bf6-95b0-f360cd387f3e

Is it possible to retrieve "NW\LFreeman" from this GUID?  If so, what method call will enable me to do this mapping?

Edit:
Here is the code that worked for me based on the answer and link given:
Guid ownerId = new Guid(codeReviewRequestWorkItem.Fields["Associated Context Owner"].Value.ToString());

Guid[] teamFoundationIds = new Guid[1];
teamFoundationIds[0] = ownerId;

TeamFoundationIdentity[] users = ims.ReadIdentities((Guid[])teamFoundationIds, MembershipQuery.None);

Shelveset[] shelves = vcs.QueryShelvesets(codeReviewRequestWorkItem.Fields["Associated Context"].Value.ToString(), users[0].UniqueName.ToString());

Answer: IIdentityManagementService.ReadIdentities is what you are looking for.
Comment: Thanks!  That solved the issue.  I will add the details to the question.


CSS, vertical alignment doesn't correctly work in Mozilla Firefox

Question: I am trying to create a page that has fixed height Header and also footer (=Nav), where there in between of them is a contentWrapper div, that fully stretches to fill the maximum height of the screen. In the contentWrapper, there is a content div, that includes a form. I need this content div to be both vertically and horizontally aligned according to its parent div contentWrapper. I found a solution for this, which works pretty well, but only in Chrome and IE, not in Firefox (version 22.0).
I created this fiddle where you can observe this behaviour, try different browsers.
http://jsfiddle.net/qWYqb/
Any ideas how to fix this for Mozilla Firefox?
HTML:

                    Logo

                        <form>

                                        Full Name
                                        <input id="fullName" type="text" name="fullName" required="required" />

                                        E-mail
                                        <input id="email" type="email" name="email" required="required" />

                                <input type="submit" id="submit-go" value="Start Now"/>

                        </form>

Option1

Option2

CSS
* {
    margin: 0;
    padding: 0;
    outline:none;
}
html, body{
    min-height: 100%;
        margin: 0;
    padding: 0;
}

table
{
    border-collapse: collapse;
    border-spacing: 0;
}

td, th {
    vertical-align:top;
}

body{
    background-color: #E3E3E3;
}
/* This padding is there to stop margin collapsing */
div {
    padding: 1px 0;
}

#pageWrapper{
    position:absolute; top:0; bottom:0; left:0; right:0;
    padding: 126px 0 100px 0;
    margin: 0 auto;
    width: 400px;
    overflow: hidden
}

/* --- HEADER --- */
header{
    width: 100%;
    height: 126px;
    margin-top:-126px;
    background: yellow;
}

/* --- MAIN CONTENT --- */
#contentWrapper{
    width: 100%;
    position: static;
    display: table;
    overflow: hidden;
    min-height: 100%;
    background: red;
}

.valignMiddle {
    position: static;
    display: table-cell;
    vertical-align: middle;
    width: 100%;
}

#content{
    width: 293px;
    margin: 0 auto;
    background: green;
}

/* --- NAVIGATION --- */
nav {
    width: 100%;
    height: 100px;
    margin-bottom:-100px;
    background: pink;
}

nav li {
    display: inline-block;
    list-style: none outside none;
}

nav ul {
    text-align: center;
}

Answer: Have a look at working demo here: Demo
#contentWrapper{
    width: 100%;
    position: static;
    display: table;
    overflow: hidden;
    min-height: 100%;
    height: 100%;
    background: red;
}

This is working fine in Firefox . Is this what you are looking for?
Comment: This works, thank you! Only I found another cross-browser compatibility issue. This this solution doesn't work for older IE versions (tried on IE8). In older IE everything get aligned to the left side. Even inline alignment of li doesn't work. Any idea how to fix this?


How to determine where a multivariable function isn't differentiable?

Question: consider $f(x,y) = \max(x+2y, x^2+y^2)$, how do i find the points at which this isn't differentiable.
I've tried taking the partial derivative of $x$ and $y$, for general points, but i get stuck with an equation that i can't seem to simplify, is this the wrong method?
Comment: I see that it is the 18th time you post here. Please do use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: How can a function depend on two variables but only contain one in its argument? I think you mean $f(x,y)$.
Comment: Basically what you have is a function that changes its behaviour along one or more curves (the curve where$ x+2y = x^2 + y^2$, maybe excluding the origin). Find a parametrization for such a curve and tey to find whether the function is differentiable there. My bet is that approaching this curve from the$ x+2y $part and the $x^2 + y^2$ part will yield different results. Maybe it will be differentiable at some points, but not differentiable in most of those points
Answer: Hint.
The attached plot shows $f(x,y)$

Considering the change of coordinates
$$
\{x,y,z\}\Leftrightarrow\{r \sin (\phi ) \cos (\theta ),r \sin (\phi ) \sin (\theta ),r \cos (\phi )\}
$$
in the equations
$$
x^2+y^2 = z\\
x + 2y = z
$$
we get the parameterization for the intersection curve as
$$
\left\{\cos (\theta ) (2 \sin (\theta )+\cos (\theta )),\sin (\theta ) (2 \sin (\theta )+\cos (\theta )),(2 \sin (\theta )+\cos (\theta ))^2\right\}
$$
for $0 \le \theta < 2\pi$ shown in blue.
Answer: To get the function differentiable at the intersection of both surfaces, you need that the derivatives are the same, $(1,2)=(2x,2y)$. This is only the case for the point $(x,y)=(\frac12,1)$. Now $x+2y=\frac94$ and $x^2+y^2=\frac54$, so that this is inside the intersection circle where the first function is dominant, not on its boundary.


I can't download needed assets and dependencies using $ rake bower:install

Question: my environments are follows
    os.   :   mac
    rails : 5.0.5
    rvm  :  ruby-2.4.0
    node  :  v6.11.2
    npm.  :   5.3.0
To download needed assets I run the following command on terminal.
    $ rake bower:install
and i got follow errors.
rake aborted!
NoMethodError: undefined method `load_defaults' for #<Rails::Application::Configuration:0x007feb54ef8b38>
/Users/admin/.rvm/gems/ruby-2.4.0/gems/railties-5.0.5/lib/rails/railtie/configuration.rb:95:in `method_missing'
/Users/admin/workspace/now/angular_example/config/application.rb:12:in `<class:Application>'
/Users/admin/workspace/now/angular_example/config/application.rb:10:in `<module:AngularExample>'
/Users/admin/workspace/now/angular_example/config/application.rb:9:in `<top (required)>'
/Users/admin/workspace/now/angular_example/Rakefile:4:in `require_relative'
/Users/admin/workspace/now/angular_example/Rakefile:4:in `<top (required)>'
/Users/admin/.rvm/gems/ruby-2.4.0@global/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
(See full trace by running task with --trace)

Answer: In Rails 4.1.4, and maybe some other versions after 4.0.8, the first line in those files is generated as Rails.application.configure.do rather than, using a project called sample_app as an example, SampleApp::Application.configure.do as in 4.0.8.
Comment: I want to know the way to fix this bug and download needed assets.
And I can't understand how this answer could solve my error.
Comment: change your config/application.rb with SampleApp::Application.configure. after that update bundle.


Why do some sites use jquery with a $j instead of just a $?

Question: I generally use this in jquery
<code>$(document).ready(function() {
    //stuff
}
</code>
I was just on a site that heavily uses jquery and they call it using
<code>$j(document).ready(function() {
    //stuff
}
</code>
On this site they start almost everything out with a j...
<code>function PostComment(form) {
  form = $j(form);
  $j('#CommentSubmitButton').hide();
  $j('#CommentInProgress').show();
  $j.post('/utils/ajaxhandler.aspx', form.serialize(), function(data) {
    $j('#CommentInProgress').hide();
    $j('#CommentSubmitButton').show();
  });
}
</code>
Is this just another way of doing it or is this dependent on a differnt version of jquery or other?
Answer: You can define, how you want to call the jquery functionality.
Maybe this site uses another library, which reserves the $, and for that reason used the alias $j.
Comment: http://docs.jquery.com/Using_jQuery_with_Other_Libraries#Overriding_the_.24-function
Comment: good to know, can you just "do it" or do you need to define it/set it somewhere else?
Answer: This is to avoid colision with other libraries with:
<code> jQuery.noConflict();
</code>
For instance some libraries like prototype also use the $ sign, and if you end up using both it will most likely break. If you developed your jquery functions using $j it won't.
Comment: In the case of this site, they probably say $j = jQuery.noConflict(); - then $j is available as the $ from jQuery, and the previous meaning of $ (if any) is overwritten.
Answer: It's simply a method to avoid naming conflicts. Many JavaScript libraries (jQuery happens to be one of them) uses $ as a shortcut. For more information, see jQuery.noConflict()
Answer: Its definitely to avoid collision with other libraries.  The most notorious of which would be prototype and scriptaculous.


Why can't I :require :refer in clojurescript?

Question: See: https://github.com/clojure/clojurescript/wiki/Differences-from-Clojure#namespaces
It bothers me that idiomatic clojure is:
(ns clojure-example
  (:require [clojure.set :refer [union]]))

But idiomatic clojurescript is:
(ns clojurescript-example
  (:use [clojure.set :only [union]]))

Of course, the clojurescript code would work in clojure as well, but that brings out demons who say I should use require with :refer instead!
What is the cause of this?
Answer: Actually ClojureScript does support :require :refer and has supported it for a long while (here's my commit introducing support for :refer from 12 Jun 2012). That wiki page is out of date. I have edited the section on namespaces on the wiki to bring it up to date.
As for what is idiomatic, there are of course people who dislike :use, but that hardly makes it unidiomatic after several years of production use. You're free to make up your own mind as to whether you prefer :require :refer or not.
(Although the use case where :use actually offers capabilities that :require does not -- pulling in several namespaces with (:use lib.foo lib.bar lib.quux) -- is indeed not supported in ClojureScript, by design.)
Comment: NB. the same commit adds support for skipping `:as` in `:require` libspecs, as well as the use of symbols as libspecs (`lib.foo` being equivalent to `[lib.foo]` -- no `:as`, no `:refer`).


Need an IF-ELSE inside a CASE-WHEN choice

Question: I've got an existing stored procedure that looks like this:
SELECT TOP 1
...
    CASE PX.Client.value('(Type)[1]', 'varchar(25)')
      WHEN 'Sole Proprietor' THEN 'SPR'
      WHEN 'Partnership' THEN 'PAR'
      WHEN 'Corp (C)' THEN 'COR'
      WHEN 'Corp (S)' THEN 'SCO'
      WHEN 'LimitedCorp' THEN 'LLC'
      WHEN 'Trust' THEN 'TRU'
    END AS MyStructure,
...
INTO #Prod
FROM
  @XMLIN.nodes('/MyDataset/MyRegistration') AS PX(Client)

Everything works great except I need to change the logic. Right now if Type is "LimitedCorp" then MyStructure is always "LLC".  But I need to change it so that it sub-divides MyStructure based on the TaxClassification like so (pseudo-code):
...
WHEN 'LimitedCorp' THEN
    IF PX.Client.value('(TaxClassification)[1]') == 'Partnership' THEN 'LP'
    ELSE IF PX.Client.value('(TaxClassification)[1]') == 'SCorp' THEN 'LLS'
    ELSE 'LLC'
WHEN 'Trust' ...

In my .NET code this would be a piece of cake!  I'm not very strong on my stored procedure syntax though!  Thanks!
Answer: Nest another case:
WHEN 'LimitedCorp' THEN

    case
       when PX.Client.value('(TaxClassification)[1]') == 'Partnership' then 'LP'
       when PX.Client.value('(TaxClassification)[1]') == 'SCorp' then 'LLS'
       else 'LLC'
    end

WHEN 'Trust' THEN 'TRU'