Showing posts with label algorithms. Show all posts
Showing posts with label algorithms. Show all posts

Tuesday, October 1, 2019

Showing A Custom Toast message in Android

Many a times we have to go beyond the built-in options and build our own custom interfaces. Here I will share with you the code to build your own custom Android Toast Messages.

Code Snippet


//Show custom Toast Message.
Toast t = new Toast(this);
View v = LayoutInflater.from(this).inflate(R.layout.no_data, null);
TextView messageTV = (TextView) v.findViewById(R.id.textViewNoDataMessage);
messageTV.setCompoundDrawablePadding(4);
messageTV.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.bullet_ball_glass_red_16), null, null, null);
messageTV.setText(R.string.device_unauthorized_message);
messageTV.setTextSize(25);
messageTV.setTypeface(Typeface.DEFAULT);
t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
t.setDuration(Toast.LENGTH_LONG);
t.setView(v);
t.show();



Here you go guys! Hope this helps you! Enjoy!

Thursday, May 3, 2018

Check palindrome, simplest approach

Check palindrome:

The simplest approach to a quick, and efficient check palindrome program:

We don't need loops for everything!

The internal working is with a couple of if statements.


Always try to condense the program logic to skip loops if possible. There any many ways to implement simple tests which ensure the skipping of loops.


CODE(Javascript):


function checkPalindrome(inputString) {
    if(inputString.length == 1)
        return true;
    if(inputString.length % 2 == 0){
        if(inputString.slice(0, inputString.length / 2) == inputString.slice(inputString.length / 2, inputString.length).split("").reverse().join(""))
            return true;
    }
    else{
        if(inputString.slice(0, inputString.length / 2) == inputString.slice((inputString.length / 2) + 1, inputString.length).split("").reverse().join(""))
            return true;
    }
    
    
    return false;

}

Explanation:

  • String reverse in javascript 
    (ARRAY).split("").reverse().join("")
    

    This snippet can be used to reverse strings in javascript. The split("") splits the string into an array of characters. Next, the reverse() function reverses a JS Array. The join("") function joins them up again.
  • String slice is used to slice the string into smaller chunks. We slice at the center, if the string is of even length, if the string is of odd length, we slice around the center character.
  • If the string is of length 1, we know it’s a palindrome.
  • If the half of the string matches exactly with the other half, then we know it is a palindrome.



That is the logic behind this code! Isn't simple? Do try it out, I am sure it works for all test cases! Until next time!



Wednesday, April 4, 2018

$No_Code 2 var C0D3R Pt1

Coding coding coding.
Everyone wants to know about it.
Some get it, some don't. 
I for one always knew that I was going to be a computer programmer.

Ever since my school days, I have wondered how those amazing games (EA: Need for Speed series, etc.) worked in the background. I thought about graphics that went into them, learnt about game development, and web development.

I just had the highest level of curiosity for cool things. I always loved reverse engineering stuff, taking things apart and figuring out step by step how to put it back together. Such interest has propelled me to reverse engineer many real-world objects, and at a novice level many games, websites and mobile apps. It is just so interesting to figure something out and generate new ideas from that newfound theory.

Hence, I spent most of my days doing things like web development, gaming, and coding. I picked up languages one by one. Now I know so many I cannot even keep track of half of what I know and what I remember. But just know one thing, one must always know what kind of programming languages he can use to get the required results.

Now, this comes with practice. However, you must continue to try to reverse engineer and learn new things every day. Only then can you catch up with the current trends right?

There are few approaches I would like to suggest people who wish to be good developers:

  • Always write logically and syntactically correct code. i.e. Don't waste time on silly things like syntax and logic.
  • Code formatting and documentation is an indirect marketable skill. Clear, readable, understandable code is the dream of many Tech team leads. When you write code, be sure to make it readable and formatted well. Always include very meaningful variable names, supporting documentation, using comments, etc. This helps anyone who reads your code to understand exactly what is happening and they can pick up where you left off, as it is very unlikely you will work single-handedly on any project.
  • Try to understand the underlying differences in approaches while using various different languages.
  • When writing code, keep in mind:
    • Keep unnecessary steps to a minimum,
    • Iteratively make your algorithm better,
    • Only generate it into production code when the algorithm seems to be at its best,
    • Try to come back after a while to check on the algorithm once more. Usually, you'll find incredibly stupid/silly things that can be fixed or updated. Hence, point 1.
    • Keep the number of lines of code to a minimum, per function. A function/method should only perform one task. Example: function makePizza() needn't worry about delivering it.
  • Look into coding challenges online on the tens of hundreds of platforms such as HackerRank, GeeksForGeeks, etc. Solve one a day at the least.
  • Work on different IDEs, online and offline. 
  • Try to find the balance between designing and developing.
  • You are bound to fail, just don't give up. Programs will work only at the last hour before deadlines. Such is many people's fate.
I have spent hours and hours on a single step or single problem, only to realize next day what I missed. It can happen to anyone. You could also find it difficult to read and understand even standard code or others' code. 

Tricks:

  1. Learn & develop in multiple languages simultaneously. It gives a better level of control over your emotions as a programmer.
  2. Write the same program in different languages.
  3. Decide before you begin exactly what your stack is going to be. (see below for stacks)
  4. Be willing to spend the rest of your life in front of a computer in the worst case. Further, get ready to spend more than 12-14 hrs a day, <coding>
  5. Choose the latest stack, and do company specific stack building.

Stacks:

  • Stacks are groups of technologies/libraries or frameworks, which are used to build a specific application.
  • There are many ways to categorize them. I will categorize them broadly using:
    • Ease of Learning
      • MEAN, python Django, .NET+web, JAVA(core/enterprise)
    • Productivity
      • Racket, Scheme, Lisp, - Almost ready for anything
      • Python - numpy, scipy, sklearn, serial, pygame etc.
      • C/C++ - Windows, Linux, Systems Programming, OpenGL, GameDev
      • JAVA - CORE/EE Powerful enough to run anywhere, anything.
    • Type of application
      • Web: Frontend +PHP, NodeJs, Ruby, etc. Where Frontend can be AngularJs, ReactJs, etc.
      • Mobile: AndroidSDK, IOS_Swift, etc, React-native, IconicFramework/Cordova, AngularJS etc.
      • Dekstop: C/C++, JAVA, python, etc.
Computer Architecture/How it works basics (can skip):
  1. Fact - Computers are dumb until made smarter by equipping them with Human-based intelligence.
  2. Computers can only understand 0/1, Binary.
  3. Steps for programs to run on the CPU:
    • A program is written in a high-level language
    • Compile means it is converted to assembly and optimized as best as can to run faster. 
    • The compiled program can then be converted further to binary in the linking step.
    • Further optimizations are done.
    • Finally, the program is assigned a position in the CPU running queue.
  4. Next?
    • The CPU contains certain architecture to make the program have its own space and allow it to work from there.
    • This architecture is called the Stack. The CPU consists of closely bound elements such as the Stack, Registers, and Cache.
    • The Main memory is the next fastest. The Secondary memory, (DISK) is the slowest. hence, one should try to load chunks of working data into the main memory or the cache to have the fastest processing speed.
    • So basically, when the assembly program arrives, the CPU assigns certain stack space for each such program. The variables that are found to be alive are sorted into registers when they appear in the code. These registers are the only ones who can operate on data. We all know that most of the worlds most complex problems can be reduced to simple mathematical equations. This is one of the main reasons that the CPU is hooked up to the ALU- Arithmetic and Logic Unit. There is a whole book on this topic Computer Architecture, but mainly, each program becomes a function for the CPU. Most functions are reduced to math or logic operations completed by ALU. If there is a store/read command, then the memory is accessed and the registers are updated.
    • This process of CPU is so repeated in every aspect of programming. If we have large data, we divide and conquer. If we need fast processing, we try to place most of the required files into the same working directory (example: external js libs vs local js lib files downloaded ahead of time)
  5. Now, you don't need to get into any of this. From programmers standpoint always remember one thing. Answer these questions:
    1. What's the output?
    2. What's the input?
    3. Can I code it?
      • What do I need?
      • What do I have?
      • Where do I get other dependencies? Can I get them?
    4. Choose the language
Feel free the leave comments, or contact me personally on my Gmail. I am willing to provide one-on-one training on any technology I'm comfortable with. Be sure to ask!






Friday, March 30, 2018

Web effects, HTML, Jquery, CSS Part 1.1 - My code for my front page.

Front page animation Sam's Playground (Portfolio)

Code Snippet for my animation on my front page here

Javascript

So first we start by defining a few variables. Next we extract the characters from the head tag and perform required steps in the extract function. This is a function I defined to perform animation. It is a helper function. Also, we register animation frame for the window. All happening inside the ready function.

var head1 = $("h1#head1");
var total = 0;
var scene;
var camera;
var renderer;
var mwidth = 900, mheight = 900;
// Jquery Ready function, triggered when document is "ready"
$(document).ready(function() {
//Extract the head tag value
extract(head1);
// Use built-in function to create new animation frame to make it smooth.
window.requestAnimFrame(dripp);
// Variable to store oldtext from head value.
var oldtxt;
});


// Extracting Characters from the string from head tag. Making this a slightly modular approach.
function extract(_textholder){
var htext = _textholder.text();
var hlen = htext.length;
total += hlen;
_textholder.text("");
for(i=0; i< hlen; i++){
_textholder.append("<h1
class='drippers'>"+htext[i]+"</h1>");
}
}
// Function that actually performs addition and deletion of animation class so that we can animate random characters.

function dripp(){
rnd = parseInt(Math.random() * total);
$(".drippers").each(function(i, obj) {
if(i == rnd)
$(this).toggleClass("drippin");
});
window.requestAnimFrame(dripp);
}

// Fix for built-in function for setting callback time.
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000);
};
})();

CSS

.drippin is a CSS class which enables the 'drippin' keyframe animation. This is the class we apply and remove to perform the animation. The animation itself is defined in keyframes. The first part of the animation starts at 0% and the text-shadow property allows to create the effect. We define the property value for each of the time steps in the keyframe. We define individual keyframe animations for each browser.
Chrome - @-webkit-keyframe
Mozilla - @-moz-keyframe
Opera - @-o-keyframe
Others - @keyframe

.drippin {
 -webkit-animation: ease drippin 1.5s infinite;
 /* Safari 4+ */
 -moz-animation: ease drippin 1.5s infinite;
 /* Fx 5+ */
 -o-animation: ease drippin 1.5s infinite;
 /* Opera 12+ */
 animation: ease drippin 1.5s infinite;
 /* IE 10+, Fx 29+ */
}
.drippers {
 text-transform: full-width;
}


@-webkit-keyframes drippin {
 0% {
  text-shadow: 0px -5px 2px black;
 }
 10% {
  text-shadow: 0px -0px 2px red;
 }
 15% {
  text-shadow: 0px -3px 3px red;
 }
 20% {
  text-shadow: 0px -4px 3px red;
 }
 100% {
  text-shadow: 0px -10px 4px white;
 }
}
@-moz-keyframes drippin {
 0% {
  text-shadow: 0px -5px 2px red;
 }
 10% {
  text-shadow: 0px -0px 2px red;
 }
 15% {
  text-shadow: 0px -3px 3px red;
 }
 20% {
  text-shadow: 0px -4px 3px red;
 }
 100% {
  text-shadow: 0px -100px 4px maroon;
 }
}
@-o-keyframes drippin {
 0% {
  text-shadow: 0px -5px 2px red;
 }
 10% {
  text-shadow: 0px -0px 2px red;
 }
 15% {
  text-shadow: 0px -3px 3px red;
 }
 20% {
  text-shadow: 0px -4px 3px red;
 }
 100% {
  text-shadow: 0px -100px 4px maroon;
 }
}
@keyframes drippin {
 0% {
  text-shadow: 0px -5px 2px blue;
 }
 10% {
  text-shadow: 0px -0px 2px lightgreen;
 }
 15% {
  text-shadow: 0px -3px 3px blue;
 }
 20% {
  text-shadow: 0px -4px 3px red;
 }
 100% {
  text-shadow: 0px -100px 4px lightgreen;
 }
}

If any of the code doesn't work, you can troubleshoot it by:

  1. Checking the variable names, definitions, and other related syntax 
  2. Remove all or misplaced comments.
  3. Check for keyword spelling mistakes.
  4. Try a different browser.
  5. Open Inspector > Console to check for errors.

Best of luck, and happy coding! Hope you have fun and create more such animations to place on your websites!

Samartha  K V

Working with SERIAL input from devices

Working with Windows Device Manager

Device Manager
These can be setup in the Device Manager section of the Control Panel in Windows. To access the Device Manager, please follow these steps.
         Click the bottom-left Start button on desktop, type “device manager” in the search box and tap Device Manager on the menu.
         Or else, Open Device Manager from Quick Access Menu. Press Windows + X to open the menu and choose Device Manager on it. 
         One might also Access Device Manager in Control Panel. [Google]
Once device manager is visible, we can find the device under Ports (COM & LPT). The RADAR should be listed under this section only.
Note: Device Manager is used to setup both the devices.

Reading from serial input

When we have USB COMM Port devices, we need can read data generated by them using various toolkit libraries, such as pySerial in python etc. However, we might need to Poll the device for data once or twice before actually setting up automated tasks using python.

Here I go into the thinking involved while working with such devices.
I take as example the ICM 20948 IMU component. While reading data from this device, one must:
  • Refer to the Datasheet for possible COMM Port settings and requirements.
  • Utilize Putty to connect serially and read data
  • Looking up related documentation for downloading and installing drivers. 
  • Sometimes we might have to install unsigned Drivers
    • Please refer to Google to find out how to disable Windows Driver Signature Verification at boot.
  • Next, lookout for consumer facing data reading software.
    • For example, ICM 20948 can be used with MotionLink provided by the manufacturers to view the real time data from all the sensors.
    • Such software can be customized using their own IAR Workbench IDE. 
    • Look for manufacturer provided examples. 
    • Look at other alternative locations to download related datasheets and configuration files or supporting applications
    • Be sure to try different versions of the IDE to figure out what works on your system with that particular component.

Link to my report on system for 3D-DIC measurements and techniques using ICM and RADAR component, while hooking it up with RaspberryPi.

I worked on an academic project with the Mechanical Department, where I worked with these components and used pyserial library to interact with both of them simultaneously as was the need of the project. The complete guide to software development in these scenarios can be found alongside the report of calibration and usage.
You may access the report from my drive link here

GitHub Repo












PYTHON COURSE 1a - BASIC INTRODUCTION TO PYTHON DEVELOPMENT

INSTALLING AND WORKING WITH PYTHON
1. DOWNLOAD VS CODE EDITOR

WHILE INSTALLING, BE SURE TO CLICK
  1. ADD TO PATH IF POSSIBLE
  2. ADD TO CONTEXT MENU FOR
    1. FOLDER
    2. FILE
VERSION 2.7.XX
select Add to Path option while installing.

2. NEXT,
  1. Open the command prompt by typing cmd in the Start application
  2. Then type python in Console Window to check if python is installed.
  3. If yes, the console should go into the python shell. LIKE SO

3. NEXT,
  1. Exit the shell by keying in “exit()” into python shell
  2. When in cmd console
    1. You should see the cmd root like
    2. “samar” is replaced by your username – THIS is your HOME folder.
    3. Common CMD line commands are
                                                       i.      Make Directory
        1. mkdir <space> <DIRECTORY_NAME>
                                                     ii.      Change Directory
        1. cd                        Current Directory
        2. cd <space> <DIRECTORY_NAME>  Goto DIRECTORY_NAME
        3. cd <space> <DOT DOT> (cd ..) Go One folder up or Back.
        4. Examples:
          1. cd ..
          2. cd Desktop
          3. cd Desktop/Some_Folder
          4. cd Desk*
                                                                                                                      i.      Autocompletes characters with * - 0 or more chars.
                                                                                                                    ii.      Autocompletes characters with + - 1 or more chars.
                                                   iii.      List Directories and files
        1. dir in Windows.
        2. ls in Linux.
                                                    iv.      Whatever you type here in cmd is a program
        1. If the program exists, it is opened
          1. If its console program, only console is shown.
          2. If its GUI – window based program, both console and window is shown
        2. If the program doesn’t exist, then the error command not found is shown.
4. NEXT,
  1. Download the program.
    DOWNLOAD HERE - test.py
  2. Open CMD C:\users\your_username> <ENTER CMD>
    1. Navigate to Desktop cd Desktop
  3. Create a folder using mkdir NEW_FOLDER_NAME (ex: mkdir test)
  4. Copy the test.py into the directory. Enable Show File extensions for known formats from View Options at the top
  5. AFTER making sure that the current directory is open by using cd
    1. cd should show you C:\Users\YouRs\Desktop\test
    2. else use cd test to enter the newly created folder housing the test.py file.
    3. To edit the file, use vs-code. Try Right-Click in folder and select Open with Code.
  6. Once the cmd is in test folder, we can try running the program.
  7. Just type python test.py to run the code. You should get this output
To learn more try


  1. Tutorials Point - python course