working on it ...

Filters

Explore Public Snippets

Sort by

Found 40k snippets

    public by ronrihoo modified Friday at 3:37:37 AM  122  0  5  0

    Example usage for the BackgroundColor class

    Companion usage example for the arbitrary libGDX Table BackgroundColor class.
    BackgroundColor backgroundColor = new BackgroundColor("white_color_texture.png");
    backgroundColor.setColor(2, 179, 228, 255); // r, g, b, a
    table.setBackground(backgroundColor);																														

    public by ronrihoo modified Friday at 3:13:48 AM  88  0  4  0

    Example helper class for GDXFacebook

    This helper class simplifies the usage of GDXFacebook in libGDX games and apps. (This is a backup to https://github.com/ronrihoo/GDX-Facebook-API-Helper and it's used in https://stackoverflow.com/a/46230835/6664817)
    // add package here
    
    import com.badlogic.gdx.Application;
    import com.badlogic.gdx.Gdx;
    import com.badlogic.gdx.utils.Array;
    import de.tomgrill.gdxfacebook.core.*;
    
    public class FacebookApi {
    
        private final static String CLASS_NAME = FacebookApi.class.getSimpleName();
        private final static String ERR_IN = "Error: in " + CLASS_NAME;
        private final static String EXC_IN = "Exception: in " + CLASS_NAME;
    
        private final static boolean VERBOSE_DEFAULT = true;
        private final static boolean DEBUG_DEFAULT = true;
    
        private boolean verbose;
        private boolean debug;
    
        private Array<String> permissions;
    
        private GDXFacebookConfig config;
        private GDXFacebook facebook;
        private GDXFacebookAccessToken token;
    
        /* if there's a class where credentials are stored or retrieved from,
         * then a constructor like this one could be used
         */ /*
        public FacebookApi() {
            this(Credentials.FB_API_ID);
        }
        /**/
    
        public FacebookApi(String appId) {
            this(appId, null, null);
        }
    
        /**
         *
         * @param appId The Facebook API ID is required.
         * @param prefFilename Optional (example: ".facebookSessionData").
         * @param apiVersion Optional. Graph API Version (default: v2.6).
         */
        public FacebookApi(String appId, String prefFilename, String apiVersion) {
            init(appId, prefFilename, apiVersion, DEBUG_DEFAULT);
        }
    
        private void init(String appId, String prefFilename,
                          String apiVersion, boolean debug) {
            setVerbose(VERBOSE_DEFAULT);
            setDebug(debug);
            if (appId != null) {
                setAppId(appId);
            } else {
                try {
                    throw new RuntimeException(EXC_IN +
                            ".init(...): appId is null. Has it been passed correctly?");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (prefFilename != null)
                setPrefFilename(prefFilename);
            if (apiVersion != null)
                setGraphApiVersion(apiVersion);
            initPermissionsArray();
            installGdxFacebookInstance();
            setGdxFacebookInstance();
            addBasicPermissions();
        }
    
        private void setGdxDebug(boolean debug) {
            debugLog("setGdxDebug(boolean debug)");
            if (debug)
                Gdx.app.setLogLevel(Application.LOG_DEBUG);
            // TODO: turn it off when debug == false
        }
    
        private void instantiateConfig() {
            debugLog("instantiateConfig()");
            config = new GDXFacebookConfig();
        }
    
        private boolean verifyConfig() {
            debugLog("verifyConfig()");
            if (config == null) {
                try {
                    instantiateConfig();
                }
                catch (Exception e) {
                    System.out.println(EXC_IN + ".verifyConfig(): \n" + e);
                    return false;
                }
            }
            return true;
        }
    
        private void setAppId(String appId) {
            debugLog("setAppId(String appId)");
            if (verifyConfig())
                config.APP_ID = appId;
        }
    
        private void setPrefFilename(String filename) {
            debugLog("setPrefFilename(String filename)");
            if (verifyConfig())
                config.PREF_FILENAME = filename;
        }
    
        private void setGraphApiVersion(String version) {
            debugLog("setGraphApiVersion(String version)");
            if (verifyConfig())
                config.GRAPH_API_VERSION = version;
        }
    
        private void installGdxFacebookInstance() {
            debugLog("installGdxFacebookInstance()");
            if (verifyConfig())
                facebook = GDXFacebookSystem.install(config);
        }
    
        /**
         * No parameters, as it is handled by GDXFacebookSystem
         */
        public void setGdxFacebookInstance() {
            debugLog("setGdxFacebookInstance()");
            if (facebook != null)
                facebook = GDXFacebookSystem.getFacebook();
        }
    
        /**
         *
         * @return GDXFacebook object.
         */
        public GDXFacebook getGdxFacebookInstance() {
            debugLog("getGdxFacebookInstance()");
            return facebook;
        }
    
        private void initPermissionsArray() {
            debugLog("initPermissionsArray()");
            permissions = new Array<String>();
        }
    
        private void addBasicPermissions() {
            debugLog("addBasicPermissions()");
            permissions.add("email");
            permissions.add("public_profile");
            permissions.add("user_friends");
        }
    
        public void addPermission(String permission) {
            debugLog("addPermission(String)");
            if (permissions != null)
                permissions.add(permission);
            else
                System.out.println(ERR_IN + ": permissions array is null");
        }
    
        /**
         * Basic sign-in with read-mode
         */
        public void signIn() {
            debugLog("signIn()");
            signIn(SignInMode.READ);
        }
    
        public void signIn(SignInMode signInMode) {
            debugLog("signIn(SignInMode)");
            if (facebook != null) {
                if (permissions == null) {
                    addBasicPermissions();
                    debug(CLASS_NAME +
                            ": returned to signIn(SignInMode) from addBasicPermissions()");
                }
                facebook.signIn(signInMode, permissions, new GDXFacebookCallback<SignInResult>() {
    
                    @Override
                    public void onSuccess(SignInResult result) {
                        if (verbose)
                            System.out.println("Successfully signed in Facebook.");
                        token = result.getAccessToken();
                        debug(CLASS_NAME + ".signIn() succeeded.");
                        debug(CLASS_NAME + ": accessToken is " + token);
                    }
    
                    @Override
                    public void onError(GDXFacebookError error) {
                        if (debug)
                            System.out.println(ERR_IN + ".signIn(): " +
                                    error.getErrorMessage());
                        debug("signIn() invoked by GDXFacebook instance, facebook, in " +
                                CLASS_NAME + " faced an error.");
                    }
    
                    @Override
                    public void onCancel() {
                        // When the user cancels the login process
                        debug("signIn() invoked by GDXFacebook instance, facebook, in " +
                                CLASS_NAME + " canceled.");
                    }
    
                    @Override
                    public void onFail(Throwable t) {
                        // When the login fails
                        debug("signIn() invoked by GDXFacebook instance, facebook, in " +
                                CLASS_NAME + " failed.");
                    }
                });
            } else {
                debug(ERR_IN + ".signIn(): " +
                        "GDXFacebook instance, facebook, is null.");
            }
        }
    
        public void signOut() {
            debug(CLASS_NAME + ".signOut()");
            facebook.signOut();
        }
    
        protected void setVerbose(boolean verbose) {
            this.verbose = verbose;
        }
    
        protected void setDebug(boolean debug) {
            this.debug = debug;
            setGdxDebug(debug);
        }
    
        private void debug(String msg) {
            if (debug)
                System.out.println(msg);
        }
    
        private void debugLog(String methodName) {
            if (verbose)
                debug(CLASS_NAME + "." + methodName);
        }
    
    }

    public by ronrihoo modified Sep 9, 2017  203  3  5  1

    libGDX Table background color

    Create an instance of this class by giving the constructor the filename of a white PNG from your project resources. Then, use one of the instance's setColor(red, green, blue, alpha) methods. Finally, pass the instance to the libGDX Table using the Table's setBackground(Drawable drawable) method. This is not meant to be a perfect solution for all --
    import com.badlogic.gdx.Gdx;
    import com.badlogic.gdx.graphics.Color;
    import com.badlogic.gdx.graphics.Texture;
    import com.badlogic.gdx.graphics.g2d.Batch;
    import com.badlogic.gdx.graphics.g2d.Sprite;
    import com.badlogic.gdx.graphics.g2d.TextureRegion;
    import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
    
    public class BackgroundColor implements Drawable {
    	
    	private Float x;
    	private Float y;
    	private Float width;
    	private Float height;
    	
    	private Boolean fillParent;
    	
    	private String filename;
    	private Texture texture;
    	private TextureRegion textureRegion;
    	private Sprite sprite;
    	private Color color;
    	
    	public BackgroundColor(String filename) {
    		this(filename, 0.0f, 0.0f, 0.0f, 0.0f);
    	}
    	
    	public BackgroundColor(String filename, float x, float y) {
    		this(filename, x, y, 0.0f, 0.0f);
    	}
    	
    	public BackgroundColor(String filename, float x, float y, float width, float height) {
    		this.setPosition(x, y);
    		this.setSize(width, height);
    		initialize(filename);
    	}
    	
    	private void initialize(String filename) {
    		setFilename(filename);
    		if (x == null || y == null)
    			setPosition();	// x = 0.0f; y = 0.0f;
    		if (width == null || height == null || width < 0.0f || height < 0.0f)
    			setSize();		// width = 0.0f; height = 0.0f;
    		if (color == null)
    			setColor(255, 255, 255, 255);
    		if (sprite == null) {
    			try {
    				setSprite();
    			} catch (Exception e) {
    				System.err.println(e);
    			}
    		}
    		if (fillParent == null)
    			fillParent = true;
    	}
    	
    	private void setTexture() {
    		if (texture != null)
    			texture.dispose();
    		texture = new Texture(Gdx.files.internal(getFilename()));
    	}
    	
    	private void setTextureRegion() {
    		textureRegion = new TextureRegion(texture, (int) getWidth(), (int) getHeight());
    	}
    	
    	private void setSprite() {
    		if (texture == null)
    			setTexture();
    		setTextureRegion();
    		sprite = new Sprite(textureRegion);
    		setSpriteColor();
    	}
    	
    	private void setSpriteColor() {
    		sprite.setColor(color.r, color.g, color.b, color.a);
    	}
    	
    	private void setPosition() {
    		this.x = 0.0f;
    		this.y = 0.0f;
    	}
    	
    	private void setPosition(float x, float y) {
    		this.x = x;
    		this.y = y;
    	}
    	
    	private void setSize() {
    		this.width = sprite.getWidth();
    		this.height = sprite.getHeight();
    	}
    	
    	private void setSize(float width, float height) {
    		this.width = width;
    		this.height = height;
    	}
    	
    	public void setColor(int r, int g, int b, int a) {
    		color = new Color(r/255f, g/255f, b/255f, a/255f);
    	}
    
    	public void setColor(float r, float g, float b, float a) {
    		color = new Color(r/255f, g/255f, b/255f, a/255f);
    	}
    	
    	private void setSpritePosition(float x, float y) {
    		sprite.setX(x);
    		sprite.setY(y);
    	}
    	
    	private void updateSprite(float x, float y, float width, float height) {
    		if (fillParent) {
    			setSpritePosition(x, y);
    			if (width != textureRegion.getRegionWidth() || 
    					height != textureRegion.getRegionHeight()) {
    				setSize(width, height);
    				setSprite();
    			}
    		}
    	}
    	
    	@Override
    	public void draw(Batch batch, float x, float y, float width, float height) {
    		updateSprite(x, y, width, height);
    		sprite.draw(batch);
    	}
    
    	@Override
    	public float getLeftWidth() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    	@Override
    	public void setLeftWidth(float leftWidth) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public float getRightWidth() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    	@Override
    	public void setRightWidth(float rightWidth) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public float getTopHeight() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    	@Override
    	public void setTopHeight(float topHeight) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public float getBottomHeight() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    	@Override
    	public void setBottomHeight(float bottomHeight) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public float getMinWidth() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    	@Override
    	public void setMinWidth(float minWidth) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public float getMinHeight() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    	@Override
    	public void setMinHeight(float minHeight) {
    		// TODO Auto-generated method stub
    		
    	}
    	
    	private void setFilename(String filename) {
    		this.filename = filename;
    	}
    	
    	private String getFilename() {
    		return filename;
    	}
    
    	public float getX() {
    		return x;
    	}
    
    	public void setX(float x) {
    		this.x = x;
    	}
    
    	public float getY() {
    		return y;
    	}
    
    	public void setY(float y) {
    		this.y = y;
    	}
    
    	public float getWidth() {
    		return width;
    	}
    
    	public void setWidth(float width) {
    		this.width = width;
    	}
    
    	public float getHeight() {
    		return height;
    	}
    
    	public void setHeight(float height) {
    		this.height = height;
    	}
    
    	public Boolean getFillParent() {
    		return fillParent;
    	}
    
    	public void setFillParent(Boolean fillParent) {
    		this.fillParent = fillParent;
    	}
    
    }
    																																				

    public by giovanni.gambaro modified Jun 27, 2017  422  1  3  1

    Date formatting using ThreadLocal variable

    How to avoid synchronization for a not thread safe classes
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class Foo
    {
        // SimpleDateFormat is not thread-safe, so give one to each thread
        private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
            @Override
            protected SimpleDateFormat initialValue()
            {
                return new SimpleDateFormat("yyyyMMdd HHmm");
            }
        };
    
        public String formatIt(Date date)
        {
            return formatter.get().format(date);
        }
    }

    public by IanUnderhill modified May 16, 2017  196  15  2  0

    lazy singleton

    public final class Singleton {
        private static volatile Singleton INSTANCE = null;
    
        private Singleton() {// singleton instance}
    
        /**
         * @return the single instance of the class
         */
        public static Singleton getInstance() {
            if (INSTANCE == null) {
                synchronized(Singleton.class) {
                    if (INSTANCE == null) {
                        INSTANCE = new Singleton();
                    }
                }
            }
            return INSTANCE;
        }
    }                                    

    public by AlexZezekalo modified May 8, 2017  602  0  4  0

    Potential NPE

    //@Override
    //public boolean isSatisfiedBy(T candidate) {
    //return left.isSatisfiedBy(candidate) && right.isSatisfiedBy(candidate);
    //потенциальный NPE   
    
    //Nonnull as solvation?
    
    
    public class AndSpecification<T> extends CompositeSpecification<T> {
    
        @Nonnull
        private final Specification<T> left;
    
        @Nonnull
        private final Specification<T> right;
    
        public AndSpecification(@Nonnull Specification<T> left, @Nonnull Specification<T> right) {
            this.left = left;
            this.right = right;
        }
    
        @Override
        public boolean isSatisfiedBy(T candidate) {
            return left.isSatisfiedBy(candidate) && right.isSatisfiedBy(candidate);
        }
    
    }
    

    public by hamidmousavi modified Feb 18, 2017  1552  0  5  0

    This method will return WebElement After Given wait

    // This method will return WebElement After Given wait           
    public static WebElement FindWithWait(WebDriver driver,By locator, int seconds) throws Exception{
    		// Sleep until the Element we want is visible or n seconds is over
    		WebElement element=null;
    		
    		//Because if implict wait is set then fluint wait will not work
    		driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
    		try{
    					FluentWait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
    							.withTimeout(seconds, TimeUnit.SECONDS)
    							.pollingEvery(200, TimeUnit.MILLISECONDS)
    							.ignoring(NoSuchElementException.class)
    							.ignoring(StaleElementReferenceException.class)
    							.ignoring(WebDriverException.class);
    									 
    				element=fluentWait.until(
    							
    							ExpectedConditions.visibilityOfElementLocated(locator)
    							
    							);
    				return element;
    					
    		} catch(Exception e){
    			
    			throw new Exception("Timeout reached when searching for element! Time: " + seconds+" seconds " +"\n" +e.getMessage());
    			
    		}
    		finally {
    			driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    		}
    		
    	}

    public by GennadyBal modified Jan 31, 2017  1643  0  3  1

    Using Scanner to Read System Inputs - Java Stdin and Stdout

    Using Scanner to Read System Inputs - Java Stdin and Stdout
    import java.util.*;
    
    Scanner scanner = new Scanner(System.in);
    String myString = scanner.next();
    int myInt = scanner.nextInt();
    scanner.close();
    
    System.out.println("myString is: " + myString);
    System.out.println("myInt is: " + myInt);

    public by cghersi modified Jan 10, 2017  2026  9  5  3

    How to write bytes into file in Java

    Efficient way to write strings or bytes onto a file.
      import java.nio.file.Files;
      import java.nio.file.Paths;
    
      public static void writeFile(String path, String content) throws Exception {
    		if (isNullOrEmpty(path) || isNullOrEmpty(content)) {
    			return;
    		}
    		Files.write(Paths.get(path), content.getBytes());
    	}                     

    public by cghersi modified Jan 10, 2017  2229  2  5  1

    Read file in Java

    Efficient way to read file in Java using Files class
      import java.nio.file.Files; 
      import java.nio.file.Paths;
    
      public static String readFile(String path) throws Exception {
    		if (isNullOrEmpty(path)) {
    			return "";
    		}
    		return new String(Files.readAllBytes(Paths.get(path)));
    	}      
    • Public Snippets
    • Channels Snippets