text:
Q: Help with volume of solids of revolution I have a region $R$ defined by $y=x^2$, $y=2+x$ and $x=0$.
How would be the integrals (no need to develop them) of the solid obtained by the revolution of $R$:
$a)$ around $x$-axis integrating in relation to $1)$ $x$ and $2)$ $y$?
$b)$ around $y$-axis integrating in relation to $1)$ $x$ and $2)$ $y$?
I just started studying calculus by myself and I would like to check some answers.
In the item a.1 I found $\int_0^2\pi|x^4-(1+x)^2| dx$. Is that correct? How would be the others?

A: No, that is not correct.
The correct formula is $V = \pi \int_a^b [f(x)]^2 \ dx$. The limits of integration are $x = 0, 2$ as you have said, but $f(x) = \text{top - bottom} = (2+x) - x^2$.


text:
Q: How to remove an item in a two dimensional array with a list box Hi I have an assignment for coding and I am having a hard time to figure out how to code it. My teacher wanted us to build a program that uses a list box that holds product names and a 2-D array that holds quantity in stock and price. Then in the one of the buttons in the application, which is the remove button, the item in the list box as well as the data from the array should be removed. When the user deletes an item, not only must the list loose the name of the item but the 2-D array must also be readjusted.

A: I am sorry. My brain just doesn't want to do what your teacher wants. If you can make sense of the following, maybe you can convince your teacher not to ask you to use 2D arrays in this instance.
Public Class Product
    'These are automatic properties
    'The compiler provides the getter, setter and backer fields.
    Public Property Name As String
    Public Property Quantiy As Integer
    Public Property Price As Double
    'ToString is a method inherited from Object. It will return a fully
    'qualified name of the Type, not what we want in a ListBox
    'The ListBox will call .ToString on Product and we will get the Name
    'property of the Product object.
    Public Overrides Function ToString() As String
        Return Name
    End Function

    Public Sub New(prodName As String, prodQuantity As Integer, prodPrice As Double)
        'We add a parameterized Constructor to make it easy to add our Product objects
        'to the ListBox. Intelisense will help out once we type the New keyword
        Name = prodName
        Quantiy = prodQuantity
        Price = prodPrice
    End Sub

End Class

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'The New keyword calls the Constructor of the Product class
        'so a Product object is added to the ListBox
        ListBox1.Items.Add(New Product("Bell", 30, 2.98))
        ListBox1.Items.Add(New Product("Book", 7, 200))
        ListBox1.Items.Add(New Product("Candle", 42, 14.99))
    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
        'When a Product is deleted from the ListBoX with the RemoveItem button
        'this event will fire. (The index changed) -1 means nothing is selected which is
        'what happens after the delete. If Nothing is selected our cast will fail and
        'we will get an exception.
        If ListBox1.SelectedIndex <> -1 Then
            'The ListBox items are objects but underneath the objects are Products
            'so we can Cast the object back to a Product
            Dim p As Product = CType(ListBox1.SelectedItem, Product)
            'All the properties of the Procuct are then available
            MessageBox.Show($"Product Name is {p.Name}. There are {p.Quantiy} on hand. The price is {p.Price:N2}")
        End If
    End Sub

    Private Sub btnRemoveItem_Click(sender As Object, e As EventArgs) Handles btnRemoveItem.Click
        ListBox1.Items.Remove(ListBox1.SelectedItem)
    End Sub

End Class

A: This should work, though it's really the wrong way to approach this:
LBProducts = Form ListBox
lblQuantity = Form Label
lblPrice = Form Label
btnDelete = Form Button
Public Class Form1
'5 Rows, (Price, Qty)
Private ProductArray(5, 1) As Integer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    LBProducts.Items.Add("Apples")
    LBProducts.Items.Add("Bananas")
    LBProducts.Items.Add("Grapes")
    LBProducts.Items.Add("Oranges")
    LBProducts.Items.Add("Peaches")

    For x = 0 To 5
        ProductArray(x, 0) = x
        ProductArray(x, 1) = 1
    Next
End Sub

Private Sub LBProducts_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LBProducts.SelectedIndexChanged
    Dim Index = LBProducts.SelectedIndex()

    If Index >= 0 Then
        lblPrice.Text = "Price: " & ProductArray(Index, 0)
        lblQuantity.Text = "Qty: " & ProductArray(Index, 1)
    End If

End Sub

Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
    Dim Index = LBProducts.SelectedIndex()
    If Index >= 0 Then
        LBProducts.Items.RemoveAt(Index)

        Dim NewArray(UBound(ProductArray) - 1, 1) As Integer

        Dim i As Integer = 0
        For x = 0 To UBound(ProductArray)
            If x <> Index Then
                NewArray(i, 0) = ProductArray(x, 0)
                NewArray(i, 1) = ProductArray(x, 1)
                i += 1
            End If
        Next

        ProductArray = NewArray

    End If
End Sub
End Class

redpajama_set_name: RedPajamaStackExchange


text:
Q: Could not get a resource from the pool JedisConnectionException Hi All I am trying to set up redis server using java.
My Redis server is linux server with ulimit unlimited.
Here is my spring bean which creates connection
public class JedisService implements IJedisService, InitializingBean, DisposableBean{
    private JedisPool jedisPool;
public JedisService() {

}

public JedisPool getJedisPool() {
    return jedisPool;
}

@Override
public void destroy() throws Exception {
    if(jedisPool != null){
        jedisPool.destroy();
    }

}

@Override
public void afterPropertiesSet() throws Exception {
    JedisPoolConfig poolConfig = new JedisPoolConfig();
    poolConfig.setMaxActive(1000);
    poolConfig.setMaxIdle(10);
    poolConfig.setMinIdle(1);
    poolConfig.setMaxWait(30000);
    poolConfig.setNumTestsPerEvictionRun(10);
    poolConfig.setTestOnBorrow(true);
    poolConfig.setTestOnReturn(true);
    poolConfig.setTestWhileIdle(true);
    poolConfig.setTimeBetweenEvictionRunsMillis(30000);

    jedisPool = new JedisPool(poolConfig,Config.REDIS_HOST,
            RestrictionUtils.REDIS_PORT,RestrictionUtils.REDIS_CONNECTION_TIMEOUT);

}

public boolean validateHitsCount(String hostKey,String urlKey,int hostHitsCount, int urlHitsCount, long timeKey,Map<String, Object> overLimit){
    int retryCount = 0;
    return recursiveRedisConnection(retryCount,hostKey,urlKey,hostHitsCount,urlHitsCount,timeKey,overLimit);
}

private boolean recursiveRedisConnection(int retryCount,String hostKey,String urlKey,int hostHitsCount, int urlHitsCount, long timeKey,Map<String, Object> overLimit){
    Jedis jedis = null;
    boolean returnObj = true;
    try {
        //Connection
        jedis = getJedisPool().getResource();
        jedis.connect();

        //Delete previous keys
        try {
            deletePreviouskeys(jedis, urlKey, hostKey, timeKey);
        } catch (Exception e) {
        }

        //Validation
        String value = jedis.get(hostKey+timeKey);
        if(value != null){
            try {
                int count = Integer.parseInt(value);
                System.out.println("HostCount: "+hostKey+ "    "+count);
                if(count < hostHitsCount){
                    jedis.incr(hostKey+timeKey);
                    returnObj = validateURLHits(jedis, urlKey, urlHitsCount, timeKey, overLimit);
                }else{
                    returnObj = false;
                    overLimit.put("Data", "You have reached maximum limit for hits---"+hostKey);
                }
            } catch (Exception e) {
            }

        }else{
            value = 1+"";
            jedis.set(hostKey+timeKey, value);
            jedis.expire(hostKey+timeKey, 60);
            returnObj = validateURLHits(jedis, urlKey, urlHitsCount, timeKey, overLimit);
        }

    } catch (Exception e) {
        retryCount ++;
        if(retryCount < 3){
            recursiveRedisConnection(retryCount,hostKey,urlKey,hostHitsCount,urlHitsCount,timeKey,overLimit);
        }else{
            e.printStackTrace();
            returnObj = false;
        }
    }finally{
        if(jedis != null && jedis.isConnected()){
            getJedisPool().returnResource(jedis);
        }
    }
    return returnObj;
}

private boolean validateURLHits(Jedis jedis,String urlKey, int urlHitsCount, long timeKey,Map<String, Object> overLimit){
    boolean returnObj = true;
    String value = jedis.get(urlKey+timeKey);
    if(value != null){
        try {
            int count = Integer.parseInt(value);
            System.out.println("URLCount: "+urlKey+ "    "+count);
            if(count < urlHitsCount){
                jedis.incr(urlKey+timeKey);
            }else{
                returnObj = false;
                overLimit.put("Data", "Reached maximum limit of hits for this URL");
            }
        }catch(Exception e){
        }
    }else{
        jedis.set(urlKey+timeKey, 1+"");
        jedis.expire(urlKey+timeKey, 60);
    }
    return returnObj;
}

private void deletePreviouskeys(Jedis jedis,String urlKey, String hostKey, long timeKey){
    /*Set<String> keys = jedis.keys("*");
    for(String key :  keys){
        if(!key.equalsIgnoreCase(urlKey+timeKey)){
            if(!key.equalsIgnoreCase(hostKey+timeKey)){
                jedis.del(key);
            }
        }

    }*/
}

}
The method validateURLHits is called in controller.
But when i Run this code in multiple threads i get this error
redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
    at redis.clients.util.Pool.getResource(Pool.java:22)
    at com.til.ibeat.service.JedisService.recursiveRedisConnection(JedisService.java:60)
    at com.til.ibeat.service.JedisService.recursiveRedisConnection(JedisService.java:95)
    at com.til.ibeat.service.JedisService.recursiveRedisConnection(JedisService.java:95)
    at com.til.ibeat.service.JedisService.validateHitsCount(JedisService.java:52)
    at com.til.ibeat.controller.MashupController.handleRequest(MashupController.java:66)
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:763)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:709)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:613)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:525)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.util.NoSuchElementException: Could not create a validated object, cause: ValidateObject failed

A: Did you check that your JedisPool is instanciated only once and not more?
As your Spring bean is accessed through many threads and Jedis is not thread-safe, it is possible that you can have more than one JedisPool that returns strange Jedis instances, or jedis instances used by different threads simutanously. Each thread can have a local copy of this JedisPool and/or Jedis instances and then gets errors from that.
You have two options: you can declare JedisPool as static final (only one value per classloader) or use a double-check locking (with volatile) to ensure there is only one JedisPool accessed by all the threads without local copy, according to that each Jedis used by a thread will not be accessed by another thread.


text:
Q: How do these three ways of creating vectors differ? While working on a submission, I found behaviour that I don't understand. I have three ways of populating my matrix from the input. One of them works, one of them compiles and runs but produces a slightly wrong result, and one of them crashes with a free(): invalid pointer.
For simplicity, I leave the part about a wrong result out of this question and reduce the code to just reading input. Let's ignore the output for a moment and just consider the error messages for two test cases:
root@41d06f89ab19:/code# gp so1.cpp && ./so1.exe <evenmat/test1.in > so1.txt
root@41d06f89ab19:/code# gp so2.cpp && ./so2.exe <evenmat/test1.in > so2.txt
Segmentation fault (core dumped)
root@41d06f89ab19:/code# gp so3.cpp && ./so3.exe <evenmat/test1.in > so3.txt

root@41d06f89ab19:/code# gp so1.cpp && ./so1.exe <evenmat/test2.in > so1_2.txt
free(): invalid pointer
Aborted (core dumped)
root@41d06f89ab19:/code# gp so2.cpp && ./so2.exe <evenmat/test2.in > so2_2.txt
Segmentation fault (core dumped)
root@41d06f89ab19:/code# gp so3.cpp && ./so3.exe <evenmat/test2.in > so3_2.txt

Clearly, the behaviour of the three code snippets is not equivalent.
Consider the three files below. How do their semantics differ? Why are they not all equivalent?
// File so1.cpp -
#include <iostream>
#include <vector>
#include <iterator>
#include <iomanip>
#include <cassert>
#include <algorithm>
#include <functional>
typedef std::vector<std::vector<int>> VVI;
typedef unsigned int uint;
int main () {
    std::ios_base::sync_with_stdio(false);

    int t; std::cin >> t;

    for (int testcase = 0; testcase < t; testcase ++){
        // num matrix rows
        unsigned int n; std::cin >> n;

        // populate matrix
        VVI matrix; matrix.reserve(n);
        //VVI matrix(n, std::vector<int>(n));
        for(unsigned int row=0; row<n; row++){
            for(unsigned int col=0; col<n; col++){
                if(col==0){
                    // initialize row vector
                    //std::vector<int> myvec (n);
                    //matrix[row] = myvec;
                    matrix[row] = std::vector<int>(n);      // free(): invalid pointer happens here
                }
                int el; std::cin >> el;
                matrix[row][col]=el;
            }
        }

        for (unsigned int i = 0; i < n; i++){
            for (unsigned int j = 0; j < n; j++){
                std::cout << matrix[i][j] << ' ';
            }
            std::cout << '\n';
        }
        std::cout << "\ntestcase " << testcase << ':' << std::endl;
    }
}

// file so2.cpp
#include <iostream>
#include <vector>
#include <iterator>
#include <iomanip>
#include <cassert>
#include <algorithm>
#include <functional>
typedef std::vector<std::vector<int>> VVI;
typedef unsigned int uint;
int main () {
    std::ios_base::sync_with_stdio(false);

    int t; std::cin >> t;

    for (int testcase = 0; testcase < t; testcase ++){
        // num matrix rows
        unsigned int n; std::cin >> n;

        // populate matrix
        VVI matrix; matrix.reserve(n);
        //VVI matrix(n, std::vector<int>(n));
        for(unsigned int row=0; row<n; row++){
            for(unsigned int col=0; col<n; col++){
                if(col==0){
                    // initialize row vector
                    std::vector<int> myvec (n);
                    matrix[row] = myvec;        // segfault on this line
                    //matrix[row] = std::vector<int>(n);
                }
                int el; std::cin >> el;
                matrix[row][col]=el;
            }
        }
    }
}

// file so3.cpp
#include <iostream>
#include <vector>
#include <iterator>
#include <iomanip>
#include <cassert>
#include <algorithm>
#include <functional>
typedef std::vector<std::vector<int>> VVI;
typedef unsigned int uint;
int main () {
    std::ios_base::sync_with_stdio(false);

    int t; std::cin >> t;

    for (int testcase = 0; testcase < t; testcase ++){
        // num matrix rows
        unsigned int n; std::cin >> n;

        // populate matrix
        //VVI matrix; matrix.reserve(n);
        VVI matrix(n, std::vector<int>(n));
        for(unsigned int row=0; row<n; row++){
            for(unsigned int col=0; col<n; col++){
                /*if(col==0){
                    // initialize row vector
                    //std::vector<int> myvec (n);
                    //matrix[row] = myvec;
                    matrix[row] = std::vector<int>(n);
                }*/
                int el; std::cin >> el;
                matrix[row][col]=el;
            }
        }

        for (unsigned int i = 0; i < n; i++){
            for (unsigned int j = 0; j < n; j++){
                std::cout << matrix[i][j] << ' ';
            }
            std::cout << '\n';
        }
        std::cout << "\ntestcase " << testcase << ':' << std::endl;
    }
}

I'm hoping this is an easy question for c++ experts out there. Because if it is not, I'm really not sure how well I can minimalize the test cases.
The lines where free(): invalid pointer and the segfault happen are indicated in the code snippets. Perhaps of note is that the stack in visual studio code shows that for so1.cpp the free(): invalid pointer with the second test input file happens within the following part of stl_vector.h:
#if __cplusplus >= 201103L
      /**
       *  @brief  %Vector move assignment operator.
       *  @param  __x  A %vector of identical element and allocator types.
       *
       *  The contents of @a __x are moved into this %vector (without copying,
       *  if the allocators permit it).
       *  Afterwards @a __x is a valid, but unspecified %vector.
       *
       *  Whether the allocator is moved depends on the allocator traits.
       */
      vector&
      operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
      {
    constexpr bool __move_storage =
      _Alloc_traits::_S_propagate_on_move_assign()
      || _Alloc_traits::_S_always_equal();
    _M_move_assign(std::move(__x), __bool_constant<__move_storage>());
    return *this;
      }

For reproducibility:

*

*test1.in

*test2.in

A: The problem is not how you create the row the problem is that with matrix[row] you acces an element that does not exist.
Here
    // populate matrix
    VVI matrix; matrix.reserve(n);

You are not populating the matrix. reserve merely allocates space for elements. It does not add elements or change the vectors size. matrix has zero element and that does not change throughout your first code. Accesing the vector out-of-bounds in undefined behavior.
If you want to have matrix with n rows you need to initialize it with n elements:
VVI matrix{n};

or
VVI matrix;
matrix.resize(n);

Or... In your second code you correctly initialize the matrix with n elements that are std::vector<int>s of size n:
VVI matrix(n, std::vector<int>(n));


text:
Q: Moveable EditText hiding issue when open keyboard in Android According to my need i have implemented move-able EditText on over the screen but getting problem is that when EditText move to bottom and open keyboard, then EditText getting hide and does'nt show. how can i resolved this.
   editText.setOnTouchListener(ImageStickerActivity.this);
 float newDx;
float newDy;
int latAPerformedAction;
@Override
public boolean onTouch(View view, MotionEvent event) {
    editText.setCursorVisible(true);
    switch (event.getActionMasked()) {
        case MotionEvent.ACTION_DOWN:
            newDy = view.getY() - event.getRawY();
            latAPerformedAction = MotionEvent.ACTION_DOWN;
            isMoving = false;
            break;

        case MotionEvent.ACTION_MOVE:
            float newY = event.getRawY() + newDy;

            if (newY <= 0 || newY >= screenHight - view.getHeight()) {
                latAPerformedAction = MotionEvent.ACTION_MOVE;

                break;
            }
            isMoving = true;
            view.setY(newY);
            latAPerformedAction = MotionEvent.ACTION_MOVE;
            break;

        case MotionEvent.ACTION_UP:
            if (latAPerformedAction == MotionEvent.ACTION_DOWN)
                isMoving = false;
            break;

        default:
            isMoving = false;
            return false;
    }
    return false;

}

A: I don't know if this works with your custom EditText implementation, but you can try and set the following attribute in your AndroidManifest
<activity android:windowSoftInputMode="adjustResize"> ... </activity>

If that doesn't work, you could alternatively add an event listener to see when the viewport changes. This is a common method to retrieve events when the keyboard gets shown or hidden. Then you move your EditText up or down as much pixels as the viewport changes. This way, the EditText is always above the keyboard.
Here is some sample code you can try for your viewport listener:
rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    public void onGlobalLayout(){
        int viewportHeightDiff = rootLayout.getRootView().getHeight() - rootLayout.getHeight();
        // TODO: Move your editText by viewportHeightDiff, this is how much difference
        // there is between the viewport height and the screen height
    }
});


text:
Q: Membership custom message I searched a lot in this site and in google but unfortunately I wasn't lucky to find the answer. I have a digital downloads marketplace via Woocommerce and membership. I sell those products as a single product downloadable or via membership. I managed to add a custom message when a user has bought my single product, but I can't find how I can add one custom message ONLY for my membership users. Example to be a small text under 'Purchase/Download' button which says: Download for $0 this item. But I need this custom message to be available only for active membership users. Is this possible? Can someone post a code so I can add in functions.php ?
all the best,
Fidan


text:
Q: Where's the option to go directly to inbox on startup in outlook 2007? Where's the option to go directly to inbox on startup in outlook 2007?

A: *

*Select Options from the Tools menu.

*In the Options window click the Other tab.

*Under General, click the Advanced Options button.

*In the Advanced Options window, under General Settings, next to Startup in this folder: click the Browse button.

*Scroll down and click on the plus sign to the left. This will reveal all your folders.

*Click on the INBOX folder and click OK.

*Click OK in the Advanced Options window.

*Click OK in the Options window.

A: If Outlook starts with Outlook Today, Click Customize. The option is there.

A: Using the menu's:

*

*Tools

*Options

*Other

*Advanced Options

Click on Browse and select the folder


text:
Q: Inbound E-Mail has problems with utf-8? I have a problem with an inbound E-Mail. In my Apex code I just use the following:
global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){
    Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
    String myMailContent = email.plainTextBody;
    String someLine = myMailContent.split('\n', 0)[4];
    .....
}

Now the problem is, that in my E-Mail program the E-Mail displays special chars, but when I use someLine and assign it to lets say Lead.OtherStreet, it doesn't display special chars like "ö, ü, ä, ß".
I have heard that Apex automatically uses utf-8 for inbound e-mails, so I really don't get, what could be the problem here?
Does anyone have a clue, why that happens?


text:
Q: Specify Compile Order in Babel I have my React components broken up into separate JS files for manageability and using the following command to compile the files in my src folder into a single JavaScript file:
babel -w src -o scripts.js

My problem is the order in which the files are compiling. I want to make certain that the base file containing my render() function is last and that a file containing 'use strict;' is first.
Is there a way to tell Babel the order of files to process?
Thanks!
-Eric


text:
Q: Adding rows for recordsets that have incomplete date ranges This one is tricky for me, can't figure it out.
We have a system where we calculate inventory numbers on the fly.  If there's a month where a customer doesn't have any orders, there's no record for that month but the beginning inventory is still calculated and displayed as a rolling calculation based on the previous transaction data.
I'm now pulling this data but need to "fill in the blanks" so to speak.
For example, the table has the following fields:
MonthYear DATETIME
WarehouseID INT
Quantity DECIMAL(18,2)

If I put all this in a temporary table to do calculations, I'll end up with something like this:
2010-01-01 00:00:00.000 135 1000.00
2010-04-01 00:00:00.000 135 2000.00
2010-07-01 00:00:00.000 135 3000.00
2010-06-01 00:00:00.000 235 1000.00
2010-07-01 00:00:00.000 235 2000.00
2011-02-01 00:00:00.000 135 1000.00
2011-03-01 00:00:00.000 135 2450.00

etc., etc.
What I need to do is for each warehouse, if a record exists for that year, add a blank row for any months that aren't in the table.
In the example above for warehouse 135 I need to add a record for 02, 03, 05, 08, etc.
Is there any easier way of doing this rather than with cursors and loops?
Thanks.

A: Search Recursive CTE. Then LEFT JOIN. Gotta bolt out the door. Sorry for quick answer.


text:
Q: How to differentiate $y=\frac{2^x+4^x}{3^x+5^x}$
Differentiate
$$y=\dfrac{2^x+4^x}{3^x+5^x}$$

I think you have to use implicit differentiation, but I don't know how to start. I first ln both sides and separated the fraction into subtraction because of the ln property.

A:
$$\frac{d}{dx}\left[a^x\right]=a^x\ln a$$
$$\frac{d}{dx}\left[\frac{u}{v}\right]=\frac{u'v-v'u}{v^2}$$

Now put $u=2^x+4^x$ , $v=3^x+5^x$
$$y= \frac{2^x+4^x}{3^x+5^x}$$
$$\implies y'=\frac{(2^x\ln2+4^x\ln4)(3^x+5^x)-(3^x\ln3+5^x\ln5)(2^x+4^x)}{(3^x+5^x)^2}$$

A: $$y=\dfrac{2^x+4^x}{3^x+5^x}$$
$$y'=\dfrac{(3^x+5^x)(2^x ln(2)+4^xln(4))+(2^x+4^x)(3^x ln(3)+5^xln(5))}{(3^x+5^x)^2}$$
Simple Quotient rule application.
Using the fact that
$$(\dfrac{f}{g})'=\dfrac{f'g+g'f}{g^2}$$
and
$$(n^x)'=n^x*ln(n)$$


text:
Q: Conceptual limits on mtry in Random Forest algorithm I have a random forest being applied to 7 different input variables to predict a particular classification.  I've done a grid search on the hyperparameters mtry and ntree and it seems as though the algorithm is most accurate when mtry is at 6 (the highest value for mtry I allowed as a hypothetical value in my search).  This finding has also been confirmed when applied to a test set.  I have an intuition that mtry should always be less than the number of total variables in the model but I can't find anything that explicitly states this.
My question Is there an upper limit to mtry as I think there should be?  And if indeed that's the case, what would it indicate if my model gets more accurate as I approach that upper limit?  Is that something to be concerned about?

A: mtry is indeed bound by the number of variables in your model, as it specifies the size of the variable subset that is randomly picked for each random forest iteration.
Given that it is a hyper-parameter, there is no way to know ahead of time what would be the best value of mtry. However, values of mtry that are close to the total number of variables in the model may weaken the forest by making the individual decision trees more correlated; when the decision trees consider similar sets of variables to split on, they are more likely to be similar, even if each is fit to a different bootstrapped data set. Ensemble models usually strive for independence of their members, as that improves predictive ability.
Despite these concerns, the value picked by through proper validation, even if it is large, is probably a fair value to consider for a model.

A: Could the reason for mtry being able to exceed p be because some of the variables are categorical, and automatically one-hot-encoded into several dummy variables?


text:
Q: CSS Selector: Children of class with one of the following classes I have a requirement for a CSS selector where all children of a given class which contain one of n classes are affected.
My container is .k-editor and the children I am looking to affect are all the bootstrap columns col-xs-1, col-xs-2 etc.
So I tried this
.k-editor
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1,
.col-xs-2, .col-sm-2, .col-md-2, .col-lg-2,
.col-xs-3, .col-sm-3, .col-md-3, .col-lg-3,
.col-xs-4, .col-sm-4, .col-md-4, .col-lg-4,
.col-xs-5, .col-sm-5, .col-md-5, .col-lg-5,
.col-xs-6, .col-sm-6, .col-md-6, .col-lg-6,
.col-xs-7, .col-sm-7, .col-md-7, .col-lg-7,
.col-xs-8, .col-sm-8, .col-md-8, .col-lg-8,
.col-xs-9, .col-sm-9, .col-md-9, .col-lg-9,
.col-xs-10, .col-sm-10, .col-md-10, .col-lg-10,
.col-xs-11, .col-sm-11, .col-md-11, .col-lg-11,
.col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
    padding: 0;
}

but this seems to ignore the .k-editor parent and apply itself to all columns.
Anyone able to provide some input on what I might be doing wrong?

A: This code can be shortened:
.keditor [class^="col"] {
     padding: 0;
}

A: This is the shortest solution: .k-editor [class^="col"] will match all the children of .k-editor whose class starts with col.
The other way is to prefix .k-editor to each of your comma-separated selectors:
.k-editor .col-xs-1, .k-editor .col-sm-1, .k-editor .col-md-1, .k-editor .col-lg-1 etc


text:
Q: Keeping track of a list of integers in C, and sampling from the list Let's just say that at the simplest, I have a function that generates random integers. Every number generated I want to tack onto the end of the list.
Then, at the end, I want to sample a random numbers from this list.
I'm quite newb at C, manoeuvring around singly-linked lists and pointer arguments, so any advice would be welcome.
edit: I have no problem switching to C++ if there are structures that would help me out. I just need lists and sampling.

A: Here's a go at it:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>

int main() {
    srand(time(NULL));

    int size = 0;
    int capacity = 4;
    int *data = malloc(capacity * sizeof(int));

    for (int i=0; i < 1000; ++i) {
        // Allocate more space
        if (size == capacity) {
            capacity *= 2;
            data = realloc(data, capacity * sizeof(int));
            if (data == NULL)
                exit(-1);
        }

        // Append a random number
        data[size] = rand();
        size++;
    }

    // Choose a random number (poorly)
    printf("%d\n", data[rand() % size]);
}

Now, why is this code terrible?

*

*rand() is terrible. It's allowed to return random numbers in the range [0, 32768). Or larger if your implementation supports it.

*rand() is allowed to use relatively terrible algorithms to generate random numbers.

*rand() % size is not necessarily uniform.

*time(NULL) is a terrible seed. time(NULL) returns the current time with a precision of seconds. So if I run this code twice quickly, it will often return the same result.

A: So if you know how many elements you will be putting into your list
then you can just do this
 double array[100] // or whateversize you want
 for(int i = 0; i < 100; i++){
   array[i] = yourRandomNumber;
 }

 double index = Rand(0,100);
 return array[index];

Keep in mind I did not do the correct sytax for 'yourRandomNumber' and the Rand function. This is just an outline of what you can do.
Your second option is to create a mutable list if you do not know the size of the list before hand. I.e basically a C++ vector. This has to be coded by hand.
 typedef struct
{
    size_t elementsAllocated;
    size_t elementsUsed;
    int* buffer;
} vector;

 vector* push_front(vector* v, int item)
 {
    if (elementsUsed == elementsAllocated)
    {
        // Time to grow the buffer.
        int elementsAllocated = v->elementsAllocated * 2;
        if (elementsAllocated <= v->elementsAllocated)
        {
          abort(); // Overflow occurred.
        }

        int* buffer = realloc(v->buffer, elementsAllocated * sizeof *buffer);
        if (buffer == NULL)
        {
          abort();
        }

        // Shift the existing data over.
         memmove(buffer + elementsAllocated - v->elementsUsed,
               buffer + v->elementsAllocated - v->elementsUsed,
               v->elementsUsed * sizeof *buffer);
        v->buffer = buffer;
        v->elementsAllocated = elementsAllocated;
   }

   // Prepend the new item.
    int* p = v->buffer + v->elementsAllocated - v->elementsUsed - 1;
    *p = item;
    v->elementsUsed++;
   return p;
}

Using std::vectors in c++
 #include <iostream>
 #include <vector>
 int main(){
     std::vector<double> myVec;

     while(cin){ // this lines syntax is not correct because I don't know how you are
                 // getting your values
       myVec.push_back(value);
     }

     std::cout << myVec[Rand(0, myVec.size())] << std::endl;

 }

All the syntax is not correct I.e cin and rand because I don't know how you are gettting your inputs and Rand can be implemented differently. BUT the rest should be straight forward.

A: If you know in advance at least an upper bound on the count of points you may accept, then you can use a variation on @Jay's answer.  Otherwise, you need some kind of dynamic allocation.  You could use a linked list and allocate nodes as you go, but it might be faster and easier to simply malloc() an array and realloc() if you find you need more space:
#include <stdlib.h>

double select_one() {
    int capacity = 100;
    int count;
    double rval;
    double *accepted = malloc(capacity * sizeof(double));

    // accepted == NULL on malloc() failure
    count = 0;

    while (/* more points to test */) {
        double point = /* next point to test */;

        if (/* point is accepted */) {
            if (count >= capacity) {
                /* expand the array */
                double *temp;

                capacity = 3 * capacity / 2;
                temp = realloc(accepted, capacity * sizeof(double));
                if (temp == NULL) {
                    /* need to handle allocation failure to avoid a memory leak */
                } else {
                    accepted = temp;
                }
            }

            accepted[count++] = point;
        }
    }

    /* Note: not perfectly uniform because of the modulus */
    rval = accepted[rand() % count];

    /* clean up the allocated memory, AFTER selecting the value */
    free(accepted);

    return rval;
}


text:
Q: How to plot a graph with matplotlib Good evening, I am a student taking a required python course (completely new to coding) in Hong Kong.
I was asked to write a python program that shows a graph in an assignment, but I had encountered some difficulties.
I tried to follow some source codes I found on the internet, but it end up showing a bug-like page.
Can someone please kindly tell me which part of my code is wrong, how to correct it, and why is this resulting happening?
Also, I would like to ask that is there any difference between import as mpl and as plt?
source code:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

xaxis = np.array([2,8])
yaxis = np.array([4,9])

plt.plot(xaxis, yaxis )
plt.show()

plt.savefig('table.png')

result:
bug-like result
Thank you all very much. Hope you have a nice day.


text:
Q: Save the data in Realm database by clicking a button I want to save data to Realm database by clicking button
I try but it don't work
the class is:
final     EditText name = (EditText) findViewById(R.id.nameET);

final EditText in_stock = (EditText) findViewById(R.id.avibleET);

final     EditText price = (EditText) findViewById(R.id.priceET);

final         EditText size = (EditText) findViewById(R.id.sizeET);

final EditText color = (EditText) findViewById(R.id.colorET);

   Button buadd=(Button)findViewById(R.id.button4);

 buadd.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {

            stuff s=new stuff();

            s.setName(name.getText().toString());

            s.setPrice(price.getText().toString());

            s.setIn_stock(in_stock.getText().toString());

            s.setColor(color.getText().toString());

            s.setSize(size.getText().toString());

        //working with database

        Realm.init(getApplicationContext());

        Realm realm=Realm.getDefaultInstance();

        realm.beginTransaction();

        realm.copyToRealmOrUpdate(s);

        realm.commitTransaction();

  Toast.makeText(context.class,"the stuff has been added",Toast.LENGTH_LONG).show;

but when I run it and press the button it says: unfortunately the app has stopped

A: Convert your Time to Unix time and save to Realm.
Or parse time to object as
data class Date(val year, val day, val hours, val minutes, val seconds)


text:
Q: Kotlin searchView does not reload Firebase array I have one activity with 2 recyclerViews, both recyclers are used with Firebase. One of the recyclers displays the results of a query, the other recycler has a listener that updates every time there is an update in Firebase. I added a searchView to filter the results from Firebase. The issue I'm having is when I'm trying to search the results from the Firebase query, when I start typing I see results but when I click the X to stop searching, the adapter does not reload the array and i don't see the list of items unless I reload the activity. I'm not sure what I'm missing here. Any help/suggestion is greatly appreciated. Here is my code:
Adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.eduardoz.ezmdapp.Model.Charges
import com.eduardoz.ezmdapp.R

class ChargesAdapter (private var charges: ArrayList<Charges>
                      , private var chargesAll: ArrayList<Charges>
                      , private val itemClick: (Charges) -> Unit)
    : RecyclerView.Adapter<ChargesAdapter.ViewHolder>()
    , Filterable {

    inner class ViewHolder(itemView: View, val itemClick: (Charges) -> Unit) :
RecyclerView.ViewHolder(itemView) {
        private val chargeCode = itemView.findViewById<TextView>(R.id.chargeCodeTxt)
        private val chargeDescription = itemView.findViewById<TextView>(R.id.chargeDescriptionTxt)

        fun bindCharges(charges: Charges) {
            chargeCode?.text = charges.chargeCode
            chargeDescription?.text = charges.chargeDescription

            itemView.setOnClickListener { itemClick(charges) }
        }
    }

    init {
        this.charges = charges
        chargesAll = java.util.ArrayList(charges)
    }

    override fun getItemCount(): Int {
        return charges.count()
    }
    override fun onBindViewHolder(holder: ChargesAdapter.ViewHolder, position: Int) {
         holder.bindCharges(charges[position])
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChargesAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.charges_list, parent, false)
        return ViewHolder(view, itemClick)
    }

    override fun getFilter(): Filter {
        return searchFilter
    }

    private val searchFilter: Filter = object: Filter() {
        override fun performFiltering(constraint: CharSequence?): FilterResults {
            val filteredList: ArrayList<Charges> = ArrayList()
            if (constraint!!.isEmpty()) {
                filteredList.addAll(chargesAll)
            } else {
                for(item in chargesAll) {
                    if
(item.chargeDescription.toLowerCase().contains(constraint.toString().toLowerCase())) {
                        filteredList.add(item)
                    }
                }
            }
            val searchResults = FilterResults()
                searchResults.values = filteredList

            return searchResults
        }

        override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
            charges.clear()
            charges.addAll(results!!.values as Collection<Charges>)
            notifyDataSetChanged()
        }
    }
}

Activity
descriptionSearch.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
               return false
            }
            override fun onQueryTextChange(newText: String): Boolean {
                if (newText.isNotEmpty()) {
                    searchViewBar(newText)
                } else {
                if (newText.isEmpty()) { //I ADDED THIS TO RELOAD THE ADAPTER
                    charges.clear()
                    chargeList()
                }
               }
               return false
            }
        })

 private fun searchViewBar(newText: String) {
        chargesListener = chargesCollectionRef
            .whereGreaterThanOrEqualTo(CHARGE_DESCRIPTION, newText)
            .whereLessThanOrEqualTo(CHARGE_DESCRIPTION, newText+"z")
            .addSnapshotListener(this) { snapshot, exception ->
                if (exception != null) {
                   println("error")
                }
                if (snapshot != null) {
                    charges.clear()
                    parseData(snapshot)
                }
            }
    }

fun parseData(snapshot: QuerySnapshot) {
    for (document in snapshot.documents) {
        val data = document.data
        val chargeCode = data!![CHARGE_CODE] as String
        val chargeDescription = data[CHARGE_DESCRIPTION] as String
        val chargeSpecialty = data[CHARGE_SPECIALTY] as String

        val newChargeList = Charges(chargeCode, chargeDescription, chargeSpecialty)

        charges.add(newChargeList)
    }
    chargesFromAdapter.notifyDataSetChanged()
}


text:
Q: The limit of $n^2 P(|X| > n)$ as $n \rightarrow \infty$ Let $X$ be a random variable such that $\mathbb{E}[X^2] < \infty.$ I want to prove or disprove that $$\lim_{n \to \infty} n^2 P(|X| > n) = 0 .$$
I have already proved that if $\mathbb{E}[|X|] < \infty$, then
$$\lim_{n \to \infty} n  P(|X| > n) = 0.$$
The way I proved the above case was by defining $Y_n = |X| \mathbf{1} _ { \{|X| > n \}}$ and then using the dominated convergence theorem.
See https://stats.stackexchange.com/questions/306508/if-ex-is-finite-is-lim-n-to-infty-npxn-0
I am trying to relate these two questions but I cannot seem to do it. If I define $Y_n = |X| \mathbf{1} _ { \{|X| > n^2 \}},$ then
$$Y_n \geq n^2 \mathbf{1} _ { \{|X| > n^2 \}} \ \ \ \ \implies \ \ \ \ \mathbb{E}[Y_n] \geq n^2 P(|X| > n^2).$$
Obviously this is a problem as the probability is not what I am looking for. If I define $Y_n = |X| \mathbf{1} _ { \{|X| > n \}},$ then
$$Y_n \geq n \mathbf{1} _ { \{|X| > n \}} \ \ \ \ \implies \ \ \ \ \mathbb{E}[Y_n] \geq n P(|X| > n) \ \ \ \ \implies n \mathbb{E}[Y_n] \geq n^2 P(|X| > n). $$
This look a little more promising. Since I have already proved the other case I know that $\mathbb{E}[Y_n] \rightarrow 0.$ But I have no way of knowing what happens to $n \mathbb{E}[Y_n]$ as $n \rightarrow \infty.$
Can someone help?


text:
Q: css3 transitions: fluid layout animations on floating items I would like to archieve something like fluid layout transitions in Silverlight, or like seen in the new css transition powered photolist view in skydrive. I thought this could be done using CSS3 somehow.
assuming I have something like this:

        1

        2

        3

Where item could be some square or an image or anything.
Now we have a floated list of items, that wraps the items when getting resized.
What I'd like to achieve is getting those items to animate fluently, when they're getting wrapped to the next row, or float away to make place for an newly added item in between.
This could probably done with some javascript magic using absolute positioning, but then you'll sacrifice css layouting and have to do everything manually.
Is there any way to say something like transition: left, top 1s ease-in-out;?
I tried wrapping the item inside some parent div, that is floated, while the item itself has absolute positioning, but then the position is relative to its parent, so no transition there.
Here is a video from channel9 that shows several effects, I was talking about the one thats showing up around 1:20.

A: jQuery does exactly that.  But back up for a second.
I'm blurried eyed and need so sleep, so I apologize if this is only half coherent, but maybe it'll tip you in the right direction.
First it's important to consider the right tool for the job.  CSS3 is awesome, but not very backwards compatible, so you'd be depending on javascript for older browsers anyway.  If you do want to go for it, Nuttuts is always a great resource, and here's an article on CSS3:
Without a doubt, I would suggest jQuery (a library of javascript). You don't have to use absolute positioning, and it's all about your specific goal.  You'd have to post that to get more specific advice.  Animate() is a good all purpose function, along with Fadin(), fadeout(), which should serve that exact need.  Search for examples, and you should find what you're looking for.
There's premade scripts and tools for just about everything you can imagine, I'd google for scripts/plugins for exactly what you're looking for.  Chances are, it's out there.  That's a pretty popular need as well, at least that general concept.
Good luck!  (if you're having trouble, send more specifics of the exact goal/function, and if you have it, the site as it is currently)


text:
Q: Help with completion of a simple proof by induction. I need some help completing the following proof by induction. I am not sure how to finish it.

Thm. $\forall n \in \mathbb N (x-1)|(x^n-1)$
Pf by induction:
Inductive Hypothesis:
Let $P(n) = (x-1)|(x^n-1)$
Base Case: n=1
$\frac{x-1}{x^1-1} = 1 \checkmark$
Inductive Step:
For $n \geq 1$ show that $P(n) \to P(n+1)$ is true.
Assume $P(n)$ is true, assume $(x-1)|(x^n -1)$
Examine $(x^{n+1} -1) \equiv x^n \cdot x^1 - 1 $

What next? Not exactly sure how to finish this proof. Can someone take me through how to complete this?

A: If You have proven that $x-1|x^{n}-1$, $x^{n+1}-1=x(x^{n}-1)+x-1$.
So it is proven by induction.

A: $a\mid b$ if and only if $a\neq 0$ and $b=ak$ for some $k$.
Base case is clear, $(x-1)=(x-1)\cdot 1 \,\rightarrow\, (x-1)\mid (x-1)$.
Suppose that $(x-1)\mid(x^n-1)$.
Goal is to show that $(x-1)\mid (x^{n+1}-1)$, meaning just show $x^{n+1}-1=(x-1)k$ for some $k$.
$$x^{n+1}-1=x^{n+1}-x^n+x^n-1=x^n(x-1)+x^n-1$$
Apply the induction hypothesis and you finish the proof.


text:
Q: Photoswipe 4.0: Initiate 'swipe to next' programatically SITUATION
I have been trying to trigger the 'slide to next picture' animation when the NEXT button is clicked, but i have not found a solution for this.
There is an ongoing discussion about this on GitHub, but it is only about adding the option for a slide animation, not about how to actually do it with PS as it is right now.
There was an option for it in 3.0 but as 4.0 is a complete rewrite it does not work anymore.
QUESTION
Instead of just 'jumping' to the next/prev picture when an arrow is clicked, i need the 'slide transition' that is also used when swiping/dragging the image.
There is no option to trigger that, so how can i manually trigger this effect with JS?

A: PhotoSwipe Slide Transitions
So, I added slide transitions to Photoswipe, and it's working nicely without disturbing native behavior.
http://codepen.io/mjau-mjau/full/XbqBbp/
http://codepen.io/mjau-mjau/pen/XbqBbp
The only limitation is that transition will not be applied between seams in loop mode (for example when looping from last slide to slide 1). In examples I have used jQuery.
Essentially, it works by simply adding a CSS transition class to the .pswp__container on demand, but we need to add some javascript events to prevent the transition from interfering with Swipe, and only if mouseUsed. We also add a patch so the transition does not get added between loop seams.
1. Add the below to your CSS
It will be applied on-demand from javascript when required.
.pswp__container_transition {
  -webkit-transition: -webkit-transform 333ms cubic-bezier(0.4, 0, 0.22, 1);
  transition: transform 333ms cubic-bezier(0.4, 0, 0.22, 1);
}

2. Add javascript events to assist in assigning the transition class
This can go anywhere, but must be triggered after jQuery is loaded.
var mouseUsed = false;
$('body').on('mousedown', '.pswp__scroll-wrap', function(event) {
  // On mousedown, temporarily remove the transition class in preparation for swipe.     $(this).children('.pswp__container_transition').removeClass('pswp__container_transition');
}).on('mousedown', '.pswp__button--arrow--left, .pswp__button--arrow--right', function(event) {
  // Exlude navigation arrows from the above event.
  event.stopPropagation();
}).on('mousemove.detect', function(event) {
  // Detect mouseUsed before as early as possible to feed PhotoSwipe
  mouseUsed = true;
  $('body').off('mousemove.detect');
});

3. Add beforeChange listener to re-assign transition class on photoswipe init
The below needs to be added in your PhotoSwipe init logic.
// Create your photoswipe gallery element as usual
gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);

// Transition Manager function (triggers only on mouseUsed)
function transitionManager() {

  // Create var to store slide index
  var currentSlide = options.index;

  // Listen for photoswipe change event to re-apply transition class
  gallery.listen('beforeChange', function() {

    // Only apply transition class if difference between last and next slide is < 2
    // If difference > 1, it means we are at the loop seam.
    var transition = Math.abs(gallery.getCurrentIndex()-currentSlide) < 2;

    // Apply transition class depending on above
    $('.pswp__container').toggleClass('pswp__container_transition', transition);

    // Update currentSlide
    currentSlide = gallery.getCurrentIndex();
  });
}

// Only apply transition manager functionality if mouse
if(mouseUsed) {
  transitionManager();
} else {
  gallery.listen('mouseUsed', function(){
    mouseUsed = true;
    transitionManager();
  });
}

// init your gallery per usual
gallery.init();

A: You can just use a css transition:
.pswp__container{
     transition:.3s ease-in-out all;
}
This might not be ideal for performance on mobile, but I just add this transition in a media query and allow users to use the swipe functionality on smaller screens.

A: I finally bit the bullet and spent some time making this work as nobody seemed to have a solution for that, not here neither on GitHub or anywhere else.
SOLUTION
I used the fact that a click on the arrow jumps to the next item and triggers the loading of the next image and sets the whole slide state to represent the correct situation in an instant.
So i just added custom buttons which would initiate a slide transition and then triggered a click on the original buttons (which i hid via CSS) which would update the slide state to represent the situation i created visually.

*

*Added NEW next and prev arrows

*Hid the ORIGINAL next and prev arrows via css

*Animated the slide myself when the NEW next or prev arrows were clicked

*Then triggered the click on the ORIGINAL next or prev arrows programmatically

So here is the code:
HTML
// THE NEW BUTTONS
<button class="NEW-button-left" title="Previous (arrow left)">PREV</button>
<button class="NEW-button-right" title="Next (arrow right)">NEXT</button>

// added right before this original lines of the example code
<button class="pswp__button pswp__button--arrow--left ...

CSS
pswp__button--arrow--left,
pswp__button--arrow--right {
  display: none;
}
NEW-button-left,
NEW-button-right {
  /* whatever you fancy */
}

JAVASCRIPT (helper functions)
var tx = 0; // current translation
var tdir = 0;
var slidepseactive = false;

// helper function to get current translate3d positions
// as per https://stackoverflow.com/a/7982594/826194
function getTransform(el) {
  var results = $(el).css('-webkit-transform').match(/matrix(?:(3d)\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}\d+))(?:, (-{0,1}\d+))(?:, (-{0,1}\d+)), -{0,1}\d+\)|\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}\d+))(?:, (-{0,1}\d+))\))/)
  if(!results) return [0, 0, 0];
  if(results[1] == '3d') return results.slice(2,5);
  results.push(0);
  return results.slice(5, 8);
}

// set the translate x position of an element
function translate3dX($e, x) {
  $e.css({
    // TODO: depending on the browser we need one of those, for now just chrome
    //'-webkit-transform': 'translate3d(' +String(x) + 'px, 0px, 0px)'
    //, '-moz-transform': 'translate3d(' +String(x) + 'px, 0px, 0px)'
    'transform': 'translate3d(' +String(x) + 'px, 0px, 0px)'
  });
};

JAVASCRIPT (main)
// will slide to the left or to the right
function slidePS(direction) {
  if (slidepseactive) // prevent interruptions
    return;

  tdir = -1;
  if (direction == "left") {
    tdir = 1;
  }

  // get the current slides transition position
  var t = getTransform(".pswp__container");
  tx = parseInt(t[0]);

  // reset anim counter (you can use any property as anim counter)
  $(".pswp__container").css("text-indent", "0px");

  slidepseactive = true;
  $(".pswp__container").animate(
    {textIndent: 100},{
      step: function (now, fx) {
        // here 8.7 is the no. of pixels we move per animation step %
        // so in this case we slide a total of 870px, depends on your setup
        // you might want to use a percentage value, in this case it was
        // a popup thats why it is a a fixed value per step
        translate3dX($(this), tx + Math.round(8.7 * now * tdir));
      },
      duration: '300ms',
      done: function () {
        // now that we finished sliding trigger the original buttons so
        // that the photoswipe state reflects the new situation
        slidepseactive = false;
        if (tdir == -1)
          $(".pswp__button--arrow--right").trigger("click");
        else
          $(".pswp__button--arrow--left").trigger("click");
      }
    },
    'linear');
}

// now activate our buttons
$(function(){

  $(".NEW-button-left").click(function(){
    slidePS("left");
  });

  $(".NEW-button-right").click(function(){
    slidePS("right");
 });

});

I used info from those SE answers:

*

*jQuery animate a -webkit-transform

*Get translate3d values of a div?

A: The PhotoSwipe can do this by itself when you use swipe gesture. So why not to use the internal code instead of something that doesn't work well?
With my solution everything works well, the arrow clicks, the cursor keys and even the loop back at the end and it doesn't break anything.
Simply edit the photoswipe.js file and replace the goTo function with this code:
    goTo: function(index) {
    var itemsDiff;

    if (index == _currentItemIndex + 1) { //Next
        itemsDiff = 1;
    }
    else { //Prev
        itemsDiff = -1;
    }

    var itemChanged;
    if(!_mainScrollAnimating) {
        _currZoomedItemIndex = _currentItemIndex;
    }

    var nextCircle;

    _currentItemIndex += itemsDiff;

    if(_currentItemIndex < 0) {
        _currentItemIndex = _options.loop ? _getNumItems()-1 : 0;
        nextCircle = true;
    } else if(_currentItemIndex >= _getNumItems()) {
        _currentItemIndex = _options.loop ? 0 : _getNumItems()-1;
        nextCircle = true;
    }

    if(!nextCircle || _options.loop) {
        _indexDiff += itemsDiff;
        _currPositionIndex -= itemsDiff;
        itemChanged = true;
    }

    var animateToX = _slideSize.x * _currPositionIndex;
    var animateToDist = Math.abs( animateToX - _mainScrollPos.x );
    var finishAnimDuration = 333;

    if(_currZoomedItemIndex === _currentItemIndex) {
        itemChanged = false;
    }

    _mainScrollAnimating = true;

    _shout('mainScrollAnimStart');

    _animateProp('mainScroll', _mainScrollPos.x, animateToX, finishAnimDuration, framework.easing.cubic.out,
        _moveMainScroll,
        function() {
            _stopAllAnimations();
            _mainScrollAnimating = false;
            _currZoomedItemIndex = -1;

            if(itemChanged || _currZoomedItemIndex !== _currentItemIndex) {
                self.updateCurrItem();
            }

            _shout('mainScrollAnimComplete');
        }
    );

    if(itemChanged) {
        self.updateCurrItem(true);
    }

    return itemChanged;

},


text:
Q: Can records have capitalized fields? In purescript, {foo :: Foo} desugars to Record ("foo" :: Foo), as far as my understanding goes. Could I make something like Record ("F" :: Foo)? How would that look in record access syntax? Would thing.F be syntactically valid?

A: Quoting fields is exactly the way to do it, both in the type:
type MyRecord = { "Usually impossible field name" :: Boolean }

And in accessors / patterns:
make :: Boolean -> MyRecord
make = { "Usually impossible field name": _ }

get :: MyRecord -> Boolean
get = _."Usually impossible field name"

update :: MyRecord -> Boolean -> MyRecord
update = _ { "Usually impossible field name" = _ }

Quoting fields this way allows you to name the record fields whatever you want, using caps, symbols, numbers, etc.
This is a little similar to obj["property"] in JavaScript, but you can only use string literals for the property name rather than arbitrary values.


text:
Q: Dealing with nested if then else/nested switch statements Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?
I remember coming across some methods used by the Google folks listed in a Google code blog post. Can't seem to find it now though

A: Have you read this on flattening arrow code from Coding Horror?
You can replace throw with return or goto if you're using a language without exceptions.

A: You want to use a refactoring that replaces a conditional using a polymorphic class. For example.
Or here's another example
Essentially the ideal is very simple you create an object heirarchy, and move the various behaviors into an overriden method. You will still need a method to create the right class but this can be done using a factory pattern.
Edit
Let me add that this is not a perfect solution in every case. As (I forgot your name sorry) pointed in my comments, some times this can be a pain especially if you have to create an object model just to do this. This refactoring excells if you have this:
function doWork(object x)
{

   if (x is a type of Apple)
   {
      x.Eat();

   } else if (x is a type of Orange)
   {
      x.Peel();
      x.Eat();
   }

}

Here you can refactor the switch into some new method that each fruit will handle.
Edit
As someone pointed out how do you create the right type to go into doWork, there are more ways to solve this problem then I could probally list so some basic ways. The first and most straight forward (and yes goes against the grain of this question) is a switch:
class FruitFactory
{
   Fruit GetMeMoreFruit(typeOfFruit)
   {
         switch (typeOfFruit)
         ...
         ...
   }
}

The nice thing about this approach is it's easy to write, and is usually the first method I use. While you still have a switch statement its isolated to one area of code and is very basic all it returns is a n object. If you only have a couple of objects and they;re not changing this works very well.
Other more compelx patterns you can look into is an Abstract Factory. You could also dynamically create the Fruit if your platform supports it. You could also use something like the Provider Pattern. Which essentially to me means you configure your object and then you have a factory which based on the configuration and a key you give the factory creates the right class dynamically.

A: I actually wrote about how to solve this issues in my blog in April of 2008. Take a look here and let me know what you think.
I recommend you:

*

*Use polymorphism to get the correct run-time behavior you need without conditional statements.

*Take all your conditional statements, and move them into some sort of "factory" which will hand you the appropriate type at run-time.

*You're done. Wasn't that easy? :)
If you want to see some actual code sample on how transform your code, head over to my blog.
P.S. This is not a cheap attempt at self promotion; I've been a SO user for a long time now, and this is the first time I've linked to my blog - and I've only done so because I think it's relevant.

A: Were you thinking of Google's "The Clean Code Talks -- Inheritance, Polymorphism, & Testing" video? It discusses approaches to using Object Oriented techniques to remove if/switch conditionals.

A: You don't say what language you're using, but if you are using an OO language such as C++, C# or Java, you can often use virtual functions to solve the same problem as you are currently solving with a switch statement, and in a more extensible way.  In the case of C++, compare:
class X {
public:
    int get_type();     /* Or an enum return type or similar */
    ...
};

void eat(X& x) {
    switch (x.get_type()) {
    TYPE_A: eat_A(x); break;
    TYPE_B: eat_B(x); break;
    TYPE_C: eat_C(x); break;
    }
}

void drink(X& x) {
    switch (x.get_type()) {
    TYPE_A: drink_A(x); break;
    TYPE_B: drink_B(x); break;
    TYPE_C: drink_C(x); break;
    }
}

void be_merry(X& x) {
    switch (x.get_type()) {
    TYPE_A: be_merry_A(x); break;
    TYPE_B: be_merry_B(x); break;
    TYPE_C: be_merry_C(x); break;
    }
}

with
class Base {
    virtual void eat() = 0;
    virtual void drink() = 0;
    virtual void be_merry() = 0;
    ...
};

class A : public Base {
public:
    virtual void eat() { /* Eat A-specific stuff */ }
    virtual void drink() { /* Drink A-specific stuff */ }
    virtual void be_merry() { /* Be merry in an A-specific way */ }
};

class B : public Base {
public:
    virtual void eat() { /* Eat B-specific stuff */ }
    virtual void drink() { /* Drink B-specific stuff */ }
    virtual void be_merry() { /* Be merry in an B-specific way */ }
};

class C : public Base {
public:
    virtual void eat() { /* Eat C-specific stuff */ }
    virtual void drink() { /* Drink C-specific stuff */ }
    virtual void be_merry() { /* Be merry in a C-specific way */ }
};

The advantage is that you can add new Base-derived classes D, E, F and so on without having to touch any code that only deals with pointers or references to Base, so there is nothing that can get out of date the way that a switch statement can in the original solution.  (The transformation looks very similar in Java, where methods are virtual by default, and I'm sure it looks similar in C# too.)  On a large project, this is a huge maintainability win.

A: You might want to look at the Strategy Pattern, wherein instead of putting a long chain of ifs with linked conditions, you abstract each condition to a different object, each one defining what its specific behavior.
The class that defines those objects will implement an Interface which will be called by the parent object.

A: How about:
/* Code Block 1... */

if(/* result of some condition or function call */)
{
   /* Code Block 2... */

   if(/* result of some condition or function call */)
   {
      /* Code Block 3... */

      if(/* result of some condition or function call */)
      {
         /* Code Block 4... */
      }
   }
}

Becomes this:
/* Code Block 1... */
IsOk = /* result of some condition or function call */

if(IsOK)
{
   /* Code Block 2... */
   IsOk = /* result of some condition or function call */
}

if(IsOK)
{
   /* Code Block 3...*/
   IsOk = /* result of some condition or function call */
}

if(IsOK)
{
   /* Code Block 4...*/
   IsOk = /* result of some condition or function call */
}

/* And so on... */

You can of course return if ever IsOk becomes false, if appropriate.


text:
Q: Abstract tree vs parser tree I need your opinions in order to choose the best alternative between the choice of to generate an parser tree (ST) or to generate an abstract syntax tree (AST). The is the context:
I want to parse a language like C (just a subset of C with some changes to make it more pseudocode-oriented), but not in order to translate it in other output language/file, but to execute its sentences for animating its execution process (I use Qt to draw). A feature of this C subset is it enables nested scopes. My doubt related to my election between ST and AST arises from the symbol table. The general idea is (using Boost.spirit):

*

*Parsing a source code file by means of a custom Boost.spirit parser.

*The semantic actions produces a Syntax Tree, just a copy of the source code's syntax tree (or also, a copy of the Boost.spirit's internal syntax tree, but with my own classes and structures). Thus, there isn't a AST.

*With this ST in the hand, the program read this syntax tree in a top-down direction as following:

*

*Execute the first sentence.

*Upload the symbol table with the new (outcome of the sentence) values.

*Save the actual state of the symbol table in a program state stack.

*To 3.1 until the ST is completely processed.

*Animate the algorithm reading and drawing the program state stack.

Two reasonings:

*

*If I work with a AST, I lost, after parsing, information about variable declarations, its types and so on. Thus, I have to work with the symbol table by means of the semantic actions of the parser, complicating the parser writing and understanding. Moreover, I have to work all the time with a symbol table with all variables, irrespective of the actual scope (if I'm in the scope i, only need the scopes i, i-1, ...., 1; not all the scopes throughout the algorithm). This spends memory.

*I only need, in my program state stack, variables of the actual and previous scopes, for not complicating the understandability of the algorithm through the animation. If I work with a ST, I have to delete all symbols I don't need before save it in the stack. This spends time.

*A static symbol table with control scopes is more difficult to design and use than a dynamic symbol table. A static symbol table must have an identifier (for example) for each scope, and to relate each node of the tree with each identifier. A dynamic symbol table works easier because if I'm in the scope i, only need two "vectors" (perhaps a double-queue and a stack):

*

*A container (double-queue?) with symbols and its related information: the last variable in the container is the nearest declared variable.

*A container (stack) of integers, showing the beginning (index of the double-queue) of each scope.

For example, for the scope i:

*

*Container 1: [x y z x a b z f a z]

*Container 2: [0 3 6 8]

If I leave the scope i, only I have to erase the last integer and the symbols from position 8 up to the end. The tree keep unmodified.

*Due to I have to execute each sentence in execution time, a ST facilitates my execution.
Two question:

*

*Which is better then?

*Exist any form to extract the internal tree of Spirit or customizing it in order to not copy it?

A: I think what you're looking for is an abstract semantic graph (ASG) that represents the semantics (as opposed to the syntax) of a program. What you can do is:

*

*Parse the source to an AST, then

*convert the AST into an ASG, and finally

*walk the ASG to execute the actual code.

Also, I'd say that you can indeed build an AST which is no too abstract; for example, I'm currently building my own scripting language interpreter, and the AST will contain the variable names (this is useful for debugging the parser/interpreter and the parsed program itself as well).


text:
Q: Binary mask in image space from point cloud data Hy!
I have a point cloud representing walls and the floor of an indoor scene.
I projected the points of the floor on a plane. That means it's a "2d point cloud" now.
All z-coordinates are zero.
I have to deal with missing parts. My idea now is to fill the holes.
Is there a way to transform the points into the image space to create a
binary mask? I would like to use techniques like: "imfill" in Matlab...
Thanks
Edit:
To make it more clear, I will explain an simple example. I have points in 2D. After I made a triangulation, I can access each triangle. For each triangle I create a binary mask with poly2mask(), and each mask I write to an final image.
Here is an example:

Now I can use morphological operations on the image.
E.G: Here is an more complex example, where the triangulation gives me bad results:

To fill the hole on the right side, I could use morphological operation.
My problem: The points can be negative, and the distance between the triangles can be very small (E.g.: x coordinates of triangle: (1.12 1.14 1.12), will give me the point 1 in the image space


text:
Q: A function satisfying $\left \lvert f'(x) \right \rvert \leq 1,$ $ \left\vert\int_{0}^{2} f(x)dx\right\vert \leq 1$ and $ f(0)=f(2)=1$? Please help me with the following problem.
Let $f$ be a differentiable (therefore continuous) on $[0,2]$ so that the three followings are satisfied:
$$\forall x \in [ 0,2 ],\quad \left \lvert f'(x) \right \rvert \leq 1,$$
$$ \left\vert\int_{0}^{2} f(x)dx\right\vert \leq 1.$$
$$ f(0)=f(2)=1$$
Does such function exist?
I think not but I haven't proved it yet.
I have tried Rolle and Langrange theorem, also Taylor formula, they might be useful but I am not there yet.
Please help me or suggest some potential idea.
Thank you.

A: Note that the mean value theorem shows that $f(x) \ge |1-x|$, and since
$\int_0^2 f(x) dx \le 1$ and $\int_0^2 |1-x| dx = 1$, we must have $f(x) = |1-x|$, which is impossible since $f$ is differentiable.

A: From $|f'(x)| \le 1$, we have $f(x) \ge f(0) - \int_0^x dx = 1-x$. And similarly, $f(x)\ge f(2) - \int_2^x dx = x-1$. Define $g(x)=\max(1-x,x-1)=|x-1|$. We have $f\ge g$, so $\int_0^2 f \ge \int_0^2 g = 1$. But since the integral is bounded by $1$, we get $\int_0^2 f = 1$ and $f=g$. But this is impossible because $g$ is not differentiable.


text:
Q: Syncronizing between online and offline databases in PHP based application I have a CRM system built on PHP and MySQL, and want to make an offline version of it in case of any internet issues.
my point now is, I want to syncronize both local and online MySQL databases so that it won't be affected if the internet went down, but any update on the records in the local host or online appear on both local and online version of the crm.
Example Scenario, A lead is update through the online crm should be updated on the localhost crm once it is connected to the internet.
if the localhost lead is update on the localhost crm, it should be updated on the online crm as well once it is connected to the internet.
is there a way to accomplish this both databases are exactly the same structure and both are MySQL, the difference will be the lead updates, and new leads added


text:
Q: Changing from System.Web.Mail to System.Net.Mail I've updated my old style of sending emails from
System.Web.Mail

to a more updated style:
System.Net.Mail

Sub SendEmail()
    Using objMailMessage As New MailMessage()

        objMailMessage.From = New MailAddress(txtFrom.Text)
        objMailMessage.To.Add(txtTo.Text)

        objMailMessage.Subject = txtSubject.Text
        objMailMessage.Body = txtContent.Text & " | email sent from " & strUser & "'s pc"

        objMailMessage.IsBodyHtml = True
        objMailMessage.Priority = MailPriority.Normal

        objSmtpClient = New SmtpClient("server_name_goes_here")
        objSmtpClient.Send(objMailMessage)

    End Using
End Sub

The problem is that the new style, does not let me type in a mail group name.
For example, in the old style, I was able to type in
objMailMessage.From = "HR Department"

HR Department was a group of emails set on the exchange server which had everyone in the HR listed and would send the email to all of them.
In the new coding style, It does not let me do that.  Each time I try, it gives me a message saying that I have not entered in a proper email address.
i.e, this does not work:
objMailMessage.From = New MailAddress("HR Department")

I have to do this
objMailMessage.From = New MailAddress("hr_user_1@mail.com, hr_user_2@mail.com, hr_user_3@mail.com")

A: Try replacing this:
objMailMessage.From = New MailAddress("HR Department")

To this:
objMailMessage.From = New MailAddress("HR Department@yourdomain.com", "HR Department")


text:
Q: What SO site to use for font related questions? Is there a SO family + SE site where I can ask questions related to fonts and also font recommendations?

A: Take a look at https://ux.stackexchange.com/ - but search first and look for any existing questions.
In fact there's already a question that might fit the bill - What fonts are good and which ones should we avoid for our application's UI?
However, font recommendations can be subjective so be careful how you word your question (if you do decide to post) and try to make it as objective as possible.


text:
Q: I know this is pretty primitive but i want to make this function work in a shorter in more efficient manner
instructions =
  Given an int array length 2, return True if it contains a 2 or a 3.

  def has23(nums):
    if nums[0] == 2 or nums[0]== 3 :
      return True
    elif nums[1] == 2 or nums[1]==3 :
      return True
    else:
      return False

A: Try this:
def has23(nums):
    return 2 in nums or 3 in nums

A: Some performance of the answers:
def has23(nums):
    if '3' in str(nums) or '2' in str(nums):
        return True
    else:
        return False
%timeit has23([1,3])
# 415 ns ± 14.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

def has23(nums):
    return 2 in nums or 3 in nums
%timeit has23([1,3])
# 138 ns ± 7.77 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

def has23(nums):
    return set(nums) & {2, 3}
%timeit has23([1,3])
# 340 ns ± 4.01 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

I am personally a fan of @John Anderson's answer, as it's concise and fast with small arrays as OP specified.
P.S. as suggested by @UltraInstinct
def has23(nums):
    for x in nums:
        if x in (2,3):
            return True
    return False
%timeit has23([1,3])
# 171 ns ± 1.82 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

A: I created your solution with example and explanation. There are 2 functions, one to check single match the other to check all matches overall.
# Function to check if the value is inside the array
def isMatch(value, myList):
    # Set the value to False by default
    result = False
    # Check if the value is inside the array
    if value in myList:
        # Set the result to True
        result = True
    # Return the result for that match term
    return result

# Function to check every matches terms
def checkIfIsMatch(listOfMatches, listOfValues):
    # Return True is there is any match
    return any(isMatch(value, listOfValues) for value in listOfMatches)

# List of values to check inside array
listOfMatches = [2,3]

# Example array 1
listOfValues1 = [5,3]
# Store the result into a variable
result1 = checkIfIsMatch(listOfMatches, listOfValues1)
# Print example 1
print result1
# Output: True

listOfValues2 = [5,7]
# Store the result into a variable
result2 = checkIfIsMatch(listOfMatches, listOfValues2)
# Print example 2
print result2
# Output: False

A: you could try writing it this way:
def has23(nums):
    for x in nums:
        if x in (2,3):
            return True
        else:
            return False

or
    if nums[0] in (2,3) or nums[1] in (2,3):
        return True
    else:
        return False

/ogs

A: def has23(nums):
    if '3' in str(nums) or '2' in str(nums):
        return true
    else:
        return false

A: You can use set intersection:
def has23(nums):
    return set(nums) & {2, 3}

A: You could create a filtered list that only will hold 2 or 3 and test that, if any(filtered_list) means it contains a 2 or 3 and True will be returned if not False
def has23(num):
    return any([*filter(lambda x: x == '2' or x == '3', str(num))])

print(has23(21)) # => True
print(has23(83)) # => True
print(has23(54)) # => False


text:
Q: How do I exclude bias from regularization using TensorFlow's `matrix_solve_ls`? Given a design matrix (with an initial column of 1s corresponding to a bias factor), I can perform standard NN-style L2-Regularized parameter estimation, in which only the weights are regularized, with a variety of Python tools such as
scipy.optimize.minimize(lambda p: np.mean((np.dot(dmat, p) - y_data)**2) + lamb*np.dot(p[1:], p[1:]), np.zeros(n_params).T).x

or
scipy.optimize.minimize(lambda p: np.mean((np.dot(dmat, p) - y_data)**2) + 2*lamb*tf.nn.l2_loss(p[1:]).eval(), np.zeros(n_params).T).x

But I see no way to exclude the bias from regularization with TensorFlow's tf.matrix_solve_ls which treats
tf.matrix_solve_ls(dmat, np.array([y_data]).T, l2_regularizer=lamb*len(dmat)).eval()

as equivalent to
scipy.optimize.minimize(lambda p: np.mean((np.dot(dmat, p) - y_data)**2) + lamb*np.dot(p, p), np.zeros(n_params).T).x

How do I exclude bias (or, by construction, the first parameter) from regularization using tf.matrix_solve_ls?

A: Unfortunately, this is not possible with the current version of matrix_solve_ls. On the other hand, the default (fast) path in matrix_solve_ls was recently changed to simply be a composite Python function:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/linalg_ops.py#L293
You can easily make a version of this code where the l2_regularizer is a vector (with a separate value for each parameter). It would probably be a good idea to implement such a generalization in matrix_solve_ls in general. Perhaps you can submit this change as a pull request?


text:
Q: Popovercontroller go away when i try to type in UITextfield? I have one popovercontroller, in popover controller there is one textfield.Whenever i try to type in textfield uipopovercontroller goes away upper left side.Problem is that i want popup enable while typing.
Thanks in advance

A: What you can try is, while editing is being done on your UITextField, in your popoverControllerShouldDismissPopover: method you return NO. Example below..
- (BOOL)popoverControllerShouldDismissPopover:(UIPopoverController *)popoverController {

    if([someTextField isFirstResponder])
          return NO;

   return YES;
}

Mark this is the answer if it is your solution.


text:
Q: How should I represent to-be binary data? I'm writing some serialization code, and I'm wondering how to deal with binary data. As I'm doing it in Python, my goal is to make it very simple, not require a lot of programmer overhead, etc.
Three options I am considering:

*

*The fields that will be binary data are represented as hex-encoded strings. Thus you'd have something like:
obj = {
   'foo': 100,
   'bar': [1, 2, 3, 4],
   'baz': "ab0123ffbbaa55",
}

ObjectSpec.loads(ObjectSpec(obj).dumps())

ObjectSpec is the class which determines how to serialize the object.

*

*The pros: it's easy to look at, easy to make object literals, easy to print out.

*The cons: you have to remember to hex-encode the fields. If you have bytes, you have to hex-encode them before the serialization code then hex-decodes them. If you want to store the objects, there's more overhead unless you hex-decode the strings first.

*The fields are byte strings, instead, e.g.:
obj = {
   'foo': 100,
   'bar': [1, 2, 3, 4],
   'baz': '\xab\x01#\xff\xbb\xaaU',
}

*

*The pros: less overhead, both in space, and in not having to hex-encode if you already have bytes.

*The cons: harder to make literals, harder to print out. If you accidentally leave in a hex-encoded string then it will serialize the wrong thing (the hex representation instead of the thing itself).

*The binary data fields use some custom type, e.g. bson.Binary:
from bson import Binary

obj = {
   'foo': 100,
   'bar': [1, 2, 3, 4],
   'baz': Binary('\xab\x01#\xff\xbb\xaaU'),
}

*

*The pros: Same as #2, but also clearly delineates binary types.

*The cons: Same as #2, except harder to accidentally encode the wrong thing. Requires wrapping the data in a type just to get the serialization code to accept it, instead of leaving bytes in.

What would the most sensible approach be? Is there another variant that is better?

A: You can define binary and hexadecimal values in python, just use 0xff or 0b1001010101001. They are defined as sub-class of int. chr and ord function reads them very clearly.
object = {
   "foo": 100
   "bar": [1,2,3,4],
   "baz": 0xffaff34441faabc # i realy dont get what foo,bar and baz are so i dont really know what your string should represent.
}

And then use binary operators and binary shift left, binary shift right to manage it into a right order. for example sending 13 byte data to someport with imaginary syntax PORT:STOP:MESSAGE : 0xFF00737461636B65786368616E6765, or send "stackexchange" to port 255, where 0xff is port, 0x00 is STOP, and the rest is message. So your function would be something like this, first 2 bytes are port, if next iz 0x00 then split and the rest "translate" to string.
If you want to test in safe enviorment you can use
map(chr, [0x73,0x74,0x61,0x63,0x6B,0x65,0x78,0x63,0x68,0x61,0x6E,0x67,0x65])


text:
Q: ng-repeat update after build I have a list of events that gets build from a JSON call to my server. The list gets parsed through ng-repeat. I want to implement a like button for the event and if its liked, replace that with unlike.
Like
Unlike

Everything works perfectly except I have to refresh the feed to show "Unlike". Is there a way I can update the specific list item at the index that was liked once clicked without the need to refresh.
Please let me know if you need more information. Thanks!
edit: adding like function & unlike function. All it does is send request to my server to like or unlike a specific event with the event_id and user token.
$scope.like = function (event_id) {
   var url = www.server.com?type=unlike&event_id=...
    $http.post(url).success(function (data) {
        console.log('success like');
        //I want it to update my index here
    }).error(function (data) {
        console.log('fail like');
    });
};
$scope.unLike = function (event_id) {
    var url = www.server.com?type=unlike&event_id=...
    $http.post(url).success(function (data) {
        console.log('success unlike');
        //I want it to update my index here
    }).error(function (data) {
        console.log('fail unlike');
    });
};

A: Instead of passing in the event_id, pass the object to the like and unLike functions and update the object in success handler.
HTML
Like
Unlike

Controller
$scope.like = function(event) {
    var url = 'www.server.com?type=unlike&event_id=' + event.event_id;
    $http.post(url).success(function (data) {
        event.liked = true;
        console.log('success like');
    }).error(function (data) {
        console.log('fail like');
    });
};
$scope.unLike = function(event) {
    var url = 'www.server.com?type=unlike&event_id=' + event.event_id;
    $http.post(url).success(function (data) {
        event.liked = null;
        console.log('success unlike');
    }).error(function (data) {
        console.log('fail unlike');
    });
};


text:
Q: Cannot scale gif move frame in Android Canvas I have problem with scaling GIF movie frame. I'm using Canvas.scale(float sx, float sy) before drawing the frame. But it doesn't draw scaled frame, it draws nothing. Any ides ?

A: If your trying to make a dedicated View that is scale-able and reusable within another layout you should use the View's getWidth() and getHeight() methods as well.
I ran into this issue when changing the View's dedicated size: canvas.getWidth() is the width of the entire screen and not the views width so I modified the onDraw method as follows.
@Override
protected void onDraw(Canvas canvas) {
    canvas.drawColor(Color.TRANSPARENT);
    super.onDraw(canvas);

    long now = android.os.SystemClock.uptimeMillis();

    Paint p = new Paint();
    p.setAntiAlias(true);

    if (cur == 0) cur = now;

    if(movie != null)
    {
        float scale = 1f;
        if(movie.height() > getHeight() || movie.width() > getWidth())
            scale = ( 1f / Math.min(canvas.getHeight() / movie.height(), canvas.getWidth() / movie.width()) ) + 0.25f;
        else
            scale = Math.min(canvas.getHeight() / movie.height(), canvas.getWidth() / movie.width());

        canvas.scale(scale, scale);
        canvas.translate(((float)getWidth() / scale - (float)movie.width())/2f,
                ((float)getHeight() / scale - (float)movie.height())/2f);

        int relTime = (int)((now - cur) % movie.duration());
        movie.setTime(relTime);
        movie.draw(canvas, 0, 0);

        invalidate();
    }
}

Notice the getWidth(), getHeight() if statement checking to see if the movie is larger than the view, in my case my views height was 160 but my GIF was 260, however using the other method it would always draw the GIF too big, with these changes I was able to test and see it working in both cases where my View was 1280 X 900 and the image scaled up and also where my view was 1000 X 160 and it scaled down.
Best of luck, and have fun :D
-Chris

A: This should work.
protected void onDraw(Canvas canvas)
{
    canvas.drawColor(Color.TRANSPARENT);

    canvas.scale(0.5f, 0.5f); // scale gif to its half size

    super.onDraw(canvas);

    /* movie.setTime . . . */

    movie.draw(canvas, ...);

    this.invalidate();

}

A: This was my solution:
public class GifImageView extends View {
    private InputStream mInputStream;
    private Movie mMovie;
    public int mWidth, mHeight;
    private long mStart;
    private Context mContext;

    public GifImageView(Context context) {
        super(context);
        this.mContext = context;
    }

    public GifImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GifImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        if (attrs.getAttributeName(1).equals("background")) {
            int id = Integer.parseInt(attrs.getAttributeValue(1).substring(1));
            setGifImageResource(id);
        }
    }

    private void init() {
        setFocusable(true);
        mMovie = Movie.decodeStream(mInputStream);
        mWidth = mMovie.width();
        mHeight = mMovie.height();

        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(mWidth, mHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        long now = SystemClock.uptimeMillis();

        if (mStart == 0) {
            mStart = now;
        }

        if (mMovie != null) {
            int duration = mMovie.duration();
            if (duration == 0) {
                duration = 1000;
            }

            float scale = Math.min((float) canvas.getHeight() / (float) mMovie.height(), (float) canvas.getWidth() / (float) mMovie.width());

            canvas.scale(scale, scale);
            canvas.translate(((float) mWidth / scale - (float) mMovie.width()) / 2f,
                ((float) mHeight / scale - (float) mMovie.height()) / 2f);

            int relTime = (int) ((now - mStart) % duration);

            mMovie.setTime(relTime);
            mMovie.draw(canvas, 0, 0);
            invalidate();
        }
    }

    public void setGifImageResource(int id) {
        mInputStream = mContext.getResources().openRawResource(id);
        init();
    }

    public void setGifImageUri(Uri uri) {
        try {
            mInputStream = mContext.getContentResolver().openInputStream(uri);
            init();
        } catch (FileNotFoundException e) {
            Log.e("GIfImageView", "File not found");
        }
    }

    public void setSize(int dimension) {
        mWidth = dimension;
        mHeight = dimension;
    }
}

add it to your layout-file:
<GifImageView
        android:id="@+id/gifView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerHorizontal="true"
        android:background="@drawable/image" />

then you can simply set the dimension in your Java code:
gifView.setSize(dimension);

A: This sample allows us to resize GIF and fit in to the screen accordingly to the original size of image.

PlayGifView.class
public class PlayGifView extends View{

    private static final int DEFAULT_MOVIEW_DURATION = 1000;

    private int mMovieResourceId;
    private Movie mMovie;

    private long mMovieStart = 0;
    private int mCurrentAnimationTime = 0;
public Context context;
    @SuppressLint("NewApi")
    public PlayGifView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
       /**
        * Starting from HONEYCOMB have to turn off HardWare acceleration to draw
        * Movie on Canvas.
        */
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
           setLayerType(View.LAYER_TYPE_SOFTWARE, null);
       }

   }

    public void setImageResource(int mvId){
        this.mMovieResourceId = mvId;
       mMovie = Movie.decodeStream(getResources().openRawResource(mMovieResourceId));
       requestLayout();
    }

    public void setMovieData(Movie movieImg){
        mMovie = movieImg;
        requestLayout();
    }

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
   if(mMovie != null){

       //Find higest
       int exceptedSize = 200;
       int highest = 0;
       int quality = 0;
       if(mMovie.height()>mMovie.width()){
           highest=mMovie.height();
       }else{
           highest=mMovie.width();
       }

       //Get Display Size
       Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay();
       Point size = new Point();
       display.getSize(size);

       setMeasuredDimension((int)(((float)mMovie.width()/(float)highest)*((float) size.x))
               , (int)(((float)mMovie.height()/(float)highest)*((float)size.x)));
   }else{
       setMeasuredDimension(getSuggestedMinimumWidth(), getSuggestedMinimumHeight());
   }
}

@Override
protected void onDraw(Canvas canvas) {
   if (mMovie != null){
       updateAnimtionTime();

       //Get Display Size
       Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay();
       Point size = new Point();
       display.getSize(size);

       float scale = Math.max((float) canvas.getHeight() / (float) mMovie.height(), (float) canvas.getWidth() / (float) mMovie.width());

       canvas.scale(scale, scale);
       canvas.translate(((float) size.x / scale - (float) mMovie.width()) / 2f,
               0);

       drawGif(canvas);
       invalidate();
   }else{
//       drawGif(canvas);
   }
}

private void updateAnimtionTime() {
   long now = android.os.SystemClock.uptimeMillis();

   if (mMovieStart == 0) {
       mMovieStart = now;
   }
   int dur = mMovie.duration();
   if (dur == 0) {
       dur = DEFAULT_MOVIEW_DURATION;
   }
   mCurrentAnimationTime = (int) ((now - mMovieStart) % dur);
}

private void drawGif(Canvas canvas) {
   mMovie.setTime(mCurrentAnimationTime);
   mMovie.draw(canvas, 0, 0);
   canvas.restore();
}

}

Main Activity.class
PlayGifView pGif = findViewById(R.id.viewGif);
pGif.setImageResource(R.drawable.ads1);

activity_main.xml
<com.---- Yours-----.PlayGifView
    android:id="@+id/viewGif"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />


text:
Q: Maintain Perfectly Circular Corners on Variable-Height Element I have a button with perfectly rounded corners; meaning, the button is 50px high and the border radius is 25px, making a perfect half-circle on either side of the button:

Achieving this with CSS is easy, provided you already know the height of the button (button height ÷ 2 = border radius).
But is it possible to maintain the perfectly-circular edges if the button's height increases dynamically (more text is added, for example)?:

A: Just set the border-radius to something high, like 360px.
div {
    height:50px;
    width:500px;
    background:red;
    border-radius:360px;
}

Look at this jsFiddle example to see what I mean.


text:
Q: Sum of NaNs to equal NaN (not zero) I can add a TOTAL column to this DF using df['TOTAL'] = df.sum(axis=1), and it adds the row elements like this:
   col1  col2  TOTAL
0   1.0   5.0    6.0
1   2.0   6.0    8.0
2   0.0   NaN    0.0
3   NaN   NaN    0.0

However, I would like the total of the bottom row to be NaN, not zero, like this:
   col1  col2  TOTAL
0   1.0   5.0    6.0
1   2.0   6.0    8.0
2   0.0   NaN    0.0
3   NaN   NaN    Nan

Is there a way I can achieve this in a performant way?

A: Add parameter min_count=1 to DataFrame.sum:

min_count : int, default 0
  The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.
New in version 0.22.0: Added with the default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1.

df['TOTAL'] = df.sum(axis=1, min_count=1)
print (df)
   col1  col2  TOTAL
0   1.0   5.0    6.0
1   2.0   6.0    8.0
2   0.0   NaN    0.0
3   NaN   NaN    NaN


text:
Q: Moq + Unit Testing + System.Reflection.TargetParameterCountException: Parameter Count mismatch I am getting a "System.Reflection.TargetParameterCountException: Parameter Count mismatch" exception when attempting to mock our ApiClient.
I am using the following code to Setup the Moq response
private void SetupApiClientForGetZones(IEnumerable<Zone> zone)
{
    this.MockHubApiClient.Setup(x => x.GetAsync<IEnumerable<Zone>>(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()))
                .Returns(
                    (string name) =>
                    {
                        return zone == null ? Task.FromResult<IEnumerable<Zone>>(null) : Task.Run(() => zone);
                    });

            this.MockApiClientFactory.Setup(x => x.CreateClient(It.IsAny<string>()))
                .Returns(this.MockHubApiClient.Object);
        }

The iApiClient interface I attempting to Mock is
public interface IApiClientAsync : IApiClient
    {
        Task<string> GetAsync(string apiController);

        Task<T> GetAsync<T>(string apiController) where T : class;

        Task<string> GetAsync(string apiController, IDictionary<string, string> param, string queryString);

        Task<T> GetAsync<T>(string apiController, IDictionary<string, string> param) where T : class;
}

My unit test is
[Test]
public void GetZonesNotCached()
{
    var data = new List<Zone> { new Zone { ZoneId = 1, ZoneName = "Test Zone 1" }, new Zone { ZoneId = 2, ZoneName = "Test Zone 2" } };

    this.SetupApiClientForGetZones(data);

    this.MockCache.Setup(x => x.GetItemFromCache<IEnumerable<Zone>>(It.IsAny<string>()));

    var organisationService = new OrganisationService(this.MockUnitOfWorkAsync.Object, this.MockApiClientFactory.Object, this.MockCache.Object);

    var results = organisationService.GetZones(1, 1).ToList();

    Assert.IsNotNull(results);
    Assert.AreEqual(3, results.Count, "There should be 3 records returned");

    this.MockCache.Verify(x => x.GetItemFromCache<IEnumerable<Zone>>(It.IsAny<string>()), Times.Once());
    this.MockHubApiClient.Verify(x => x.GetAsync<IEnumerable<Zone>>(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()), Times.Once());
}

I have found numerous other posts with the same exception but none of the solutions or examples are the same as mine.
I have been able to successfully Mock the response when calling the GetAsync method that only has the single string paramter.
    private void SetupApiClientForAllDealerDetails(IEnumerable<DealerDetail> dealerDetails)
    {
        this.MockHubApiClient.Setup(
            x => x.GetAsync<IEnumerable<DealerDetail>>(It.IsAny<string>()))
            .Returns(
                (string name) =>
                {
                    return dealerDetails == null ? Task.FromResult<IEnumerable<DealerDetail>>(null) : Task.Run(() => dealerDetails);
                });

        this.MockApiClientFactory.Setup(x => x.CreateClient(It.IsAny<string>()))
            .Returns(this.MockHubApiClient.Object);
    }

Any ideas anyone?

A: If you use an expression in your .Returns instead of a value, then that expression's parameters must match those of the method signature you are mocking.
For example, I found this in SetupApiClientForGetZones:
this.MockHubApiClient.Setup(x => x.GetAsync<IEnumerable<Zone>>(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()))
                .Returns(
                    (string name) =>
                      {
                        return zone == null ? Task.FromResult<IEnumerable<Zone>>(null) : Task.Run(() => zone);
                      });

When really it should be:
this.MockHubApiClient.Setup(x => x.GetAsync<IEnumerable<Zone>>(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()))
                .Returns<string, IDictionary<string, string>>(
                    (name, dict) =>
                      {
                        return zone == null ? Task.FromResult<IEnumerable<Zone>>(null) : Task.Run(() => zone);
                      });