text:
Q: WPF combobox value and display text I'm used to doing things like
State.Items.Add(new ListItem { Text = "SomeState", Value = NumericIDofState });

Where State is a Listbox in ASP.NET.
How do i achieve the same with a WPF ComboBox? I do see a property called 'Content' in the ComboBoxItem object but how do i assign each item a value other than what's displayed to the user? Please help.

A: WPF Combobox has:

*

*SelectedValuePath property that specifies the path to the
property that is used to determine the value of the SelectedValue
property. It's similar to ASP.NET ListItem's Value property.

*DisplayMemberPath property that defines a default template
that describes how to display the data objects. It's similar to ASP.NET ListItem's Text property.

Let's say you want your Combobox to show a collection of the following KeyValuePair objects:
private static readonly KeyValuePair<int, string>[] tripLengthList = {
    new KeyValuePair<int, string>(0, "0"),
    new KeyValuePair<int, string>(30, "30"),
    new KeyValuePair<int, string>(50, "50"),
    new KeyValuePair<int, string>(100, "100"),
};

You define a property in your view model returning that collection:
public KeyValuePair<int, string>[] TripLengthList
{
    get
    {
        return tripLengthList;
    }
}

Then, your XAML for the Combobox would be:
<ComboBox
    SelectedValue="{Binding FilterService.TripLengthFrom, Mode=TwoWay}"
    ItemsSource="{Binding TripLengthList, Mode=OneTime}"
    SelectedValuePath="Key"
    DisplayMemberPath="Value" />

Where you set SelectedValuePath and DisplayMemberPath properties to the desired property names of the objects (Key and Value correspondingly) displaying by the Combobox.
Or, if you really want to add items to Combobox in code behind instead of using a binding, you can do it as well. For example:
<!--XAML-->
<ComboBox x:Name="ComboBoxFrom"
    SelectedValue="{Binding FilterService.TripLengthFrom, Mode=TwoWay}" />

// Code behind
public partial class FilterView : UserControl
{
    public FilterView()
    {
        this.InitializeComponent();

        this.ComboBoxFrom.SelectedValuePath = "Key";
        this.ComboBoxFrom.DisplayMemberPath = "Value";
        this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(0, "0"));
        this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(30, "30"));
        this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(50, "50"));
        this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(100, "100"));
    }

A: If you only want to expose a simple property in the viewmodel and handle the text for the choices in the view you can do a simple solution like this:
    <ComboBox SelectedValuePath="Tag" SelectedValue="{Binding YourIntProperty, Mode=TwoWay}">
        <ComboBoxItem Content="First choice" Tag="0"/>
        <ComboBoxItem Content="Second choice" Tag="1"/>
        <ComboBoxItem Content="Third choice" Tag="2"/>
    </ComboBox>

Example with a bool property:
    <ComboBox SelectedValuePath="Tag" SelectedValue="{Binding IsActive, Mode=TwoWay}">
        <ComboBoxItem Content="No" Tag="False"/>
        <ComboBoxItem Content="Yes" Tag="True"/>
    </ComboBox>

Type-verbose alternatives (original examples)
Below are more verbose alternatives where the types are explicitly declared. Depending on your preferred style (or maybe some types that requires it), maybe it suits you better.
<ComboBox SelectedValuePath="Tag" SelectedValue="{Binding YourIntProperty, Mode=TwoWay}">
    <ComboBoxItem Content="First choice">
        <ComboBoxItem.Tag>
            <sys:Int32>0</sys:Int32>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
    <ComboBoxItem Content="Second choice">
        <ComboBoxItem.Tag>
            <sys:Int32>1</sys:Int32>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
    <ComboBoxItem Content="Third choice">
        <ComboBoxItem.Tag>
            <sys:Int32>2</sys:Int32>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
</ComboBox>

Example with a bool property:
<ComboBox SelectedValuePath="Tag" SelectedValue="{Binding IsActive, Mode=TwoWay}">
    <ComboBoxItem Content="No">
        <ComboBoxItem.Tag>
            <sys:Boolean>False</sys:Boolean>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
    <ComboBoxItem Content="Yes">
        <ComboBoxItem.Tag>
            <sys:Boolean>True</sys:Boolean>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
</ComboBox>

The sys namespace is declared as this:
xmlns:sys="clr-namespace:System;assembly=mscorlib"

A: See these properties of combo:

*

*DisplayMemberPath

*SelectedValuePath

A: If you skip the Value, then I think it's quite simple to add a new item into a ComboBox during runtime.
comboBox1.Items.Add("SomeText");

comboBox1.SelectedIndex = comboBox1.Items.Count - 1;

The SelectedIndex property is set to Items.Count-1 so that the newly added item appears in the ComboBox as the selected item.


text:
Q: I am having a Quick Sort error with infinite re cursion I am having problems with my quicksort function constantly re cursing the best of three function. I dont know why it is doing that and i need help. I am trying to practice this for my coding class next semester and this is one of the assignments from last year that my friend had and im lost when it comes to this error
This is my quicksort function:
def quick_sort ( alist, function  ):
    if len(alist) <= 1:
        return alist + []
    pivot, index = function(alist)
    #print("Pivot:",pivot)

    left = []
    right = []

    for value in range(len(alist)):
        if value == index:
            continue
        if alist[value] <= pivot:
            left.append(alist[value])
        else:
            right.append(alist[value])
    print("left:", left)
    print("right:", right)

    sortedleft = quick_sort( left, function )
    print("sortedleft", sortedleft)
    sortedright = quick_sort( right, function )
    print("sortedright", sortedright)

    completeList = sortedleft + [pivot] + sortedright

    return completeList

#main

alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

x = quick_sort(alist, best_of_three)
print(x)

this is my best of three function:
def best_of_three( bNlist, nine = False ):
   rightindex = 2
   middleindex = 1
   if nine == False:

      left = blist[0]
      rightindex = int(len(blist) - 1)
      rightvalue = int(blist[rightindex])
      middleindex = int((len(blist) - 1)/2)
      middlevalue = int(blist[middleindex])
      bNlist.append(left)
      bNlist.append(middlevalue)
      bNlist.append(rightvalue)
      BN = bNlist
      print("Values:",BN)
   left = bNlist[0]
   middle = bNlist[1]
   right = bNlist[2]

   if left <= middle <= right:
      return middle , middleindex
   elif left >= middle >= right:
      return middle, middleindex
   elif middle <= right <= left:
      return right, rightindex
   elif middle >= right >= left:
      return right, rightindex
   else:
      return left, 0

#main
bNlist = []
print('Best of Three')
blist = [54,26,93,17,77,31,44,55]
print("")
print( "List:   [54,26,93,17,77,31,44,55]" )
x, index = best_of_three(bNlist)

print("Pivot: ",x)
print("----------------------------")

i really dont know why it keeps infinitely re cursing,
There is also a third function called ninther
def ninther( bNlist ):

   stepsize = int(len(blist) / 9)
   left = 0
   middle = left + 2
   right = left + 2 * stepsize

   blist[left]
   blist[middle]
   blist[right]
   leftvalue = blist[left]
   rightvalue = blist[right]
   middlevalue = blist[middle]

   left2 = right + stepsize
   middle2 = left2 + 2
   right2 = left2 + 2 * stepsize

   blist[left2]
   blist[middle2]
   blist[right2]
   left2value = blist[left2]
   middle2value = blist[middle2]
   right2value = blist[right2]

   left3 = right2 + stepsize
   middle3 = left3 + 2
   right3 = left3 + 2 * stepsize

   blist[left3]
   blist[middle3]
   blist[right3]
   left3value = blist[left3]
   middle3value = blist[middle3]
   right3value = blist[right3]

   bN3list = []
   bN2list = []
   bNlist = []

   bNlist.append(leftvalue)
   bNlist.append(middlevalue)
   bNlist.append(rightvalue)

   bN2list.append(left2value)
   bN2list.append(middle2value)
   bN2list.append(right2value)

   bN3list.append(left3value)
   bN3list.append(middle3value)
   bN3list.append(right3value)

   BN3 = bN3list
   BN2 = bN2list
   BN = bNlist
   print("Ninter ")
   print("Group 1:", BN)
   print("Group 2:", BN2)
   print("Group 3:", BN3)

   x = best_of_three(bNlist, True)[0]
   c = best_of_three(bN2list, True)[0]
   d = best_of_three(bN3list, True)[0]
   print("Median 1:", x)
   print("Median 2:", c)
   print("Median 3:", d)

   bN4list = [x,c,d]
   print("All Medians:", bN4list)

   z = best_of_three(bN4list, True)

   return z[0], z[1]

#main

blist = [2, 6, 9, 7, 13, 4, 3, 5, 11, 1, 20, 12, 8, 10, 32, 16, 14, 17, 21, 46]
Y = ninther(blist)

print("Pivot", Y)
print("----------------------------")

i have looked everywhere in it and i cant figure out where the problem is when calling best of three

A: Summary: The main error causing infinite recursion is that you don't deal with the case where best_of_three receives a length 2 list. A secondary error is that best_of_three modifies the list you send to it. If I correct these two errors, as below, your code works.
The details: best_of_three([1, 2]) returns (2, 3), implying a pivot value of 2 at the third index, which is wrong. This would give a left list of [1, 2], which then causes exactly the same behavior at the next recursive quick_sort(left, function) call.
More generally, the problem is that the very idea of choosing the best index out of three possible values is impossible for a length 2 list, and you haven't chosen how to deal with that special case.
If I add this special case code to best_of_three, it deals with the length 2 case:
if len(bNlist) == 2:
    return bNlist[1], 1

The function best_of_three also modifies bNlist. I have no idea why you have the lines of the form bNlist.append(left) in that function.
L = [15, 17, 17, 17, 17, 17, 17]
best_of_three(L)
print(L)  # prints [15, 17, 17, 17, 17, 17, 17, 54, 17, 55]

I removed the append lines, since having best_of_three modify bNlist is unlikely to be what you want, and I have no idea why those lines are there. However, you should ask yourself why they are there to begin with. There might be some reason I don't know about. When I do that, there are a couple of quantities you compute that are never used, so I remove the lines that compute those also.
Then I notice you have the code
rightindex = 2
middleindex = 1
if nine == False:
    rightindex = int(len(blist) - 1)
    middleindex = int((len(blist) - 1)/2)
left = bNlist[0]
middle = bNlist[1]
right = bNlist[2]

This doesn't seem to make any sense, since you set rightindex and middleindex to other values, but then you still access values using the old indices (2 and 1 respectively). So I removed the if nine == False block. Again, ask yourself why you had this code to begin with, maybe there's some other way you should modify this to account for something I don't know about.
The result is the following for best_of_three:
def best_of_three(bNlist):
    print(bNlist)
    if len(bNlist) == 2:
        return bNlist[1], 1
    rightindex = 2
    middleindex = 1
    left = bNlist[0]
    middle = bNlist[1]
    right = bNlist[2]

    if left <= middle <= right:
        return middle , middleindex
    elif left >= middle >= right:
        return middle, middleindex
    elif middle <= right <= left:
        return right, rightindex
    elif middle >= right >= left:
        return right, rightindex
    else:
        return left, 0

If I use this, your code does not recurse infinitely, and it sorts.
I don't know why you mentioned ninther at all, since it seems to have nothing to do with your question. You should probably edit it to remove that code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Magento 1.9 - PayPal gateway has rejected request error Mail remainder,

Payment transaction failed. Reason PayPal gateway has rejected
  request. A successful transaction has already been completed for this
  token (#10415: Transaction refused because of an invalid argument. See
  additional error messages for details).
Checkout Type onepage
Customer: Abc (abc@gmail.com)
Items abc x 1 USD 11
   xyz x 1 USD 10 Total: USD 33.93

What is the main cause for this above error?


text:
Q: difference between jsonp and jQuery.support.cors for cross domain request ? also why i can't POST data in jsonp request? i wrote and test my code in local knowing that cross domain request are tricky but i just forgot that .
now i want to publish my code it got me .
so i did a little research and apparently i have two options

1 - using jsonp dataType and callback function
  2 - simply adding
  jQuery.support.cors = true  and crossDomain: true to my ajax code

ofcurse second options seems much easier and i don't need to modify my code as much , but what are the drawbacks ? i mean i'm guessing there are some advantages in using jsonp ? i have to mention my server side code returns a json object to the request
another question ,  why can't i use POST method to send data in my jsonp request ?
$.ajax({
 url:'".base_url()."site/remote_group_like/' ,
 dataType: 'jsonp',
 jsonpCallback: 'getResources' ,
 type: 'POST',
 data: {url : url , domain : domain} ,
 success:function(data){
 },
 error:function(){
 },
});

i have put type: 'POST' in the code  but it keeps sending a GET request ?
and why it doesn't show the ajax request being send in the fire bug ?


text:
Q: Bluetooth suddenly turned off and will not restart on Ubuntu 18.04 I'm running Ubuntu 18.04. I was listening on my Bluetooth connected headphones when they suddenly turned off, so I attempted a reboot.
I got these error messages, before the reboot initiated:
Bluetooth: hci0: command 0x0c03 tx timeout
Bluetooth: hci0 sending initial HCI reset command failed (-110)
usb 1-7: device descriptor read/64, error
usb 1-7: device descriptor read/64, error
usb 1-7: device descriptor read/64, error
usb 1-7: device descriptor read/64, error

and finally
reboot: Restarting system

The Bluetooth toggle will not switch to ON right now in the settings page. What I want to know is:

*

*Why/how could this happen suddenly?

*What do these error messages mean?

*How can I reconnect my Bluetooth headphones once again?


text:
Q: Convert partial differential equation (Fokker-Planck equation) from polar to cartesian coordinates I am trying to convert the following equation in polar form to the cartesian coordinates using Mathematica (Phys. Rev. A 78, 013810 (2008), https://journals.aps.org/pra/abstract/10.1103/PhysRevA.78.013810). I am new in Mathematica, so if somebody can help me it would be great.
\begin{eqnarray}
        \partial_{\tau} W(\tau, r, \varphi) &=& \left\{ (r^2-1)\partial_{\varphi} - \frac{1}{16}\left(\frac{1}{r}\partial_r\partial_{\varphi} + \partial^2_r\partial_{\varphi} + \frac{1}{r^2}\partial^3_{\varphi} \right) \right.
        \nonumber\\
        &+& \left. \xi + \frac{\xi}{2} \left(r +\frac{1}{2}\left(\frac{1}{2} +
        N\right) \frac{1}{r}\right) \partial_r \right.
        \nonumber\\
        &+& \left.\frac{\xi}{4}\left(\frac{1}{2} + N\right) \left(\partial^2_r + \frac{1}{r^2}\partial^2_{\varphi}\right) \right\}W(\tau, r, \varphi),
\end{eqnarray}
where $\gamma = re^{i\varphi}$, $\tau = -\kappa t$ with initial condition $W(0, \gamma) = \frac{2}{\pi}
e^{-2|\alpha-\gamma|^2}$.

A: Clear["Global`*"];
pde = D[w[t, r, phi], r] == (r^2 - 1)*D[w[t, r, phi], phi] -
   1/16 (1/r*D[D[w[t, r, phi], r], phi] +
      D[D[w[t, r, phi], {r, 2}], phi] +
      1/r^2*D[w[t, r, phi], {phi, 3}]) + zeta +
   zeta/2*(r + 1/2 (1/2*n)*1/r)*D[w[t, r, phi], r] +
   zeta/4*(1/2 + n)*(D[w[t, r, phi], {r, 2}] +
      1/r^2*D[w[t, r, phi], {phi, 2}]);

$$
w^{(0,1,0)}(t,r,\phi )=\frac{1}{4} \left(n+\frac{1}{2}\right) \zeta  \left(\frac{w^{(0,0,2)}(t,r,\phi )}{r^2}+w^{(0,2,0)}(t,r,\phi
   )\right)+\frac{1}{2} \zeta  \left(\frac{n}{4 r}+r\right) w^{(0,1,0)}(t,r,\phi )+\left(r^2-1\right) w^{(0,0,1)}(t,r,\phi )+\frac{1}{16}
   \left(-\frac{w^{(0,0,3)}(t,r,\phi )}{r^2}-\frac{w^{(0,1,1)}(t,r,\phi )}{r}-w^{(0,2,1)}(t,r,\phi )\right)+\zeta
$$
 << MoreCalculus`

DChange[pde, "Polar" -> "Cartesian", {r, phi}, {x, y}, w[t, r, phi],
 Assumptions -> {r > 0 && -Pi < phi <= Pi}]

gives
{-((y*Derivative[0, 0, 1][w][t, x, y] +
       x*Derivative[0, 1, 0][w][t, x, y])/Sqrt[x^2 + y^2]) ==
     (1/(16*(x^2 + y^2)))*(16*x^2*zeta + 16*y^2*zeta +
     2*(8*x^5 + 8*x*y^2*(-1 + y^2) + 8*x^3*(-1 + 2*y^2) +
        4*x^2*y*zeta +
               y*(-1 - n + 4*y^2)*zeta)*
      Derivative[0, 0, 1][w][t, x, y] +
     2*(1 + 2*n)*(x^2 + y^2)*zeta*Derivative[0, 0, 2][w][t, x, y] -
          x^3*Derivative[0, 0, 3][w][t, x, y] -
     x*y^2*Derivative[0, 0, 3][w][t, x, y] +
     16*x^2*y*Derivative[0, 1, 0][w][t, x, y] -
          16*x^4*y*Derivative[0, 1, 0][w][t, x, y] +
     16*y^3*Derivative[0, 1, 0][w][t, x, y] -
     32*x^2*y^3*Derivative[0, 1, 0][w][t, x, y] -
          16*y^5*Derivative[0, 1, 0][w][t, x, y] -
     2*x*zeta*Derivative[0, 1, 0][w][t, x, y] -
     2*n*x*zeta*Derivative[0, 1, 0][w][t, x, y] +
          8*x^3*zeta*Derivative[0, 1, 0][w][t, x, y] +
     8*x*y^2*zeta*Derivative[0, 1, 0][w][t, x, y] +
     x^2*y*Derivative[0, 1, 2][w][t, x, y] +
          y^3*Derivative[0, 1, 2][w][t, x, y] +
     2*x^2*zeta*Derivative[0, 2, 0][w][t, x, y] +
     4*n*x^2*zeta*Derivative[0, 2, 0][w][t, x, y] +
          2*y^2*zeta*Derivative[0, 2, 0][w][t, x, y] +
     4*n*y^2*zeta*Derivative[0, 2, 0][w][t, x, y] -
     x^3*Derivative[0, 2, 1][w][t, x, y] -
          x*y^2*Derivative[0, 2, 1][w][t, x, y] +
     x^2*y*Derivative[0, 3, 0][w][t, x, y] +
     y^3*Derivative[0, 3, 0][w][t, x, y]),
   Association["Mapping" -> {x == r*Cos[phi], y == r*Sin[phi]},
  "Assumptions" -> {}]}

But DChange complained about Transformation rule is ambiguous which I am not sure why.
You can download DChange from Analogue for Maple's dchange - change of variables in differential expressions  written by Kubba.


text:
Q: Undeclared template class error when using friend class with templates I'm trying to build a custom regular mesh, so I'm having one template class for the cell, and one template class for the mesh.
But it's giving me an error when trying to make both of them in the same header and both being templates.
Here's the code:
#include <list>

using namespace std;

template<typename T>
class Cell{
    list<T> points;
public:
    friend class Mesh<T>; // Error here "Explicit specialization of undeclared template class"
    Cell(): points() {}
    void insert(const T &data) { points.push_back(data); }
    T *search(const T &data);
    bool delete(const T &data);
};

template<typename T>
class Mesh { // Error here "Redefinition of 'Mesh' as different kind of symbol"
    float xMin, yMin, xMax, yMax;
    float tamaCellX, tamaCellY;
    vector<vector<Cell<T>>> mr;

    Cell<T> *getCell(float x, float y);
public:
    Mesh(int aXMin, int aYMin, int aXMax, int aYMax, int aNDiv);
    void insert(float x, float y, const T &data);
    T *search(float x, float y, const T &data);
    bool delete(float x, float y, const T &data);
};

What am I doing wrong?

A: You need to pre-declare the class template you're using:
template<typename T>
class Mesh;

This is needed before the Cell definition. However, you also need to change delete members as that's a reserved keyword. You'll need to include <vector> as you're using it. Finally, it's very much non-recommended to do using namespace std; (because, when you'll have large projects, you might encounter multiple libs defining their own list, vector, etc.) - just write std:: before standard lib classes.

A: bool delete(float x, float y, const T &data);
delete is a operator in c++ try to rename in both classes and your class Mesh is defined after class Cell make a header for class Mesh


text: Q: Can we get username auto-complete without a ping? I'm frequently in the Android chatroom. Part of our rules (based on many people's preferences) is that excessive use of @User pings is forbidden/discouraged. It would be nice if there was an alternate notation I could use instead to auto-complete a user's name (or just hitting tab to trigger the autocomplete).


text:
Q: c# XNA or c++ directX11 in the future? I have recently started to learn XNA, and quite enjoy it and it's managed code. However, after doing some reading it seems that for windows 8 and windows 8 phones XNA will not be updated to work with these new features, and that Directx11 will be what's used.
So, does anyone know if this is true? I do not know any c++, but i'm fairly confident with c#, so i would like to stick with XNA but if the future will be using c++ and Directx maybe i should switch over now? Also how much harder is c++ to learn if i know c#?
if the case is that directX is the way of the future, i might just go with unity so i can keep using c#.
Any help with this topic is greatly appreciated, thanks a ton

A: At last year's Build conference and other venues, MS's Herb Sutter spoke about it like this (paraphrased):

Over the last decade, hardware got more powerful so quickly that we were able to afford the overhead of productive languages like .net. If we pushed the perf limits, so what, next years computers would handle it no sweat. the cost to make software in a managed language was less than native and we had the hardware power to mitigate the managed overhead.
In the coming decade, the hardware used to get things done is getting smaller, mobile, less powerful, more energy efficient. Suddenly code efficiency and performance in the software is increasingly more important. So far native has that edge.

I guess since graphics software (games) can be a dev area that hits perf limits quickly, it is understandable that this might be one of the first to undergo this shift.

A: As far as i know(and from information found on the web) windows will move away from XNA, though technically it should be backwards compatible. If you're looking for an article to read up on about the future of XNA:
https://gamedev.stackexchange.com/questions/22292/what-is-the-future-of-xna-in-windows-8-or-how-will-manged-games-be-developed-in

A: I would stick to C#, you are faster in development and the performance difference is not too much so you don't have to complain over it.
If you wan't to target mobile plattforms too, i would advice to use OpenGL, it's harder to start with it, but you should be able to develop a framework which supports both mobile and desktop plattforms ( using MonoTouch and Monodroid ).

For the people who scream now that DirectX is better: I know, generally you are right, but DirectX is not supported on mobile plattforms like iOS and Android. There is a clone of XNA for all plattforms which might be working but i don't know if it will support the new DirectX/OpenGL features.


text:
Q: bootstrap navigation bar side by side How can i make a nav bar like this in bootstrap

I tried this code:

                Test

 Test

                            Sign In

                    Title

                    Title

Which will result to this:

I tried also in-line styling but I red in the net that it is not a good practice, I also tried overidding the classes that ruin the bootstrap. It has spaces between. Is't possible to do this with just bootstrap or no inline styling?

A: The space that you see between columns is called Gutter Width. I had the same problem in one of my projects. If you don't want to modify any CSS, then I suggest you get a customized bootstrap. You can modify the Grid System.
Customize Bootstrap at http://getbootstrap.com/2.3.2/customize.html


text:
Q: how to recover deleted rows from MYSQL database Today morning I surprisingly found that some data is deleted form my MYSQL database, I am unable to find that data in any table.
Please suggest how to recover data from MySQL database, DOES MYSQL keeps any Log if yes where it is located?
Please suggest any query to get all records.
I am using MYSQL Workbench 5.

A: If you have binary logs active on your server then you can use mysqlbinlog
You can use the following:
mysqlbinlog binary_log_file > query_log.sql

If you don't have this, then you have probably lost it.
You can look here for more information on how to convert the binary logs to sql.
You can check if binary logging is enabled or not by running the following command:
SHOW VARIABLES LIKE 'log_bin';

A: For InnoDB tables, if binary logs are not enabled, there is a recovery tool provided by Percona which may help.
Created a script to automate the steps from the Percona tool which recovers the deleted rows (if exist) and provides SQL queries to load the data into database.
Please note:

The time between the deletion of rows and the database stop is
crucial. If pages are reused you can't recover the data.


text:
Q: Howto enable output from intel graphics card having nvidia drivers activated I want to know how to activate my second graphics card. The nvidia output is working well, but the second monitor (which is connected to the intel card) doesn't work.
I installed the intel drivers with the graphic installer. My configuration hasn't nothing to do with optimus chips, just a nvidia graphic card connected to a PCI port, and an  integrated intel graphic card into the mainboard. Thanks in advance.

A: That won't work in most cases. Each video card has a Bios in it, trying to take control of all video in the computer. You would need SLI or Crossfirecards to use two graphicscards.


text:
Q: Click function, inside .off removed handler, want it back Need Your help.
I want to:

*

*Click on DIV makes it .active

*Click on SPAN inside DIV removes the .active from THIS DIV

There's DEMO of the way i tried to do this:
http://jsfiddle.net/2RwJJ/
$('div').on( 'click', function() {

  if (!$(this).hasClass('active'))
    $(this).addClass('active');

  // SPAN pressed
  $('div.active span').click( function() {
    $('div.active').off();                         // removing DIV handler
    $('div.active').removeClass('active');
 });
});

Problem: once i've clicked DIV and then SPAN in it, i cannot click it with the jquery action further times, only once in the element
Am I doing something wrong with handlers? Please tell me how to do this.

A: Since the active class is creating dynamically, you need to use delegate for binding click event
$('document').ready(function () {

    $('div').on('click', function () {

        if (!$(this).hasClass('active'))
            $(this).addClass('active');

    });
    $(document).on("click", "div.active span", function () {

        $(this).parent().removeClass('active');
    });
});

Demo

A: Try This
$( function() {

  $('div').click(function() {

    if (!$(this).hasClass('active'))
      $(this).addClass('active');
  });
     // x pressed
 $('body').on('click','div.active span', function() {
     $(this).parent().removeClass('active');
    });
});

DEMO HERE


text:
Q: How to deploy the Consul client on K8s with custom config.yaml? I am trying to deploy the Consul client on a k8s cluster ( the Consul server is on a docker swarm cluster). I want to use a config.yaml (mentioned in https://www.consul.io/docs/k8s/installation/deployment-configurations/servers-outside-kubernetes) to set up the configuration. I found a Helm Chart Configuration page (https://www.consul.io/docs/k8s/helm#client) and a Configuration page (https://www.consul.io/docs/agent/options#config_key_reference). What is the difference between them?  It seems that I need to refer to the Helm Chart Configuration page since I am working on the k8s. However, on the Helm Chart Configuration page, I can not find how to set up something like node_name, data_dir, client_addr, bind_addr, advertise_addr. Besides, I also need to set  verify_incoming, encrypt, verify_outgoing, verify_server_hostname. For ca_file, cert_file, and key_file, I assume that cert_file  is for caCert (in Helm Chart Configuration), key_file is for caKey, and I am not sure what the ca_file stand for.
k8s version:
Server Version:v1.22.4
There ate four servers in the cluster.
Any help would be appreciated.
Thanks

A:
I can not find how to set up something like node_name, data_dir, client_addr, bind_addr, advertise_addr. Besides, I also need to set verify_incoming, encrypt, verify_outgoing, verify_server_hostname. For ca_file, cert_file, and key_file, I assume that cert_file is for caCert

Most of these parameters are specified by the Helm chart when deploying the Consul client or server pods. Is there a particular reason that you need to override these particular settings?
With that said, you can use server.extraConfig and client.extraConfig to provide additional configuration parameters to the server and client agents. Normally you would only specify parameters that are not already specified by deployments created by the Helm chart.


text:
Q: Are there any advantages to using calloc() instead of a malloc() and memset()? I was wondering whether calloc() is preferable to a malloc followed by a memset.  The latter appears to be the most common way of allocating and initializing memory.
A github code search turns up many calloc test and implementations but in the first number of pages no code actually using calloc.
Does anyone who knows of any projects/organizations that use or recommend using calloc and the circumstances where recommend it?
From the comments and answers below, here's some the thoughts that have emerges so far:

*

*calloc(n, size) can prevent overflow that is possible with malloc(n * size)

*combining malloc and memset gives calloc a chance to request a page that is known to already be zeroed.

*a disadvantage to calloc that the combined steps may preclude other wrappers around malloc.

A: Well, I use calloc in quite a bit of C code, so I guess that's an answer.  I think the slightly unusual call method (number of elements and size of element) may throw people.  However, one other reason why you may not see as many calls as you would expect is that a lot of larger projects use wrappers around malloc, calloc, and friends that do error handling (usually terminating the program) on memory allocation failure.  So the actual code uses xcalloc instead.
One reason to use calloc over malloc plus memset is that calloc may be more efficient.  If the C library already knows that a page is zeroed (perhaps it just got new zeroed memory from the OS), it doesn't have to explicitly zero it.


text:
Q: "Easy-to-make-typos" alternative? Is there a good, compact word or phrase that would explain one's ability to make typos?
I mean, I'm trying to write something like this:

Now you can use this feature without either non-predictable XML, or easy-to-make-typos "magic strings"

It regards a fluent API project.

A: I would reword that,

Now you can use this feature without unpredictable XML or typo-prone "magic strings."

(Neither . . . nor is redundant with without.)

A: How about a simple easily mistyped?

Now you can use this feature without unpredictable XML or easily mistyped "magic strings".

As Callithumpian and Colin Fine suggest, "without neither... nor..." should be re-worded, and unpredictable is the word you are looking for. I will add that I'm not quite sure what "unpredictable XML" is supposed to mean to begin with, but I guess it will be clear in context.


text:
Q: Prevent Designer from adding namespace to custom control constructor I have created a usercontrol ´MyButton´ in the namespace ´MyControls´
Namespace MyControls

   <ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip)>
   Public Class MyButton
       Inherits ToolStripButton
       ' Controls staff
   End Class

End Namespace

Using designer my control was added to the form. And everything works ok. But after making some changes in the designer I got error

Type 'MyProject.MyControls.MyButton' is not defined.

Error's codeline is: Me.ButtonClose = New MyProject.MyControls.MyButton()
So problem is because In the project I have a module with same name as project name - MyProject and generated code New MyProject.MyControls.MyButton() trying to find type of MyButton in that module.
Changing code of designer manually (adding Global keyword or removing MyProject prefix) will not work, because after next change in designer, code will be re-generated and errors will comeback.
In other hand designer not added MyProject namespace in the definition of the control
Friend WithEvents ButtonClose As MyControls.MyButton
Question: Is it possible to prevent designer adding MyProject namespace or removing Global? Because I cannot change a name of the module - it is used in other projects already


text:
Q: junit ClassNotFoundException in ScalaIDE I've uploaded my scala project to github

https://github.com/jeesim2/Scala210

Problem is

*

*I need to use scala 2.10 (due to spark 1.6 compatiblilty)
but on ScalaIDE(latest version) I can not run junit test.

Run Unit Test

But Fails with,
Class not found Junit
java.lang.ClassNotFoundException: Junit
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)

When I change Scala version to 2.11 in pom.xml, then It works.
(I commented working properties in pom.xml )
<properties>
    <scala.version>2.10.6</scala.version> <-- not work
    <!-- <scala.version>2.11.5</scala.version> --> <-- work
</properties>

<dependencies>
    <dependency>
        <groupId>org.scalatest</groupId>
        <artifactId>scalatest_2.10</artifactId>  <-- not work
        <version>2.2.6</version> <-- not work
        <!-- <artifactId>scalatest_2.11</artifactId> -->  <-- work
        <!-- <version>3.0.0</version> -->  <-- work
    </dependency>

Why I can not run Scala 2.10's Junit on eclipse?

A: Scala IDE 3.0.3 works for me.
http://scala-ide.org/download/prev-stable.html
I think newer version's not stable for 2.10.x
:D


text:
Q: Möbius: Find the general form I am studying about supplementary questions of the theory of linear transformations. A bilinear transformation with one fixed point is said to be parabolic. Please, can you help me to solve this problem:
"Find the general form of the parabolic transformation of the disk $|z|<R$ into itself if the point R is fixed"


text:
Q: Isomorphisms in Product Rings I'm working on a problem in Michael Artin's Algebra that asks:
Describe the ring obtained from the product ring $\mathbb{R} \times \mathbb{R}$ by inverting the element $(2,0)$.
In the last problem, I proved $$R[x]/(x^2-1) \cong \mathbb{R} \times \mathbb{R}$$
I'm note really sure what to do with this, however.
I considered creating $\varphi: \mathbb{R}[x] \to \mathbb{R} \times \mathbb{R}$ given by $\varphi(f(x))=(f(1),\ f(-1))$. Then $\varphi(x+1)=(2,0)$.
But I don't think that helps me because modding out $(x+1)$ wouldn't really invert the element $(2,0)$, so I'm not really sure where to proceed from here.

A: Let $f:R\times R\to R$ be the first projection, which is a surjective ring morphism. The image of $(2,0)$ is invertible. Suppose that $g:R\times R\to S$ is a ring morphism such that $g(2,0)$ is invertible in S. Since $(0,0)=(2,0)(0,a)$, applying $g$ to both sides and using that $g(2,0$) is invertible you get that $g(0,a)=0$. It follows that $g$ does not depend on the second component of its argument, so there is a unique function $h:R\to S$ such that $g(x,y)=h(f(x,y))$. Indeed, $h(x)$ is $g(x,0)$ for all $x \in R$.
Show that $h$ is morphism of rings.
This implies that the map $f$ has the correct universal property to be a localization of $R\times R$ at $(2,0)$ and therefore the localization you are looking for is $R$.

A: If you're following along in Artin and are trying to solve the problem with only the tools provided up to that point in the book, here's another solution:
In the previous problem, it is shown that:
$$\mathbb{R}[\alpha]=\mathbb{R}[x]/(x^2-1) \cong e\mathbb{R} \times e'\mathbb{R} \cong \mathbb{R} \times \mathbb{R}$$ where $e=1/2-1/2\alpha$, $e'=1-e$ and $\alpha$ satisfies the relationship $\alpha^2=1$.
With this, inverting $(2,0)$ is akin to identifying the ring:
$$\mathbb{R}[\alpha][y]/(y(1-\alpha)-1)$$ since $e$ is the multiplicative identity in $e\mathbb{R}$.
Note:
$$\mathbb{R}[\alpha][y]/(y(1-\alpha)-1)=(\mathbb{R}[x]/(x^2-1))[y]/(y(1-x)-1)=\mathbb{R}[x,y]/(x^2-1,\ y(1-x)-1)$$
It is simple to show that $(x+1,\ y(1-x)-1)=(x^2-1,\ y(1-x)-1)$ by first noting: $$x+1=-y(x^2-1)-(x+1)(y(1-x)-1)$$
We thus identify the ring
$$\mathbb{R}[x,y]/(x+1,\ y(1-x)-1)=(\mathbb{R}[x,y]/(x+1))/(y(1-\bar{x})-1)$$
One can first show $\mathbb{R}[x,y]/(x+1) \cong \mathbb{R}[y]$ by sending $x\mapsto -1$ and then show $$\mathbb{R}[y]/(y(1-\bar{x})-1)=\mathbb{R}[y]/(2y-1) \cong \mathbb{R}[1/2]=\mathbb{R}$$
We thus have that inverting $(2,0) \in \mathbb{R} \times \mathbb{R}$ gives us back a ring isomorphic to $\mathbb{R}$.


text:
Q: Creating an Object [multiple of same instance] I created an Matrix object (like the math Matrix, a 4x4 block of numbers for instance) and it works fine, can set row,col,variable just fine, but, I cant have more than one of the same object, I have it creating an ArrayList of a dozen Matrix objects, each with the three variables, but when I call changeVar(Matrix x,int variable) and refresh the printout of the matrix, it changes all of the numbers to what i changed the variable to. So it looks like its just creating the same instance over and over, and if you change one, it changes them all, am i missing anything obvious?
public class Matrices {

    private static int row, col, value, newRow, newCol;

    public Matrices(int row, int col, int value) {
        this.value = value;
        this.row = row;
        this.col = col;
    }

    public static void setRow(int row) {
        Matrices.row = row;
    }

    public static void setValue(int value) {
        Matrices.value = value;
    }

    public static void setCol(int col) {
        Matrices.col = col;
    }

    public static int getCol(Matrices x) {
        return col;
    }

    public static int getRow(Matrices x) {
        return row;
    }

    public static int getValue(Matrices x) {
        return value;
    }

    public static Matrices changeValue(Matrices x, int value) {
        newRow = getRow(x);
        newCol = getCol(x);
        return new Matrices(newRow, newCol, value);
    }
}

A: The problem is your usage of the "static" keyword.
The short answer is: remove all the static keywords.
The longer answer is that static fields/methods are not associated with any particular instance of the class, so what your code does is set up one field called "row", one called "col" etc and use those for all instances of the class. What you really want is one field per instance: making the fields non-static will achieve this.
In general, avoid using static unless you really, really mean it, i.e. if you want a singleton class, or you have a utility class that shouldn't be instantiated.

A: You are using static members. Static members are shared across all instances.
Don't do that: remove the 'static' keyword.
I am surprised there were no warnings on the this.x = x lines...
Happy coding

A: The "static" modifier on your class fields (i.e.,row,col,value,newRow, and newCol) means that there is one copy of those variables per CLASS rather than per OBJECT.
Further, you are currently modifying those static values in static methods.  In addition to removing the static modifier on your class fields, you will need to remove the static modifiers on your methods and then access the object's attributes (fields) using "this" (if your fields have the same names as the method's parameters).


text:
Q: Distinct σ-Algebras of a Set with infinite number of elements Is it possible to construct 2 distinct σ-Algebras of a Set (e.g. Integers) with neither of them having finite number of elements?

A: Sure. For any $k$, let $B_k$ be the collection of subsets of $\mathbb{N}$ that either contain every multiple of $k$ or none of them. Then $B_k$ is a $\sigma$-algebra for every $k$, and no two of them are the same. In fact, $B_2$ and $B_3$ aren't even contained in one another.
In the comments, Basti gave a good example of a pair of distinct $\sigma$-algebras on $\mathbb{R}$.


text:
Q: Integral ${\large\int}_0^1\frac{\ln^2\ln\left(\frac1x\right)}{1+x+x^2}dx$ Gradshteyn & Ryzhik, 7th ed., p. 570, formula 4.325(5) give the following definite integral:
$$\begin{align*}{\large\int}_0^1\frac{\ln\ln\left(\frac1x\right)}{1+x+x^2}dx&=\frac\pi{\sqrt3}\ln\frac{\sqrt[3]{2\pi}\,\Gamma\left(\frac23\right)}{\Gamma\left(\frac13\right)}\\&=\frac\pi{\sqrt3}\left(\frac{4\ln2\pi}3-\frac{\ln3}2-2\ln\Gamma\left(\tfrac13\right)\right)\end{align*}$$
This and other similar integrals are discussed in several papers:

*

*Vardi, Integrals, an introduction to analytic number theory. Am. Math. Mon. 95, 308–315 (1988)

*Adamchik, A class of logarithmic integrals. Proceedings ISSAC, 1–8, 1997

*Medina, Moll, A class of logarithmic integrals, Ramanujan J. 20 (2009), no. 1, 91–126

*Blagouchine, Rediscovery of Malmsten's integrals, their evaluation by contour integration methods and some related results, Ramanujan J. 2014; 35: 21

Is it possible to find a closed form for a similar integral having the square of the logarithm in the numerator?
$${\large\int}_0^1\frac{\ln^2\ln\left(\frac1x\right)}{1+x+x^2}dx$$

A: You may write
$$\begin{align*}
{\large\int}_0^1\frac{\ln^2\ln\left(\frac1x\right)}{1+x+x^2}dx&={\large\int}_0^\infty \left(1-e^{-t}\right)\frac{\ln^2t}{1-e^{-3t}}e^{-t}dt\\
&=\sum_{n=0}^\infty{\large\int}_0^\infty \left(e^{-t}-e^{-2t}\right)e^{-3nt}\ln^2t\:dt\\
&=\sum_{n=0}^\infty \left({\large\int}_0^\infty e^{-(3n+1)t}\ln^2t\:dt-{\large\int}_0^\infty e^{-(3n+2)t}\ln^2t\:dt\right)\\
&=\sum_{n=0}^\infty \left. \partial_{s}^2 \left({\large\int}_0^\infty t^se^{-(3n+1)t}\:dt-{\large\int}_0^\infty t^s e^{-(3n+2)t}\:dt\right)\right|_{s=0}\\
&=\left. \partial_{s}^2 \left(\Gamma(s+1) \left(\sum_{n=0}^\infty \frac{1}{(3n+1)^{s+1}}-\sum_{n=0}^\infty \frac{1}{(3n+2)^{s+1}}\right)\right)\right|_{s=0}\\
&=\left. \partial_{s}^2 \left(\frac{\Gamma(s+1)}{3^{s+1}} \left(\zeta\left(s+1,\frac13\right)-\zeta\left(s+1,\frac23\right)\right)\right)\right|_{s=0}\\
\end{align*}$$ Then, using the Laurent series expansion of the Hurwitz zeta function near $1$, $$ \zeta(s+1,a)
= \frac1s+\sum_{k=0}^{\infty}\frac{(-1)^{k}}{k!} \gamma_{k}(a) s^{k}, \quad a>0, \, s\to 0,
$$ with $\displaystyle \gamma_{0}(a)= - \psi(a)=-\Gamma'(a)/\Gamma(a)$, we get

$$
\color{#0052A3}{\frac{\pi^3\sqrt{3}}{54}+\frac{\sqrt{3}\pi}{9}  (\gamma+\ln 3)^2+\frac{2}{3} (\gamma+\ln 3)\! \left(\gamma_1\!\!\left(\frac{1}{3}\right)-\gamma_1\!\!\left(\frac{2}{3}\right)\right)+\frac{1}{3}\!\!\left(\gamma_2\!\!\left(\frac{1}{3}\right)-\gamma_2\!\!\left(\frac{2}{3}\right)\right)}.
$$

Observe that, as pointed out by Vladimir Reshetnikov, you can make the following substitution

$$
\color{#3366FF}{\gamma_1\left(\tfrac13\right)-\gamma_1\left(\tfrac23\right)=\frac\pi{\sqrt 3}\left(6\ln\Gamma\left(\tfrac13\right)-\gamma+\frac{\ln 3}2-4\ln(2\pi)\right)}.
$$


text:
Q: Can I use a 12V and a 5V line from a PC power supply to get a safely useable 7V I'd like to connect a fan at 7V in a PC.  If I connect the fan's + to a 12V rail and - to a 5V rail, can I safely use that for 7V?  Would the current rating just be the lower of what the 5V and 12V rail will handle?

A: This was asked like a week ago.. Undervolting PC Fan from 12V to 7V.
Short answer, technically yes it could work. As long as 5v rail is constantly sourcing more power than the fans maximum pull. I don't really recommend it though.

A: The answer is probably not.

simulate this circuit – Schematic created using CircuitLab
Figure 1. A simplified representation of a switched-mode power supply output.
The problem isn't your maths - it's the current flow. Both the 12 V and 5 V supplies are designed to source current. It can only flow out through the diodes. In your configuration you are asking the 5 V supply to sink current. In most cases - and almost certainly in yours - the 5 V supply can not do this. There is no way for it to bleed off current to pull the voltage down. D2 stops reverse current flow.

What is the situation if the 5 V supply is already sourcing more current than the fan draws? Will it simply impose noise on the 5 V rail? – Andrew Morton

In this case it would work. The load would draw off the current. e.g., Fan requires 100 mA, 5 V load requires 150 mA then the fan supplies 100 mA and the 5 V supply another 50 mA.
But what happens if the 5 V load is reduced to 80 mA? The voltage will rise on the 5 V line and most logic chips will be destroyed at 6 to 6.5 V. (CMOS is an obvious exception as it can go to 15 V.)

A: LDO's are emitter followers with no active pulldown so with no load it will fail and 5V will rise.
However if there is a static load externally on the 5V rail, that pulls down the +5V  voltage opposed by a regulator that pumps up the current (and V ), then a light fan current only decreases the main 5V load very slightly and will work properly.
Fans only take <5W and this is 1~2% of typical CPU power supplies with the assumption that is what you are using.  If not then a dummy load on 5V to offset opposing fan current is needed.


text:
Q: Patching external SVN repository I'm asking this for a coworker, I think it would be better, if he has a patch for an open source project to just send it to the admin of the project, but he wants an immediate solution and I don't want to convert an external repository.
So, is there any way to set up SVN to patch a file in an external repository when you check it out  or update the repository?

A: No. It's not possible to run a hook on checkout or update... so svn isn't going to be able to directly apply your patch.
I know you mentioned you don't want to convert your svn:external to an internal repo... However I'd most likely to go that route.  The red book has a solid article on vendor branches. Hopefully the patch your coworker submits will be in the next release of the library, so you won't incur a cost updating to that new release and reapplying your patch - you could just go back to an svn:external at that point.
If that's not workable, other things that come to mind: having the build script apply the patch, or patch & build the library and publish it to an artifact repository (nexus or archiva) and having the team resolve the dependency from there.


text:
Q: Query to group by the contents of the field I need help to make query to group by content of field. I have the following Database:
+----+--------------+-----------------+------------------------------+
| id | depart_kode  |    depart_task  |            value             |
+----+--------------+-----------------+------------------------------+
| 1  |     001      |  Create Profil  |  Some Value                  |
| 2  |     001.12   |  Create Profil  |  Some Value                  |
| 3  |     001.452  |  Create Profil  |  Some Value                  |
| 4  |     002.914  |  Create Profil  |  Some Value                  |
| 5  |     002      |  Create Profil  |  Some Value                  |
| 6  |     003      |  Create Profil  |  Some Value                  |
+----+--------------+-----------------+------------------------------+

I need to make a query where I group by depart_kode and I should print by the first 3 digits like this in format json
  "001":[
    {
    "depart_kode":"001,
    and other
    },
    {
   "depart_kode":"001.12"
    },
    ],
    "002":[
    {
     "depart_kode":"002"
    }
]

something like that, most importantly they will be grouped in an array based on the first 3 numbers like 001.
and json just an example, which I want to split into an array based on the first 3 digits

A: Something like this?
$departs = [];
foreach ($sqlRows as $row) {
    $departKey = substr($row['depart_kode'], 0, 3);

    if (!array_key_exists($departKey, $departs)) {
        $departs[$departKey] = [];
    }

    $departs[$departKey][] = $row['depart_kode'];
}

Working example.
references

*

*substr - get a specific part of a string (first 3 chars in our example)

*array_key_exists - checks if the key in an array exists


text:
Q: Setting the generic parameter from an object's variable Say I have a number of different classes that implement this interface:
public interface IRequest
{
    Type ResponseType { get; }
}

Where the idea is that each Request-class specifies the Type of the reponse it would receive.
And I have a class for serializing/deserializing, where the deserialize-method signature is so:
public static T Deserialize<T>(byte[] data) where T : IRequest
{ ... }

How can I call Deserialize, and use the ResponseType variable as the generic parameter?
var request = new SomeRequest() // object which implements IRequest
byte[] receivedData = myNetworkService.SendRequest(request.Serialize());
var response = MyBinarySerializer.Deserialize<request.ResponseType>(receivedData);

Or is there another way to go about this? The class I am using for serializing/deserializing is 3rd party, so I cannot change it. Its Deserialize<T>() needs to be called with the generic parameter T

A: You can add another overload of Deserialize which accepts a Type argument. Then you can delegate the generic call to that as well.
public static T Deserialize<T>(byte[] data) where T : IRequest
{
    return Deserialize(typeof(T), byte[] data) as T;
}

public static object Deserialize(Type, byte[] data)
{
   ...
}

A: The generic parameter is a design time type, where the property is a runtime type. You can't use a runtime type as a design time type, but there should be an overload of Deserialize that takes a type:
object deserialisedObject =  Deserialise(Type t, Object o);
if(deserialisedObject is MyType)
{
    var property = ((MyType)deserialisedObject).MyProperty;
}


text:
Q: Возможно ли установить Callback-функцию при завершении работы скрипта? Нужно назначить код, который бы автоматически выполнялся в конце работы скрипта. Чтобы работало как директива auto_append _file (авто-подключение файла в конце выполнения скрипта), но с такой разницей:

*

*это должна быть callback-функция вместо инклуда файла;

*устанавливалось во время выполнения, а не через .htaccess

Возможно ли в пхп такое?

Попытка решения (неуд.): Сначала хотел заюзать деструктор главного объекта (ведь он полюбому выполнится в конце), но все красивое решение развалилось, когда до меня дошло, что деструктируются все остальные объекты, и, когда выполнение доходит до главного деструктора, все нужные объекты уже уничтожены. Поэтому нужнен коллбэк, чтобы выполнился ДО срабатывания всех деструкторов.
A: Повесьте обработчик на register_shutdown_function()


text:
Q: rails multiple create (JSON through POSTMAN) I want to create an API, and I need to create multiple post, like this (but the list can reach an undefined number of items):
{"item":{"name":"Objeto 1","description":"Descripcion 1","price":100}},
{"item":{"name":"Objeto 2","description":"Descripcion 2","price":200}},
{"item":{"name":"Objeto 3","description":"Descripcion 3","price":300}},
{"item":{"name":"Objeto 4","description":"Descripcion 3","price":400}}

I have this controller:
class ItemController < ApplicationController
  before_action :set_item, only: [:show, :update, :destroy]

  # GET /item
  # GET /item.json
  def index
    @item = Item.all

    render json: @items
  end

  # GET /items/1
  # GET /items/1.json
  def show
    render json: @item
  end

  # POST /items
  # POST /items.json
  def create
    @item = Item.new(item_params)

    if @item.save
      render json: @item, status: :created, location: @item
    else
      render json: @item.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /items/1
  # PATCH/PUT /items/1.json
  def update
    @item = Item.find(params[:id])

    if @item.update(item_params)
      head :no_content
    else
      render json: @item.errors, status: :unprocessable_entity
    end
  end

  # DELETE /items/1
  # DELETE /items/1.json
  def destroy
    @item.destroy

    head :no_content
  end

  private

    def set_item
      @item = Item.find(params[:id])
    end

    def item_params
      params.require(:item).permit(:name, :description, :price)
    end
end

My question is, how can I spend this list? Do I need to create a new method?
I'm sending the JSON array through POSTMAN
This is the model
class Item < ActiveRecord::Base

end

A: Option 1
Without making changes to your ItemsController...
From Postman, you need to perform one request at a time, like this:

Option 2
If you want to send multiple items you need to modify your create action to accept many items or add a new one to handle this problem.
For example, you can create the create_many action:
In /your-app/config/routes.rb
Rails.application.routes.draw do
  resources :items do
    collection do
      post 'create_many'
    end
  end
end

In /your-app/app/controllers/items_controller.rb
class ItemsController < ApplicationController
  # other actions...

  def create_many
    # I've done a very basic implementation.
    # I think you can use a service to extract from the controller the ability to create multiple items and handle errors.
    # See "2. Extract Service Objects" http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/)
    @items = []
    items_params[:items].each do |item_data|
      @items << Item.create(item_data)
    end
  end

  private

  def items_params
    params.permit(items: [:name, :description, :price])
  end
end

In /your-app/app/views/items/create_many.html.erb
<%= @items.inspect %>

From postman you can do:

Option 3
I asked you about your models because if you have a "user has_many :items" relation for example, you could create nested items in a Rails way using nested attributes


text:
Q: Images don't get smaller I have a table and each image is in a div inside a table cell. As there were many images with different sizes I wrote the following code to make them smaller if their height was biggher than 200px and else if their width was bigger than 118px but this script is not working properly, sometimes it works when I refresh my page. What am i doing wrong?
var tableImages = $("table td>div> img");
        tableImages.each(function () {
            var curTableImgHeight = $(this).height();
            var curTableImgWidth = $(this).width();

            if (curTableImgHeight > 200) {
                $(this).css({ "max-width": "188px", "height": "100%" });
            }
            else if (curTableImgWidth > 188) {
                $(this).css({ "max-height": "200px", "width": "100%" });

                var parDivHeight = $(this).parent().height();
                var topmargin = (parDivHeight - $(this).height()) / 2;
                $(this).css('margin-top', topmargin);
            }

        });

A: I guess you might want to use $( window ).load() :
$( window ).load(function() {
    var tableImages = $("table > td > div > img");
    ....
});

Hope this helps.

A: I think you shouldn't use jQuery here.
.img {
    max-width:188px;
    max-height:200px;

    /* set min width and height if needed */
}

Simple and clean
If you have all images different size you won't get them to look exactly same. You have to choose your layout width or height and say that all images have to match that width...


text:
Q: Template literals & string interpolation as a javascript method So I currently have a weatherAPI that will return an icon code that is a string and starts with a number 02d,01d,01n,04d, etc. Now, what I want to do is pull in a react svg component dynamically depending on what the icon code is. Let me explain how I am trying to do it and then you can see if there is a better way to handle this.
To make things simple, I am passing down the response from the API down to a dumb component. I then created a folder weatherIcons, which contains all my svg components:
src
|_components
  |_dashboard
  | |_DumbComponent.js
  |_weatherIcons
    |_02d.js
    |_01d.js
    |_01n.js
    |_index.js

In my DumbComponent.js I am requiring all my svg components through the index file located under weatherIcons folder like so: import * as Icon from '../common/svg/weatherIcons';
The index.js file inside of weatherIcons folder will serve up each component like:
export {default as 01d} from './01d';
export {default as 02d} from './02d';
export {default as 01n} from './01n';

This allows me then to call these files as methods inside my DumbComponent.js like: Icon.01d(). This will then return the svg component in src/components/weatherIcons/01d.js'. As you know though, this WON'T actually return that file, because a method cannot start with an integer and thus my dilemma. Nor can I give a name of01d,02d,01nlike I did in myweatherIcons/index.js` file.
My thought process was to give them a name spacing that starts with a character:
export {default as code01d} from './01d';
export {default as code02d} from './02d';
export {default as code01n} from './01n';

Then try and interpolate the code from the api response as a function. Icon.code${apiRESPONSE}(). Any ideas on how this can be done or any other work around for this current situation.
ps. I have looked into react-svg and other svg importers and prefer to not take the approach of importing the svg's as html and through a path.


text:
Q: I want to take run an executable and take input from a text file and then write the output in Windows cmd In ubuntu I would do it by following command
./a.out < input.txt | cat > ouput.txt

how can I do this in Windows cmd?

A: You can do it in two lines:
a.exe < input.txt >output.txt
type output.txt

A: This should work assuming that a.exe writes to STDOUT:
a.exe < C:\path\to\input.txt > C:\path\to\output.txt


text:
Q: Sending an image as an attachment I am creating a application where i want to send captured image as an attachment
to email body but not able to achieve above.Can anyone please guide me.
 emailsend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.i("Send email", "");
            String[] TO = {""};
            String[] CC = {""};
            Intent emailIntent = new Intent(Intent.ACTION_SEND);

            emailIntent.setData(Uri.parse("mailto:"));
            emailIntent.setType("application/image");
            emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
            emailIntent.putExtra(Intent.EXTRA_CC, CC);
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
            emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");
            emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));
            try {
                startActivity(Intent.createChooser(emailIntent, "Send mail..."));
                finish();
                Log.i("Finished sending", "");
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(clickimages.this, "There is no email client installed.", Toast.LENGTH_SHORT).show();
            }
        }
    });'

A: To add an image to an email you are trying to send you can do the following :
Uri uri = Uri.parse("file://" + filepath);
intent(Intent.EXTRA_STREAM, uri);

Where intent is the operation to send your mail and the path to your image is found in the filepath variable.


text:
Q: ruby on rails sunspot solr search show some specific results on top I'm using Sunspot Solr for indexing and searching in our Rails application
search = Product.search do
            with(:categoery, [1,2,3])
            order_by(:priority)
            #and some other filters
         end

But for some specific Users i want to display some product with id suppose [8,9] ordered on-top of search result and then other products(as i don't want to discard other results), is it possible in same search query?

A: Have a look at the Query Elevation Component :

The Query Elevation Component lets you configure the top results for a
  given query regardless of the normal Lucene scoring. This is sometimes
  called "sponsored search," "editorial boosting," or "best bets." This
  component matches the user query text to a configured map of top
  results.
The text can be any string or non-string IDs, as long as it's indexed.
  Although this component will work with any QueryParser, it makes the
  most sense to use with DisMax or eDisMax.
The Query Elevation Component is supported by distributed searching.


text:
Q: PyGithub, can't get repos from enterprise I am creating a bot with Spark (chat for enterprise), in Python, I use PyGitHub for the librairy.
So when I write "repos" in my room with the bot he has to send me back the list of my repos.
It works fine with my github personnal account but not with my professionnal account.
If you can explain me why ?
here my code:
def gitTest(self, details, message):
        url = "https://enter-prise.com"
        token = "abcd"
        github = Github(token, base_url=url)
        for repo in github.get_organization("org").get_repos():
            self.answer(details.roomId, markdown=repo.name)

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/mflamant/Documents/bot/CiscoSparkPython/testbotforgithub/main.py", line 44, in Main
    bot.isRunnable()
  File "/home/mflamant/Documents/bot/CiscoSparkPython/testbotforgithub/utils/Compute.py", line 47, in isRunnable
    self.spark(message[0], message[1])
  File "/home/mflamant/Documents/bot/CiscoSparkPython/testbotforgithub/testbotforgithub.py", line 33, in spark
    return self.answer(details.roomId, markdown=self.gitTest(details, message))
  File "/home/mflamant/Documents/bot/CiscoSparkPython/testbotforgithub/testbotforgithub.py", line 56, in gitTest
    for repo in github.get_organization(adt).get_repos():
  File "/usr/local/lib/python2.7/dist-packages/PyGithub-1.35-py2.7.egg/github/Organization.py", line 539, in get_repos
    self.url + "/repos",
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

Can you explain me what is wrong with my code ? thank you

A: If gitTest is an instance method, you need to assign to the attribute self.url, not just to the local variable url. So your method should probably look like this:
def gitTest(self, details, message):
    self.url = "https://enter-prise.com"
    self.token = "abcd"
    github = Github(token, base_url=url)
    for repo in github.get_organization("org").get_repos():
        self.answer(details.roomId, markdown=repo.name)

This is why you pass in the reference to self as the first argument of any instance method.


text:
Q: "[AppName] has stopped" in my physical device. ERROR in logcat: java.lang.NullPointerException I have been working on a game in android studio and libgdx and whenever I run it on my physical device it says "[AppName] has stopped".
I have checked for the names of the images that i used (spelling, capitalization), other than that I have no idea what the problem is.
This is the error that I received in logcat:
10-06 12:01:51.055 21591-21627/com.jpfalmazan.ninjaassault E/AndroidRuntime: FATAL EXCEPTION: GLThread 2891
                                                                             java.lang.NullPointerException
                                                                                at com.jpfalmazan.ninjaassault.GameScreens.MenuScreen.<init>(MenuScreen.java:23)
                                                                                at com.jpfalmazan.ninjaassault.NinjaAssault.create(NinjaAssault.java:19)
                                                                                at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:275)
                                                                                at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1505)
                                                                                at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)

Here is my code for the game:
package com.jpfalmazan.ninjaassault;

import com.badlogic.gdx.Game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.jpfalmazan.ninjaassault.GameScreens.MenuScreen;

public class NinjaAssault extends Game {
    public SpriteBatch batch;
    Texture img;

    @Override
    public void create () {
        batch = new SpriteBatch();
        this.setScreen(new MenuScreen(this));   ////This is the "NinjaAssault.java:19 " error shown in logcat
    }

    @Override
    public void render () {
        super.render();
        Gdx.gl.glClearColor(1,0,0,1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
    }

    @Override
    public void dispose () {
        batch.dispose();
        img.dispose();
    }
}

And here is my code in the MenuScreen class:
package com.jpfalmazan.ninjaassault.GameScreens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.jpfalmazan.ninjaassault.NinjaAssault;

public class MenuScreen implements Screen{
    NinjaAssault game;
    public MenuScreen (NinjaAssault game){
        this.game = game;
    }
    public SpriteBatch batch;
    public Texture background;
    public Texture title;
    public Texture playButtonINACTIVE;
    public Texture playButtonACTIVE;

    public float screenWidth = Gdx.graphics.getWidth();
    public float screenHeight = Gdx.graphics.getHeight();
    public float titleWidth = title.getWidth();  //This is the "MenuScreen.java:23" error shown in logcat
    public float titleHeight = title.getHeight();
    public float xLimit1 = (float) ((screenWidth/2)-(titleWidth/2));
    public float xLimit2 = (float) ((screenWidth/2)+(titleWidth/2));
    public float yLimit1 = (float) ((screenHeight*.35));
    public float yLimit2 = (float) ((screenHeight*.35)+titleHeight);

    @Override
    public void show() {
        batch = new SpriteBatch();
        background = new Texture("BGYELL.png");
        title = new Texture ("BGASTRO.png");
        playButtonINACTIVE = new Texture("BTPLAY.png");
        playButtonACTIVE = new Texture("BTPLAYON.png");

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1,0,0,1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        game.batch.begin();
        game.batch.draw(background,0,0,screenWidth,screenHeight);
        if((Gdx.input.getX()> xLimit1 && Gdx.input.getX() < xLimit2) && (Gdx.input.getY() < yLimit2 && Gdx.input.getY() > yLimit1 ) ){
            game.batch.draw(playButtonACTIVE,(screenWidth/2)-(playButtonACTIVE.getWidth()/2), (float) (screenHeight*.35));
        }else  game.batch.draw(playButtonINACTIVE,(screenWidth/2)-(playButtonINACTIVE.getWidth()/2), (float) (screenHeight*.35));
        game.batch.draw(title,(screenWidth/2)-((float)(screenWidth*.8)/2), (float) (screenHeight*.65),(float)(screenWidth*.8) , (float) ((screenWidth*.8)*(titleHeight/titleWidth)));

        game.batch.end();
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {

    }
}

A: You have not set "title" to anything yet. You have only declared it to exist.
title is set in show() which is called after the constructor.
You need to do
title = new Texture ("BGASTRO.png");

BEFORE you try to get the height of the texture. This goes for all other variables too, make sure they are set to something before using them.
Also, you should remove
 Gdx.gl.glClearColor(1,0,0,1);
 Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
 batch.begin();

from you render() in NinjaAssault class. It is unnecessary and if you call
batch.begin()

you need to call
batch.end()

too, but in this case its never used anyway so no need for it at all.


text:
Q: Voronoi approach to making districts while also using a multilinestring I have a spatial objects with multiple points (buildings) on a map. What I wanted to do is divide an area based on the nearest point. The calculated Voronoi looks quite promising, but has some strange aspects if you know the "real world". For example a small part of a district is also at the other side of a river because of the closeness (surprise).
What I want to do is combine this with a multi linestring which contains rivers, railroads. What I want to do either end the district at this line OR add a penalty for 'crossing' it. Is anyone able to shed light on the problem, or possible suggest an alternative voronoi method that works?


text:
Q: Pronunciation rule if two consecutive consonants followed by a vowel The person is pronouncing the number 80 in this sentence as /neiti/ for the number 184.
Is it a common rule to elide the last one if there are two consecutive consonants followed by a vowel just like this case one hundred "and eighty"?
Which pronunciation rule she is using?

A:
Is it a common rule to elide the last consonant if there are two consecutive ones followed by a vowel?

It's a good deal more complicated than that. As Peter Shor tells you, "It depends on the consonants"; it also depends on the surrounding vowels, on where the stress falls,and why, on where word and syllable boundaries fall, on local practice (dialect), and on individual practice (idiolect).
In your example, for instance, (at least) three principles are operating. (I'm illustrating with US pronunciations, but I don't think that British pronunciation in these instances would call for different arguments.)

*

*English doesn't much like 'closed' syllables—syllables which end on a consonant. In speech we prefer our syllables as 'open' as possible: the happiest ending is a vowel, next is a more vowel-like consonant (a continuant), next is a voiced stop, and last is a voiceless stop. Other things being equal, a consonant or consonant cluster at the end of a syllable tends to be reduced towards vowelness.
For instance, in speaking last man, the voiceless stop /t/ will tend to be dropped: /læs mæn/. In speaking canned peas, the voiced stop /d/ will tend to be dropped: /kæn piz/.

*However, if the following syllable begins with a vowel, the consonant or cluster can be 'tied' to it, leaving the preceding syllable 'open': last ever becomes /læ stɛvr/. But this only works to the extent that the tied consonant cluster is acceptable at the beginning of a syllable. /st/ is a common syllable onset, but English syllables never begin with /nd/; so in speaking canned okra the cluster is split, leaving /kæn doʊkrə/.

*That would lead you to expect and eighty to be pronounced as /æn deɪɾɪ/. But in practice, unstressed and is almost always reduced to mere /n/. In this instance that principle comes into play first, before the liaison takes place. Consequently, you end up with /neɪɾɪ/.


text:
Q: ¿Cómo regresar un valor de tipo string? Cómo le hago para que una función me regrese el valor de usuario porque si le dejo ToInt32 me regresa un número.
Si le Pongo ToStringme arroja el siguiente error:

El código de la función es el siguiente:
 Public Function Tecnico() As Integer
    Dim con As String
    con = "Data Source=GDJF04973;Initial Catalog=NovariantNPI;User ID=f5;Password=f5report"
    Dim cnn As New SqlConnection
    cnn.ConnectionString = con
    Dim query As New SqlCommand("select Usuario from Usuarios where Usuario = '" & My.Forms.Login.UsernameTextBox.Text & "'", cnn)
    cnn.Open()
    Return Convert.ToString(query.ExecuteNonQuery)
End Function

Espero me puedan ayudar.

A: Si lo que quieres es que tu función retorne un String entonces te falta cambiar el tipo de dato de retorno a String en la cabecera de tu función, de la siguiente manera:
Public Function Tecnico() As String

A: El ExecuteScalar sólo devuelve valores numéricos, por lo cual, para devolver un valor texto deberás crear un DataReader, por ejemplo, así:
Public Function Tecnico() As String
    Dim con As String
    con = "Data Source=GDJF04973;Initial Catalog=NovariantNPI;User ID=f5;Password=f5report"
    Dim cnn As New SqlConnection
    cnn.ConnectionString = con
    Dim query As New SqlCommand("select Usuario from Usuarios where Usuario = '" & My.Forms.Login.UsernameTextBox.Text & "'", cnn)
    cnn.Open()
    Dim Consulta As SqlDataReader
    Consulta = query.ExecuteReader()
    Dim res As String = Nothing
    If Consulta.Read() Then res = Consulta(0)
    Consulta.Close()
    cnn.Close()
    Return res
End Function

A: No estoy seguro, pero creo saber qué pasa.
Public Function Tecnico() As Integer

Eso devuelve un entero, debes colocarlo como:
Public Function Tecnico() As String

Cuando no le pones el toInt32, te regresa un número 1 o 0 dependiendo de si es true o false la conversión.


text:
Q: Is there such a thing as IMAP for podcasts? Is there such a thing as IMAP for podcasts?
I own a desktop, laptop, iPod, smartphone and a web-client all downloading StackOverflow Podcasts. (among others) They all tell me which episodes are available and which are already played. Everything is a horrible mess, ofcourse. My iPod is somewhat in sync with my desktop, but everything else is a random jungle.
The same problem with e-mail is solved by IMAP. Every device gets content and meta-information from one server, and stays in sync with it. Per device, I can set preferences (do or do not download the complete archive including junkmail).
Can we implement the IMAP approach for podcasts? Or is there a better metaphore/standard to solve this problem? How will the adoption-strategy look like?
(by the way: except for the Windows smartphone, I own a full Apple-stack of products. Even then, I run into this problem)
UPDATE The RSS-to-Imap link to sourceforge looks promesting, but very alpha/experimental.
UPDATE 2 The one thing RSS is missing is the command/method/parameter/attribute to delete/unread items. RSS can only add, not remove. If RSS(N+1) (3?) could add a value for unread="true|false", it would be solved. If I cache all my RSS-feeds on my own server, and add the attribute myself, I only would have to convince iTunes and every other client to respect that.

A: Podcasts are basically just RSS, so an IMAP solution doesn't totally make sense in this case.
You'd have to have your own podcast stack in order to achieve something like this.

A: I think there's an opportunity to miss the point by interpreting your question too literally, but....
RSS->IMAP Server might be a good fit (if you have the resources to host it)?  I wonder if it supports attachments/enclosures.

A: Have you considered Google Reader for listening to your podcasts?  If might be ideal if each device has a sufficient network available when it comes time to consume the podcast.

A: Since answering a question you didn't ask seems to be the norm around here, have you considered pop4?
pop4.org

A: Odeo used to do this before the creators of it went and started this little website called Twitter. That's how I used to manage podcasts. Whether it still does this, I do not know. I tend to keep my podcast subscriptions to one computer and an synced-up iPod.

A: Look into gpodder - I use it and find it excellent.


text:
Q: How to avoid UpdatePanel scrolling on AutoPostBack? I have an ASP.NET FormView within an updatepanel. I'm auto-saving the form by setting AutoPostBack=true for each of the items within the FormView.
This means the user can click a few elements in quick succession and fire off a few async postbacks almost simultaneously.
The issue I have is that the user is able to keep scrolling down the form while the async postbacks are not yet complete. The browser always scrolls back to the position it was in at the first postback.
Page.MaintainScrollPositionOnPostback is set to False.
I've tried all sorts of things in ajax and jquery with:

*

*pageLoad

*add_initializeRequest

*add_endRequest

*document.ready

*etc..

but I always only seem to be able to access the scroll Y as it was on the first postback.
Is there any way to retrieve the current scroll Y when the postback completes, so I can stop the scrolling occurring? Or perhaps is it possible to disable the scrolling behaviour?
Thanks!

Update
Thanks to @chprpipr, I was able to get this to work. Here's my abbreviated solution:
var FormScrollerProto = function () {
    var Me = this;
    this.lastScrollPos = 0;
    var myLogger;

    this.Setup = function (logger) {
        myLogger = logger;
        // Bind a function to the window
        $(window).bind("scroll", function () {
            // Record the scroll position
            Me.lastScrollPos = Me.GetScrollTop();
            myLogger.Log("last: " + Me.lastScrollPos);
        });
    }

    this.ScrollForm = function () {
        // Apply the last scroll position
        $(window).scrollTop(Me.lastScrollPos);
    }

    // Call this in pageRequestManager.EndRequest
    this.EndRequestHandler = function (args) {
        myLogger.Log(args.get_error());
        if (args.get_error() == undefined) {
            Me.ScrollForm();
        }
    }

    this.GetScrollTop = function () {
        return Me.FilterResults(
                window.pageYOffset ? window.pageYOffset : 0,
                document.documentElement ? document.documentElement.scrollTop : 0,
                document.body ? document.body.scrollTop : 0
            );
    }

    this.FilterResults = function (n_win, n_docel, n_body) {
        var n_result = n_win ? n_win : 0;
        if (n_docel && (!n_result || (n_result > n_docel)))
            n_result = n_docel;
        return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
    }
}

Main page:
...snip...

var logger;
    var FormScroller;

    // Hook up Application event handlers.
    var app = Sys.Application;

    // app.add_load(ApplicationLoad); - use pageLoad instead
    app.add_init(ApplicationInit);
    // app.add_disposing(ApplicationDisposing);
    // app.add_unload(ApplicationUnload);

    // Application event handlers for component developers.
    function ApplicationInit(sender) {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        if (!prm.get_isInAsyncPostBack()) {
            prm.add_initializeRequest(InitializeRequest);
            prm.add_beginRequest(BeginRequest);
            prm.add_pageLoading(PageLoading);
            prm.add_pageLoaded(PageLoaded);
            prm.add_endRequest(EndRequest);
        }

        // Set up components
        logger = new LoggerProto();
        logger.Init(true);
        logger.Log("APP:: Application init.");

        FormScroller = new FormScrollerProto();
    }

    function InitializeRequest(sender, args) {
        logger.Log("PRM:: Initializing async request.");
        FormScroller.Setup(logger);
    }

...snip...

function EndRequest(sender, args) {
        logger.Log("PRM:: End of async request.");

        maintainScroll(sender, args);

        // Display any errors
        processErrors(args);
    }

...snip...

function maintainScroll(sender, args) {
        logger.Log("maintain: " + winScrollTop);
        FormScroller.EndRequestHandler(args);
    }

I also tried calling the EndRequestHandler (had to remove the args.error check) to see if it reduced flicker when scrolling but it doesn't. It's worth noting that the perfect solution would be to stop the browser trying to scroll at all - right now there is a momentary jitter which would not be acceptable in apps with a large user base.
(The scroll top code is not mine - found it on the web.)
(Here's a helpful MSDN page for the clientside lifecycle: http://msdn.microsoft.com/en-us/library/bb386417.aspx)

Update 7 March:
I just found an extremely simple way to do this:
<script type="text/javascript">

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_beginRequest(beginRequest);

function beginRequest()
{
    prm._scrollPosition = null;
}

</script>

A: You could bind a function that logs the current scroll position and then reapplies it after each endRequest.  It might go something like this:
// Wrap everything up for tidiness' sake
var FormHandlerProto = function() {
    var Me = this;

    this.lastScrollPos = 0;

    this.SetupForm = function() {
        // Bind a function to the form's scroll container
        $("#ContainerId").bind("scroll", function() {
            // Record the scroll position
            Me.lastScrollPos = $(this).scrollTop();
        });
    }

    this.ScrollForm = function() {
        // Apply the last scroll position
        $("#ContainerId").scrollTop(Me.lastScrollPos);
    }

    this.EndRequestHandler = function(sender, args) {
        if (args.get_error() != undefined)
            Me.ScrollForm();
        }
    }
}

var FormHandler = new FormHandlerProto();
FormHandler.Setup(); // This assumes your scroll container doesn't get updated on postback.  If it does, you'll want to call it in the EndRequestHandler.

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(FormHandler.EndRequestHandler);

A: Simply put the Timer control within the content template.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="5000" OnTick="Timer1_Tick">
</asp:Timer>
<asp:ImageButton ID="ImageButton1" runat="server" Height="350" Width="700" />
</ContentTemplate>
</asp:UpdatePanel>


text:
Q: Extracting data from a pandas dataframe on string matching I have two dataframes. One consists of a series of processed excerpts (split, stopwords and punctuation removed) and the other consists of a corpus of words and a corresponding 'frequency' score.
I am trying to obtain an 'average frequency score' for each excerpt in my dataframe.  To do this I want a function or loop that takes each word in each excerpt of my dataframe and match it to the frequency score given in the corpus dataframe, and then sums and finds the average of these scores. I am having trouble doing this. My code so far:
def average_frequency_score(text):
    for word in text:
        text_freq = []
        if word == word_freq_df[word_freq_df['words'][i]]:
            freq = word_freq_df['frequency'][i]
            text_freq.append(freq)
        else:
            freq = 9.0
            text_freq.append(freq)

df['frequencies'] = df['fully_processed'].apply(average_frequency_score)

excerpt =['roger','predicted','snow','departed','quickly','came','two','days','sleigh','ride','scarcely','vestige','white','ground','tennis','possible','great', 'game','progress','court','pine', 'laurel','patty', 'roger', 'playing', 'elise']

word_freq_df[1:5]

   words    frequency
1   home    20.9677
2   us      20.9296
3   page    20.8022
4   search  20.7471

I would then apply another function to obtain the average.  Above I am trying to use the index [i] in the word_freq_df to identify the correct frequency but the error is saying that i is not defined.  Can anyone help me with this?!


text:
Q: Extract upper triangular matrix from the result of "magma_dgeqrf2_gpu" (which is a general matrix) without transferring to host I'm building a kernel which among other things uses the Magma function magma_dgeqrf2_gpu to perform a QR factorization. This outputs the upper triangular matrix R into a general matrix d_A on the GPU device.
Without transferring d_A back to host (since I need the GPU for further operations), is there a lib way to just reduce or extract the d_A into an upper triangular matrix R on the device?

A: It's a bit silly but I found the solution was simply to use magmablas_dlacopy() and set the attributes to copy the upper triangular matrix to another matrix (which has been set to 0) on the device.


text:
Q: Cannot access the file '....docx' because it is being used by another process. When accessing the MS Word Doc Saved through VSTO Add-In I've written a VSTO-Add In for MS Word which saves the document on cloud instead of saving it locally.
To achieve this I'm doing as follows:

*

*When user is saving MS Word Document (Ctrl + S), I'm saving it to a temporary location

*From the saved location (D:\Temp\xxx-yyy-zzz.docx) I'm uploading the document on server.

I'm getting below error:
The process cannot access the file 'D:\Temp\xxx-yyy-zzz.docx' because it is being used by another process.
when trying to access the file to upload on server.
Following is the code I'm using it:
Microsoft.Office.Interop.Word.Application wdApp = Globals.ThisAddIn.Application;
Microsoft.Office.Interop.Word.Document wdDoc = wdApp.ActiveDocument;
object saveFileName = "D:\Temp\xxx-yyy-zzz.docx";
object fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault;
object missing = System.Reflection.Missing.Value;

wdDoc.SaveAs2(FileName: ref saveFileName, FileFormat: ref fileFormat);

When trying to read the saved file. 'Can not access .......being used by another process' Exception is thrown. Below is the code
byte[] byteArray = File.ReadAllBytes("D:\Temp\xxx-yyy-zzz.docx");

Any help on this is highly appreciated.


text:
Q: Can't execute any basic command in linux console I know how the problem was created, but really have no idea how to restore the server command execution.
The thing is, I was configuring the environment variables of Glassfish in my Ubuntu server, and I modified the .bashrc file from root and added an export clause (with GLASSFISH_HOME variable) and a PATH clause (pointing to the $GLASSFISH_HOME/bin).
Right after I close the console and open it again so the changes take effect, and (BAM!) once I start the new console session then none of the basic commands (dir, find, nano, ifconfig, anything) work now, I can only use cd to move in directories, I am trying to edit again the .bashrc file to undo the changes but can't edit it either, none of the editors open! In the command line I only get -bash: dir: command not found.
Please, if you have any solution for this; I know it seems trivial, but I'm kind of blind without being able to see or find the files and folders where commands/applications are located.

A: You've overwritten your $PATH, rather than appending to it, you probably have something like this in your .bashrc:
export PATH=$GLASSFISH_HOME/bin

or similar, but you need to append the current $PATH to the end of it:
export PATH=$GLASSFISH_HOME/bin:$PATH

To edit this in the terminal, you will have to append /usr/bin to your editor (e.g. /usr/bin/vim ~/.bashrc) until you correct the problem.
You may wish to read more about the $PATH variable.

A: Do an export of the binary paths:
export PATH=$PATH:/bin:/usr/bin

right after that you're able again to operate and to reverse your changes.
Otherwise just do an edit with your favorite editor while given the full path to your editors binary:
/usr/bin/emacs -nw /root/.bashrc

A: Probably you erased your path when you were changing the environment variables; this will prevent most commands from being found.
Fortunately, you can work around this by using the full path name when specifying the command.
vim doesn't work?  Use /usr/bin/vim
ls doesn't work?  Use /usr/bin/ls
Most command you want to use will be in /usr/bin; if not found there you can check /bin or /usr/sbin
With access to the editor you should be able to fix the startup script to get your path back.


text:
Q: Storing binary file versions My application stores large binary files (100Mb - 1Gb) that change over time on s3. I want to offer the ability to roll back or download previous versions of these files without having to store snapshot copies.
What would be the best way to achieve this?

A: Since Nexus is able to work with s3 repositories (see ticket NEXUS-1121), I would advise you to record those different versions in an artifact repo like Nexus, and not in a VCS (Version Control System tool like SVN, or even worse, distributed ones like Git or Mercurial).
A VCS has features (branching, merging, diff) that large binaries won't take advantage of.


text:
Q: How to read extra-ASCII characters in R? I am reading input text file line by line with the following function:
lines_reader<-function(filename){
    conn<-file(filename,open="r")
    linn<-readLines(conn,encoding="UCS-2LE")
    close(conn)
    return(linn)
}

If I try to plot these lines in the R enviroment, letters with accent marks are treated not adequately appearing like "Ã" or  "è" instead of "à" or "è".
How to cope with this? What encoding I should choose?
Here they are my session and local system info:
> sessionInfo()
R version 3.2.0 (2015-04-16)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 8 x64 (build 9200)

locale:
[1] LC_COLLATE=Italian_Italy.1252  LC_CTYPE=Italian_Italy.1252
[3] LC_MONETARY=Italian_Italy.1252 LC_NUMERIC=C
[5] LC_TIME=Italian_Italy.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] tools_3.2.0

> Sys.getlocale()
[1] "LC_COLLATE=Italian_Italy.1252;LC_CTYPE=Italian_Italy.1252;LC_MONETARY=Italian_Italy.1252;LC_NUMERIC=C;LC_TIME=Italian_Italy.1252"

A: How about changing the encoding that you are using:
lines_reader<-function(filename){
    conn<-file(filename,open="r")
    linn<-readLines(conn,encoding="UTF-8")
    close(conn)
    return(linn)
}


text:
Q: EFCore Migrations; what is the role of HasData( ... ) in the ContextModelSnapshot? I had in mind that when a migration is run, the database data is updated, a snapshot is taken and we thus end up with a synced system:

*

*database data looks like X

*ContextModelSnapshot looks like X

Later I can either update the data in the database, or I can update the data in the snapshot and then, depending on what I did, I can tell EFCore migrator to either:

*

*update the database (if i edited the snapshot) and generate a sql/fluent style update of the database DB so that the db will be back in sync with the snapshot => using the db table as "what was" and the snapshot as "what shall be"

*update the snapshot (if I updated the db) and again generate some sql/fluent style updates to sync the two, but this time using the snapshot as the reference of "what was" and the db as reference of "what shall be

In either case a migration can be created, and I'm just telling EF which is the authority on what the data should be
Fast forward to creating my migration; I'd actually advanced one db relative to another db, and the snapshot wasn't synced with either thanks to another migration that had been applied elsewhere but I wasn't privy to. So I instead wrote an SQL that would generate snapshotty looking code (concat strings together to create c# code) from the "what was" db, and dropped my manually created code into the snapshot, then asked EF to migrate (with the "what shall be" DB configured in the app settings)
It generated some of what I expected; some update queries.. But mostly it generated inserts for data that already existed so now I get PK violations. I thus guess I'm completely wrong about how the migrator works internally. If I was in a situation where the only frames of reference for how I wanted my DB migration to go, were two DBs (one production, one my dev) how would I go about creating a migration if ef core was out of sync with both?


text:
Q: Can I printf g++'s architechture I'd like to do something similar to this in g++:
printf("Architecture: %s", M_ARCH);

but I don't know how or if it's even possible?

A: No, there doesn't appear to be anything that easy.
Specific architectures are defined such as __amd64__ and __i386__, but you would have to write your own macro to check #ifdef __amd64__ etc to define your own M_ARCH.
(You can check all of the existing preprocessor definitions by using gcc -dM -E foo.c > defines.)


text:
Q: How to improve memory usage and performance of apache poi? I am trying to write 200,000 rows in Excel with around 300 columns each, using apache-poi for Java.
Have done couple of things like:
SXSSFWorkbook workBook = new SXSSFWorkbook(1000);
workBook.setCompressTempFiles(true);

//...populated rows

sheet.autoSizeColumn(colNum);  //in the end.

The program is taking more than 1 hour to write 200,000 * 300 data.
How can I improve the performance without drastically increasing memory usage?


text:
Q: Xamarin Plugin.BLE // I can't pull data There is a device that measures tire tread depth and air pressure.
I made a connection but I can't pull data. Can you direct me on how to do it?
I pulled data using Android DLLs but failed with plugin.ble.
Note: The state in the device object disconnect after a certain time. I do not know the reason.
Source code I wrote
Part-1
bluetoothBLE = CrossBluetoothLE.Current;
adapter = CrossBluetoothLE.Current.Adapter;
list = new ObservableCollection();
DevicesList.ItemsSource = list;

Part-2
adapter.ScanTimeout = 10000;
adapter.ScanMode = ScanMode.Balanced;
adapter.DeviceDiscovered += (obj, a) =>
{
if (!list.Contains(a.Device))
list.Add(a.Device);
};
await adapter.StartScanningForDevicesAsync();

Part-3
device = DevicesList.SelectedItem as IDevice;
await adapter.StopScanningForDevicesAsync();
var connectParams = new ConnectParameters(true, true);
await adapter.ConnectToDeviceAsync(device, connectParams);

Part-4
var xservices = await device.GetServicesAsync();
var xservice = await device.GetServiceAsync(xservices[0].Id);
var Characteristic = await xservice.GetCharacteristicsAsync();
var xxxcharacteristicread = await xservice.GetCharacteristicAsync(xitem.Id);
var c = await xxxcharacteristicread.ReadAsync();

Version of the Plugin: 2.1.1
Platform: iOS 10.1 / Android 7.0
Device: samsung note 5 /i Phone 7


text:
Q: Correct signature of / detect presence of Container::reserve() Given a type C which is an STL-conforming container, how do I correctly detect if C contains a member function reserve? I tried the following approach (with GCC 4.6.3):
template< typename C, typename = void >
struct has_reserve
  : std::false_type
{};

template< typename C >
struct has_reserve< C, typename std::enable_if<
                         std::is_same<
                           decltype( &C::reserve ),
                           void (C::*)( typename C::size_type )
                         >::value
                       >::type >
  : std::true_type
{};

This works for C being std::vector, but not for the unordered containers, e.g. std::unordered_set. The reason is, that reserve is a (direct) member function of std::vector, but for the unordered containers it is inherited from a base class, i.e., its signature is not void (C::*)( typename C::size_type ) but void (B::*)( typename C::size_type ) for some unspecified base class B of C.
I know how to work around it and detect reserve even if inherited, but it looks clumsy and I wonder what is allowed by the standard. So...
My question is: Does the standard allow reserve to be inherited from an unspecified base class or is the synopsis binding and requires a direct member function?

A: All the standard says about inheritance from base classes is that it is allowed:

17.6.5.11 Derived classes [derivation]
1 - An implementation may derive any class in the C++ standard library from a class with a name reserved to the implementation.

It doesn't say either way whether methods (and, indeed, other members such as typedefs) are allowed to be inherited from a base class; obviously, since implementations do so, the standard should describe this behaviour.
In any case, detecting e.g. reserve by cast to a member function type is not guaranteed to work even if a member of the most derived type, since:

17.6.5.5 Member functions [member.functions]
2 - An implementation may declare additional non-virtual member function signatures within a class:

*

*by adding arguments with default values to a member function signature186; [...]

  186) Hence, the address of a member function of a class in the C++ standard library has an unspecified type.

The correct way to check whether reserve exists is to attempt to call it:
template< typename C, typename = void >
struct has_reserve
  : std::false_type
{};

template< typename C >
struct has_reserve< C, typename std::enable_if<
                         std::is_same<
                           decltype( std::declval<C>().reserve( std::declval<typename C::size_type>() ) ),
                           void
                         >::value
                       >::type >
  : std::true_type
{};

This has the advantage of paralleling the container requirements (table 103 for unordered_set), which are normative where the synopses tend more to the informative.