In app purchase live url show sandbox popup and allow subscription for sandbox user

Question: I have added in-app purchase in my application it is working well in sandbox environment but when I change it's URL from sandbox to live and run the application it is behaving unexpectedly.
Here is my code:
Below are the method in which we are requesting to apple for getting in app purchase detail of user.
-(BOOL) getSubscriptionStatusFromAppleWithReceipt:(NSData *) receiptData

{
NSError *error;
NSMutableDictionary *requestContents = [NSMutableDictionary dictionaryWithObject:
                                        [receiptData base64EncodedStringWithOptions:0] forKey:@"receipt-data"];
NSString *sharedSecret = @"*********************";
if (sharedSecret) requestContents[@"password"] = sharedSecret;
NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents options:0 error:&error];

NSString *strUrl = @"";

// Live server
strUrl = @"https://buy.itunes.apple.com/verifyReceipt";

// Devlopment server

//  strUrl = @"https://sandbox.itunes.apple.com/verifyReceipt";
NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl]];
[storeRequest setHTTPMethod:@"POST"];
[storeRequest setHTTPBody:requestData];

queue = [NSOperationQueue mainQueue];

//    NSError *error = nil;
NSHTTPURLResponse *response = nil;

NSData *data = [NSURLConnection sendSynchronousRequest:storeRequest returningResponse:&response error:&error];

if (!error)
{
    NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    if ([jsonResponse[@"latest_receipt_info"] isKindOfClass:[NSArray class]])
    {
        NSArray *receiptInfo = (NSArray *) jsonResponse[@"latest_receipt_info"];
        return [self parseJsonFromAppleServer:receiptInfo];
    }
}
else
{        NSLog(@"%@", error.localizedDescription);
}

return false;

}
And next method in this I m retrieving the last index of receipt array and try to get user's subscription details.
Should I upload it on test flight or any other way in it's differentiation from live to development?
How to test it in live environment.
Thanks
Answer: App should be code-singed with production provisioning profile in order to run IAP with Live server. I think that you can only test with production servers using test flight since app have to be signed by Apple servers.
Comment: "app have to be signed by Apple servers." means do we submit it for beta app review then we can test it?
Comment: You don't have to go through beta review if you are going to test with internal tester accounts.


Syntax in php variable with ' and "

Question: In php, I have a variable with shortcodes using atts:
$ret = 'Link';

I don't know how to manage ' and " in this variable in shortcodes for "title" and "url".
I tried: \"title\" => does not work
[slshar text="title"] = "Titre du post 2"  = "Titre du post 2"
[slshar text="url"]   = "slug of post 2"' = "https;//pur-plan.com/post2"
The result must be :
$ret = 'Link;
I tested the shorcode: every thing is ok and the values returned are ok.
With this syntax, the URL returned is truncated after "?text=". THis is normal because of the "
I hope my explanations are enough for you to help me.
Can you, please, help me to fix that.
Regards,
Bruno
Comment: What is held in your text and url variables on the server side?
Comment: What does "does not work" mean? Are those short codes supposed to be replaced by actual values, or are you trying to transport those shortcodes as URL parameters? If the former: where/when/how are you trying to replace them? If the latter: you need to URL-encode those values since you're trying to transport them in a URL, and then HTML-encode the entire URL since you're trying to put it into HTML.
Comment: You must turn the shortcodes into values separately from the URL, e.g.: `$title = '[slshar text="title"]; $title = shortcode_magic($title);` Then *URL-encode* it, then put it into the URL.
Comment: How `[slshar text="title"]` get changed to `Titre du post` how do these 2 strings relate?
Answer: Thank you for your answers.
I solved the problem with the belowed solution and some css to design the buttons.
If you customize a loop in an archive (with Elementor Custom Skin for exemple), this code displays link to share posts on twitter and facebook.
add_shortcode( 'social-sharing-inf', function ( $atts) {
    extract(shortcode_atts(array(
        'inf'   => '',
    ), $atts));
    global $post;
    switch ( $inf ) {
        case 'twitter' :
            $ret  = 'post_title .'%0DCliquez sur le lien suivant pour y accéder :';
            $ret .= '&url=https://pur-plan.com/' . $post->post_name;
            $ret .= '" onclick="window.open(this.href, \'twitterwindow\',\'left=20,top=20,width=600,height=300,toolbar=0,resizable=1\'); return false;" ';
            $ret .= 'class="share-button-twitter-a">Twitter';
        break;
        case 'facebook' :
            $ret  = 'post_name;
            $ret .= '" onclick="window.open(this.href, \'facebookwindow\',\'left=20,top=20,width=600,height=700,toolbar=0,resizable=1\'); return false;" ';
            $ret .= 'class="share-button-facebook-a">facebook ';
        break;
    }
    wp_reset_postdata();
    return "$ret";
});

and I call with the shortcode: [social-sharing-inf inf="twitter"] and [social-sharing-inf inf="facebook"]
Certainely, this code could be optimized but it works good.
If you have any improvements, I'll take it!

Syntax in php variable with ' and "


JMeter: java.net.SocketException: Connection reset

Question: Once a Login script is executed with few user, I don't see connection reset problem, whereas, when the same is run 100 users, "java.net.SocketException: Connection reset" starts throwing for very first link.
What I don't understand is if there is connection problem, then it should even show the same error for single or few users as well.
Comment: What is the web server you are using? Maybe the MaxConnection is set to a limited number
Answer: It might be the case described in Connection Reset since JMeter 2.10 ? wiki page.
If you are absolutely sure that your server is not overloaded and is configured to accept 100+ connections (defaults are good for development, not for production, they need to be tweaked) you can try work it around as follows:

In user.properties file add the next 2 lines:
httpclient4.retrycount=1
hc.parameters.file=hc.parameters

In hc.parameters file add the following line:
http.connection.stalecheck$Boolean=true

Both files live in JMeter's bin folder.
You need to restart JMeter to pick the properties up.

Above instructions are applicable for HttpClient4 implementation, make sure you use it, the fastest and the easiest way to set HttpClient4 implementation for all the HTTP Request samplers is using HTTP Request Defaults
Answer: This means that your server is rejecting connections because it is either overloaded or misconfigured.
It is regular that you don't face it with 1 user and face it with 100, this is typically what load testing brings, ie simulate traffic on your server


Check extension of choosing picture in SP 2013 Picture Library

Question: I need to check pictures extension when user has chosen picture and try to upload it into picture library.
I've found the way to edit master page with js script, but i haven't to edit master page. Then i try to use event receiver Adding, but it can't get the name of file or file path. I used:
var file = properties.ListItem.File.Name; //properties.ListItem - returns null

AfterProperties also returns null.
The another way i see is to edit Adding Picture form with js:
I think is's simplest way but i can't found information about it.
Problem: how to set js script to the form (see picture) or how to do such actions with another way
Answer: It can be realized with event receiver ItemAdding and with

properties.AfterUrl

The same answered question with code in:
Customizing upload file functionality in SharePoint picture library
Answer: In your case, a simple JS form validation will do.
First I would prevent default action of the submit button.
Then, I would analyze the contents of the filename textbox and check the extention. If it's not one of the listed in the validation script, return false + alert "THis file extention is not supported".
Why would you want to use event receiver? It catches the event on server side.


Different bandwidth utilization in JMeter and in Browser

Question: I am trying to measure bandwidth utilization of a site using WireShark by simultaneously logging in 25 users and performing various activites on site in JMeter
I have recorded a script in JMeter to login and perform activites. But when I perform same activities for 1 user, in Browser and JMeter, I am getting different bandwidth utilization.
Expected result = Bandwidth should be same when same activites are performed in Browser and JMeter for 1 user.
Actual Result = I am getting Avg. 32k bytes/sec in Browser and Avg. 430k bytes.sec in JMeter
Answer: The reason behind this is already in the Jmeter Documentation

JMeter is not a browser, it works at protocol level. As far as web-services and remote services are concerned, JMeter looks like a browser (or rather, multiple browsers); however JMeter does not perform all the actions supported by browsers. In particular, JMeter does not execute the Javascript found in HTML pages. Nor does it render the HTML pages as a browser does.
Comment: useful info for me...however I added think time to each request and the bandwidth is approx. close to Browser.. i.e I am getting 30k bytes/sec in Browser and 32-34k bytes/sec in JMeter.
Comment: Yep, that is already in the doc too. It's possible to view the response as HTML etc., but the timings are not included in any samples, and only one sample in one thread is ever displayed at a time.


Let $\alpha = 2\cos(\frac{2\pi}{7})$. What is the minimal polynomial of $\alpha$ over $\mathbb{Q}$?

Question: Let $\alpha = 2\cos(\frac{2\pi}{7})$. What is the minimal polynomial of $\alpha$ over $\mathbb{Q}$?
After a lot of calculation, I found a polynomial such that $\alpha $ is a root: $f(x) = x^6 + 2x^5 -3x^4 - 6x^3 + 2x^2 + 4x + 1$
Now the problem is, I can't tell if this polynomial is reducible or not. I feel like it's irreducible but all my attempts to prove it have either failed, or become so tedious (I believe there must be a better way). If it's irreducible, is there any way I can show that without resorting to a huge system of equations?

Edit: So according to the comment, $f(x) = (x^3 + x^2 - 2x - 1)^2$. This makes me wonder, is there a way to directly show that $\alpha^3 + \alpha^2 - 2\alpha - 1 = 0$?
The way I originally found the polynomial was by using Chebyshev's method on $\cos(\frac{2\pi}{7})$ and then removing the extra factor $(x-1)$ and then dividing the coefficients by powers of 2 so that $2\cos(\frac{2\pi}{7})$ is a root. However looking at the new polynomial, it looks so simple so I think there must have been a better way, but I don't know what it is.
Comment: It is $(x^3 + x^2 - 2 x - 1)^2$, I got this via [Wolfram Alpha](https://www.wolframalpha.com/input?i=factor+x%5E6+%2B+2x%5E5+-3x%5E4+-+6x%5E3+%2B+2x%5E2+%2B+4x+%2B+1)
Comment: Note, you can use the Euclidean algorithm to efficiently compute $\gcd(f, f') = x^2 + x^2 - 2x - 1$, which gives this same factorization. (We got lucky here since $f$ is a square, but reducing to the squarefree case in this way is the usual first step in general algorithms for factoring polynomials anyway.)
Comment: Thank you, I don't know why it didn't occur to me to use Wolfram Alpha..
Answer: Yes, you can directly show this. This is a classic trick which you can generalise to many similar examples. Let $\zeta=\exp\left(2\pi i\cdot\frac{1}{7}\right)$.
So $\alpha=\zeta+\zeta^{-1}$. Consider that $\zeta^6=\zeta^{-1},\,\zeta^5=\zeta^{-2},\,\zeta^4=\zeta^{-3}$. The symmetry overlaps at $3$, so I am motivated to consider the polynomial: $$(x-(\zeta+\zeta^{-1}))(x-(\zeta^2+\zeta^{-2}))(x-(\zeta^3+\zeta^{-3}))$$Let's use Vieta's formulae. The sum of roots here is: $$\zeta+\zeta^2+\zeta^3+[\zeta^{-3}=\zeta^4]+\zeta^5+\zeta^6=-1$$(consider the geometric series, e.g., it is known that the sum of the roots of the unity is always zero). The product of the first two roots is: $$(\zeta+\zeta^{-1})(\zeta^2+\zeta^{-2})=\zeta^3+\zeta^{-3}+\zeta+\zeta^{-1}=\zeta+\zeta^3+\zeta^4+\zeta^6$$Similarly, the other three products are: $$\zeta^2+\zeta^3+\zeta^4+\zeta^5,\,\zeta+\zeta^2+\zeta^5+\zeta^6$$If we sum all of these we get two copies of each power of $\zeta$, so the sum is $2\cdot(-1)=-2$. You can calculate the product of all three roots as $1$. Vieta then tells us: $$x^3-(-1)x^2+(-2)x-(1)=x^3+x^2-2x-1$$Is the desired polynomial. It is also clear that if you remove any of the roots, we get non-real coefficients. So this cubic is the minimal polynomial that you want!
Answer: Use $\cos 4\theta = \cos 3\theta$. This is satisfied by $4\theta = 2n \pi \pm \cos 3\theta$, so by $\cos\big(\frac{2n \pi}{7} \big)$, but only four of these are distinct (say for $n$ = $0$, $1$, $2$ and $3$). But the equation can also be written $8 \cos^4 \theta -8\cos^2 \theta + 1 = 4 \cos^3 \theta - 3 \cos \theta$, which, on taking out the factor corresponding to the root 1, and dividing the coefficients by powers of 2 as you describe, gives the polynomial you have.


Making an object move in an orbit when I have the x and y coordinates

Question: This code is mostly just the generic start up of a pygame window but I'm trying to make it so the object moves (the planet object I've made) in the orbit around the sun object I've made for the coordinates I've given it. I know the x and y values are updating but I don't understand why the object doesn't move.
#import the library
import pygame
import math

#classes

class button:
    def _init_ (self,screen, colour, x, y, width,height, letter):
        self.screen = screen
        self.colour = colour
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.letter = letter
        self.radius = radius
    def draw(self):
        pygame.draw.rect(self.screen, self.colour,(self.x,self.y, self.width, self.height))
        if self.letter!= '+' and self.letter!= '-':
            font = pygame.font.SysFont('agencyfb',15,True,False)
        else:
            font = pygame.font.SysFont('agencyfb',25,True,False)

        text = font.render(self.letter, True, black)
        text_rect = text.get_rect(center=(self.x+self.width/2,self.y+self.height/2))
        screen.blit(text, text_rect)

class orbit:
    def __init__(self,screen,colour,x,y,radius,width):
        self.screen = screen
        self.colour = colour
        self.x = x
        self.y = y
        self.width = width
        self.radius = radius
    def draw_circle(self):
        pygame.draw.circle(self.screen,self.colour,(self.x,self.y),self.radius,self.width)

#define colours
##Sun = pygame.draw.circle(screen,Sun,[1000,450],100,0)
Black = (0,0,0)
White = (255,255,255)
Green = (0,255,0)
Red = (255,0,0)
Blue = (0,0,255)
Sun = (255,69,0)
Sun = []
Planet = []

#initialise the engine

pygame.init()

#Opening a window

size = (1920,1080)

screen = pygame.display.set_mode(size)

#set window title

pygame.display.set_caption("Orbit Simulator")

#loop unti the user clicks the close button

done = False
#
x=1000
y=450
Sun.append(orbit(screen,Red,1000,450,100,0))
Planet.append(orbit(screen,White,x,y,50,0))

#

#used to manage how fast the screen updates

clock = pygame.time.Clock()
#------ Main program Loop ------

while not done:

    #--- Main event loop

    for event in pygame.event.get(): #user did something

        if event.type == pygame.QUIT: #if user clicked close

            done = True #flag that we are done and exit the loop

    #------ Game logic should go here ------

    #------ Drawing code should go here -------

    #first, clear the screen to white. Don't put other drawing commands above this or they will be erased with this command.

    screen.fill(Black)

    for i in Sun:
        i.draw_circle()
    for i in Planet:
            r=150
            angle=0
            count = 0
            while angle <= 360:

                angle_radians = math.radians(angle)

                x = int(math.cos(angle_radians)*r)
                y = int(math.sin(angle_radians)*r)

                angle +=1
                count +=1
                print(count)
                x+=1000
                y+=450

                pygame.draw.circle(screen,White,[x,y],10,0)

                print("Position [",x,",",y,"]")

    #update the screen

    pygame.display.flip()

    #------ Limit to 60 frames per second ------

    clock.tick(60)

#------ When the loop ends, quit ------

pygame.quit()

Answer: You can make an object rotate around another by using trigonometry or vectors. With vectors you just have to rotate a vector which defines the offset from the rotation center each frame and add it to the position vector (self.pos which is the rotation center) to get the desired self.rect.center coordinates of the orbiting object.
import pygame as pg
from pygame.math import Vector2

class Planet(pg.sprite.Sprite):

    def __init__(self, pos, *groups):
        super().__init__(*groups)
        self.image = pg.Surface((40, 40), pg.SRCALPHA)
        pg.draw.circle(self.image, pg.Color('dodgerblue'), (20, 20), 20)
        self.rect = self.image.get_rect(center=pos)
        self.pos = Vector2(pos)
        self.offset = Vector2(200, 0)
        self.angle = 0

    def update(self):
        self.angle -= 2
        # Add the rotated offset vector to the pos vector to get the rect.center.
        self.rect.center = self.pos + self.offset.rotate(self.angle)

def main():
    pg.init()
    screen = pg.display.set_mode((640, 480))
    screen_rect = screen.get_rect()
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    planet = Planet(screen_rect.center, all_sprites)
    yellow = pg.Color('yellow')

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return

        all_sprites.update()
        screen.fill((30, 30, 30))
        pg.draw.circle(screen, yellow, screen_rect.center, 60)
        all_sprites.draw(screen)

        pg.display.flip()
        clock.tick(60)

if __name__ == '__main__':
    main()
    pg.quit()

Comment: Here's a link to a pygame sprite and sprite group tutorial if you haven't learned about them yet: http://programarcadegames.com/index.php?chapter=introduction_to_sprites#section_13
Comment: Thank you that helps massively


Android IllegalStateException: attempt to use Inflater after calling end

Question: Here is my Stacktrace:
<StackTrace>java.lang.IllegalStateException: attempt to use Inflater after calling end
    at java.util.zip.Inflater.checkOpen(Inflater.java:332)
    at java.util.zip.Inflater.setInput(Inflater.java:312)
    at com.android.okhttp.okio.InflaterSource.refill(InflaterSource.java:106)
    at com.android.okhttp.okio.InflaterSource.read(InflaterSource.java:62)
    at com.android.okhttp.okio.GzipSource.read(GzipSource.java:80)
    at com.android.okhttp.okio.RealBufferedSource$1.read(RealBufferedSource.java:374)
    at java.io.InputStream.read(InputStream.java:162)
    at com.myProgram.services.DownloadService.onHandleIntent(DownloadService.java:58)
    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:158)
    at android.os.HandlerThread.run(HandlerThread.java:61)
</StackTrace>

and here is the code from DownloadService:
 InputStream input = connection.getInputStream();
 byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            Bundle resultData = new Bundle();
            resultData.putInt("progress" ,(int) (total * 100 / fileLength));
            receiver.send(U_PROGRESS, resultData);
            output.write(data, 0, count);
        }

58 line is:
while ((count = input.read(data)) != -1) {

This error occurs in random cases. Download service is used to download new version of the app.
Answer: Note that you cannot close the downloading InputStream from a different thread than your download service (i.e. the one which is calling InputStream.read).
Do you have another thread that by any chance is trying to close the stream using InputStream.close() api? such a behavior will cause this kind of runtime exception. On more recent versions of OkHttp, a somewhat similar exception will be produced from the closing thread. See below for a reference: https://github.com/square/okhttp/issues/1842


For a number field $K$, is an integer a sum of two $K$'s elements squares iff it is a sum of two integer squares?

Question: Sorry for my bad English.
There is a famous problem of elementally number theory as follow;
Is an integer a sum of two rational squares iff it is a sum of two integer squares?
Now I want know about this generalization for a number field.
i.e. is the next Prop. true?

Let $K$ be any algebraic number field ,and $\mathscr{O}_K$  be ring of integers  of $K$.
For any $a\in \mathscr{O}_K$, $a$ can be written as $r^2+s^2$ for some $r,s\in K$ iff can be written as $b^2+c^2$ for some $b,c\in \mathscr{O}_K$.
Answer: This is not true. For example, let $K=\Bbb{Q}(i)$ with
$\mathcal{O}_K=\Bbb Z[i]$. Then
$$
i = \left(\frac{1+i}{2}\right)^2 + \left(\frac{1+i}{2}\right)^2.
$$
This shows $i$ is a sum of two squares in $\Bbb {Q}(i)$.
However, it is impossible to write $i$ as a finite sum of squares in ${\Bbb Z}[i]$ since
$$
(a+bi)^2 = a^2 - b^2 + 2abi
$$
has even imaginary part when $a$ and $b$ are in $\Bbb {Z}$.  Thus any finite sum of squares in $\Bbb {Z}[i]$ has even imaginary part, so such a sum can't be equal to $i$.


Why can't I insert values to a list?

Question: I have a problem with a part of my program in Python 3.7.
It's a program, where you can add vocabulary with their translation in any language to a .txt file and this program can ask you a word and you enter the translation - this is working fine.
Receiving this data works also very good. But I also want to save the two languages, which you enter in the program, to this .txt file.
I can add these two to the first line of the .txt file and if I try to print the first line of this file it also works, but I need to split the two values of the text file, because they are written like this in the text file (f.e):
German - English
Finally I want to add this two split values to a new list. But if I try to print the first value of the list, I get following error:

IndexError: list index out of range

and if I check if the list is empty, I can see that it is empty, but why?
Thanks for your help
This is my code, which is responsible for this error:
new_currSprache = []

with open(name + ".txt", "r") as file:
    lines = file.readlines()
    for lines[0] in file.readlines():
        lang_1, lang_2 = lines[0].split(" - ")
        print(lang_1)
        print(lang_2)
        new_currLanguage.append(lang_1, lang_2)
    firstLanguage = new_currLanguage[0]
    secondLanguage = new_currLanguage[1]

Answer: You don't need to go through all the lines, and split already returns a list
with open(name + ".txt", "r") as file:
    lines = file.readlines()
    new_currLanguage  = lines[0].split(" - ")
    firstLanguage = new_currLanguage[0]
    secondLanguage = new_currLanguage[1]

Comment: Thank you, it works!!! Yes, it was stupid to go through all the lines :)
Thank you very much!!!

Why can't I insert values to a list?


Can dispensers (with a bucket) empty a cauldron?

Question: I've been experimenting in 1.17.1 (Java), particularly with the new dripstone. However, I've been unable to figure out a way to empty filled cauldrons. At first, I thought it was a problem of aiming the dispenser correctly, but I've now got a setup where it is directly above the cauldron and aiming downwards.
Can I expect this to work? Or will it just dump the empty bucket into the lava cauldron?
Answer: No, that is not going to work. A dispenser cannot perform that type of functionality. This also applies to attempting to dispense into cauldrons, it will just dump a full bucket out.
Strangely enough, this is actually a bug: when items that would behave specially are inserted into the dispenser but the block conditions aren't met, the dispenser should just stop instead of ejecting the item like a dropper, similar to how bonemeal works, not ejecting the bonemeal if there is a problem.


How do I handle a transition from concrete to dirt underneath a flagstone patio?

Question: I had a pool installed a few years ago and the builder threw in a narrow concrete patio around it. See fuzzy picture below (sorry about that. Google earth must be a little tipsy tonight).
So now that I've paid off the pool, I'm thinking of putting down a flagstone patio, but the trick is that I want to extend it beyond the paltry concrete patio that already exists (dotted square around pool).
I assume it will be a pretty easy job to lay down the stone on top of a nice level concrete patio, but I am a little concerned about how to make the transition between the concrete part and the grass part.
(1) Is this even advisable, or should I just extend the concrete out to the entire area I want for the patio before laying stone (adding considerable cost)?
(2) Assuming I don't extend the concrete, what should I do when the stone transitions from the concrete subsurface to the dirt? I'm nervous that cracks will occur over time, and I'd like to do whatever I can to avoid that.
Comment: did the pics come from a brownie on the space station?  lololol
Comment: Google Earth just doesn't have very good resolution at my location. That's all.
Answer:
(1) Is this even advisable, or should I just extend the concrete out to the entire area I want for the patio before laying stone (adding considerable cost)?

Rolls-Royce job (Money no object): Extend the concrete slab out to the area you wish to pave or remove the existing slab and start allover again.

(2) Assuming I don't extend the concrete, what should I do when the stone transitions from the concrete subsurface to the dirt? I'm nervous that cracks will occur over time, and I'd like to do whatever I can to avoid that.

Good enough job (and what most paving pro's would do, at least the ones I know back in the UK): Excavate 6 to 8 inches (150 to 200mm) from the area you want to extend into. Back fill that area with sub-base (crushed rock) material. Back fill in 2 to 3 inch (50 to 75mm) layers, each layer should be "properly" compacted. This will give you a sub-base that is "nearly" as good/stable as the existing concrete slab.

Something to consider, regardless of chosen method, how is the paving area going to drain? Do you need to put in some sort of drainage system , thus preventing the surrounding softscape from flooding due to the new hardscape?
Answer: you can dig a foundation square where your dotted line is. atleast 15CM wide and 10cm foundation. You dont need to put a concrete slab on the whole thing. The trick is to cemeent the last slabs to the foundation. at an angle so that the grass/ground go. Like inside the blue lines.

This is not a brilliant autocad picture but it illustrates how to end your tiles. The red is cement/adhesive to the foundation. The length of the foundation should be atleast 1 tile flat. The poles in the ground are optional. If you have clayish ground you should use those and about 1 metre long. If you have topsoilish sand that does not tend to move due to moisture then dont worry about it.
The squigly line is the natural grass/ground level and the straight brown area is hard/compacted not dug ground. Obvoisly the picture is not brilliant but you need sand under your tiles that i missed out. where on the concrete the adhevsive/cement will make up the height for the sand layer!
I hope this makes sense - I have done many paved areas like this and its a great long lasting solution.


C++/CLI error C1189 when I Include marshal library

Question: I've got a application that is communicating with a PLC.
I have some libraries included for the communication but when I add marshal:
#include <msclr\marshal_cppstd.h>
it gives me the following error:
C1189: #error: The C++ Standard Library forbids macroizing keywords. Enable warning C4005 to find the forbidden macros.
C4005: 'inline': macro redefinition
this C4005 warning shows in
xkeycheck.h line 203 which contains:
#define inline EMIT WARNING C4005
and I get a ton more of errors(1800+).
So what does this error mean?
Comment: Might help: [xkeycheck.h and macro defined keywords](https://social.msdn.microsoft.com/Forums/vstudio/en-US/6cb13b36-1da5-49ec-895c-e002dfb7546a/xkeycheckh-and-macro-defined-keywords?forum=vcgeneral)
Comment: @crashmstr and how do I define `_ALLOW_KEYWORD_MACROS` in my project settings?
Comment: C++ preprocessor settings to use for all files or add `#define ...` in the problem file above there the include that is causing the error.
Comment: xkeycheck.h already contains `_ALLOW_KEYWORD_MACROS`
Comment: Not in my copies (Visual Studio 2015 or 2010), but you would need to set it in the project settings or `#define` it before the first time that file is included.
Comment: Doesn't make a difference, when I at the `_ALLOW_KEYWORD_MACROS ` it gives errors about my library. Kinda frustrating this isn't working. Just simply adding a .h file and it won't run anymore. And I know this is about defining or including stuff twice...
Comment: I'm guessing the libraries you are using have some things in the header that won't play well. If you can build a native C++ DLL or library first (to isolate the usage of the header into non-CLR code), then build a C++/CLI wrapper, that might work.
Comment: I'm new to C++/CLI, this is my first project working with some libraries and including them. Building a DLL or library isn't an option for me.
Comment: Then you might need to put the inclusion of the header files in a seperate file that does not use the C++/CLI functionality and then have C or C++ functions that use the library but don't require the usage of the header file elsewhere.
Comment: Yea, never mind I should find something else to convert my `unsigned char to System::String`.
Comment: `marshal_cppstd.h` is for converting to/from standard C++ strings (`std::string` and `std::wstring`). You can use `marshal.h` for C strings (you can search this site for examples).
Comment: I've read something also about converting `unsigned char` to `System::String^`. [link](http://www.codeproject.com/Articles/19579/Using-and-extending-the-Orcas-marshal-as-library#_comments)
Answer: inline is a C++ keyword which this #define is re-defining. It's warning you that it's pretty risky to change the meaning of inline.
msclr\marshal_cppstd.h has functions marked with inline so this is probably the first occurrence of code using the re-defined inline definition and it's realizing that it is probably not what you're expecting.
I would question why xkeycheck.h is redefining inline -- perhaps inlining is not allowed with their library?  Perhaps you need to push/pop the definition of inline around your include or #undef inline before your include?
Update: Did more research, I was assuming xkeycheck was from the PLC code. It's not.  So, xkeycheck is set up to report this error if it sees that you've redefine any of the C++ keywords. inline in this case.    As I said above, marshal_cppstd.h actually uses inline so that's the first sign of trouble and it's emitting the warning.   So.... my advice is to search all your code and find out where you or a header you include has #define'd inline to something else.
I would put the cursor on inline and press F12 to go to the definition.


(VB 2010) Label's Text extends from it's locked size. How do I scroll to last line?

Question: I've been writing a program that calls batch files (which download some stuff). I've added a label that reports the download progress to the user. The program is going to allow for multiple downloads so at some point the Label will be full of text. When that happens, the text extends from the label and I can't see any of it. What I want is to have the label scroll to the newer line of text added in the label. In other words I want to always have the focus of the label text to be on the last written line. Can some1 post an example that can do this on a label ?
Comment: Not sure why it doesn't work for you but the point is, don't use a label.
Comment: I would suggest you use a listbox for this. Labels don't have the functionality to do what you are asking. The closest you can do is right-align the text so you always see the end, as opposed to the beginning.
Comment: Thnx for your input. What do you mean by "right-align" the text ?
Comment: Click on the label. In the properties window find the property "Text Alignment", change it from top-left to ?-right.
Comment: I already have the text aligned to the Bottom Right. All it does is that the text starts from there and goes upward. When the text reaches the top, then it stops showing me the new lines.
Answer: Similar to Steve's comment I would recommend using a multiline text box or RichText control for this purpose.  You can set the control's ReadOnly property to True, and the ScrollBars property to Both.
When adding new text to this control, you can use the following code to ensure that it is visible to the user:
TextBox2.AppendText('New text')
TextBox2.SelectionStart = TextBox2.Text.Length
TextBox2.ScrollToCaret()


Radio Buttons in the header?

Question: Our web app allows users to switch between (currently 3, potentially more in the near future) different "contexts". For example, they could choose to view the app from the point of view of a "Corporation", "Small Business" or "Single User". Each of these "contexts" provide something additional to the application as a whole, targeted (obviously) to a specific kind of user.
Currently, we use a drop-down menu that allows our users to swap between these "contexts". Our Project Manager has proposed using radio buttons instead of the drop-down approach. To me, radios just seem wrong in that context. I see radios as a "form element", and certainly not something that belongs in a header. I spend most of my time on StackOverflow, which clearly isn't the place for this kind of question, so I just wanted to get some input from some seasoned UX guys.
What do you think?
Answer: Drop-down boxes tend to be the more common pattern, and because most 'view controls' try to use as little viewport estate as possible, the space-saving properties of a dropdown are useful. If a radio button is laid out vertically, it'll take up a lot of space, but if it's horizontal, it's hard to scan, because users can't seek left to right as effectively as top to bottom.
So, the key difference is that:

radio buttons make all choices visible constantly, but are harder to scan
dropdowns are space efficient and attractive, but don't show all possibilities at once

Only you can really say, knowing your context, which set of advantages trumps the other, but as your 'views' rarely change, I can't really imagine how seeing all choices would help. A radio button will, as I say, take up space, which means you'll have to change your form should you start adding items to the list, or other elements to the control - and that change creates cognitive friction for your users. Unless there's a compelling reason, stick to the dropdowns.
Answer: Perhaps you could ask the PM if any of the users are sometimes utility companies, sometimes commercial entities, and sometimes residential users.
If in fact, as seems likely, users align with one category only, they'll probably want to set it and forget it.
Comment: Our users are most certainly "one type of user". Very rarely are, say, Utility users going to want to do stuff from a Residential point of view. I agree that set-it-and-forget-it is the best bet here.
Answer: Dropdown is a much better option. I see two main reason for using them:
1) Convention. Other websites have already trained your users to work with this setup.
2) Since you are planning to add more options, radio buttons can run out of space pretty fast, considering that you have them in the header. Dropdowns offer much greater flexibility.
I try to limit the use of dropdown, but in your cases, they are a much better option.
Answer: What is the rational you have been given for wanting to change from drop-down to radio buttons? Are users finding it confusing at the moment? If there's a valid reason for changing then it would be worth investigating why.
The problem you'll have if you try to switch to radio buttons in the header is that it's going to be harder to tell which radio button belongs to which label. For example, at a glance is it the Commercial Entity or Residential User that's selected here:

Also, you'll find it difficult making space for when you add extra ones in at a later date. No, stick with the drop-down, it's more 'future proof' allows longer labels and takes up much less space.
Comment: Lets just change things is rarely a good start to any design change.
Comment: The rationale was that he wanted to change things up. There wasn't any real *thought* about it. I agree that radio buttons can be tough to associate with the correct label for the user, resulting in the wrong selection sometimes. Space is also a concern of mine. The way I see it (and the fact that the drop-down is **very** clear in its function), there's no reason to switch to a potentially less-clear concept.
Answer: Jquery's Button function makes radio buttons look like nice big buttons which still show a mutually exclusive state.
Here's the default style, though it has poor "pressed" affordance:

As Matt Rockwell indicated these are very common in mobile apps to keep "screens" in a single logical container. You're doing a similar thing with your website, but the jquery buttons let you have a good looking (normal radio buttons look too much like a form control) and customization solution that has the same functionality as radio buttons.
Answer: Twitter uses a "segmented control" as it is termed by Apple (in this case it is used in conjunction with a search field - together called a "scope bar") , but really what it is is a collection of radio buttons. This works very well, and Facebook uses this as well on its mobile app.

This is easily understandable, clean and a great solution to your problem, unless the number of options available exceed 5 or 6, then a drop down would be more appropriate.
Comment: I agree that segmented controls can be nice for mobile apps, but that isn't the context we're working with. I'm not sure there's enough precedent for it on the desktop, and I don't want to argue something that might be confusing for users. Any examples of this in use _outside_ the mobile environment?
Comment: Try apple.com :) They use it for their nav, but the concept is similar.

Radio Buttons in the header?


Why can't I purchase more of the same weapon?

Question: So I bought Fable: The Lost Chapters on Steam during the year-end sale.  However, I can't seem to purchase multiple of the same type of weapon - for weapons I've already purchased, the entry on the vendor list is grayed out.  The vendors do have sufficient inventory for me to buy the item.
I'm trying to maintain a bit of a theme here; is there any way for me to be able make these purchases?
Answer: In Fable, you cannot own more than one of the same weapon or item of clothing.
Comment: This is what I suspect, but do you have any references for this?  I'd appreciate something official, if it exists.  I find this restriction stupid and annoying - especially because I could have sworn I was given a duplicate of something after I'd previously bought one.
Comment: @Clockwork-Muse It's possible you received a variation of what you already had, like "Dark Mage Robes" when you already have "Light Mage Robes" or something like that.
Comment: @Clockwork-Muse You can find duplicates in chests or from certain events but you don't receive another item.


How can I add a dependency on Siddhi CEP to my pom.xml file?

Question: Does anyone know how to add a dependency on the latest version of Siddhi CEP (preferably without cloning the source)? I tried (from the Github repo):
<dependency>
    <groupId>org.wso2.siddhi</groupId>
    <artifactId>siddhi</artifactId>
    <version>3.0.0-SNAPSHOT</version>
</dependency>

But I get a missing dependency error. Pretty sure this is because I don't know enough about Maven, but I haven't been able to figure this out so far.
Update - as requested. all of the pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>examples</artifactId>
        <groupId>eu.ferari</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>examples.distributedcount</artifactId>
    <build>
    <plugins>
    <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4.1</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>eu.ferari.examples.distributedcount.misc.Coordinator</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>${commons.version}</version>
        </dependency>
        <dependency>
            <groupId>com.espertech</groupId>
            <artifactId>esper</artifactId>
            <version>${esper.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>${gson.version}</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>${jedis.version}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>${hamcrest.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>${mockito.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>eu.ferari</groupId>
            <artifactId>ferari-core</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.storm</groupId>
            <artifactId>storm-core</artifactId>
            <version>${storm.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>log4j-over-slf4j</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>logback-classic</artifactId>
                    <groupId>ch.qos.logback</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.siddhi</groupId>
            <artifactId>siddhi-core</artifactId>
            <version>0.4.0</version>
        </dependency>
    </dependencies>
</project>

Comment: Can you post the rest of your pom? So if you clone the project. One of the modules is the dependency your talking about
Answer: Finally stumbled on the answer. First you need to add to you pom.xml file:
<repositories>
    <repository>
        <id>WSO2</id>
        <url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
    </repository>
</repositories>

Then add the following dependencies:
<dependency>
    <groupId>org.wso2.siddhi</groupId>
    <artifactId>siddhi-core</artifactId>
    <version>3.0.0-M1</version>
</dependency>
<dependency>
    <groupId>org.wso2.siddhi</groupId>
    <artifactId>siddhi-query-api</artifactId>
    <version>3.0.0-M1</version>
</dependency>
<dependency>
    <groupId>org.wso2.siddhi</groupId>
    <artifactId>siddhi-query-compiler</artifactId>
    <version>3.0.0-M1</version>
</dependency>
<dependency>
    <groupId>org.antlr</groupId>
    <artifactId>antlr4-runtime</artifactId>
    <version>4.5</version>
</dependency>

Answer: Please include following 3 dependencies and try
<dependency>
    <groupId>org.wso2.siddhi</groupId>
    <artifactId>siddhi-core</artifactId>
    <version>3.0.0-SNAPSHOT</version>
</dependency>
<dependency>
    <groupId>org.wso2.siddhi</groupId>
    <artifactId>siddhi-query-api</artifactId>
    <version>3.0.0-SNAPSHOT</version>
</dependency>
<dependency>
    <groupId>org.wso2.siddhi</groupId>
    <artifactId>siddhi-query-compiler</artifactId>
    <version>3.0.0-SNAPSHOT</version>
</dependency>

Comment: I think it's almost there. The only problem I now have is that when I run one of the samples I get an exception which doesn't happen when I add the Siddhi source to the project. `Exception in thread "main" java.lang.NoClassDefFoundError: org/antlr/v4/runtime/atn/ATNDeserializer
 at org.wso2.siddhi.query.compiler.SiddhiQLLexer.(SiddhiQLLexer.java:506)
 at org.wso2.siddhi.query.compiler.SiddhiCompiler.parse(SiddhiCompiler.java:52)
 `
Comment: For that error did you include antlr dependency?

dependency>
                org.antlr
antlr4-runtime
4.5
Comment: I made a mistake. I'm actually getting a `Missing artifact org.wso2.siddhi:siddhi-core:jar:3.0.0-SNAPSHOT pom.xml` on all 3 dependencies. Looking into my .m2 directory I see the path `repository/org/wso2/wso2/1/` which contains .pom, .sha, .md5 and .repositories files but no jars.
Answer: I'm not sure what you've done already, but.
(Assuming you've got Git installed)
Open Cmd
git clone https://github.com/wso2/siddhi.git

Open Eclipse (assuming more)
Also have m2e (Maven 2 Eclipse as plugin)
then import Maven project, point to the main directory. This will import all of the subpackages as well...
The dependency you are referring to is the main pom op that project...
I hope I'm clear... It's hard to guess what you have and work with
(btw, I know it can be a pain to start working with GIT and Maven,,, but later... :-) )
Comment: Is there no way to add the dependency without cloning the source?
Comment: too old... http://maven-repository.com/search?q=siddhi ... Only really old (3 years) http://mvnrepository.com/search?q=siddhi
Comment: Yep, definitely too old. This is v0.4 and they're up to 3.0 by now.
Comment: If this project is really important to you, I could try to help you overcome the difficulties you are facing. Theoretically there is a 'chat' function here (don't know where)


How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

Question: I have ViewPager and below it I have 10 buttons. By clicking on button, for example #4, the pager goes immediately to page #4 by mPager.setCurrentItem(3);. But, I want to disable the paging by swiping with finger horizontally. Thus, the paging is done ONLY by clicking on the buttons.
So, how I can disable the swiping with finger?
Comment: With ViewPager2, disabling the swipe takes just one line of code: https://stackoverflow.com/questions/54978846/how-to-disable-swiping-in-viewpager2
Comment: How about using [ViewFlipper](https://developer.android.com/reference/android/widget/ViewFlipper) in the first place? It will save you a great deal of a headache.
Answer: You need to subclass ViewPager.  onTouchEvent has a lot of good things in it that you don't want to change like allowing child views to get touches.  onInterceptTouchEvent is what you want to change.  If you look at the code for ViewPager, you'll see the comment:
    /*
     * This method JUST determines whether we want to intercept the motion.
     * If we return true, onMotionEvent will be called and we do the actual
     * scrolling there.
     */

Here's a complete solution:
First, add this class to your src folder:
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;
import java.lang.reflect.Field;

public class NonSwipeableViewPager extends ViewPager {

    public NonSwipeableViewPager(Context context) {
        super(context);
        setMyScroller();
    }

    public NonSwipeableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        setMyScroller();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Never allow swiping to switch between pages
        return false;
    }

    //down one is added for smooth scrolling

    private void setMyScroller() {
        try {
            Class<?> viewpager = ViewPager.class;
            Field scroller = viewpager.getDeclaredField("mScroller");
            scroller.setAccessible(true);
            scroller.set(this, new MyScroller(getContext()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class MyScroller extends Scroller {
        public MyScroller(Context context) {
            super(context, new DecelerateInterpolator());
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/);
        }
    }
}

Next, make sure to use this class instead of the regular ViewPager, which you probably specified as android.support.v4.view.ViewPager.  In your layout file, you'll want to specify it with something like:
<com.yourcompany.NonSwipeableViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

This particular example is in a LinearLayout and is meant to take up the entire screen, which is why layout_weight is 1 and layout_height is 0dp.
And setMyScroller(); method is for smooth transition
Comment: This answer does not prevent page swiping when using the keyboard left/right keys (try it in the emulator). May not be a problem for touch devices but with TV and laptops it may be one.
Comment: @MarvinLabs @Thorbear The correct way to disable the page scroll by keyboard is to override the `executeKeyEvent()`.
This is the method that then call `allowScroll()`.

`// Never allow swiping by keyboard LEFT, RIGHT, TAB and SHIFT+TAB keys`
`@Override public boolean executeKeyEvent(KeyEvent event) { return false; }`
Comment: well, this disables also the vertical scrolling... this is bad, if you're using listviews.
Comment: I hope google could have just provided a method to which we supply our interface method on how to handle touches/swiping because I believe it wouldn't hurt?
Comment: @louielouie On a side-note: is there any particular reason, why you chose the `0dp` height/`1` weight solution over `match_parent` height to achieve the full-screen effect? Do you gain performance improvements by doing so?
Comment: Still scroll page little bit. but if you keep swipe it it will eventually scrolling the page.
Comment: relying on variable name "mScroller" which can be changed in future is not a good solution.
Comment: First, don't override `onInterceptTouchEvent()` - it will prevent child views to receive input. Second, don't use reflection to get access to private fields (especially in production systems) - you might get problems in the future. Third, read documentation on what result `onTouchEvent()` should return. Forth, to disable 'swipes by little bit' you can try overriding the following method:
`protected void onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
            scrollTo(0, 0);
 }`.
Comment: It worked for me, but I'm including this "static" ViewPager inside another ViewPager and at this page I can't swipe parent ViewPager. How can I get this to work?
Comment: @ubuntudroid For the answer to the 0dp height/1 weight, please read this Q&A: http://stackoverflow.com/questions/12016781/why-is-0dp-considered-a-performance-enhancement
Comment: Something I missed or someone else would miss: Don't forget to change all ViewPager classes in your Java file to NonSwipeableViewPager. Don't miss any. Great answer!
Comment: @MarvinLabs In order to prevent paging through keyboard (dpad) you can override `arrowScroll()` in the same way the other methods are overridden (or even the same way as the one suggested in the answer by @Rajul ).
Comment: @louielouie in your answer you mentioned that you can use onTouchEvent to allow child views to receive touches.Can you make items inside a recyclerview which is the child of a ViewPager swipeable with this method?
Comment: working fine for me. I was having a problem previously that i disable swiping between pager but the editext able to swipe the pager.
Comment: @louielouie how can i use that programical ?
Comment: Remember use <com.yourcompany.yourproject.NonSwipeableViewPager instead <com.yourcompany.NonSwipeableViewPager to remove of the error: InflateException: Binary XML file line Error inflating class
Answer: The more general extension of ViewPager would be to create a SetPagingEnabled method so that we can enable and disable paging on the fly.
To enable / disable the swiping, just overide two methods: onTouchEvent and onInterceptTouchEvent. Both will return "false" if the paging was disabled.
public class CustomViewPager extends ViewPager {

    private boolean enabled;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.enabled = true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.enabled) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.enabled) {
            return super.onInterceptTouchEvent(event);
        }

        return false;
    }

    public void setPagingEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}

Then select this instead of the built-in viewpager in XML
<mypackage.CustomViewPager
    android:id="@+id/myViewPager"
    android:layout_height="match_parent"
    android:layout_width="match_parent" />

You just need to call the setPagingEnabled method with false and users won't be able to swipe to paginate.
Comment: You can simplify your `onTouchEvent` and `onInterceptTouchEvent` methods with `return enabled && super.onTouchEvent(event);`
Comment: I would also recommend changing the name of field from "enabled" to "swipePageChangeEnabled" or something like that. A month after writing the code you'll hardly remember what "enabled" means, especially when your class is called "CustomViewPager", where it isn't clear what the customization is.
That's also a matter of style, but style matters if you don't want to end up with unsupportable project, that is easier to rewrite completely than to fix it.
Comment: Where do I call setPagingEnabled? ._.
Comment: Works perfectly for a view that has several subviews where one uses horizontal scrolling (eg. AChartEngine chart). In my fragment I use a callback to my activity telling it to turn or off the paging depending on if the user touched (ACTION_MOVE) the chart or left it (ACTION_CANCEL). Thanks a lot!
Comment: @Ntikki, you may call `setPagingEnabled()` method after you declare your `ViewPager` like this: `CustomViewPager yourCustomViewPager = (CustomViewPager) findViewById(R.id.yourCustomViewPager); yourCustomViewPager.setPagingEnabled(false)`
Comment: Why are you returning `false` in `onTouchEvent()` and `onInterceptTouchEvent()`? This way touching the pager titles (or icons) will do the swipe. Return `true` instead to disable also that.
Comment: after I setPagingEnabled() to true, all of the views inside the layout become non click able...it is just like there is a transparent wall overlay on top of the layout
Comment: @Rajul hey great code snippet.How could this be modified so that it enables paging to the right and paging to the left respectively?
Comment: this is how it should be done - enabled/disable it as you need
Answer: Now we no need to create custom ViewPager
A new ViewPager2  name View available in android

Vertical orientation support

ViewPager2 supports vertical paging in addition to traditional horizontal paging. You can enable vertical paging for a ViewPager2 element by setting its android:orientation attribute

Using XML

<androidx.viewpager2.widget.ViewPager2
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:orientation="vertical" />

Using code

To disable swiping in viewpager2 use
viewPager2.setUserInputEnabled(false);

To enable swiping in viewpager2 Use
viewPager2.setUserInputEnabled(true);

for more information check this

ViewPager2
ViewPager2 under the Hood
Hands on With ViewPager2

UPDATE

Please check : Migrate from ViewPager to ViewPager2

For complete example please check this Use of ViewPager2 in Android
Comment: It's great, but still looks to be incomplete. I've tried it out with 5 different fragments and after switching between pages one of fragments was kind of lost, i.e. view wasn't neither restored nor re-inflated
Comment: @PhaniRithvij please check this answer https://stackoverflow.com/a/54643817/7666442 i Have added all details how to use `viewpager2` with `RecyclerView.Adapter`
Comment: @Toochka sorry to hear that for me it's working fine you can find the sample working code from here https://stackoverflow.com/a/54643817/7666442 if possible please share your code
Comment: @PhaniRithvij its ok let me know if you required any help
Comment: In ViewPager2 you cannot control animation speed. Its defaulted to slow. So ViewPager is better for customization
Answer: The simplest way is to setOnTouchListener and return true for ViewPager.
mPager.setOnTouchListener(new OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            return true;
        }
    });

Comment: Does not work sometimes. I'm using a ViewPager with a FragmentPagerAdapter and several Fragment . After setting OnTouchListener to pager, if I fling left, the UI will still move to left a little bit.
Comment: It works when you add `pager.setCurrentItem(pager.getCurrentItem());` before returning `true`.
Comment: This is a PARTLY working solution. Horizontal swipes are handled in some strange way. I tested this with a Drag'n Drop Gridview as part of a ViewPager. When dragging using this solution, dragging from left to right and right to left fails. Personally I find Rajul's approach the best.
Comment: seems to work for me.

To solve some layout glitches i have
`public int getItemPosition(Object object) {
        return POSITION_NONE;
    }`in my adapter, which forces recreation of pages and maybe solving other problems too.
Comment: On Android 6 (haven't tested on any other versions yet) if you click and drag left many times you can see the view pager swiping left. It is very funny.
Answer: Overriding only onTouchEvent and onInterceptTouchEvent is not sufficient in case you have ViewPager itself inside another ViewPager. Child ViewPager would steal horizontal scroll touch events from parent ViewPager unless it is positioned on its first / last page.
To make this setup work properly you need to override also the canScrollHorizontally method.
See LockableViewPager implementation below.
public class LockableViewPager extends ViewPager {

    private boolean swipeLocked;

    public LockableViewPager(Context context) {
        super(context);
    }

    public LockableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public boolean getSwipeLocked() {
        return swipeLocked;
    }

    public void setSwipeLocked(boolean swipeLocked) {
        this.swipeLocked = swipeLocked;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return !swipeLocked && super.onTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return !swipeLocked && super.onInterceptTouchEvent(event);
    }

    @Override
    public boolean canScrollHorizontally(int direction) {
        return !swipeLocked && super.canScrollHorizontally(direction);
    }

}

Comment: Thank you, this works very well on a ViewPager inside another ViewPager.
Comment: This works for me, also for a ViewPager inside another ViewPager. The correct solution didn't work for me in that case.
Comment: stops animation too when used in tabs.
Comment: If I disable it and suppose I want to enable it then where I can get the event to call setSwipeLocked(false)?
Answer: Better to declare it styleable, so you can change its property from xml:
private boolean swipeable;

public MyViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyViewPager);
    try {
        swipeable = a.getBoolean(R.styleable.MyViewPager_swipeable, true);
    } finally {
        a.recycle();
    }
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    return swipeable ? super.onInterceptTouchEvent(event) : false;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    return swipeable ? super.onTouchEvent(event) : false;
}

And in your values/attr.xml:
<declare-styleable name="MyViewPager">
  <attr name="swipeable" format="boolean" />
</declare-styleable>

so that you can use it in you layout xml:
<mypackage.MyViewPager
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/viewPager"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:swipeable="false" />

Of course, you can still have a get/set property.
Answer: If you are extending from ViewPager, you must also override executeKeyEvent as indicated previously by @araks
@Override
public boolean executeKeyEvent(KeyEvent event)
{
    return isPagingEnabled ? super.executeKeyEvent(event) : false;
}

Because some devices like the Galaxy Tab 4 10' show these buttons where most devices never show them:
Comment: Samsung is always screwing things up for Android devs.
Comment: @toobsco42 Samsung is not alone in this instance. SwiftKey (popular keyboard app) allows users to put arrows on their keyboards.
Comment: This is also the fix if you want to stop someone using a keyboard/trackerball from paging your pager.
Answer: To disable swipe
mViewPager.beginFakeDrag();

To enable swipe
mViewPager.endFakeDrag();

Comment: It's not a good solution because it allows small portions of movement, at least in my app.
Answer: I needed to disable swiping on one specific page, and give it a nice rubber-band animation, here's how:
    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {
            if (position == MANDATORY_PAGE_LOCATION && positionOffset > 0.5) {
                mViewPager.setCurrentItem(MANDATORY_PAGE_LOCATION, true);
            }
        }

Comment: It waits until the next page is partly visible. A code for the next page in `onPageSelected` will be executed. Even the next page will switch. So, this code doesn't do needed.
Answer: I wrote a CustomViewPager with a swiping control:
public class ScrollableViewPager extends ViewPager {
    private boolean canScroll = true;
    public ScrollableViewPager(Context context) {
        super(context);
    }
    public ScrollableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public void setCanScroll(boolean canScroll) {
        this.canScroll = canScroll;
    }
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return canScroll && super.onTouchEvent(ev);
    }
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return canScroll && super.onInterceptTouchEvent(ev);
    }
}

If you set canScroll to true, this ViewPager can be swiping with finger, false on the contrary.
I use this in my project, and it works great until now.
Comment: What if i have a button inside the ViewPager and i want the click? this solution stops everything below viewpager to be clicked..
Comment: I did not have the issue that @aimiliano had. I have multiple clickable items in my ViewPager and that all worked fine with this solution. This worked perfectly for me!
Answer: If your are using ViewPager2 you just have to use:
viewpager.setUserInputEnabled(false);
From the docs:

Enable or disable user initiated scrolling. This includes touch input (scroll and fling gestures) and accessibility input. Disabling keyboard input is not yet supported. When user initiated scrolling is disabled, programmatic scrolls through setCurrentItem still work. By default, user initiated scrolling is enabled.

Thanks to: https://stackoverflow.com/a/61685871/9026710
Answer: I know it's mighty late to post this but here's a tiny hack to achieve your outcome ;)
Simply add a dummy view below your viewpager:
<android.support.v4.view.ViewPager
     android:layout_width="match_parent"
     android:layout_height="match_parent">
</android.support.v4.view.ViewPager>

<RelativeLayout
     android:id="@+id/dummyView"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
</RelativeLayout>

Then add a OnClickListener to your RelativeLayout.
dummyView = (RelativeLayout) findViewById(R.id.dummyView);

dummyView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
         //Just leave this empty
    }
});

Get a bit creative with layouts, their placements and their behaviour and you'll learn to find a way to do absolutely anything that you imagine :)
Good luck!
Comment: wouldn't this also block touches within the viewpager?
Comment: An easier way is use `setClickable` instead of `setOnClickListener`, if you don't need to handle `onClick` event.
Comment: Yes it will. It's the expected behaviour required by OP @androiddeveloper
Comment: @RickGrimesTheCoder I don't think you understood my question. I mean views within the viewpager's fragments. Will they still be touchable?
Comment: No they will not be since the viewpager itself has a click listener. This is only suitable for instances where you don't have interactive elements within the fragments. For example a Welcome ViewPager that changes its fragments dynamically @androiddeveloper
Answer: in kotlin
viewPagerNavigation.isUserInputEnabled = false

Answer: I used this class with success. Overriding the executeKeyEvent is required to avoid swiping using arrows in some devices or for accessibility:
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;

public class ViewPagerNoSwipe extends ViewPager {
    /**
     * Is swipe enabled
     */
    private boolean enabled;

    public ViewPagerNoSwipe(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.enabled = false; // By default swiping is disabled
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return this.enabled ? super.onTouchEvent(event) : false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return this.enabled ? super.onInterceptTouchEvent(event) : false;
    }

    @Override
    public boolean executeKeyEvent(KeyEvent event) {
        return this.enabled ? super.executeKeyEvent(event) : false;
    }

    public void setSwipeEnabled(boolean enabled) {
        this.enabled = enabled;
    }

}

And in the xml call it like this:
<package.path.ViewPagerNoSwipe
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Comment: It works. Only swipe is disabled and clicking on a tab is enabled. AS warns that `performClick()` method is not overriden.
Answer: In Kotlin, my solution, combining above answers.
class CustomViewPager(context: Context, attrs: AttributeSet): ViewPager(context, attrs) {
    var swipeEnabled = false

    override fun onTouchEvent(ev: MotionEvent?): Boolean {
        return if (swipeEnabled) super.onTouchEvent(ev) else false
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return if (swipeEnabled) super.onInterceptTouchEvent(ev) else false
    }

    override fun executeKeyEvent(event: KeyEvent): Boolean {
        return if (swipeEnabled) super.executeKeyEvent(event) else false
    }
}

Comment: Overriding `onInterceptTouchEvent()` will prevent child views to receive input. In most cases this is not the intended behavior.
Comment: I was able to interact with child views of each fragment.  Not sure what you are referring to.
Comment: This did the trick for me - thanks! And yes - I am also able to interact with child views. Swipes, taps, etc.
Answer: In kotlin, we can solve this by creating a custom widget inheriting the ViewPager class and adding a flag value for controlling swipe behavior.
NoSwipePager.kt
class NoSwipePager(context: Context, attrs: AttributeSet) : ViewPager(context, attrs) {

    var pagingEnabled: Boolean = false

    override fun onTouchEvent(event: MotionEvent): Boolean {
        return if (this.pagingEnabled) {
            super.onTouchEvent(event)
        } else false
    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        return if (this.pagingEnabled) {
            super.onInterceptTouchEvent(event)
        } else false
    }
}

In xml
<your.package.NoSwipePager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/tab_layout" />

Disable swiping programmatically. If kotlin-android-extensions plugin is applied in build.gradle, swiping can be disabled by writing below code.
view_pager.pagingEnabled = false

Otherwise we can disable swiping using code below:
val viewPager : ViewPager = findViewById(R.id.view_pager)
viewPager.pagingEnabled = false

Comment: Overriding `onInterceptTouchEvent()` will prevent child views to receive input. In most cases this is __not__ the intended behavior.
Comment: How is this relevant to the current question? Fragments are placed inside some containers (which are __Views__) and their own layout contains __Views__. No matter what content I have inside the ViewPager, I am still dealing with the fact that overriding `onInterceptTouchEvent()` method prevents it (content) from receiving input.
Comment: @AlexSemeniuk Had you observed any problem after implementing this? I had enabled swiping on recycler view items for some actions and it is working fine. So the implementation is working fine in my case.
Comment: Sagar Chapagain: or course, I did. Each of my pages contains custom view, which processes touches in various ways (including scrolling, dragging, single and long taps). Not calling `super.onInterceptTouchEvent(event)` results in these views not receiving any input (which is the documented purpose of `onInterceptTouchEvent` method).
Comment: If that is the case you should rather use child fragment and maintain backstack.
Answer: Try overriding and returning true from either onInterceptTouchEvent() and/or onTouchEvent(), which will consume touch events on the pager.
Comment: wouldn't he want to return `true` to imply the touch event has been handled?
Answer: None of the above code is working smoothly.i tried this
<HorizontalScrollView
                    android:id="@+id/horizontalScrollView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:fillViewport="true">

                    <android.support.v4.view.ViewPager
                        android:id="@+id/pager"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" />
                </HorizontalScrollView>

Answer: Another easy solution to disable swiping at specific page (in this example, page 2):
int PAGE = 2;
viewPager.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
        if (viewPager.getCurrentItem() == PAGE) {
                viewPager.setCurrentItem(PAGE-1, false);
                viewPager.setCurrentItem(PAGE, false);
                return  true;
        }
        return false;
}

Answer: If you write an image gallery with ImageViews and ViewPager, that supports zoom and pan, see a simple solution described here: Implementing a zoomable ImageView by Extending the Default ViewPager in Phimpme Android  (and Github sample - PhotoView). This solution doesn't work with ViewPager alone.
public class CustomViewPager extends ViewPager {
    public CustomViewPager(Context context) {
        super(context);
    }

    public CustomViewPager(Context context, AttributeSet attrs)
    {
        super(context,attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        try {
            return super.onInterceptTouchEvent(event);
        } catch (IllegalArgumentException e) {
            return false;
        }
    }
}

Answer: This worked for me

viewPager.setOnTouchListener(new View.OnTouchListener() {
                                         @Override
                                         public boolean onTouch(View v, MotionEvent event) {
                                             if (viewPager.getCurrentItem() == 0) {
                                                 viewPager.setCurrentItem(-1, false);
                                                 return true;
                                             }
                                             else if (viewPager.getCurrentItem() == 1) {
                                                 viewPager.setCurrentItem(1, false);
                                                 return true;
                                             }
                                             else if (viewPager.getCurrentItem() == 2) {
                                                 viewPager.setCurrentItem(2, false);
                                                 return true;
                                             }
                                             return true;
                                         }
                                     });

Answer: * NonSwipebleViewPager for kotlin

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.animation.DecelerateInterpolator
import android.widget.Scroller
import androidx.viewpager.widget.ViewPager
import java.lang.reflect.Field

class NonSwipebleViewPager : ViewPager {
    constructor(context: Context?) : super(context!!) {
        setMyScroller()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) {
        setMyScroller()
    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        return false
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        return false
    }

    private fun setMyScroller() {
        try {
            val viewpager: Class<*> = ViewPager::class.java
            val scroller: Field = viewpager.getDeclaredField("mScroller")
            scroller.isAccessible = true
            scroller.set(this, MyScroller(context))
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    inner class MyScroller(context: Context?) :
        Scroller(context, DecelerateInterpolator()) {
        override fun startScroll(
            startX: Int,
            startY: Int,
            dx: Int,
            dy: Int,
            duration: Int
        ) {
            super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/)
        }
    }
}

Answer: If you dont want any type of scroll horizontal or vertical from user fingers then you can try -
yourViewPager.isUserInputEnabled = false

use "isUserInputEnabled ".
Answer: If you want to implement the same for Android in Xamarin, here is a translation to C#
I chose to name the attribute "ScrollEnabled". Because iOS just uses the excat same naming. So, you have equal naming across both platforms, makes it easier for developers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V4.View;
using Android.Util;

namespace YourNameSpace.ViewPackage {

    // Need to disable swiping for ViewPager, if user performs Pre DSA and the dsa is not completed yet
    // http://stackoverflow.com/questions/9650265/how-do-disable-paging-by-swiping-with-finger-in-viewpager-but-still-be-able-to-s
    public class CustomViewPager: ViewPager {
        public bool ScrollEnabled;

        public CustomViewPager(Context context, IAttributeSet attrs) : base(context, attrs) {
            this.ScrollEnabled = true;
        }

        public override bool OnTouchEvent(MotionEvent e) {
            if (this.ScrollEnabled) {
                return base.OnTouchEvent(e);
            }
            return false;
        }

        public override bool OnInterceptTouchEvent(MotionEvent e) {
            if (this.ScrollEnabled) {
                return base.OnInterceptTouchEvent(e);
            }
            return false;
        }

        // For ViewPager inside another ViewPager
        public override bool CanScrollHorizontally(int direction) {
            return this.ScrollEnabled && base.CanScrollHorizontally(direction);
        }

        // Some devices like the Galaxy Tab 4 10' show swipe buttons where most devices never show them
        // So, you could still swipe through the ViewPager with your keyboard keys
        public override bool ExecuteKeyEvent(KeyEvent evt) {
            return this.ScrollEnabled ? base.ExecuteKeyEvent(evt) : false;
        }
    }
}

In .axml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <YourNameSpace.ViewPackage.CustomViewPager
      android:id="@+id/pager"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:background="@android:color/white"
      android:layout_alignParentTop="true" />
</LinearLayout>

Answer: here is my implementation
that if you want to disable the swipe animation you can you use the swipeListener left and right and still want the scroll by finger but without animation
1-Override Viewpager method onInterceptTouchEvent and onTouchEvent
2- create your own GestureDetector
3- detect the swipe gesture and use  the setCurrentItem(item, false)
ViewPager
public class ViewPagerNoSwipe extends ViewPager {
    private final GestureDetector gestureDetector;
    private OnSwipeListener mOnSwipeListener;

    public void setOnSwipeListener(OnSwipeListener onSwipeListener) {
        mOnSwipeListener = onSwipeListener;
    }

    public ViewPagerNoSwipe(@NonNull Context context) {
        super(context);
        gestureDetector = new GestureDetector(context, new GestureListener());

    }

    public ViewPagerNoSwipe(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        gestureDetector = new GestureDetector(context, new GestureListener());

    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return true;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        gestureDetector.onTouchEvent(ev);
        return false;
    }

    public class GestureListener extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            if(mOnSwipeListener!=null)
                            mOnSwipeListener.onSwipeRight();
                        } else {
                            if(mOnSwipeListener!=null)
                                mOnSwipeListener.onSwipeLeft();
                        }
                        result = true;
                    }
                } else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        if(mOnSwipeListener!=null)
                            mOnSwipeListener.onSwipeBottom();
                    } else {
                        if(mOnSwipeListener!=null)
                            mOnSwipeListener.onSwipeTop();
                    }
                    result = true;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }

    public interface OnSwipeListener {

         void onSwipeRight();

        void onSwipeLeft();

        void onSwipeTop();

        void onSwipeBottom();
    }
}

the when you are set up the ViewPager set the swipeListener
postsPager.setOnSwipeListener(new ViewPagerNoSwipe.OnSwipeListener() {
            @Override
            public void onSwipeRight() {

              postsPager.setCurrentItem(postsPager.getCurrentItem() + 1,false);

            }

            @Override
            public void onSwipeLeft() {

            postsPager.setCurrentItem(postsPager.getCurrentItem() - 1, false);

            }
             ...
           }

Answer: I just customized the viewpager a little and disable swiping easily.
public class CustomViewPager extends ViewPager {

private boolean swipeLocked;

public CustomViewPager(Context context) {
    super(context);
}

public CustomViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public boolean getSwipeLocked() {
    return swipeLocked;
}

public void setSwipeLocked(boolean swipeLocked) {
    this.swipeLocked = swipeLocked;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    return !swipeLocked && super.onTouchEvent(event);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    return !swipeLocked && super.onInterceptTouchEvent(event);
}

@Override
public boolean canScrollHorizontally(int direction) {
    return !swipeLocked && super.canScrollHorizontally(direction);
}
}

Answer: shareViewPager?.setOnTouchListener(object :View.OnTouchListener{
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                for (PAGE in 0..shareViewPager.adapter!!.count){
                    if (shareViewPager.currentItem==PAGE){
                        shareViewPager.setCurrentItem(PAGE-1,false)
                        shareViewPager.setCurrentItem(PAGE,false)
                    }}
                return true
            }

        })


How to summarise a data frame based on values occurring at unique data points in a particular column?

Question: I've got a data frame df given by:
r  t s      v
1  1 a   4.50
2  1 b   3.00
3  2 c   3.22
4  3 d   2.00
5  3 a   5.00
6  1 c   1.00
7  1 f  14.00
8  2 b 144.00
9  3 c   2.00
10 4 a  22.00
11 2 a   2.20
12 3 e 232.00
13 4 g  45.00
14 3 g   4.30
15 3 b   3.20
16 4 b   2.00
17 4 c   2.60

and I want to convert this into another data frame df1 as
r t    a     b    c  d   e    f  g
1 1  4.5   3.0 1.00 NA  NA 14.0 NA
2 2  2.2 144.0 3.22 NA  NA   NA NA
3 3  5.0   3.2 2.00  2 232 NA 4.3
4 4 22.0   2.0 2.60 NA  NA NA 45.0

where the colnames in df1 are the unique values from s column in df and they are grouped by their occurrence in t column in df.
There won't be any duplicates of 's' in each 't' so it can be assumed that each 's' only appears once for every 't' value.
Is there an easy way (using dplyr or similar) to manipulate the data in df to get df1?
Comment: Possible duplicate of [How to reshape data from long to wide format?](https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format)
Comment: When you have multiple rows with the same values of `t` & `s`, what do you want to do with the `v`'s? Would you want to average them, sum them, take the median, etc?
Comment: Try `library(reshape2); dcast(dat[-1], t ~ s)` then add column `r` if needed. Your expected output for cols `f` and `g` seems not correct.
Comment: I also used `reshape2`: `df1 <- dcast(df, t ~ s, value.var = "v")` . Example result is off.
Answer: I'm inferring that you might be having problems using answers from the duplicate target because you have included the row number as a column. We can spread on the table without the r column.Note that there are two values in rows 3 and 4 of the output which you appear to have misclassified in the example output; they should be under g and not f.

library(tidyverse)
tbl <- read_table2(
"t s      v
1 a   4.50
1 b   3.00
2 c   3.22
3 d   2.00
3 a   5.00
1 c   1.00
1 f  14.00
2 b 144.00
3 c   2.00
4 a  22.00
2 a   2.20
3 e 232.00
4 g  45.00
3 g   4.30
3 b   3.20
4 b   2.00
4 c   2.60"
)
tbl %>%
  spread(s, v)
#> # A tibble: 4 x 8
#>       t     a     b     c     d     e     f     g
#>   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1     1   4.5   3    1       NA    NA    14  NA
#> 2     2   2.2 144    3.22    NA    NA    NA  NA
#> 3     3   5     3.2  2        2   232    NA   4.3
#> 4     4  22     2    2.6     NA    NA    NA  45

Created on 2019-02-11 by the reprex package (v0.2.1)
Comment: Hi, we can assume that there won't be any duplicates for 's' in each 't' so only one value of 's' is present per 't' value.


Linq Orderby compares with itself. Why?

Question: Summary: when using Linq OrderBy with a comparer, I see that OrderBy compares items with themselves Compare (x, x), and I see that it compares the same items Comparer (x, y) several times.

Why does OrderBy Compare (x, x)?
Why does OrderBy compare the same item several times?

Problem description
If you have a (possibly empty) sequence of items, and you want the largest one, you could use OrderBy(...).FirstOrDefault().
I thought, it would be a waste of processing power to Order thousands of items if you will only be using the largest one. You could try to find this largest element in one enumeration, by creating some kind of Max method.
Similarly, if you search for the largest few elements: why order all items?
I heard someone say, that if you use OrderBy and take only the first element, then not the complete sequence is ordered.
So I thought to create a test program, where I order Customers using a Customer comparer. To see which Customers are comparer, the customer comparer writes the Id of the customers to the Console.
class Customer
{
    public int Id {get; set;}
    ...
}

class CustomerComparer : Comparer<Customer>
{
    public override int Compare(Customer x, Customer y)
    {
        int result = Comparer<int>.Default(x.Id, y.Id);
        Console.WriteLine("Compare {0} - {1} => {2}", x.Id, y.Id, result);
        return result;
    }
}

The console program
static void Main(string[] args)
{
    var customers = new[]
    {
        new Customer {Id = 2},
        new Customer {Id = 9},
        new Customer {Id = 6},
        new Customer {Id = 1},
        new Customer {Id = 4},
        new Customer {Id = 7},
        new Customer {Id = 3},
        new Customer {Id = 8},
        new Customer {Id = 5},
    };

    IComparer<Customer> comparer = new CustomerComparer;
    var result = customers.OrderBy(customer => customer, customerComparer).FirstOrDefault();

If I run the program I get the following output:
Compare 4 - 2 => 1
Compare 4 - 9 => -1
Compare 4 - 5 => -1
Compare 4 - 8 => -1
Compare 4 - 3 => 1
Compare 4 - 6 => -1
Compare 4 - 7 => -1
Compare 4 - 4 => 0
Compare 4 - 1 => 1
Compare 4 - 6 => -1
Compare 4 - 1 => 1
Compare 3 - 2 => 1
Compare 3 - 3 => 0
Compare 3 - 1 => 1
Compare 3 - 4 => -1
Compare 3 - 4 => -1
Compare 3 - 1 => 1
Compare 2 - 2 => 0
Compare 2 - 1 => 1
Compare 4 - 4 => 0
Compare 4 - 3 => 1
Compare 9 - 6 => 1
Compare 9 - 7 => 1
Compare 9 - 9 => 0
Compare 9 - 5 => 1
Compare 9 - 8 => 1
Compare 9 - 9 => 0
Compare 9 - 8 => 1
Compare 7 - 6 => 1
Compare 7 - 7 => 0
Compare 7 - 8 => -1
Compare 7 - 5 => 1
Compare 6 - 6 => 0
Compare 6 - 5 => 1
Compare 7 - 7 => 0
Compare 7 - 8 => -1
Compare 7 - 7 => 0

Some strange things is what I see:

Customer [4] is compared with itself seveal times. This is also for Customers [7] and [6], but not for Customers [8] and [1]
Customer [4] is compared with Customer [6], and a few comparisons later, Customer [4] is compared with Customer [6] again.
Customers [3] and [4] are compared twice without any other comparisons in between.
Double comparison is also for Customers [4] and [1], and a bit later for [4] and [3] but not for the other Customers

Why would this be an efficient sorting algorithm?
Comment: For comparison-based sorting algorithms, comparisons are typically assumed to be cheap (as opposed to rearranging elements). It would of course be possible to weed out redundant comparisons or cache them (trading space for time) but this would typically regress performance. Few sorting algorithms guarantee the *minimum* number of comparisons necessary, as opposed to an order of magnitude.
Answer: As mentioned by Jeroen Mostert, it is probably comparing elements against itself to make the algorithm simpler, and simplicity can in some cases can improve performance. I would expect sorting algorithms to be fairly well optimized, so I would not worry about a few extra comparisons. Also note that Orderby is guaranteed to be stable, and this might place extra restrictions on the algorithm.
To solve the problem of returning the largest value I would suggest creating your own implementation that iterates over the collection and returns the smallest/largest. This is fairly trivial to do. Or use something like MoreLinq MaxBy / MinBy

I heard someone say, that if you use OrderBy and take only the first element, then not the complete sequence is ordered.

The internal workings of OrderBy is not documented. In theory, the runtime could inspect the whole sequence of linq calls and produce optimal code.
Edit:

In .Net core 3.x and later does seem to optimize this to O(n) (thanks to Matthew Watson for pointing this out).
In .Net framework it looks like it will create a EnumerableSorter that ends up doing a quicksort of the entire thing, presumably a stable variant. i.e. O(n log n)
In entity framework the query should be translated to SQL and run thru a query optimizer, probably resulting in O(n) (or better) runtime.
Comment: .Net Core 3.x and later definitely does the optimisation where if you are only taking the first item, it is `O(N)` rather than `O(Log(N))` (but only for Linq-to-objects). But as you say, this is not documented so you can't rely on it!
Comment: @Matthew Watson, thank your for the information, that was news to me.

Linq Orderby compares with itself. Why?


How do I interpret the format of the .flame files used by apophysis?

Question: I pulled a .zip file from https://www.deviantart.com/clairejones/art/Apophysis-Starter-Flames-V-67029474 and the file I was interested was the .flame file which contains parameters for several different Fractal Flames.
One of them looks like this:
<flame name="CJ_Starter_Flame_1" version="Apophysis 2.06c beta" size="640 512" center="0.536884822382779 -0.626382357937026" scale="764.167485097157" angle="1.82997772071605" rotate="-104.85" oversample="2" filter="1" quality="5" background="0 0 0" brightness="2" gamma="5" >
   <xform weight="0.5" color="0" linear="0.98505982500501" spherical="0.0149401749949902" coefs="0.047466 -0.574133 0.524841 0.137706 0.620555 -0.116118" />
   <xform weight="0.5" color="1" spherical="0.17593513103202" bubble="0.82406486896798" coefs="0.268823 -0.261644 0.261644 0.268823 0.204257 0.083402" />
   <palette count="256" format="RGB">
      253625384A3348593D5C664C6E685B7A7260827363938169
...
   </palette>
</flame>

Having read the original Draves & Reckase paper some of this is obvious.  The coefs= probably contains the parameters of the affine transform.  The thing that really confuses me is how a single xform clause mentions two variants, e.g. linear and spherical.  It appears that the values on each attribute sum to 1 so they are probably weights/probabilities.  But why are there two xform clauses?  Are they alternating weighted transform sets?
Answer: There is some information about the XML file format used for .flame files. There are a number of forks of this program written in different languages, the original site is by definition the place to go for answers; unless you are using a fork - the original  seems to have been abandoned years ago.
Coefs is 6 floats which defines the coefficients for the affine part of the function, in row order (a d b e c f). Xform has an interpolation_type which is a string describing the method for interpolation of xform positions: options are "log", "linear", "old", etc. (a list of a few dozen options is here). There can be multiple xforms, each applies a transformation to the previous state.
The spherical transform is complex, there's a 19 page .docx tutorial with 9 pages of examples at: "Understanding Spherical Transforms: Apophysis Tut" by UniversalKinase (direct link to .ZIP file). Another tutorial is "Apo-Tuto Sphericals" by Fiery-Fire.


How to map a value to another in Django Rest

Question: The class_name is a numeric field corresponding to the player's character class.
I want to map those values to the character class name and display it in the serializer.
class Character(models.Model):
   name = models.CharField(primary_key=True, max_length=10)
   level = models.IntegerField(blank=True, null=True)
   class_name= models.SmallIntegerField(blank=True, null=True)
   pk_count = models.IntegerField(blank=True, null=True)
   resets = models.SmallIntegerField(blank=True, null=True)

class CharacterSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Character
        fields = ('name', 'level', 'class_name', 'pk_count', 'resets')

Current Output
{
  "name": "Player1",
  "level": 250,
  "class_name": 1,
  "pk_count": 200,
  "resets": 27
}

Desired Output
{
  "name": "Player1",
  "level": 250,
  "class_name": "Warrior",
  "pk_count": 200,
  "resets": 27
}

Is it possible to map this values?
Something like that { 1 : "Warrior" }
Thanks everyone.
Answer: In your class:
class Character(models.Model):
    name = models.CharField(primary_key=True, max_length=10)
    level = models.IntegerField(blank=True, null=True)
    class_name= models.SmallIntegerField(blank=True, null=True)
    pk_count = models.IntegerField(blank=True, null=True)
    resets = models.SmallIntegerField(blank=True, null=True)
    #add a dict for your values
    values = {'1':'Warrior','2':'Whatever'}

    @property
    def class_name_value(self):
          return values[self.class_name] if values[self.class_name] else 'default'

And then your serializer:
class CharacterSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Character
        fields = ('name', 'level', 'class_name_value', 'pk_count', 'resets')

Answer: dmitryro's answer is a good way to easily get access to those mapped values anywhere in the site.  Another way to map a value to the field name, only within the serializer in question, would be to use a SerializerMethodField
class CharacterSerializer(serializers.ModelSerializer):
    class_name = serializers.SerializerMethodField()

    class Meta:
        model = models.Character
        fields = ('name', 'level', 'class_name', 'pk_count', 'resets')

    def get_class_name(self, obj):
        try:
            return obj.values[str(obj.class_name)]
        except KeyError:
            return 'default'